# Email variations: multilingual sends and A/B tests

A **variation** is another version of an email, sent instead of it to some
contacts: the email in another language, a version for a segment, or a test
version in an A/B test. Flows, broadcasts and notifications keep referencing the
original email, and each contact gets the version for them when it's sent.

What is still open or unverified is in `docs/email-variations-follow-ups.md`.

## Where the code is

| Piece | Where |
|---|---|
| Model, choosing a version, family IDs, create/update/copy/export/import, delete cascade, A/B tests, the broadcast test, editor data | `Groundhogg\Email_Variations`, `includes/email-variations.php` |
| The site's languages and a contact's language | `Groundhogg\Multilingual`, `includes/multilingual.php` |
| An email's text as translation strings, and staleness | `Groundhogg\Email_Strings`, `includes/email-strings.php` |
| The footer built in the language it's sent in | `Block_Registry::footer()`, `includes/block-registry.php` |
| The AI translate job | `Groundhogg\AI\Jobs\Translate_Email`, `includes/ai/jobs/translate-email.php` |
| Abilities | `includes/abilities/emails/` (see below), guide sections "Variations" and "A/B tests" in `includes/abilities/guides/email.md` |
| REST | `api/v4/emails-api.php`, `api/v4/broadcasts-api.php` |
| Editor panel | `VariationsControls` and friends in `assets/js/admin/emails/email-block-editor.js` |
| Broadcast scheduler | `ABTestControls` in `assets/js/admin/features/send-broadcast.js` |
| Tests | `tests/phpunit/unit-tests/includes/class-email-variations-tests.php`, `class-email-strings-tests.php`, `class-email-ab-tests.php`, `class-multilingual-tests.php`, `class-html2markdown-tests.php` |

## Data model

- A variation is a row in the `emails` table whose `parent_id` is the email it's a
  version of. `parent_id` came with table version 2.2 (the 4.13 update). Until that
  update runs, `Emails::supports_variations()` is false, the column is left out of
  `get_columns()`, and nothing has variations.
- `parent_id` is set only when a variation is created: `Email::update()` and the
  REST create drop it.
- `Emails::query()` adds `parent_id = 0` unless the caller passes `parent_id` or
  `include`. That one place hides variations from the admin table, REST and v3
  search, the email pickers and `list-email-templates`.
- A variation's settings are its meta:
  - `variation_kind`: `audience` (the default) or `test`
  - `variation_audience`: `locales` (checked in PHP, no query) plus the Filters DSL
    (`include_filters`, `exclude_filters`). Everything given has to match.
  - `variation_priority`: the order audience variations are checked in, lowest first
  - `variation_locale`: the language it's written in
  - `variation_weight`: a test version's share, in percent
  - `variation_sources`: a hash per string of the email's text it was translated
    from (see "Translation strings")
- On the email itself: `variation_winner`, `variation_test_started` and
  `variation_broadcast_test`. These are `Email_Variations::TEST_STATE_KEYS`, and
  duplicating or exporting an email doesn't copy them.
- Inherited from the email, never set on a variation: `message_type` (read from the
  parent's column, without recursion), and being a template. Everything else varies
  freely: sender, subject, preview text, content, template settings, headers.
- Deleting an email deletes its variations (`groundhogg/email/pre_delete`).
  Duplicating it, a flow template export, and the Send Email step's import carry
  its variations.
- Templates and global blocks can't have variations, and a variation can't have
  variations of its own.

## Choosing the version at send time

Every send goes through `Email::send()`, which calls `Email_Variations::resolve()`:

1. Only a ready email resolves, and test sends never do. A draft variation is never
   chosen, so variations can be drafted without changing what anyone gets.
2. **Audience variations**, by priority, first match wins. `locales` is checked in
   PHP. Filters are one `Contact_Query` with the `IS_SUB_QUERY` flag, so they match
   without the owner restriction of whoever is sending.
3. **Closest language.** If none matched exactly, they're checked again by language
   alone, so a contact who speaks fr_CA gets the fr_FR version.
   - Not when the email itself is the closer match: the email counts as the site's
     default language, so on an en_US site an en_GB contact gets the original.
   - Not for zh, whose varieties use different scripts.
   - Filters in the audience still have to match.
   - Filter `groundhogg/email/variation/closest_language`.
4. **The A/B test.** Everyone else is in the email's test, if it has one: the
   declared winner, or the test version their bucket lands in (see "A/B tests").
5. Filter `groundhogg/email/variation/resolve` has the last word.

Then:

- `attribute_event()` rewrites the queued event's `email_id` to the variation, so
  opens, clicks, unsubscribes and the email log count for it. A retry loads the
  variation from the event, and a variation sends itself without resolving again.
- `Email::get_sent_email()` is the version that actually went out, for callers that
  read the email back after sending.
- The email is built in the variation's `variation_locale`, or else the contact's
  language (`switch_to_locale()`), so the plugin's own text in it is in that
  language too. The event queue also switches to the contact's language around
  each event.
- A variation can't be broadcast (`Broadcast::schedule()` refuses it) or sent alone
  with `send-email-template`.

## Languages

- `Multilingual` reads the site's languages, its default and the current language
  from WPML, Polylang or TranslatePress. Filters `groundhogg/multilingual/plugin`,
  `site_languages`, `default_locale` and `current_locale` cover anything else.
  Weglot isn't read: it uses language codes rather than locales.
- A contact's language is their `locale` meta (`Contact::get_locale()`, a WordPress
  locale). Without one, it falls back to the multilingual plugin's default language.
