A schema change with no migration and no cleanup ticket

The ask was small. Let a user write two versions of an email inside an outreach sequence, split the recipients between them, and report which version did better. I work on Mixmax, a sales engagement product where a multi-step email sequence is the central object.

Splitting recipients is easy. You need a stable id per version, a counter that rotates through the versions as recipients enroll, and a field on the recipient recording which version it was assigned. That was never the hard part.

The hard part is where a step's content lives. Its subject line and its body sit in flat top-level fields on a MongoDB document, and they have sat there as long as the product has existed. The database calls those documents stages and the interface calls them steps, so both words show up below. A decade of that code reads stage.subject and stage.body directly. Some of it ships inside a browser extension on its own release train, through a store review I do not control. Some of it is external integrators calling a public REST API, whose code I cannot patch at all.

So the question was never how to store two versions. It was what happens to stage.subject once the content moves somewhere else.

Why a migration had nothing to move

My first instinct was the standard one. Add the new array, backfill every existing step into a single-variant array, cut every reader over, delete the flat fields.

I rejected that early, and the reason generalizes. A migration exists to move a population across a boundary, and here there is no population to move. A sequence is created as either a legacy sequence or an A/B test sequence, and it never changes sides. Legacy sequences never gain variants. Backfilling ten years of steps into single-element arrays would churn every document in a large collection to produce data that no code path reads.

Why "temporary" was the wrong word

The second instinct is to dual-write. Keep writing the flat fields alongside the new ones, tag the code with a comment saying this is temporary, put a cleanup ticket in the backlog.

I have written that comment before. The deletion date does not arrive. The deeper problem is what the word "temporary" does to the design. If a field is scaffolding, nobody argues about its edge cases. The window where it goes stale gets a shrug instead of a guard, because it is going away.

The flat fields are doing a different job. They are the compatibility surface that lets this feature ship without a coordinated release across seven repositories and a browser extension, and that job does not end. Calling the copy permanent from day one is what forces you to give it an owner and an invariant that something enforces.

The copy, and the one sentence that defines it

The shape that shipped puts the real content inside the new array, one content object per variant, and keeps the flat fields on the step as a server-written copy of the first active variant.

{
  _id: 'stage_a',
  type: 'message',

  subject: 'Quick question about {{company}}',   // a copy of the first active variant
  body: '<p>Hi {{first name}},</p>',             // same

  abTest: {
    cursor: 7,                                   // rotation position
    variants: [
      { id: '01K1...A', label: 'A', active: true,
        content: { subject: 'Quick question about {{company}}', body: '<p>Hi ...</p>' } },
      { id: '01K1...B', label: 'B', active: true,
        content: { subject: '{{first name}}, worth 15 minutes?', body: '<p>Hi,</p>' } },
    ],
  },
}

The invariant is one sentence, and the second half of it is what makes the whole thing work. The flat fields are always a copy of the first active variant, which is exactly the variant the send path already gives a recipient who has no assignment.

That is checkable against a single line of existing code, since the function that picks a variant at send time falls back to getActiveVariants(abTest)[0] when the recipient has no variant. The definition is forced rather than chosen. The flat fields show what a reader that knows nothing about variants would have been shown anyway. Copy anything else and the extension, the CSV export and the send-time fallback start describing the same step differently.

Two properties fall out of that definition for free.

Picking a winner works in any click order. Deactivate the losing variants one at a time and the copy provably lands on the winner, because once a single variant is active, "first active" and "only active" are the same thing. A separate guard refuses the deactivation or deletion that would leave zero active variants, so the definition can never become undefined.

The copy can never go stale. Exactly one function writes the variants array, and it writes the flat fields in the same $set. Every variant mutation funnels through it, so add, edit, activate, deactivate and delete are covered by construction rather than by five people remembering.

async function persistVariants(stage, variants) {
  const activeVariants = variants.filter(isActive);
  const flatFields = buildFlatFields(stage, activeVariants[0].content);
  await stages.update(
    { _id: stage._id },
    { $set: { 'abTest.variants': variants, ...flatFields, updatedAt: new Date() } }
  );
}

The easy part to miss is recomputing on activate, deactivate and delete, not only on a content edit. Deactivating the first variant changes no content anywhere, and it still moves which variant the flat fields have to reflect.

Refusing the write that would undo it

One writer is only half the guarantee. Clients still receive the flat fields in every response, so they still send them back. Our own editor PUTs the entire step document on save with a force flag set. An assistant integration rebuilds the entire step from current server state before writing it back. Either one, landing late, silently overwrites the copy of a running test.

So any ordinary step update whose content differs from the stored copy is refused.

