# Events storage: proposal

Sites with large lists that send many broadcasts grow `gh_events` by one wide row
per recipient per send. This proposes where that information should live instead.
Nothing here is built.

Items marked **Decision** need Adrian's answer first. Sizes and row counts below are
estimates from the column definitions, **not measured**. Item 1 is to measure them.

| # | Item | Size | Depends on |
|---|---|---|---|
| 1 | Measure on a real large site's data | half a day | nothing |
| 2 | A narrow table for completed broadcast sends | large | 1 |
| 3 | Hourly send counts, so reports stop counting rows | medium | nothing |
| 4 | Move existing rows, and give the space back | medium | 2 |
| 5 | How long to keep individual send records | small | 2, 3, **Decision** |
| 6 | A compressed list per broadcast for old sends | large | 5, recommend not yet |

## What a send costs today

A completed broadcast send is a full `gh_events` row (`db/events.php`,
`create_table_sql_command()`): `ID`, `time`, `micro_time`, `time_scheduled`,
`queued_id`, `contact_id`, `funnel_id`, `step_id`, `email_id`, `event_type`,
`error_code`, `error_message`, `priority`, `status`, `args`, and four secondary
indexes. That is roughly 230 bytes a send with indexes.

For a completed broadcast send, later code reads only five of those: which
broadcast (`step_id`), which contact, which email (variations and A/B tests send
different emails inside one broadcast), when, and `queued_id`. `funnel_id` is
always 1, `event_type` always `Event::BROADCAST`, `status` always `complete`, and
the error columns are empty.

`queued_id` has to stay. Two things find a send by it:

- **Tracking links.** A link in a sent email carries the contact ID and the queue
  ID. `Tracking` resolves it with `get_event_by_queued_id()`
  (`includes/functions.php`), then checks the event's contact matches. Links in
  emails already sent must keep working.
- **The email log.** `gh_email_log.queued_event_id` is how the messages feed
  (`api/v4/messages-api.php`, `query_automated_emails()`) finds the subject that
  was actually sent.

Queue IDs are not unique over time. `Events::get_by()` orders by `ID DESC` for that
reason, and `Events::DUPLICATE_MATCH_COLUMNS` exists because a queue ID can be used
again by a different event.

## Who reads broadcast sends

From a grep of core for the `events` table. Each needs reading before the build;
this list has not been verified line by line.

**Counts**

- `includes/reporting/new-reports/traits/broadcast-stats.php`: contacts sent to, per broadcast.
- `includes/reporting/new-reports/table-top-performing-broadcasts.php`
- `includes/reporting/new-reports/total-emails-sent.php`: a date range, optionally joined to a campaign.
- `includes/reporting/new-reports/chart-email-activity.php`: per day.
- `includes/functions.php`, `num_emails_sent()`
- `includes/email-variations.php`: `report()` counts by `email_id` across flows and
  broadcasts, and the broadcast test reads `MAX(time)` for the sample.
- `includes/telemetry-snapshot.php`, `includes/site-health.php`, `includes/notices.php`

**Membership (segment filters)**

- `includes/contact-query.php`: `basic_event_filter()`, `filter_email_received()`
  (with a count and a date range), and the legacy `report` query var.

**One contact's history**

- `api/v4/contacts-api.php`, `api/v4/messages-api.php`, `includes/mobile/activity-feed.php`,
  `includes/markdown/contact-markdown.php`
- `admin/events/events-table.php` and `events-page.php`, including "run again",
  which calls `Events::move_events_to_queue()` on history rows.
- `templates/archive/events.php`

**Writers and cleanup**

- `db/event-queue.php`, `move_events_to_history()`: the only way a send reaches history.
- `db/traits/event-log.php`, `contact_deleted()`: deletes a contact's events.

**Not affected:** flow events. `includes/classes/step.php`, the split test step and
the funnel reports use the full row, and some of it drives logic (whether a contact
has been at a step). They stay in `gh_events` as they are.

