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:
-
Rollback is bricked. sqlx’s
Migrator::runhard-errors withVersionMissingwhen 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. -
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.
-
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) |
|---|---|---|
|
no-op, exit 0 |
boot |
|
no-op, exit 0 — this is what restores rollback |
boot + |
|
apply (safe by construction: Behind ⇒ applied ⊊ embedded ⇒ sqlx cannot |
refuse |
|
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 ofxon that table is a CHECK. A UNIQUE, PRIMARY KEY or EXCLUDE key fails every N−1ON CONFLICTit arbitrates (42P10; 42704 forON CONFLICT ON CONSTRAINT); PostgreSQL 18’s<table>_<column>_not_nullis aDROP NOT NULL; any other name the history cannot place, a foreign key included, fails closed. -
DROP CONSTRAINT xof 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 inADD COLUMN, or aCREATE UNIQUE INDEX) under a name it does not drop. An N−1 refusal mapped onxbecomes a 500 — the drop-and-add spelling of theRENAME CONSTRAINTthe #2369 note counts. -
DROP INDEX x, unless an earlier migration createdxas a plain index. -
ALTER [COLUMN] c DROP NOT NULL(N writes a NULL an N−1 decode into a non-Optionfield refuses),DROP IDENTITY,DROP EXPRESSIONand, on a column the file did not add,DROP DEFAULT(a fill an N−1 INSERT relies on stops; anextvaldefault 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
DOor routine body; -
a trigger function that stops filling a column;
-
a refusal moved between a catalog constraint and a trigger’s
RAISE … USING CONSTRAINTin either direction and a trigger re-pointed at another function; -
a re-created routine whose
RAISEloses aCONSTRAINTname orERRCODEwithout 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
CREATEstatement only); -
DROP OPERATOR,CAST,COLLATIONandTEXT 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 BYbumps, 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, asDROP SCHEMAdoes. -
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:
ENABLEorFORCE ROW LEVEL SECURITY,CREATE POLICY … AS RESTRICTIVE, anyALTER POLICYbut a rename, andDROP POLICY. A policy statement on a runtime-read-only table takes no waiver. -
DROP FUNCTION | PROCEDURE | ROUTINE | AGGREGATEof a routine an earlierALTER EXTENSION … DROPdetached 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 ( |
Rejected |
Rollback bricked by |
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 ( |
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).
|