ADR-063: Migration Gate + Verify-Only Boot — One Schema State Machine for Both Modes

Status

Accepted (2026-08-02), implemented in full by epic &78 (2026-08-03; MRs !1162–!1167 and !1169, plus the M5 close-out MR — M0 docs → M1 state machine → M2 migrate mode → MF registry → M3a gate-first → M3b verify-only flip → M4 test-plane pre-warm; !1168 was the interleaved #1311 AdvisoryLease fix the M4 battery surfaced, not an epic unit). Drafted FIRST (the draft-first path). As-built deltas from this document, recorded in the archived plan’s per-unit notes (the D3 scope decision in this document’s own D3 as-built note): the D1 Diverged rule was WIDENED at M0 J-review to catch doubly-incomparable sets (making Behind ⇒ applied ⊊ embedded hold by construction — the D2 apply-safety parenthetical was corrected accordingly); the D3 lint’s "destructive" scope excluded widening drops (DROP NOT NULL/IDENTITY/EXPRESSION/ CONSTRAINT/DEFAULT — see the D3 as-built note); #1765 adds the write class, #2369 the renames and retypes, and the #2571 amendment (maintainer ruling, 2026-10-21) the binding class, which moves unique-key and unplaceable DROP CONSTRAINT / DROP INDEX, a CHECK replaced under a new name, DROP NOT NULL / IDENTITY / EXPRESSION and a cross-file DROP DEFAULT off the widening list (D3 as-built notes); #2573 makes the write class read a DO or routine body too; the #2572 amendment (maintainer ruling, 2026-10-23) refuses -- floor-exempt on every floor break on a runtime-read-only table (D4); the #2606 note adds the extension, schema, domain and partition shapes, and the #2627 note DROP OWNED, foreign tables, row-level security, a narrowed domain CHECK and the two-step extension-function drop; the gate core reuses a 1-connection DbPool rather than a raw PgConnection (intent kept: no metrics, no probe); the mains' mode dispatch + the verify-only composition each live in ONE craig-api fn (run_process_modes_if_requested, bootstrap_verified) instead of 8 copies. Plan: Migration Gate + Verify-Only Boot (archived). Amended in part by § Amendment — #1399 (Proposed 2026-09-20; Accepted 2026-09-21 with the close-out of plan Field-Scheme Rewrite (#1399), epic &98): a second process-mode class — the key-bearing, offline, fenced craig-cases rewrite-scheme — beside D4’s migrate, typed ProcessHooks<E> with pre_apply before apply_by_verdict and an Option<ToolMode<E>> dispatched first, D3 unchanged (additive migration, no floor bump).

Context

Every stateful service applies its embedded migrations inline at boot (craig_db::run_migrations, called from each service’s boot orchestrator immediately after craig_api::bootstrap() returns — 8 call sites), before the only TcpListener::bind. Three verified defects:

  1. Rollback is bricked. sqlx’s Migrator::run hard-errors with VersionMissing when the database contains versions the binary does not embed — an old binary against a newer database refuses to start. The error is one-directional by design: sqlx tolerates nothing it does not know.

  2. Boot convoy. Migrations run behind sqlx’s session advisory lock before any health surface exists; N replicas convoy, orchestrator probes kill the waiters, and the fleet kill-loops precisely when a slow migration most needs to finish.

  3. Test plane. The same coupling drives #1275: lazy template-DB migration under 8-way nextest contention — waiters die at the 120 s kill.

A naive gate (run Migrator::run in a one-shot before starting the app) fails review: a rolled-back (older) gate image would itself VersionMissing against the newer database — the gate re-bricks the rollback it exists to restore. The gate must inspect first and know when doing nothing is the correct action.

Decision

D1. One schema state machine, owned by craig-db, consumed by both modes

A pure classifier classify(applied, embedded) → SchemaState over the applied records (version, checksum, success) (plain SELECT from _sqlx_migrations; only SQLSTATE 42P01 maps to "Behind from zero", every other error stays a DB error) and the embedded set filtered to up-migrations only (matching sqlx’s apply semantics, which skip down-files). With extras = applied ∖ embedded and missing = embedded ∖ applied, the relation is total with deterministic precedence, first match wins (the embedded set is nonempty by construction — all 8 services embed migrations — so max(embedded) is always defined):

Dirty { version } (any success = false) → ChecksumMismatch { version } → Diverged { unknown } (extras ≠ ∅ AND (missing ≠ ∅ OR any extra ≤ max(embedded))) → Behind { missing } (missing ≠ ∅ — reachable only when applied ⊊ embedded) → Ahead { extra } (extras ≠ ∅ — reachable only when embedded ⊊ applied and ALL extras strictly newer than max(embedded)) → Exact.

Diverged is deliberately wide. An arbitrary applied superset is NOT Ahead: embedded {1,3} vs applied {1,2} is Diverged (an unknown version inside the embedded range — the histories forked), and the mirror embedded {1,2} vs applied {1,3} is likewise Diverged (doubly-incomparable). The mirror case is why Diverged must catch missing ≠ ∅ ∧ extras ≠ ∅: a naive "missing → Behind" rule would send it to the gate’s apply, and sqlx validates EVERY applied migration against the embedded set before applying (list_applied_migrations → validate_applied_migrations, sqlx-core 0.8.6 migrator.rs:160-161) — the apply would VersionMissing. Under this precedence, Behind implies applied ⊊ embedded, so the gate’s apply is VersionMissing-free by construction.

D2. The two consumers

State Gate (migrate mode) Serving boot (verify)

Exact

no-op, exit 0

boot

Ahead

no-op, exit 0 — this is what restores rollback

boot + warn!, IF the D3 floor passes

Behind

apply (safe by construction: Behind ⇒ applied ⊊ embedded ⇒ sqlx cannot VersionMissing)

refuse

Diverged / Dirty / ChecksumMismatch

refuse, exit ≠ 0

refuse

Serving binaries, once M3b lands, never apply DDL. Refusals are typed (SchemaVerifyError / MigrateModeError, thiserror), deployment-neutral base message plus an optional caller-supplied gate_hint; the typed message IS the operator surface — refusal precedes bind, so no health endpoint exists to differentiate on.

D3. Compatibility floor — direction does not establish compatibility

Ahead-tolerance alone would boot an M-era binary against a schema whose contract migrations dropped structures it uses (the repo already contains an authorized drop; CONTRIBUTING permits removal after deprecation). A schema_compat_floor table (single row, min_required_version BIGINT, seeded 0) lands in every service schema. Destructive contract migrations MUST bump the floor to their own version in the same migration file (lint-enforced by validate-migration-constraints); verify-Ahead refuses when floor > max(embedded). Rollback support is thereby explicit and machine-checked: to the newest release whose embedded max ≥ the floor.

As-built scope (M2/#1307): "destructive" = removes a structure an old binary may READ — DROP TABLE, DROP COLUMN, the ALTER TABLE … DROP <col> shorthand (incl. multi-line). WIDENING drops (DROP CONSTRAINT / DROP DEFAULT / DROP NOT NULL / DROP IDENTITY / DROP EXPRESSION; standalone DROP INDEX) are deliberately out of scope — they widen what the schema accepts and flagging them would push authors toward a wrong floor bump, the exact harm this decision prevents. The #2571 amendment narrows this list: only a plain-index drop and a bare CHECK drop stay out. Waiver: -- floor-exempt: <reason>, only when no released binary reads the dropped structure.

As-built (#1765): the rule has a WRITE half — a statement that refuses a row an N−1 binary still writes is floor-required too, on a table the file did not create: an ADD [COLUMN] … NOT NULL with no surviving DEFAULT (none written, or the backfill idiom — ADD … NOT NULL DEFAULT x then a same-file ALTER COLUMN … DROP DEFAULT; a GENERATED, PRIMARY KEY or SERIAL column fills itself), an N−1 INSERT that cannot name the column failing 23502; and an ADD … CONSTRAINT <name> CHECK (…) (or a column’s unnamed inline CHECK, under Postgres’s default <table>_<column>_check) that drops a quoted literal the latest earlier definition of that (table, constraint) admitted, an N−1 write of the removed token failing 23514. The same bump, the same -- floor-exempt waiver and the same baseline apply. The history is read per (table, constraint) across the service’s migrations, oldest first (sorted by version, pre-baseline files included; DROP CONSTRAINT keeps the entry). The write class lexes statements: -- and (nested) /* … / comments, '…' literals and $tag$ bodies neither split a statement nor fake one (E'…\'…' escapes are not lexed; no migration uses them; #2369 added the / … */ comments). Since #2573 the write class also reads a DO body and a CREATE FUNCTION|PROCEDURE dollar body, each statement from its first depth-0 ALTER or DROP word, through the walk the read class reads (read_floor::for_each_run_origin, which also tells a body statement from a top-level one). A body statement may add a finding, never take one away: a body CREATE is not read, so it owns nothing (its guard may never fire), and a body CHECK joins the literals of its (table, constraint) history entry instead of replacing them, so a later file’s narrowing is read against both. A dollar-quoted string inside a body (EXECUTE $q$…$q$, RAISE … $m$…$m$) is read as code, which fails closed; '…' text and format('…') arguments are not. Limits, by decision: ALTER COLUMN … SET NOT NULL and a new CHECK on an existing table are not read (whether they break anything depends on what the N−1 binary writes — the inbox_payload_hash_not_null migrations record "the N−1 boundary binary already writes the column"), nor are a CHECK under a new name (unless it replaces one the same file drops — the binding class), a narrowing that removes no literal, or a DROP DEFAULT on a column an earlier file added (the binding class’s since #2571). The widening list above is read-side only: a DROP DEFAULT narrows a write when the same file added the column NOT NULL. #648’s two migrations (20260912120000_disposition_recut, 20260913120000_report_source) bumped before the lint asked; every such statement on main bumps its own version.

As-built (#2369): the read class also covers a rename (any RENAME action on a table, view, materialized view, index, sequence or type — column, relation, constraint, enum value, attribute), a SET SCHEMA, every column retype (ALTER [COLUMN] … [SET DATA] TYPE, and an ALTER TYPE’s `ALTER ATTRIBUTE … TYPE; sqlx refuses an incompatible decode, so no type change is presumed safe), the non-table drops DROP VIEW / MATERIALIZED VIEW / SEQUENCE / TYPE and ALTER TYPE … DROP ATTRIBUTE, and a column drop sharing a line with a widening drop (… DROP CONSTRAINT c, DROP col). Constraint and index names count because N−1 binaries name them (.constraint() refusal mappings, ON CONFLICT ON CONSTRAINT arbiters); functions do not (every migration-created function is a trigger function no binary calls). Drops are read per statement too, with the write class’s lexer (the validate_migration_constraints::read_floor module), and the line scan is retired with the finding lines on main unchanged: whitespace, a -- or /* … */ comment or a literal ; no longer hides a drop. Of the widening list above only DROP CONSTRAINT is a direct ALTER TABLE action — the others sit under ALTER [COLUMN] — so a direct DROP identity drops a column named identity and counts. A DO body and a CREATE FUNCTION|PROCEDURE dollar body are read (a migration may invoke a routine it creates; the retired line scan read them too; the walk the write class shares since #2573); a single-quoted body and EXECUTE '…' text are literals and are not read, while a dollar-quoted EXECUTE $q$…$q$ inside a body is read (the #1765 note). A REVOKE of a privilege an N−1 binary uses (42501) is not read; such a revoke is reasoned by hand (e.g. 20261012150000_crypto_key_lineage_runtime_dml). Waiver: as before, plus a retype every released binary still decodes (e.g. VARCHAR(n) → TEXT). The two post-baseline renames (20260902210000_ive_determination_children, 20260922130000_persons_identity_recut) bumped before the lint asked.

Amended (#2571, maintainer ruling 2026-10-21): "widening" above meant "accepts more rows". An N−1 binary also binds unique keys as ON CONFLICT arbiters, constraint names in its typed refusals (.constraint() mappings), and a column’s NOT NULL, identity or generation in its decodes and INSERTs, so these statements are floor-required too — the BINDING class (the validate_migration_constraints::bind_floor module) — on a table the file did not create:

  • DROP CONSTRAINT x, unless an earlier migration’s latest definition of x on that table is a CHECK. A UNIQUE, PRIMARY KEY or EXCLUDE key fails every N−1 ON CONFLICT it arbitrates (42P10; 42704 for ON CONFLICT ON CONSTRAINT); PostgreSQL 18’s <table>_<column>_not_null is a DROP NOT NULL; any other name the history cannot place, a foreign key included, fails closed.

  • DROP CONSTRAINT x of a known CHECK the same file does not re-create under its own name but replaces: it adds on that table another constraint (named, unnamed, inline in ADD COLUMN, or a CREATE UNIQUE INDEX) under a name it does not drop. An N−1 refusal mapped on x becomes a 500 — the drop-and-add spelling of the RENAME CONSTRAINT the #2369 note counts.

  • DROP INDEX x, unless an earlier migration created x as a plain index.

  • ALTER [COLUMN] c DROP NOT NULL (N writes a NULL an N−1 decode into a non-Option field refuses), DROP IDENTITY, DROP EXPRESSION and, on a column the file did not add, DROP DEFAULT (a fill an N−1 INSERT relies on stops; a nextval default is the SERIAL twin of an identity).

On any routine, a CREATE [OR REPLACE] FUNCTION|PROCEDURE that re-raises a refusal under a new CONSTRAINT name or ERRCODE in place of an old one is floor-required too: sqlx’s .constraint() and .code() read a raised refusal like a catalog one, so an N−1 mapping on the old one becomes a 500.

A constraint, index or column the file itself defined first is no N−1 binary’s. The same bump and baseline apply; the waiver also covers a structure no released binary binds (e.g. -- floor-exempt: <x> is a foreign key; no N-1 ON CONFLICT or decode binds it). Still widening: a plain-index drop and a bare CHECK drop with nothing added on the table. Limits, by decision:

  • a replacement split across files (the second file adds a new constraint on an existing table, the #1765 limit);

  • a renamed constraint or index (the history does not follow it, so its later drop fails closed);

  • DDL inside a DO or routine body;

  • a trigger function that stops filling a column;

  • a refusal moved between a catalog constraint and a trigger’s RAISE … USING CONSTRAINT in either direction and a trigger re-pointed at another function;

  • a re-created routine whose RAISE loses a CONSTRAINT name or ERRCODE without gaining one (read as a removed refusal, like a bare CHECK drop);

  • a CHECK widened or bare-dropped, though N may then write a token an N−1 closed-enum decode refuses — the expand step of every vocabulary change; the ruling names NOT NULL, IDENTITY and EXPRESSION, not CHECK widening.

Applied post-baseline migrations that predate the amendment can take neither a bump nor a waiver (sqlx checksums them). The lint names them in bind_floor::HISTORIC_BINDING_BREAKS and keeps their findings out of the gate (MigrationReport::floor_historic, pinned exactly by a unit test): craig-financial 20260807150000_drop_legacy_subsidy_month_index (a unique index; it bumps to M1’s version by intent, not its own), craig-financial 20260828130500_money_sign_twin_upgrades (two CHECKs replaced, unbumped), craig-rules 20260804230000_evaluation_failure_audit (DROP NOT NULL, unbumped) and craig-financial 20260901120100_ive_child_verdicts (two cross-file `DROP DEFAULT`s, unbumped; its own comment records the rolled-back-binary NOT NULL failure). Consequence, accepted by the ruling: more migrations stop an N−1 replica serving beside them during a rolling deploy.

Amended (#2606): the read class also covers DROP EXTENSION (an N−1 query calling its operators or functions fails 42883: pg_trgm’s `% and similarity() in craig-cases store/report_persons.rs; a CASCADE also takes the gin_trgm_ops indexes of craig-cases, craig-financial and craig-security), DROP SCHEMA and DROP DOMAIN, a rename or SET SCHEMA of a domain, schema or extension (the #2369 rule), and ALTER TABLE … NO INHERIT / DETACH PARTITION (the rows silently leave what an N−1 read of the parent returns). The binding class also covers, on a domain the file did not create, ALTER DOMAIN … DROP NOT NULL, DROP DEFAULT, and a DROP CONSTRAINT the history cannot place as a CHECK or that the file replaces under a new name. A domain shares the type namespace with a table’s row type, so the history keys its constraints alike. Still widening: a bare drop of a known domain CHECK, ALTER EXTENSION … DROP <member> (the member stays), ATTACH PARTITION, INHERIT, CREATE EXTENSION IF NOT EXISTS and ALTER DOMAIN … ADD CONSTRAINT. Limits, by decision:

  • ALTER EXTENSION … UPDATE (what an update script removes is not lexical);

  • an unnamed domain CHECK (not recorded, so its drop fails closed);

  • a routine body nested in another routine body (read as its CREATE statement only);

  • DROP OPERATOR, CAST, COLLATION and TEXT SEARCH CONFIGURATION (none in the tree).

Amended (#2627): five shapes the #2606 note listed as limits are read. None changes the rule: each is a structure or a row taken out of an N−1 binary’s reach, classified by the rationale above. No migration in the tree uses any of them.

  • A foreign table is a table to the read class: its drop, rename, SET SCHEMA, column drop and retype bump.

  • The write class reads ALTER DOMAIN: a domain CHECK re-created under its own name without a quoted literal its earlier definition admitted bumps (an N−1 write of the token fails 23514 on every column of the domain).

  • A new REACH class (validate_migration_constraints::reach_floor):

    • DROP OWNED BY bumps, and takes no waiver in a service with runtime-read-only tables (D4): what the role owns is not in the statement, so it fails closed, as DROP SCHEMA does.

    • Row-level security that can hide rows from an N−1 read or refuse its writes bumps, on a table the file did not create: ENABLE or FORCE ROW LEVEL SECURITY, CREATE POLICY … AS RESTRICTIVE, any ALTER POLICY but a rename, and DROP POLICY. A policy statement on a runtime-read-only table takes no waiver.

    • DROP FUNCTION | PROCEDURE | ROUTINE | AGGREGATE of a routine an earlier ALTER EXTENSION … DROP detached bumps (42883), in the same file or a later one. The detach alone stays widening.

Still widening: DISABLE and NO FORCE ROW LEVEL SECURITY, and a permissive CREATE POLICY. Limits, by decision: a CREATE POLICY inside a DO or routine body (the walk visits a body’s ALTER and DROP statements only); an ALTER POLICY is not read for whether it narrows, and a DROP POLICY not for whether the policy was permissive (both fail closed); a detached operator is not followed; a domain CHECK that narrows without removing a quoted literal (the #1765 limit, unchanged).

D4. Same image, process-mode separation — <binary> migrate

The gate is the service binary itself invoked as <binary> migrate (exact argv shape, no extras; --print-openapi precedence defined; non-Unicode argv is a typed error): zero image drift between the embedded set the gate applies and the set the app verifies — one build, one truth. The mode runs logging-only telemetry, requires exactly one env var (CRAIG_<SVC>__DATABASE_URL), and uses a minimal single connection rather than the serving pool helper (pool metrics + background probes are wrong for a one-shot).

Honesty note (superseded by #1310, 2026-08-04): same image + same DB credentials was process-mode separation, NOT a privilege boundary — a compromised serving process could still issue DDL. #1310 shipped the real boundary as the flip this note predicted (provisioning, not code): per stateful service, a migration-owner role (craig_<svc>_owner on devstack — LOGIN, owns the database, so migrations incl. the trusted pg_trgm extension apply without superuser; used ONLY by the gate) and a runtime role (craig_<svc>_app — CONNECT + schema USAGE + table DML via the owner’s ALTER DEFAULT PRIVILEGES; the serving boot’s verify reads ride the same grants). DDL under the runtime role refuses with SQLSTATE 42501 (negative-pinned); the app-role verify is regression-pinned on both the Exact and Ahead+floor paths (craig-db role_split), and the devstack gate/serving DSN split is drift-pinned structurally (xtask registry). Residual CLOSED (#1550, 2026-08-23): default privileges cannot exclude the two schema meta-tables, so the runtime role initially holds DML (not just SELECT) on sqlx_migrations + schema_compat_floor — a spoof/denial surface on what verify READS. The gate now hardens this AUTOMATICALLY on every SUCCESSFUL verdict (apply and no-op alike; a refused verdict skips straight to close): DbPool::harden_meta_tables revokes INSERT, UPDATE, DELETE on both tables from every non-owner grantee — PUBLIC included — read from the table ACL itself (aclexplode(pg_class.relacl), complete regardless of session visibility: a superuser-issued grant to a third role is caught too; the information_schema view would have session-filtered it). Convention-free — the runtime role’s NAME is a provisioning choice; a pre-#1310 shared-credential deployment yields no non-owner grantees and the pass is a no-op. SELECT is untouched (verify’s reads), the pass is idempotent, and a failure fails the gate like a schema refusal (and skips the #1395 post-apply hook — hardening precedes it). Pinned in craig-db role_split: post-hardening runtime DML on both tables refuses 42501 (app role, superuser-granted third role, and PUBLIC all revoked) while verify and domain DML keep working. cargo xtask migrate rollback restores as the OWNER role so restored objects keep both the app grants and future gate alterability — the next gate run re-hardens the restored ledger. As-built (#2337): the same pass covers each service’s attestation tables — the tables its serving role reads but must never write — named by the service through ProcessHooks::with_runtime_read_only (craig-cases crypto_field_lineage, crypto_field_rewrites, crypto_key_lineage; craig-placement placement_end_reason_rewrites) and revoked by DbPool::harden_runtime_read_only through the same ACL walk, which now also reads the column ACLs (pg_attribute.attacl) and covers TRUNCATE for both passes. The attestation migrations' own REVOKE names the devstack role, so under any other name it protected nothing, and the deployment guide’s cutover GRANT … ON ALL TABLES re-granted the DML even under the devstack name; the pass closes both on the next successful verdict. A listed table that does not exist fails the gate (42P01), never a skip. Rule: dropping or renaming a listed table must bump schema_compat_floor, never take floor-exempt (the N−1 gate reads the list), so no supported rollback meets a list naming a table that no longer exists. What no REVOKE reaches (a superuser, owner or owner-member runtime role, a pg_write_all_data member, the pre-#1310 shared credential) is stated in the deployment guide; the boot-time detection of it is #2338. Pinned by the craig-cases and craig-placement runtime_read_only legs (a runtime role named cases_app* / placement_app_*, and the cutover sequence) and craig-db role_split. Amended (#2572, maintainer ruling 2026-10-23): every floor break whose statement acts on a listed table refuses -- floor-exempt, not only a drop or a rename. The N−1 gate hardens each listed table by name (42P01 on a missing one), and craig-cases' N−1 gate hooks read two of its three (pre_apply reads crypto_field_rewrites, post_apply reconciles crypto_field_lineage), so a waived change to one can fail the N−1 gate itself. craig-placement’s placement_end_reason_rewrites has no runtime reader, so a change to it must bump even when it breaks no binary: the cost the ruling accepts, with 0 such migrations today. validate-migration-constraints enforces the rule (the validate_migration_constraints::read_only module). It reads each service’s list from its with_runtime_read_only registration in services/<svc>/src; the argument must be an array literal or the one same-file top-level const of that name, and any other argument, a second const of the name, or a file that names the method outside a .with_runtime_read_only(…) call (a UFCS call) fails the lint. A break is pinned when its statement (a DO or routine body’s included) is a DROP naming a listed table or an ALTER on one, of any kind the D3 read class names (ALTER INDEX … RENAME renames a table too), or, since #2606, any DROP SCHEMA or ALTER SCHEMA (the lint does not place a table in a schema); its finding says "must bump (ADR-063 D4)" whatever the waiver says. Not pinned: a DROP INDEX of an index on a listed table (the history does not map an index to its table).

D5. Orchestration shape

Compose (the reference orchestration): one gate service per stateful service, YAML anchors sharing image: + build: with the app (an image-only gate could run a stale :local image and exit 0 silently); restart: "no"; app services gain service_completed_successfully edges. A structural invariant test pins the graph. Kubernetes (documented, not shipped): a parallelism-1 Job or deploy hook. A per-pod init container is NOT equivalent — per-pod means N concurrent appliers, which recreates the convoy this ADR removes. Partial-application contract: gates report per-service and exit non-zero if any failed; additive migrations make retry safe.

D6. Staged transition (external deployments cannot brick)

M3a lands the gates while boot keeps applying (verdict-driven apply_by_verdict — this alone un-bricks rollback fleet-wide via Ahead-tolerance). M3b flips boot to verify-only after the gates are proven in-graph, with the pre-1.0 breaking CHANGELOG entry. The release-gating evidence: a rollback-boundary test that runs the OLD (N−1) gate and OLD verify against the NEWER database via runtime migrators over a truncated migration-dir copy; an upgrade-in-place test (existing volume through the gates, no reseed); a Postgres-only proof ×8 (migrate mode with all non-DB settings absent); an automated poisoned-gate test.

D7. Enforcement

run_migrations becomes callable only from craig-db internals + the migrate-mode helper (validate lint) — no serving path applies DDL after M3b. The destructive-migration floor lint (D3) and the structural compose invariant (D5) are validate-time gates. The xtask service inventory collapses to ONE typed registry (the cmd/migrate.rs duplicate silently omitted craig_composition — fixed as its own issue, #1308).

Alternatives considered

Alternative Verdict Why

Boot-apply status quo (Migrator::run in serving boot)

Rejected

Rollback bricked by VersionMissing; replica convoy on the advisory lock before any health surface; the same coupling storms the test plane (#1275).

Per-pod init container

Rejected

Per-pod = N concurrent appliers; recreates the convoy. Init containers are a pod-level construct and cannot be a singleton.

Leader-elected in-band migration (one replica applies, the rest wait)

Rejected

Distributed coordination inside serving boot; still couples DDL to serving startup; failure modes opaque to operators (which replica is the leader mid-kill-loop?).

Separate migrator binary / image

Rejected

Two artifacts whose embedded sets can drift; the checksum contract then fails between the migrator’s set and the app’s; doubles the release surface for zero isolation gain (same credentials either way).

Same-image process-mode separation (<binary> migrate gate + verify-only boot)

Chosen

One embedded set (zero drift); orchestration-neutral (compose one-shot / k8s Job / deploy hook); the shared state machine makes the gate itself rollback-safe (Ahead → no-op).

Consequences

Positive:

  • Rollback works, with an explicit machine-checked bound (the D3 floor).

  • Serving startup does DDL never (post-M3b) — no convoy, no kill-loop, honest probes.

  • Deterministic, typed refusals for every schema mismatch class, same vocabulary in gate and boot.

  • The test plane inherits the fix (#1275 pre-warm rides the same program).

Negative / accepted:

  • Operators MUST run the gate before the new serving image (pre-1.0 breaking; the compose graph carries it automatically, k8s deployments add a Job/hook).

  • Destructive migrations carry a floor-bump discipline (lint-backed, but a new rule to know).

  • ~~The gate is not a privilege boundary~~ — #1310 (2026-08-04) shipped the owner/runtime role split behind it (D4 honesty note carries the as-built + the recorded meta-table residual). Devstack requires a reseed on upgrade across #1310 (roles are provisioned by init.sql, which runs only on a fresh data dir).

  • One more compose service per stateful service (×8) — mitigated by YAML anchors; the one-shots are restart: "no" and exit immediately on Exact/Ahead.

Amendment — #1399 — A second process-mode class: the key-bearing, offline field-scheme rewrite (Accepted, 2026-09-21)

Standing. Proposed 2026-09-20 with the approved plan field-scheme-rewrite (#1399, epic &98). Accepted 2026-09-21 at that plan’s close-out U3 (#1959; U1 #1956 !1678 the fence + typed hooks, U2b #1958 !1680 the mode, U3 !1681 the rehearsal); the plan is archived as Field-Scheme Rewrite (#1399). The paragraphs below are the decision as ratified; the as-built note at the end records the shipped shapes.

The class. D4 established ONE non-serving process mode, <binary> migrate: argv-exact, one env var, key-less, an owner pool of one connection, designed to run WHILE old replicas serve. #1399 added a SECOND class with different guarantees, dispatched from the same ordering seam (run_process_modes_with_hooks<E>, order rewrite-scheme → migrate → --print-openapi): <binary> rewrite-scheme [--dry-run | --abort] — argv exactly the verb plus at most one of the two flags (anything else refuses before the env is read); env = the gate’s recorded variables PLUS the field key (CRAIG_FIELD_ENCRYPTION_KEY, loaded exactly as serving does — the mode runs in the serving image with the serving secret mount and the gate’s owner DSN, never on an operator host); NOT a deploy phase — it runs OFFLINE, fenced (ADR-049 § Amendment — #1399: it cannot start while any participant connection exists, and no participant can connect while it runs); it requires the schema verdict Exact before any ledger or data mutation (so it can never run ahead of the gate); it is resumable through its own durable ledger and aborts only while nothing was mutated. The hooks a service hands the seam are typed over the service’s own error (ProcessHooks<E> { pre_apply, post_apply, tool: Option<ToolMode<E>> } — ProcessHooks::new(pre_apply, post_apply) / none() carry no tool, .with_tool(ToolMode::new(verb, run)) attaches one, and craig-cases is the only attacher; no Box<dyn Error>), and pre_apply runs BEFORE apply_by_verdict: a gate that starts over a live rewrite ledger row refuses before any DDL, and the gate’s own pool connection carries the participant lock, so a RUNNING rewrite refuses it at connect.

What does not change. D3 (the compatibility floor) — the crypto_field_rewrites migration is additive, no floor bump; D6 / D7 (staged transition, enforcement). One honest gap is recorded, not papered: an N−1 image built before the fence landed is not guarded — the deployment guide’s rule is "roll the fence on every replica first; never roll below it while a ledger row is live", pinned by a grep test.

Devstack. The compose graph carries a craig-cases-rewrite profile service (profiles: [rewrite] — never started by dev start) that the clone-rehearsal wrapper cargo xtask rewrite-scheme runs against a TEMPLATE craig_cases clone in both directions and drops; the seeded volume is never rewritten (the seed identity would strand the next dev start). The typed service registry carries a slot for one-shot tool services (OneShotTool / ONE_SHOT_TOOLS) so the structural compose pin covers it.

As-built (2026-09-21, U1 #1956 / U2b #1958 / U3 #1959).

  • argv / env / dispatch. run_process_modes_with_hooks<E>(service, migrator, openapi, hooks) takes the tool FIRST when hooks.tool is Some: tool_mode_requested(args, verb) is a pure argv check — [verb] / [verb, "--dry-run"] / [verb, "--abort"]; anything else ToolModeError::UnexpectedArguments { verb, extra } BEFORE any environment is read, the verb beside migrate / --print-openapi ConflictingModes { verb }, non-Unicode argv NonUnicodeArgv (all ProcessModeError::ToolArgs); then init_gate_logging (logging-only telemetry, as the gate), CRAIG_<SVC>DATABASE_URL (ProcessModeError::ToolMissingDatabaseUrl { verb, env_var }), then (tool.run)(ToolInvocation { database_url, flag: Option<ToolFlag> }); a refusal is ProcessModeError::Tool { verb, source }, printing the service’s typed error verbatim ("rewrite-scheme refused: …"). Order rewrite-scheme → migrate → --print-openapi, as written. The cases shell (scheme_rewrite::mode, VERB = "rewrite-scheme") reads, before any connection and in this order, CRAIG_CASESJURISDICTION (required), CRAIGACTIVE_STATE_BUNDLES (optional — None = the compiled candidate set, as post_apply), CRAIG_CASESENCRYPTION_MODE (serde names; unset = required; anything else refuses) and CRAIG_FIELD_ENCRYPTION_KEY (FieldEncryptor::from_env). Exit 0 only on Report::{NoOp, DryRun, Aborted, Completed}; the report is the tool’s stdout, every refusal its stderr.

  • The Exact requirement and the gate’s own fence. The shell opens its pool with DbPool::connect_for_gate (RewriteFence::Rewriter, one connection, the gate’s 30 s statement timeout, application_name = craig-cases-rewrite-scheme; the fn’s doc now names the two one-shot modes) and verify_schema(sqlx::migrate!(), FloorCheck::Enforce, hint) must answer Exact (SchemaNotExact { extra } on Ahead, SchemaRefused otherwise — "run <binary> migrate first; nothing was written"); the embedded set is invoked a second time because tool_mode() is nullary — the same manifest dir. The gate’s own pool is a Participant (fenced at connect while the tool runs — gate_connect_fails_while_the_tool_holds_the_exclusive_lock), and pre_apply runs before apply_by_verdict (pre_apply → verdict → harden → post_apply, craig-cases/src/gate_hooks.rs), refusing on a live ledger row (gate_pre_apply_refuses_while_a_rewrite_ledger_row_is_live_before_any_migration) with a missing ledger table counting as no live row (pre_apply_treats_a_missing_ledger_table_as_no_live_row).

  • The N−1 gap, as recorded. Deployment guide § Migration gates: "roll the fence release on EVERY craig-cases replica first; never roll below the #1399 U1 fence while a crypto_field_rewrites row is live", pinned by n_minus_1_gap_is_named_in_the_deployment_guide; the migration 20260920120000_crypto_field_rewrites is additive — no floor bump, no wipe-before-apply — D3 untouched. A transaction-pooling pgbouncer between any participant (or the tool) and Postgres defeats session advisory locks: the guide requires a direct connection.

  • Devstack, as landed (U3). docker-compose.yml craig-cases-rewrite after craig-cases-migrate: its OWN build: (target: craig-cases, CARGO_PROFILE: devstack, CRAIG_CASES_FEATURES: ${CRAIG_CASES_REWRITE_FEATURES:-}) and image: ${CRAIG_CASES_REWRITE_IMAGE:-${CI_REGISTRY_IMAGE:-craig}/craig-cases:${CRAIG_IMAGE_TAG:-local}} (the shared x-craig-cases-image anchor pins the tag var, so this service cannot reuse it — the round trip needs a SECOND, state-tx-stub image under a -tx tag, the craig-intake-tx precedent); profiles: [rewrite]; command: ["rewrite-scheme", "--dry-run"] as the safe default (every real invocation passes its argv); restart: "no"; the cases key env_file; the gate’s recorded env set with the seeded owner DSN + GA env as defaults plus CRAIG_CASESENCRYPTION_MODE: required; no ports; depends_on: postgres: service_healthy. xtask::registry::OneShotTool { name, profile, image_env, features_env, default_command } / ONE_SHOT_TOOLS (one entry) / one_shot_tool(name), pinned by compose_one_shot_tools_match_the_registry_structurally (the -migrate gate filter of compose_gates_match_the_registry_structurally stays exact — the tool is not a gate); docker::REWRITE_PROFILE joins down_args ONLY (an active profile on a full-stack up starts the profile’s services — the --profile fault toxiproxy precedent — so up_args never names it: the one-shot must never start with the stack; pinned by up_args_never_activate_the_rewrite_profile); the build_specs_match_docker_compose_yml pin skips ONE_SHOT_TOOLS services (the wrapper builds them on demand — a second full cases compile per dev start is the cost D8 rejects) and asserts the tool’s fallback image is a key the serial build produces. cargo xtask rewrite-scheme [--keep-clone] (require_primary_checkout, then the xtask lifecycle lock held to the end): the seeded crypto_field_lineage + _seed_marker snapshot on a read-only pool → the guard armed → compose stop -t 5 craig-cases → the rehearsal’s admin session (a raw autocommit PgConnection on the maintenance database postgres, application_name = craig-xtask-rewrite-rehearsal — CREATE DATABASE / DROP DATABASE cannot run through dsn::connect_to’s `default_transaction_read_only=on sessions nor in a transaction block; it issues exactly those two statements on the throwaway clone, never a row, never craig_cases DDL): any client session on the clone refuses by name, a leftover clone from an interrupted run is dropped (pg_database pre-check, not a caught 42P04), any client session on craig_cases refuses by name (autovacuum excluded), then CREATE DATABASE craig_cases_rehearsal TEMPLATE craig_cases OWNER craig_cases_owner (database-level ownership is not copied by TEMPLATE) → compose --profile rewrite build craig-cases-rewrite under CRAIG_CASES_REWRITE_IMAGE=<GA>-tx + CRAIG_CASES_REWRITE_FEATURES=state-tx-stub (a non-empty host export of the features var is honoured — the guard-proof injection) → direction A: compose --profile rewrite run --rm --no-deps -e CRAIG_CASESDATABASE_URL=<clone OWNER DSN> -e CRAIGACTIVE_STATE_BUNDLES=tx-stub -e CRAIG_CASESJURISDICTION=texas craig-cases-rewrite rewrite-scheme --dry-run, the run, … craig-cases-rewrite migrate on the SAME image + env (case 1 no-op), verify_seed::verify_inner(Keyed, <clone host DSN>) (the devstack key file IS the clone’s key), SELECT count() FROM persons WHERE ssn_hmac IS NOT NULL = 0 → direction B on the GA image with the compose file’s GA env (both selector vars set EXPLICITLY — <GA> / empty — so a host export cannot put the GA leg on the tx image; verify_inner(Keyed); … WHERE ssn_last_four IS NOT NULL AND ssn_hmac IS NULL = 0) → the guard on EVERY exit path including a panic (Drop) and an interrupt (the ctrlc handler sets a flag the next step honours): compose up -d craig-cases with the reconciled ports env (no --remove-orphans, no profile flags), the replica-aware health wait (devstack::wait_for_service_health_all_replicas), DROP DATABASE IF EXISTS craig_cases_rehearsal WITH (FORCE) unless --keep-clone — all three legs run, failures aggregated, before the lock releases → the seeded snapshot re-read AFTER the restore (the up re-runs the exited craig-cases-migrate gate: Exact ⇒ no-op, post_apply insert / equal-only — inside the compare) and asserted byte-identical. --no-deps because a run that starts dependencies re-resolves ${VAR:-default} (the #1352 recreate class); an explicit CRAIG_CASES__DATABASE_URL on the host is IGNORED (a devstack-only act). Kill −9 / power loss: nothing runs — the NEXT run drops the leftover clone, and craig-cases stays stopped until cargo xtask dev start (the Drop message names it). Not a battery leg (D8 rejected stopping craig-cases inside nextest; a serialized validate step would add a second full cases compile per battery — a maintainer decision named on the U3 MR, not taken); the live round trip and the injected-failure guard proof are recorded on the U3 MR.

  • As-built (#2268). Every image carries every shipped bundle (#2212), so craig-cases-rewrite now merges x-craig-cases-image (no own build:, no CRAIG_CASES_REWRITE_IMAGE / CRAIG_CASES_REWRITE_FEATURES), the wrapper builds nothing, and both directions run the image dev start built: A under -e CRAIGACTIVE_STATE_BUNDLES=tx-stub / CRAIG_CASESJURISDICTION=texas, B under the compose activation. OneShotTool keeps name / profile / default_command; compose_one_shot_tools_match_the_registry_structurally pins the tool’s image + build as equal to the app’s, and build_specs_match_docker_compose_yml keys the tool like any app service. The injected-failure guard proof (the features knob) is gone; a Ctrl-C mid-run takes the same failed-step path to the guard.

Edit this page · latest