- Forms v2 have a hidden `gh_locale` with the page's language, because submissions
  arrive over REST, where the plugin can't tell. On submit it sets the contact's
  locale when the site is multilingual and it's one of the site's languages. Filter
  `groundhogg/multilingual/update_locale_from_form` turns that off.
- The preferences page lets the contact pick a language from the site's languages.
- `Contact_Query::filter_locale()` matches any valid locale, and contacts without one
  count as the site's default language. It doesn't use `wp_get_available_translations()`,
  which leaves out `en_US`, only loads in the admin and can make a remote request.
- Agents: `locale` is in `Contact_Schema` (and `update-contact`,
  `bulk-update-contacts`), `Segment_Schema` has `locales`, and `get-setup-status`
  lists the site's languages with how many contacts speak each.
- **Managed pages** (preferences, unsubscribe, browser view, archive) open in the
  contact's language. `Multilingual::switch_for_managed_page()` runs on
  `template_redirect` at priority 8.
  - For `browser_view` and `emails` the language is the version that was sent
    (its `variation_locale`), otherwise the contact's. Filter
    `groundhogg/multilingual/managed_page_locale`, return '' to opt out.
  - `switch_page_to()` does nothing when the site isn't in that language or
    WordPress can't switch to it, and is safe to call twice. The preferences page
    calls it again after a contact saves a new language.
  - It works because `templates/managed-page.php` is the plugin's own standalone
    template: everything on it is the plugin's gettext. No URLs in emails change.
- **The plugin's own translations after a switch.** `groundhogg_reload_plugin_textdomain()`
  in `groundhogg.php` loads them again on `change_locale`, from the language pack in
  `WP_LANG_DIR/plugins`, the plugin's `languages/`, and the folder registered for the
  text domain. See the gotcha about add-ons below.

## Translation strings

`Email_Strings` reads an email's text as strings by key, for translating a
variation:

- A string is the text between block-level tags. Inline tags become numbered
  placeholders, `<1>bold</1>` or `<2/>`, which are put back as the original tags,
  styles and URLs included, so translating can't break formatting. HTML entities
  are decoded, and encoded again when it's written back.
- Keys: `subject`, `preview`. In a block email, the block's id for its first string,
  then `{id}.2`, `{id}.3`..., and `{id}.alt` for alt text. In an HTML email,
  `text.1`, `text.2`... in order.
- Read: text, heading, button, menu and HTML blocks, and image and video alt text.
- Not read:
  - The footer, which is built in the language the email is sent in (below).
  - Global blocks and dynamic blocks (posts, query loops, shortcodes, add-ons'
    registered blocks). `Email_Strings::not_translated()` lists them with a note on
    what to do, filter `groundhogg/email_strings/not_translated`. It's in
    `get-email-strings`, `set-email-strings`, the translate job's result, and the
    editor's data for a language variation, so nobody calls a translation done
    while those are left.
- `set()` is all or nothing: an unknown key or a lost placeholder changes nothing,
  unless `$skip_invalid`, which the AI job uses. A string given its own text is
  confirmed as the same in both languages, like a name.
- **Staleness, per string.** `variation_sources` holds a short hash of the email's
  text each string was translated from. It's written by `set()`, only after the
  write succeeds, and for strings translated by hand when the editor saves the
  variation (`remember_hand_translations()` on `groundhogg/api/email/updated`).
  `compare()` gives each string a status: `untranslated`, `changed`, `translated`
  or `not_in_email`, and `missing` lists text in blocks the variation doesn't have.