**Add-ons.** A search of the other repos in `PhpstormProjects` timed out before it
finished. It did find `Event::BROADCAST` or `Broadcast::FUNNEL_ID` in the reports of
`groundhogg-edd` and `groundhogg-wooc` (revenue by broadcast). Whether they read
`gh_events` or only `gh_activity` is **unverified**. An add-on that reads broadcast
sends from `gh_events` directly would see nothing after item 2, with no error.

## 1. Measure first

On a copy of a large site's database (or groundhogg.dev seeded with a few million
rows):

- Bytes per row of `gh_events` today: `data_length + index_length` from
  `information_schema.tables`, divided by rows.
- The same for the table in item 2, filled from the same rows. Try it with
  `int unsigned` and with `bigint unsigned` ID columns.
- `EXPLAIN` and timings, before and after, for: the sent count of one broadcast,
  "received broadcast X", "received at least 3 emails in the last 30 days", and one
  contact's timeline.

Done when: the numbers replace the estimates in this file. If the saving is under
2 times, item 2 is still worth it for the queries and for making duplicates
impossible, but item 5 becomes the main way to save space.

## 2. A narrow table for completed broadcast sends

```sql
CREATE TABLE {prefix}gh_broadcast_sends (
    broadcast_id int unsigned NOT NULL,
    contact_id   int unsigned NOT NULL,
    email_id     int unsigned NOT NULL,   -- 0 for SMS
    time         int unsigned NOT NULL,
    queued_id    bigint unsigned NOT NULL,
    PRIMARY KEY (broadcast_id, contact_id),
    KEY contact_time (contact_id, time)
)
```

Estimate: about 65 bytes a send with `int` columns, about 100 with `bigint`,
against about 230 today. So 2 to 3.5 times smaller, not more.

Why this shape:

- **The primary key is the fact.** A broadcast sends to a contact once. "Received
  broadcast X" is a primary key lookup, the sent count is a range scan of the
  primary key with no `DISTINCT`, and a second copy of a send can't be inserted.
- **`contact_time`** serves a contact's timeline and "received N emails since".
- **No index on `queued_id`.** Every lookup by queue ID also knows the contact (the
  tracking link carries it, the messages feed is per contact), so it is
  `WHERE contact_id = ? AND queued_id = ?` over one contact's sends. That needs
  `get_event_by_queued_id()` to take an optional contact ID, and `Tracking` to pass it.
- **`int unsigned`** is not the WordPress habit (`bigint(20)`), but nothing needs
  more than 4 billion contacts or broadcasts, MySQL joins `int` to `bigint` with
  the index, and it is a third of the saving. **Decision.**

Only completed sends go here. Failed, skipped and cancelled broadcast events stay
in `gh_events`: they are few, they need the error columns, and the events admin
page lists them.

**Writing.** In `Event_Queue::move_events_to_history()`, completed broadcast events
go to the new table with `INSERT IGNORE`, everything else to `gh_events` as now. The
delete from the queue checks the table the row went to. `in_history_sql()` has to
know about both.

**Reading.** A `Broadcast_Sends` DB class registered as `broadcast_sends`, so
`Table_Query( 'broadcast_sends' )` works. Then, per group above:

- Counts for one broadcast read the new table. Counts over a date range read item 3.
- Filters: `filter_broadcast_received()` reads the new table.
  `filter_email_received()` with no `funnel_id` means "any email", so its subquery
  becomes a `UNION ALL` of both tables. `basic_event_filter()` and the `report`
  query var switch table when `event_type` is broadcast and `status` is complete.
- One contact's history: a `UNION ALL` of both tables by `contact_id`, mapped to
  the event columns (`funnel_id` 1, `step_id` the broadcast, `event_type`
  broadcast, `status` complete). Put this in one place, for example
  `Events::query_contact_history()`, and point the four readers at it.