Refusing on difference rather than on presence is deliberate. Both of those clients read a whole step and write it back while editing only the delay. Since the server maintains the flat fields, a client that echoes them back unchanged sends exactly the stored bytes, and any difference means something tried to write content.

Content is normalized on both sides before the comparison, through the same sanitizers the read API runs. The read path serves <p><br></p> for a body stored as <p><br/></p>. Without normalization, a client that reads a step and writes it back untouched gets refused over an HTML representation change it never made. I found that on staging.

The refusal is a 403, not a 409. The assistant integration already treats a 409 on that route as the active-recipients conflict, a different condition, and would answer it by retrying with force: true. That would be false twice over.

The guard is not gated on the feature flag. A step that has variants has them regardless of who is asking, and a flag flipped off mid-test would otherwise open the write the guard exists to refuse. It exits immediately for any step with no variants, which is why it never touches older data.

None of this was original thinking. A comment already in the repo had worked out the same hazard in the opposite direction years earlier. It keeps certain fields out of the generic step-update allowlist because the editor echoes the whole document back on save.

Then I went looking for the sixteen readers

Somewhere early I wrote that sixteen legacy readers across seven repositories read the flat fields and keep working, blind to the test. It went into the design note, the explainer and every pull request body. Nobody challenged it. I had never enumerated it.

So before merging I ran an adversarial sweep against my own sentence. It ran twenty-nine agents, all read-only, each pinned to its repository's master branch rather than my local checkout. Nine of them were surface investigators, one per suspect area. Nine more were verifiers whose only job was to refute the investigators, file by file. Three were hunters that searched by mechanism instead of by suspect list: every repository that names the step collection, every field-access pattern, and the contract-level promises like the OpenAPI document and the generated client. One priced what each removal design would actually delete, and one looked for whole surfaces nobody had been assigned.

The sweep confirmed about 60 entries, corrected 6, refuted none, and found 5 readers everyone had missed. It also moved the answer.

The readers I had been quietly scared of, the ones that put content in front of a recipient, did not need the copy any more. During implementation I had routed every send path through the single variant resolver. The sentence "remove the copy and blank emails go out" was false on the branch as written.

What actually forces the flat fields to exist is a quieter population. Eleven sites across seven repositories query the step collection directly with find, aggregate or a $lookup. They include the live-updating query behind the extension sidebar, the reporting service's per-step rows, the upcoming-sends list whose free-text search regex-matches the stored subject, the recipients CSV export, and a CRM scanner that aggregates subject and body to work out which merge tokens a sequence uses. Merge tokens are the {{company}}-style placeholders filled in per recipient. No serializer I control ever runs for any of them. The only reason they see correct content is that it is physically in the document.

The failure modes there are the quiet kind. Nothing crashes. A preview renders blank, a column in an export comes out empty, rows stop matching a search. Almost every one of those reads is guarded with || '', which is why a miss would ship without a single error.

The halfway design loses to both ends

The obvious compromise is to stop storing the flat fields and compute them at response time instead.

It deletes approximately zero server code. Clients still receive flat fields, so they still echo them back, so the difference-based guard stays, its normalization stays, and the client-side stripping stays. The only thing that moves is where the computation runs. And it still breaks all eleven direct-database readers, because they never see a response at all.

Full removal is the honest end state, and I priced that too. That is roughly 25 to 30 sites across 9 repositories, to save about 330 lines of code that is already written, already reviewed and already verified on staging in both directions. One row of that estimate is unbounded, since external integrators code against the shape they observe rather than the shape the OpenAPI document promises, and I cannot patch their code.

What the sweep found while it was not answering the question

Two findings had nothing to do with whether to keep the copy, and were worth the whole exercise on their own.

The first was a silently dropped write on my own branch. Renaming a manual task step writes to the flat subject field, because that is where a task's title has always lived. The client strips variant-owned fields out of step updates, and subject is on that list. The new name left the text box, vanished from the request body, and nothing else persisted it. No error, no warning, the name reverted on refresh.

The second is that merge-token validation only ever reads the first variant. The pre-activation check that tells a user "this recipient is missing {{company}}" extracts tokens from the flat fields, through three separate code paths, one of which a verifier caught after an investigator had wrongly cleared it. A token used only in the second variant validates as fine and then reaches the recipient stripped out. Broken with the copy, and broken without it.

Which is the honest limit of the whole design. A server-maintained copy keeps old readers correct only for a recipient who has no variant assignment. It buys compatibility at the display layer and nothing above it. Everything that has to be right per recipient still has to learn about variants, and the copy makes that easier to forget, because the screen looks right while the answer is wrong.