- **The AI job** `translate-email` runs on the site's AI key. It sends only the
  strings that need it, up to 12,000 characters a request (the rest on the next
  click), saves what comes back, and leaves any string that lost a placeholder for
  the next try.
- **The footer** is made again when the email is sent in one of the site's languages
  other than its default (`Block_Registry::footer()` on
  `groundhogg/email/block_render`, filter `groundhogg/email/footer/follows_locale`).
  - Only the `<div id="footer">` is swapped, so the block around it stays. It's made
    with `Email_Block_Renderer::inner_html()` in the email's context (so a
    transactional email has no unsubscribe line) and passed through `email_kses()`
    like saved content, so it's what the editor would save. The plain text comes
    from `block_plain_text()`.
  - Otherwise the saved footer is sent byte for byte, so a site in one language
    sees no difference.
- Plain text made in PHP uses `html2markdown()`, which gives back UTF-8 characters
  (accented letters, other scripts, emoji) but keeps `&lt;` and `&gt;`, so text
  can't become a tag. Its 4th argument `false` keeps every entity, for a caller
  that decodes them itself (the docs search).

## A/B tests

- A test version is a variation with `variation_kind = test` and a
  `variation_weight`. New ones split evenly with the email and each other unless
  given a weight. The email keeps the rest, and a draft test version's share.
- Adding a test version restarts the test: `variation_test_started` is set and the
  winner cleared.
- A contact's bucket is `abs( crc32( contact_id . ':' . email_id ) ) % 100` against
  the cumulative weights, so they always land in the same version, with nothing
  stored.
- `report()`: sent, opened, clicked and unsubscribed per version since the test
  started (or for one broadcast), the rates, who's ahead on clicks or opens, a
  two-proportion z-test against the runner-up, and a suggested winner at 95% (filter
  `groundhogg/email/variation/confidence_threshold`).
- `declare_winner()` stores `variation_winner`, and everyone in the test gets it.
  Winner 0 restarts the test.
- **The broadcast test** sends to a sample first, then the winner to the rest:
  - `start_broadcast_test()` takes 5 to 50% of the marketable audience, shuffled,
    and schedules `finish_broadcast_test()` with WP cron
    (`groundhogg/email_variations/finish_broadcast_test`). One at a time per email,
    stored in `variation_broadcast_test`.
  - The sample refuses an audience with a filter that can't be applied, like
    `Broadcast::schedule()`, and is drawn without the owner restriction, like every
    broadcast. If the sample can't be scheduled, the winner and test start it reset
    are put back.
  - The wait (1 to 168 hours) counts from the sample's last send, so batching and
    the contact's local time don't cut it short. The first check is an estimate;
    `finish_broadcast_test()` looks again while the sample is still going out. It
    stops waiting a week past the first estimate (`BROADCAST_TEST_MAX_DELAY`).
  - Then it declares the leader on the sample, sure or not, and broadcasts to the
    audience minus the sample's IDs, with the same batching. In local time the rest
    goes out at the sample's time of day, the next time it comes round.
  - A cancelled sample cancels the rest. A send that fails is recorded as `failed`
    with the error, and only the report shows it.
- Agents: `send-email-broadcast` and `POST gh/v4/broadcasts` take `ab_test`
  `{sample_percent, wait_hours, metric}`, where `{}` means the defaults. The
  scheduler's "A/B test on a sample first?" is under the batching settings, shown
  when the email has ready test versions, and hides recurring and extra dates.

## Reporting

- An email's family is the email and its variations
  (`Email_Variations::get_family_ids()`). The email reports, and the contact segment
  filters that take an `email_id` (received, opened, clicked, unsubscribed, custom
  activity), count the whole family, so the email's numbers are the total.
- The funnel and broadcast performance tables merge variations' rows into the
  email's (`merge_into_parents()`).
- `Link_Clicked::replace_links_in_email_content()` rewrites the link in every email
  of the family.
- Add-ons that match one `email_id` don't see a variation's sends until they use
  `get_family_ids()`.

## Abilities and REST