- `Event`: tracking needs an `Event` object (`get_email()`, `get_step()`,
  `is_broadcast_event()`, `get_time()`). Let `Event` be built from a send row with
  the same mapping.

**Things that change meaning. Decisions.**

1. **`gh_activity.event_id`.** Opens and clicks store the history row's `ID`, and
   an open is counted once per `event_id` (`Tracking::email_opened()`). A send row
   has no `ID`. Proposal: for broadcast sends, store the `queued_id` there and
   dedupe on broadcast, contact and type, which `gh_activity` already has columns
   for. `event_id` appears in 19 core files; the readers haven't been checked.
2. **The events admin page.** Completed broadcast sends would no longer be rows
   there. Proposal: the page keeps flow events and broadcast failures, and a
   broadcast's own report lists who it was sent to.
3. **"Run again" on a completed broadcast send.** Proposal: drop it for broadcast
   sends. Sending one contact a broadcast again is rare and can be done by sending
   the email from the contact screen.
4. **Deleting a contact** deletes their send rows, as it does their events today.

Tests: a completed broadcast event lands in the new table and not in `gh_events`;
a failed one stays in `gh_events`; a move run twice leaves one row; each filter
returns the same contacts as before, for sends in either table; a tracking link
with the old format resolves to a send in the new table; the timeline and the
messages feed are in order across both tables.

## 3. Hourly send counts

A count over a date range ("emails sent in the last 30 days", the activity chart)
can't use the table in item 2 without an index on `time`, which would give back
much of the saving. So keep counts:

```sql
CREATE TABLE {prefix}gh_send_counts (
    hour       int unsigned NOT NULL,     -- unix time of the start of the hour, UTC
    event_type int unsigned NOT NULL,
    funnel_id  bigint unsigned NOT NULL,
    step_id    bigint unsigned NOT NULL,
    email_id   bigint unsigned NOT NULL,
    sent       int unsigned NOT NULL,
    PRIMARY KEY (hour, event_type, funnel_id, step_id, email_id)
)
```

One row per hour per broadcast (or flow step) per email. A broadcast to a million
contacts is a handful of rows. It covers flow emails too, so the date-range
reports read one place, and it is independent of item 2: it can ship first.

- **Writing.** In `move_events_to_history()`, add the counts of what that run moved
  with `INSERT ... ON DUPLICATE KEY UPDATE sent = sent + VALUES(sent)`. It must
  count only rows that were actually inserted into history. The move lock can time
  out and the move then runs anyway, so a daily job recounts the last few days
  from the tables and overwrites.
- **Reading.** `total-emails-sent.php`, `chart-email-activity.php` and
  `num_emails_sent()` sum `sent` over the range. The campaign join in
  `total-emails-sent.php` works on `step_id`.
- **Backfill.** A background task fills it from `gh_events`, oldest first, before
  any reader switches.

Gotchas:

- **Time zones.** Reports use the site's time zone. Hour buckets in UTC are exact
  for zones on the hour. For half-hour zones (India, parts of Australia) a range's
  edges are off by up to 30 minutes. **Decision:** accept that, or use 15-minute
  buckets (4 times the rows, still small).
- **Deleted contacts.** Today, deleting a contact lowers past sent counts because
  their events go. With kept counts it doesn't. That is arguably right (the email
  was sent) but it is a change, and open rates are still counted from
  `gh_activity`, which does lose the contact. **Decision.**
- `Email_Variations::report()` counts sends per `email_id` since a timestamp. It
  can read this table if a test's start is rounded to the hour, or keep reading
  rows. Not decided.

Tests: counts match a row count for a seeded range; a move run twice counts once;
the recount job repairs a count that was made wrong.

## 4. Move existing rows

A background task in the style of `Remove_Duplicate_Events`
(`includes/background/remove-duplicate-events.php`): walk `gh_events` by `ID`
range, `INSERT IGNORE` completed broadcast events into the new table, delete them
from `gh_events`, record the last ID, repeat.