| Ability | |
|---|---|
| `create-email-variation` | A draft copy of the email with the same block ids. `audience` (a `Segment_Schema` object, `locales` apart), `priority`, `locale`, or `kind: test` with `weight` |
| `update-email-variation` | Audience, priority, locale or weight |
| `delete-email-variation` | |
| `resolve-email-variation` | Which version a contact gets, and why each one was or wasn't chosen |
| `get-email-strings`, `set-email-strings` | The strings, their status on a variation, `missing`, `not_translated`. Setting takes `expected_version` and respects the edit lock |
| `get-email-variation-report` | The A/B results |
| `declare-email-winner` | Ends the test, or restarts it |
| `send-email-broadcast` `ab_test` | The broadcast test |
| `get-email-template` | `variations` on an email; `variation_of` and `variation` on a variation |
| `send-email-template` | Refuses a variation |

Update and delete are their own abilities, not a `variation` field on
`update-email-template`, so an audience never mixes with email fields.

REST:

- `GET gh/v4/emails/{id}/variations` is the editor's data (`editor_data()`). It
  needs `edit_emails`, because it has A/B results and contact counts per language.
- `POST gh/v4/emails/{id}/variations` adds one, from `locale` or `kind: test`.
- `POST gh/v4/emails/{id}/variations/winner` declares or restarts.

## The editor

A "Variations" panel in Email Settings, hidden on templates and global blocks:

- Each variation with its status, audience, strings left to translate, a Translate
  button (when the site's AI can translate), and how many blocks are left to check
  by hand, with their types.
- "Add a language" offers only the site's other languages, with how many contacts
  speak each, and makes a draft copy. "Add a test version" adds one, split evenly.
- An "A/B test" section: each version's share and results, who's ahead and how sure,
  "Pick as winner" and "Start over".
- On a variation it links back to the email. Each version opens in its own editor
  rather than as tabs, which would mean the editor holding several emails at once.

## Decisions

- **Variations are child email rows, not JSON in the email's meta.** Per-version
  attribution comes free from `event.email_id`, and every email ability (outline,
  edit, update, test send, the block renderer) works on a variation's id unchanged.
  The cost is that reports and pickers have to know about families.
- **No native WPML or Polylang translation of emails.** Emails aren't posts, each
  plugin models translation differently, and it would leave TranslatePress, Weglot
  and sites without a plugin out. The plugins only say which language a contact
  speaks.
- **Conditional blocks stay for small differences**, not whole translations: they
  can't vary the subject, preview or sender, and the editor gets worse with each
  language.
- **A form submission overwrites the contact's language** when it's one of the
  site's languages. It's the most recent explicit signal.
- **No A/B test inside a language version.** Audience versions are checked first,
  and everyone else is in the test. Nesting can come later if it's needed.
- **Managed pages switch language when opened**, rather than emails linking to
  localized URLs: no per-plugin URL code, no send-time state, and none of WPML's
  different-domain cookie risk.
- **The footer is rebuilt only for a language other than the default**, so emails on
  a site in one language are sent exactly as saved.
- Defaults taken but not confirmed by Adrian, listed as open in the follow-ups doc:
  A/B tests are in core, and winners are never declared automatically for flows.

## Gotchas

- **Stale objects.** `Base_Object_With_Meta::update_meta()` passes the object's
  cached value as `prev_value`, so writing through a stale object silently does
  nothing. Call `$object->pull()` or use a fresh object at the call site (the
  variation code uses `fresh()`). `update_meta()` itself stays as it is.
- **Add-ons sharing the `groundhogg` text domain.** About 15 add-ons load their
  translations into it from their own folder. WordPress keeps one folder per text
  domain, the last one wins, and after a locale switch it loads from that folder
  only. The reload on `change_locale` loads the plugin's own files too, but only the
  last registered add-on's, so other add-ons' strings stay in the site's language
  after a switch.
- **The footer's saved language.** The saved footer is in the language of whoever
  saved the email. If that isn't the site's default, contacts in the default
  language get it in that language.
- **Polylang overrides `get_locale()`** with a `locale` filter added after the locale
  switcher's, so after `switch_to_locale()` it still returns the URL's language.
  Translations and `<html lang>` use `determine_locale()`, which follows the switch.
  On managed pages a `locale` filter at `PHP_INT_MAX` keeps `get_locale()` in line.
  Compare against `determine_locale()`.
- **Very large broadcast test samples** store their contact IDs in the broadcasts'
  queries.
- **Tests:** in `Table_Query`, `MAX(time)` needs `add_safe_column()` or it becomes
  `MAXtime`. `wp_clear_scheduled_hook( $hook )` without args leaves events scheduled
  with args, use `wp_unschedule_hook()`. Switching to a locale WordPress doesn't
  have installed needs a `WP_Locale_Switcher` made while `get_available_languages`
  is filtered (see the multilingual and strings tests).