- Readers use both tables until an option says the move has finished, then only
  the new one. Item 2's reads are written with that switch from the start.
- `INSERT IGNORE` drops the duplicate history rows as a side effect.
- **InnoDB does not give the space back** when rows are deleted. The file shrinks
  only when the table is rebuilt (`OPTIMIZE TABLE`), which needs free disk about
  the size of the table and can take minutes on a large one. Offer it as a button
  in Tools with that warning, and never run it automatically. On some hosts
  (`innodb_file_per_table` off) the space can't be given back at all.

Tests: a batch moves only completed broadcast events; a task stopped part way
resumes; reads are the same before, during and after.

## 5. How long to keep individual send records (**Decision**)

Once counts are kept (item 3) and a broadcast's own totals are in its
`cached_report_data` meta, an individual send row is needed for three things:
segment filters on that broadcast, the contact's timeline, and tracking links.
All three matter less as a send gets older.

Proposal: a setting, "Keep individual send records for", with forever (the default),
24, 12 and 6 months. A daily job deletes older send rows. What the setting's help
text has to say is lost:

- "Received broadcast X" and "received N emails" filters stop matching sends older
  than that.
- Those sends leave the contact's timeline.
- An open or click on an email older than that isn't tracked. The click must still
  redirect to its target; today a link whose event isn't found bails.

Before deleting, freeze the broadcast's totals so its report can't be recounted
from nothing.

Recommendation: build it, default forever. It is the only item that makes the
table stop growing.

## 6. A compressed list per broadcast (recommend not yet)

Old sends could be stored as one row per broadcast holding the sorted contact IDs,
delta-encoded and compressed. 100,000 recipients is a few hundred KB, about 100
times smaller than rows.

The cost is that SQL can't join to it. A filter on that broadcast has to decode the
list in PHP and pass the IDs back in, a contact's timeline has to look inside every
old broadcast's list, and "received N emails" across many old broadcasts isn't
practical. `email_id` and `queued_id` per contact are lost unless stored beside it.

Recommendation: only if a site with retention set to forever still has a send table
that is too big after item 2. It would then replace deletion in item 5 for the
"did they receive X" filter alone.

## Not proposed

- **MySQL partitioning.** It makes dropping old rows cheap but saves no space, the
  partition column has to be in every unique key, and it isn't dependable across
  the hosts customers use.
- **Narrowing flow events.** Lower volume, and steps depend on the full row.
- **Only adding an index** such as `(funnel_id, step_id, contact_id)` to
  `gh_events`. It would speed the per-broadcast queries today and is a fair stopgap,
  but it makes the table bigger.

## Open questions for Adrian

1. `int unsigned` or `bigint unsigned` in the send table?
2. `gh_activity.event_id` for broadcast opens and clicks: the queue ID, or 0?
3. Completed broadcast sends off the events admin page: acceptable?
4. Drop "run again" for a completed broadcast send?
5. Send counts: UTC hours, or 15-minute buckets for half-hour time zones?
6. Should past sent counts stay when a contact is deleted?
7. Retention: offer it at all, and is forever the right default?
8. Order: item 3 alone is the smallest release and speeds the dashboard. Ship it
   first, or hold everything for one release with item 2?
9. Add-ons: who audits the other repos for direct reads of broadcast sends, and
   does core keep a compatibility read (a filter on `Table_Query( 'events' )`) for
   third-party code?

## Conventions for whoever builds this

- PHP 7.4 syntax.
- Commit to `master`, only when Adrian asks. Don't push unprompted.
- New tables go through the `DB` base class and `Manager`, with a `get_db_version()`
  and an updater step in `includes/main-updater.php`.
- Long work (backfill, the move) is a background task that works in ID ranges and
  can resume, like `Remove_Duplicate_Events`.
- Read `docs/flow-architecture.md` before touching the queue.
