Plan: Field-Scheme Rewrite — craig-cases rewrite-scheme, the Owned Mid-Life Scheme Migration (#1399)
- Archive record
- Status
- Context
- Decisions
- D1 — Timing: now, fence first
- D2 — Home: a key-bearing, owner-DSN, OFFLINE process mode of the craig-cases binary; xtask only rehearses it
- D3 — The fence: four machine-enforced layers, none timing-based
- D4 — Provenance in a ledger; the marker changes by ONE CAS
UPDATE, the last statement of the completion transaction - D5 — The per-row algorithm is the production walk; the pure kernel lives beside the AAD it depends on
- D6 — Anomaly policy: refuse what cannot be proven, heal derived data with counts, never skip silently
- D7 — Verification before the swap, the printout, the second run,
--abort - D8 — Devstack: the guard keeps wipe + reseed; the tool is rehearsed on a CLONE the wrapper creates and drops
- D9 — Scope: the allowlist of ONE, generic in the kernel
- D10 — Docs and ADRs, by unit
- Units — each
Relates to #1399; U3Closes #1399; U0 → U1 → U2a → U2b → U3 - Test matrix (by risk) —
services/craig-cases/tests/api/scheme_rewrite.rs(keyed harness) unless noted - Verification
- Rollout + risks
- Rulings (approved 2026-09-20, rev 3)
- Review log
Archive record
Merge requests: !1676 (U0 plan page + ADR-049 / ADR-063 § Amendment — #1399 Proposed + the ADR-048 note, Relates #1399) + !1678 (U1, Closes #1956) + !1679 (U2a, Closes #1957) + !1680 (U2b, Closes #1958) + !1681 (U3, Closes #1959 / #1399 / #1960)
2026-09-21 — rev 3 approved in plan mode 2026-09-20 after a contextless round 1 (10 blockers) and the maintainer’s gate
(17 findings + 3 mismatches, then a two-lens read-only pass); ruled NOW, pre-1.0 (R0 — the boot-side fence is a one-way
door that must be in every 1.0 image): the crypto_field_lineage marker’s second, owner-role writer — <craig-cases
binary> rewrite-scheme [--dry-run \| --abort], a key-bearing, owner-DSN, OFFLINE process mode (NOT a deploy phase)
that rewrites persons.ssn_last_four between BlindIndex and Opaque (the allowlist of ONE; since #1007 a flip is a
per-row re-encryption in BOTH directions because the BlindIndex AAD binds the ssn_hmac sibling) through the pure
kernel craig_search::rewrite (classify probes with the stored sibling then sibling-less and RECOMPUTES the digest
whenever one authenticated; plaintext / undecryptable / a wrong digest REFUSE the run in either direction, only derived
siblings are healed, counted per kind) and replaces the marker LAST by ONE compare-and-swap UPDATE in the completion
transaction after a full verify pass; no --to (the TARGET is the config-resolved registry, the SOURCE the marker row);
fenced at FOUR machine-enforced layers, none timing-based — every craig-db pool connection takes the shared
hashtext('craig:scheme-rewrite')::bigint session lock at connect and fails closed BY NAME while the tool holds the
exclusive lock (RewriteFenceHeld), the tool’s exclusive lease + census (LockHeld / OtherBackends naming pid / role
/ application_name), the persons_scheme_rewrite_fence per-statement trigger refusing any non-owner writer, and the
durable crypto_field_rewrites ledger (running \| verifying \| completed \| aborted, no failed, aborted only at
rows_mutated = 0) that makes boot verify, gate reconcile and the gate’s NEW typed pre_apply (before
apply_by_verdict) refuse; the tool requires an Exact schema, resumes by adopting the live row (from_spec /
to_spec / key_kcv / db_user), and never issues DDL; craig-api ProcessHooks<E> typed end to end with
tool: Option<ToolMode<E>> dispatched FIRST (argv-exact before any env read); the devstack keeps wipe + reseed and
cargo xtask rewrite-scheme rehearses the ROUND TRIP on a TEMPLATE craig_cases clone (A on the state-tx-stub image,
B back on GA, the gate + verify-seed --expect keyed + the raw-SQL sibling assertion after each, a guard restoring
craig-cases and dropping the clone on every exit path, the seeded marker byte-identical) via the rewrite-profile
craig-cases-rewrite one-shot and the typed-registry OneShotTool slot. Rulings R0–R8 on the page; ADR-049 / ADR-063
§ Amendment — #1399 Accepted (no new ADR); 9 errata recorded on the page; follow-ups #1759 (re-derive the sibling on
hit), #1961 (crypto_key_lineage runtime-DML REVOKE), ADR-048 open question 3 (unchanged).
Status
Done (2026-09-21) — !1681
- Anchors
-
#1399 (epic &98; children U1 #1956, U2a #1957, U2b #1958, U3 #1959 — U3 closes the anchor; follow-ups #1960, #1961 filed at U0), ADR-049 § Amendment — #1025 (the lineage marker; "only the gate writes it" — superseded by § Amendment — #1399, Proposed at U0, Accepted at U3), ADR-063 (the process-mode contract this plan extends by amendment), ADR-048 § Amendment — #1007 (the v2 AAD that makes a flip a re-encryption; the "#1399 stays post-1.0" note this plan reverses; open question 3 stays open), #1310 (the owner role, landed), #1759 (index-only sibling substitution — surfaced by the verify pass, not solved), #1007, #1025.
Context
The crypto_field_lineage marker (PK (table_name, column_name), canonical_spec, spec_version, stamped_at;
runtime-role DML REVOKEd — services/craig-cases/migrations/20260811193000_crypto_field_lineage.sql:15-44) has ONE
writer: the ADR-063 gate’s post_apply hook, insert / equal-only (services/craig-cases/src/field_lineage.rs:6-15,
:175-210, :402-444). A present row that disagrees with the resolved registry is case 2 RecordedMismatch, whose
remedy text names "#1399 or a reseed" (:105-123). The census (2026-09-20, anchors verified) established:
-
A flip is a per-row re-encryption in BOTH directions. Since #1007 the base cell’s AAD carries the stored
ssn_hmaciff the effective spec isBlindIndexAND the row’s sibling is non-NULL (crates/craig-crypto/src/lib.rs: 361-400;crates/craig-search/src/row.rs:237-255derive-then-bind on encrypt,:262-274stored_sibling,:408-423decrypt — it authenticates the stored sibling, it never recomputes it). Clearing or deriving the sibling alone leaves every base undecryptable (services/craig-cases/tests/api/cell_swap_encryption.rs:369-390). No per-row byte says which scheme a cell is under (envelope_versionis 2 either way,lib.rs:250): a resume must PROBE, and the marker is the readers' only signal. A NULL-sibling BlindIndex cell is byte-identical to an Opaque cell — a BlindIndex reader decrypts it. -
The gate cannot host it.
<binary> migrateis argv-exact, one env var, a 1-connection owner pool at a 30 s statement timeout, and runs WHILE old replicas serve (crates/craig-api/src/migrate_mode.rs:34-44,:241-263,:349-377); the cases gate env is pinned key-less (xtask/src/registry.rs:332-361;crates/craig-test-lib/src/gate_proof.rs:86-89); serving loads the key byfrom_envonly (services/craig-cases/src/lib.rs:435-457;crates/craig-crypto/src/lib.rs:529-535).apply_by_verdict(:263) runs BEFORE thepost_applyhook — a fence in that hook would be too late. -
Nothing refuses to run against a serving stack, and boot verifies the MARKER only — mixed-scheme cells are invisible to it (
field_lineage.rs:218-251). Serving’s boot order inrun():craig_api::bootstrap_verified(pool
schema verdict,lib.rs:157) →boot_verified_encryptor(:159;verify_key_lineageat:429) →boot_effective_registries(:163;verify_field_lineageat:389-393). Every craig-db pool runs ONEafter_connecthook per new connection (crates/craig-db/src/lib.rs:302-330,pool_builder— the one source behindconnect_with,connect_for_gate,connect_lazy_with; it setsapplication_nameand nothing else); connections are recycled atmax_lifetime30 min andidle_timeout10 min (:126,:320). The runtime role has full DML onpersons(devstack/postgres/init.sql:32-36default privileges) — single-writer is a FENCING property, not a grant. -
The primitives exist: the walk,
FieldSpec::blind_index(crates/craig-search/src/plan.rs:714-729), verify-seed’s key load + marker-reconstructed registry + per-cell decrypt + re-derivation on a READ-ONLY pool (xtask/src/cmd/ verify_seed.rs:116-160,:456-479,:505-544— itscovered()(:98-110) inspects siblings for BlindIndex bases only, and--expect keyedloads the DEVSTACK key file,:248), the owner role (#1310;xtask/src/registry.rs:75-83), the process-mode dispatcher (migrate_mode.rs:313-333), the schema state machine (crates/craig-db/src/schema_state.rs:79-187,classify→Exact | Ahead | Behind | Diverged | Dirty | ChecksumMismatch),boot_verify::verify_key_lineage(services/craig-cases/src/boot_verify.rs:169-222: scheme + KCV + canary; ciphertext with NOcrypto_key_lineagerow refuses). -
The devstack answers a bundle flip by wipe + reseed (
xtask/src/devstack_guard.rs:903-940); the seed identity embeds the OLDregistry_fingerprintandseed.shfails loud on mismatch (tools/craig-seed/src/seed_marker.rs:24-36,:93-117;devstack/seed/seed.sh:389-396). The only Opaque declarer is the feature-gated tx-stub (services/craig-cases/Cargo.toml:15-17; the compose image is built with the defaultstate-ga;Dockerfile:70-79takesCRAIG_CASES_FEATURES); activating it needsCRAIGACTIVE_STATE_BUNDLES=tx-stub+CRAIG_CASESJURISDICTION=texas(bundle ↔ jurisdiction coherence is fail-closed,services/craig-cases/src/bundle.rs:104-118). -
Stale prose contradicts the AAD code and is corrected here:
crates/craig-cases-fields/src/resolve.rs:61-63,:97-104("at-rest bytes identical");field_lineage.rs:6-15("ONLY the gate"); ADR-048:695 andplans/archive/field-aad.adoc: 28,60("post-1.0"). The APPLIED migration20260811193000_crypto_field_lineage.sqlis never edited — SQLx checksums its full text and every existing database would refuse withChecksumMismatch; its header stays historical.
ADR-049 and ADR-063 are AMENDED; ADR-048 gets a note (no new ADR). The rulings at the end were approved with rev 3.
Decisions
D1 — Timing: now, fence first
NOW: the design is fresh, every primitive exists, and the tool may still be stop-the-world and name a pre-1.0 Changed;
after 1.0 it must also promise coexistence. The decisive argument is the one-way door: U1’s fence (the per-connection
lock, the trigger, the ledger refusals) must be in EVERY image that could ever touch a table mid-rewrite — an N−1 image
without it cannot be protected after the fact. Honest counter: no production data exists, reseed works, the only Opaque
declarer is the tx-stub. Fallback if the maintainer defers: U0 + U1 now (the fence), U2a / U2b / U3 later (R0).
D2 — Home: a key-bearing, owner-DSN, OFFLINE process mode of the craig-cases binary; xtask only rehearses it
-
<craig-cases binary> rewrite-scheme [--dry-run | --abort], dispatched from the one ordering seam (run_process_modes_with_post_apply,migrate_mode.rs:313-333) extended asrun_process_modes_with_hooks<E>(service, migrator, openapi, ProcessHooks { pre_apply, post_apply, tool: ToolMode<E> })whereToolMode<E: std::error::Error + Send + Sync + 'static> { verb: &'static str, run: FnOnce(ToolInvocation { database_url: String, flag: Option<ToolFlag> }) → Fut<Result<(), E>> }andProcessModeError<E>gainsTool([source] E)andToolArgs(ToolModeError)— typed end to end (coding-conventions: noBox<dyn Error>, noanyhowat apub fnboundary; thepost_applyprecedent is not carried forward — it is migrated to the same generic shape in U2b). argv exactly[verb],[verb, "--dry-run"]or[verb, "--abort"]; anything else →ToolModeError::UnexpectedArguments { verb }(the gate’s own text says "exactly<binary> migrate`", `:37-40); combined withmigrate/--print-openapi→ConflictingModes;init_gate_logging(:384-391) reused. Dispatch orderrewrite-scheme→migrate→--print-openapi. Erratum (2026-09-21, U2b #1958): as builtProcessHooks<E>carriestool: Option<ToolMode<E>>(Nonefromnone()/new();ProcessHooks::with_tool( ToolMode<E>)— the seven hook-less services have no tool) withToolMode::new(verb, run);ProcessModeError<E>gainsTool { verb, #[source] source: E },ToolArgs([from] ToolModeError)andToolMissingDatabaseUrl { verb, env_var };ToolModeError::{ UnexpectedArguments { verb, extra }, ConflictingModes { verb }, NonUnicodeArgv }. -
Env = the cases gate’s recorded four (
registry.rs:341-349:CRAIG_CASESDATABASE_URL= the OWNER DSN,CRAIGACTIVE_STATE_BUNDLES,CRAIG_CASESJURISDICTION,CRAIG_CASESENCRYPTION_MODE) PLUSCRAIG_FIELD_ENCRYPTION_KEYthroughFieldEncryptor::from_envexactly as serving. Production key delivery staysfrom_env: the Job / exec mounts the SAME secret as the serving pod and the gate’s deploy-scoped owner DSN. Erratum (2026-09-21, U2b #1958):CRAIG_CASESENCRYPTION_MODEis parsed throughcraig_common::EncryptionMode’s serde names (unset = `required, the serving default; any other or unparseable value ⇒ModeNotRequired), not theSettingsloader; the owner DSN arrives onToolInvocation.database_url(the dispatcher readsCRAIG_CASESDATABASE_URL and answersToolMissingDatabaseUrlwhen unset). -
No
--to: TARGET = the config-resolved registry (bundle::boot_scheme_registry_for,bundle.rs:104-118— the call the gate hook and boot make), SOURCE = the marker row; the tool can only rewrite toward what the next gate / boot verifies. -
Library entry:
craig_cases::scheme_rewrite::run(fence: &HeldFence, pool: &DbPool, enc: &FieldEncryptor, source: &'static FieldSpec, target: &'static FieldSpec, hooks: RewriteHooks) → Result<Report, RewriteError>(thiserror).HeldFenceis a sealed token produced ONLY byExclusiveLease::acquire(owner_dsn).await?.census().await?(D3), so the fence-before-pool order is enforced by type; the process mode is the env-resolving shell that acquires the fence, opens the pool, checks the schema (D5 step 3), then callsrun;RewriteHooks { after_batch: Option<AfterBatch> }is a plain field (craig-cases has notest-utilfeature,Cargo.toml:15-17; production passesRewriteHooks::default()) and is the ONE crash seam. Tests callrunwith caller-supplied&'staticspecs (craig_cases_fields::intern::intern_slice, verify-seed’s path), so direction A is provable on the GA build. Erratum (2026-09-21, U2b 1958): as built the entry isrun(fence: &mut HeldFence, pool: &DbPool, enc: &FieldEncryptor, targets: &[ResolvedTarget], target_resolved: &ResolvedRegistryData, flag: Option<craig_api::ToolFlag>, hooks: RewriteHooks)—ResolvedTarget { target: &'static RewriteTarget, source, target_spec: &'static FieldSpec }per allowlist entry; the shell passes ALL resolved targets andruncomputes the changed set, theNoOpanswer and the--abort/--dry-runbranches itself (one decision site);target_resolvedfeeds the post-swapgate_reconcile_with; the schema verdict stays in the shell (nomigratorparameter — the shell’s pool opener invokessqlx::migrate!()a second time, the same embedded set);HeldFence::releaseisasync(a graceful close) and every refusal path DROPS the lease and the pool (the socket close releases the advisory lock); the shell’sGateHookErrorgainsRewrite([from] RewriteError) (transparent) andStdout(io::Error)— a stdout failure after a committed swap is neither a rewrite failure nor swallowed. -
Rejected: an xtask verb holding the key (no writer pool —
xtask/src/dsn.rs:120-148is read-only by construction; nocraig-casesdependency; production key custody on a laptop); apost_applystep (key-less by contract; runs while old replicas serve — the opposite of quiescent).
D3 — The fence: four machine-enforced layers, none timing-based
The advisory key is hashtext('craig:scheme-rewrite') — a session lock, per DATABASE, so a clone rehearses in isolation.
-
Per-connection shared lock (every participant).
crates/craig-db/src/lib.rspool_builder’s `after_connecthook (:318-334) runsSELECT pg_try_advisory_lock_shared(hashtext('craig:scheme-rewrite')::bigint)(the 1-arg bigint form, pinned on both sides — the 2-arg form is a different lock) right after theapplication_nameset_config;false⇒ the hook returnsErr, and sqlx 0.8 NEVER hands that connection out — it logs,close_hard`s and re-dials until the acquire bound, then surfaces `PoolTimedOut(sqlx-core-0.8.6/src/pool/inner.rs:355-370). So a later reconnect fails the request closed but anonymously; the EAGER path is made explicit:connect_acquire_bounded(:255-278) first probes the lock on a raw connection and returns the namedDbConnectError::RewriteFenceHeldbefore building the pool, so a booting replica or a gate says WHY. Either way a Postgres restart, a failover or a reaped idle session cannot revive a participant while the tool holds the exclusive lock. The lock lives exactly as long as the connection. NewDbPoolOpts::rewrite_fence: RewriteFence(ParticipantbyDefault;Rewriterskips both the probe and the hook) — every service’s pool, the gate’sconnect_for_gate(:214) andconnect_lazy_withshare the one builder, so the gate is fenced with no code of its own; other services take a harmless lock in their own database. Cost: one round trip per new connection. Erratum (2026-09-20): U1’s eager probe dial mirrors sqlx’s own eager-dial tolerance —ConnectionRefusedand connect-phase-transient errors retry with backoff until the acquire bound and surface asPoolTimedOut(the #1353 boot-retry classifier and the #1340 gate bound keep their meaning); a single barePgConnection::connectwas the U1 contract’s sketch. -
The tool’s exclusive lock + census.
ExclusiveLease::acquire(owner_dsn)= a rawPgConnection(application_name = craig-cases-rewrite-scheme, opened before any pool) runningpg_try_advisory_lock(hashtext('craig:scheme-rewrite'));false⇒RewriteError::LockHeldnaming every holder frompg_locks ⋈ pg_stat_activity(pid, usename, application_name). Exclusive succeeds only when NO participant connection exists in the database — race-free against (1) by lock semantics..census()then lists any OTHER client backend (pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend', own pid excluded by pid) and refuses if any exists — a DIAGNOSTIC for non-participants (psql, a pooler, the seed:docker-compose.yml:1543-1573), not the boundary; it yields theHeldFencetoken. The tool re-checks its lease connection before every batch tx (SELECT 1on it); a dead lease stops the run with the ledger rowrunning(resume-safe). -
The statement fence (every NON-OWNER writer, participant or not). U1’s migration installs
scheme_rewrite_fence()— aplpgsqltrigger function — asBEFORE INSERT OR UPDATE ON persons FOR EACH STATEMENT: when acrypto_field_rewritesrow forTG_TABLE_NAMEisrunningorverifyingandcurrent_user <> that row’s db_user, it raisesobject_not_in_prerequisite_state"scheme rewrite in progress on persons (#1399)". Every writer on another role — an old-registry replica oncraig_cases_app, the superuser seed (docker-compose.yml:1547), app-role psql — is refused at the statement; COPY / MERGE / ON CONFLICT fire it, DELETE / TRUNCATE do not (harmless: the batch’sFOR NO KEY UPDATE+ CAS catch a vanished row). Honest limits: a writer on the OWNER role itself (the gate’s migrations, owner psql) sharesdb_userand is NOT refused here — the gate is fenced by layer 4’spre_apply, owner psql by the runbook; a superuser can disable triggers. A resume adopts the live row only whencurrent_user = db_user. Cost: one partial-index lookup per write STATEMENT onpersons, permanent (schema stays migration-owned — the tool never issues DDL). -
The durable ledger (boot, gate, tool). A live
crypto_field_rewritesrow makes the boot verify (verify_field_lineage_with, as its FIRST statement —:218-224has no mode gate) andgate_reconcile_with(after the- mode gate, before
fetch_rows, the order atfield_lineage.rs:166-170) refuse with `FieldLineageError -
RewriteInProgress { table, column, status, started_at }`, and makes the gate refuse in a NEW
pre_applyhook that runs BEFOREapply_by_verdict(migrate_mode.rs:263), so a gate can never change schema or data over a half-rewritten table.pre_applylands in U1 as part ofProcessHooks<E>—pre_applyandpost_applyboth typed over the service’s error (the generic shape D2 describes;ToolMode<E>joins the same struct in U2b). Every ledger check treats a MISSING table as "no live row" (theis_undefined_tableprecedent,crates/craig-db/src/schema_state.rs:408-430) — the gate that applies U1 itself (gate_proof.rsleg 4, a fresh database) and every pre-U1 database must not refuse on42P01. A crash mid-walk leaves the row live: every layer refuses until the run resumes or aborts.
- mode gate, before
Session advisory locks need a DIRECT connection: a transaction-pooling pgbouncer defeats (1) and (2) — a runbook line and a DSN-class note. Rejected: a per-process lease with a heartbeat (a reconnecting pool serves between ticks); a runbook-only "scale to zero" — kept as the runbook step, not the guard.
D4 — Provenance in a ledger; the marker changes by ONE CAS UPDATE, the last statement of the completion transaction
-
Additive migration
crypto_field_rewrites:idUUIDv7 PK,table_name,column_name,from_spec,to_spec,statusCHECK IN (running,verifying,completed,aborted),started_at,finished_at,cursorUUID NULL,rows_seen,rows_mutated,rows_healed,key_kcv,tool_version,db_userDEFAULTcurrent_user,last_errorNULL; partial UNIQUE(table_name, column_name) WHERE status IN ('running', 'verifying'); a role-conditional REVOKE block in the SHAPE of20260811193000_crypto_field_lineage.sql:39-44but namingcrypto_field_rewrites(INSERT, UPDATE, DELETE revoked fromcraig_cases_app; SELECT kept — the trigger reads it); the trigger function + trigger of D3.3. The migration header records the two lineage writers (the gate’s hook; this tool). No floor bump (additive — ADR-063 §D3’s bump is for destructive changes; R7), nowipe-before-apply. -
There is NO
failedstate.rows_mutatedis the ONE monotonic counter of scheme-changing writes — every row UPDATE in pass 2, rewrite OR heal (B’sHeal(RederiveSibling)turns a sibling-less cell into a sibling-bound one; A’s heals re-encrypt under the target) — advanced in the same batch tx.abortedis legal iffrows_mutated = 0— from a pass-1 refusal on a fresh run or from--abort; any refusal after the first committed batch exits ≠ 0 withlast_errorand leaves the rowrunning/verifying— never a terminal state a boot ignores. A resume refuses if the ledger’skey_kcvdiffers from the preflight KCV. -
crypto_field_lineagekeeps its shape; the swap isUPDATE crypto_field_lineage SET canonical_spec = $target, spec_version = 1, stamped_at = now() WHERE table_name = $1 AND column_name = $2 AND canonical_spec = $source— 0 rows ⇒ refuse (the marker moved underneath; the row staysverifying) — in the SAME tx asverifying → completed. The marker row stays PRESENT throughout, so the gate’s case 4 (reconcile-absent re-stamp,field_lineage.rs:365-369) is unreachable mid-run by construction.spec_versionstaysCANONICAL_SPEC_VERSION = 1(resolve.rs:49) orold_version_rows_refuse_typed(tests/api/field_lineage.rs:356) fires. -
Writers: the gate keeps insert / equal-only; the tool is the ONLY updater (grep-pinned); the runtime role stays REVOKEd on both tables (
runtime_role_cannot_write_the_marker,tests/api/field_lineage.rs:427-440, untouched). Rejected: delete + re-insert (a no-row window = case 3 / 4 semantics); provenance columns on the marker.
D5 — The per-row algorithm is the production walk; the pure kernel lives beside the AAD it depends on
Kernel — craig_search::rewrite (new module beside row.rs, table-agnostic: the caller supplies ctx: RowContext
and &'static FieldSpec`s — the walkers require ’static; the marker’s owned spec (effective_spec_from_canonical,
resolve.rs:526) is interned by the caller via intern_slice). RewriteRow { base, hmac: Option<String> } implements
EncryptableRow. classify(enc, ctx, base, hmac, source, target) → Outcome is pure over cell bytes + key + specs; it
probes in a fixed order — with the stored sibling when one is present, then sibling-less — and RECOMPUTES the digest
whenever a sibling authenticated (decrypt_row authenticates the stored sibling but never recomputes it, row.rs:408-423):
| Pre-state | A: BlindIndex → Opaque | B: Opaque → BlindIndex |
|---|---|---|
NULL base, NULL sibling |
|
|
sibling present, decrypts WITH it, |
|
|
sibling present, decrypts WITH it, |
|
|
NULL sibling, decrypts sibling-less |
|
|
sibling present, decrypts ONLY sibling-less |
|
|
NULL base, sibling present |
|
|
decrypts under NEITHER probe (incl. a substituted sibling on a BlindIndex-written row) |
|
|
populated non-envelope cell under |
|
|
rewrite_row(enc, ctx, row, probe, source, target) decrypts under the probe that authenticated — for Probe::SiblingLess
it sets row.hmac = None BEFORE decrypt_row(&mut row, ctx, &[source], Some(enc), Required) (stored_sibling then
yields None and the AAD omits the sibling, row.rs:262-274, lib.rs:385-398) — then for an Opaque target keeps
hmac = None, then encrypt_row(.., &[target], ..) — the walk’s derive-then-bind order (row.rs:245-249) verbatim; no
hand-built StorageContext (RowContext::cell, row.rs:70-81). The digest comparison calls FieldSpec::blind_index on
the BlindIndex-SIDE spec (source in A, target in B — it errs UnsupportedFilter on any other scheme) and maps a
CanonMismatch to Refuse; the plaintext refusal is row.rs:466-468. Every Heal and Rewrite is a write; Skip
and AlreadyTarget are not. Erratum (2026-09-21, U2a #1957): as built, classify returns Result<Outcome,
RewriteError> — UnsupportedPair and the caller-misuse / invariant walk errors (CanonMismatch included; unreachable
for BindValue::Text on a text spec) are Err, never an Outcome::Refuse, which carries a cell’s own state only; a
heal’s probe rides Heal::probe() (Some(SiblingLess) for the two populated-base heals, None for the orphan), not a
second tuple field.
Shell + runner — the process mode, in this order (each step’s refusal is a typed RewriteError arm):
-
ExclusiveLease::acquire(owner_dsn)→.census()→HeldFence(D3.2); -
open the tool pool:
DbPool::connect_for_gate(craig-db/src/lib.rs:214) withrewrite_fence: Rewriter,application_name = craig-cases-rewrite-scheme, the gate’s 30 s statement timeout inherited; -
schema verdict:
DbPool::verify_schema(migrator, FloorCheck::Enforce, hint)(crates/craig-db/src/lib.rs:212-221;schema_state.rs:445-449— the verify-only boot’s own path;read_applied_recordsis private) must answerSchemaVerified::Exact—Aheador any refusal ⇒ "run<binary> migratefirst; nothing was written"; -
key preflight: KCV +
envelope_version+ canary throughboot_verify::verify_key_lineage— a wrong mounted key refuses BEFORE any read, printing the KCV; Erratum (2026-09-21, U2b #1958): the KCV is derived at the ledger step and printed by the ledger row / theCompletedreport; a refusal before the ledger step (steps 1–5) prints no KCV — nothing was written, nothing to attest; -
resolve SOURCE (the marker row) and TARGET (config); ledger first: a live row → adopt iff
from_spec == marker,to_spec == targetandkey_kcvmatches — a reverted config (target == from_spec) refuses naming the forward target ("resume requiresCRAIG__ACTIVE_STATE_BUNDLES=…`"); no live row and marker == target → "already recorded under `<canonical>— nothing to do", exit 0; otherwiseINSERT … running(not under--dry-run); -
pass 1 CLASSIFY over
personsby keyset (WHERE id > $cursor ORDER BY id LIMIT 1000,REWRITE_BATCH_ROWSa const — µs-scale AEAD per row keeps a batch far inside the 30 s statement timeout, not tuned), read-only — anyRefuse⇒ exit ≠ 0;abortediffrows_mutated = 0, else the row stays;--dry-run= this pass alone, no ledger row; -
pass 2 REWRITE, one tx per batch:
SELECT id, ssn_last_four, ssn_hmac … FOR NO KEY UPDATE; per rowUPDATE persons SET ssn_last_four = $2, ssn_hmac = $3 WHERE id = $1 AND ssn_last_four IS NOT DISTINCT FROM $4 AND ssn_hmac IS NOT DISTINCT FROM $5— 0 rows ⇒ refuse as concurrent modification;updated_atuntouched, no event, noaudit_logrow — the ledger row is the record;cursor,rows_seen,rows_mutated,rows_healedadvance in the same tx; the lease is re-checked before each batch; -
running → verifying→ pass 3 VERIFY (D7) → the swap tx (D4).
The runner is field-aware by a TABLE ENTRY (RewriteTarget { table: persons::TABLE, id: "id", base: "ssn_last_four",
sibling: Some("ssn_hmac") }); a widened allowlist adds an entry — the kernel is unchanged, the runner gains a row.
Resume — a plain re-run adopts the live row (step 5) and repeats the passes from pass 1; classify skips converged
rows, so correctness never depends on the cursor. Rejected: a per-row "done" column; rewriting ssn_hmac alone.
D6 — Anomaly policy: refuse what cannot be proven, heal derived data with counts, never skip silently
REFUSE the run: Plaintext, Undecryptable, SiblingMismatch in EITHER direction (a digest that authenticates but does
not equal blind_index(plain) is a writer defect or a #1759 substitution — never erased by a rewrite);
CRAIG_CASES__ENCRYPTION_MODE ≠ required (ModeNotRequired) or a keyless env; an ExtraRow / VersionUnsupported
marker state; a key that fails the preflight; a non-Exact schema. HEAL, counted per kind, are the three Heal arms —
derived data only, each a counted write. Rejected: encrypting plaintext (a provenance guess); "skip and continue" over a
refusal (a partial rewrite under a flipped marker is exactly the 500-per-row outcome the fence prevents).
D7 — Verification before the swap, the printout, the second run, --abort
Pass 3 re-reads every row under the TARGET spec only — verify-seed’s teeth: base decrypts; BlindIndex ⇒ sibling ==
blind_index(plain); Opaque ⇒ ssn_hmac IS NULL. Any failure ⇒ the row stays verifying with last_error, marker
untouched, exit ≠ 0; the remedy is a re-run. After the swap: an in-process gate_reconcile_with over the resolved
registry (case 1). Stdout: per pass rows_seen / mutated / already_target / healed{kind: n} + duration; lineage before /
after: <canonical>; the key KCV; the ledger id — never a plaintext, a key, a last_error payload, or more than one row
id. --abort: legal iff the live row’s rows_mutated = 0 (the counter, not a read pass — in direction A a rewritten row
is byte-identical to a NULL-sibling source row, so no read pass can prove "nothing was rewritten"); otherwise refused
with "resume forward". Independent oracles after the run: cargo xtask verify-seed --expect keyed reconstructs the
registry FROM the replaced marker (verify_seed.rs:116-160) but inspects siblings for BlindIndex bases only (:98-110),
so after A the probe ALSO asserts SELECT count(*) FROM persons WHERE ssn_hmac IS NOT NULL = 0 by raw SQL.
D8 — Devstack: the guard keeps wipe + reseed; the tool is rehearsed on a CLONE the wrapper creates and drops
A devstack scheme flip is a jurisdiction flip and the seed identity would strand the next dev start (Context);
devstack_guard.rs and seed_marker stay untouched; local-dev.adoc says so in one sentence. "Gate / boot accept
without reseed" is PROVEN (i) hermetically — the keyed-harness legs (through run; KeyedHarness gains pub db: DbPool
+ close_pool().await — today it exposes only router, services/craig-cases/tests/api/keyed_harness.rs:265-280, the pool
living inside AppState — and every raw sqlx::PgPool::connect(&h.db_url) fixture is closed before
ExclusiveLease::acquire, so the census sees only the test’s own connections) and the
real-binary leg (scratch clone → pre-state → <bin> rewrite-scheme → <bin> migrate exit 0 → verify_field_lineage
Ok; direction B on the GA build, direction A with caller-supplied specs); (ii) live, at U2b-open and forever after by the
U3 wrapper — the ROUND TRIP on a clone: A on the tx-stub image with CRAIGACTIVE_STATE_BUNDLES=tx-stub
CRAIG_CASESJURISDICTION=texas, then B back on the GA image with the GA env, migrate + verify-seed --expect keyed
(clone DSN; the devstack key file is the clone’s key) + the raw-SQL sibling assertion after each. Rejected: a dev start
rehearsal mode; a battery leg that stops craig-cases inside nextest (if ever a battery leg, a serialized validate step).
_Erratum (2026-09-21, U3 #1959): as built the wrapper runs the tool and the gate with compose --profile rewrite run --rm
--no-deps on the SAME craig-cases-rewrite service (the gate leg is … craig-cases-rewrite migrate, not
craig-cases-migrate — the GA gate image cannot resolve the tx-stub bundle); a leftover clone is found by a pg_database
pre-check (not a caught 42P04) and the clone is created OWNER craig_cases_owner; --keep-clone skips the drop; the
guard’s health wait is the replica-aware devstack::wait_for_service_health_all_replicas; the seeded snapshot is re-read
AFTER the restore (the up re-runs the exited migrate gate, inside the compare); a non-empty host export of
CRAIG_CASES_REWRITE_FEATURES is honoured on the tx leg (the injected-failure guard proof) and both selector vars are set
explicitly on the GA leg; the compose build_specs pin skips ONE_SHOT_TOOLS.
D9 — Scope: the allowlist of ONE, generic in the kernel
The runner’s RewriteTarget table has ONE entry and the tool iterates ALLOWLIST entries whose recorded spec ≠ resolved
(resolve.rs:106-110 — today at most one); everything else is refused by resolve itself (:257-292). ADR-048 open
question 3 (crypto_key_lineage bootstrap) stays OUT — another table, another question; the walk is reusable, recorded.
The runtime role’s DML on crypto_key_lineage (ADR-048:693) is adjacent residue, filed at U0, untouched here.
operations/ssa-digest-rotation.adoc:21-23 borrows #1399 for the SSA digest registry: a docs fix: filed at U0,
repointed in U3. No contested-surfaces.toml class fits a one-shot process mode (the migrate gate itself is
unregistered) — not registered, recorded. Rejected: generic table / column flags.
D10 — Docs and ADRs, by unit
-
U1:
data-model-cases.adoc:96-98(the ledger row, the trigger, the two writers; boot / gate refusal); deployment guide § Migration gates gains the sentence "roll U1 on EVERY replica first; never roll below U1 while acrypto_field_rewritesrow is live" (the grep pin’s target) and the direct-connection / no-transaction-pooler note;field_lineage.rs:6-15restated ("the gate inserts, the rewrite mode updates"); CHANGELOG (pre-1.0Changed: the per-connection fence on every craig-db pool, thepersonswrite trigger, theRewriteInProgressrefusal, the gate’spre_applyrefusal). -
U2a:
resolve.rs:61-63,:97-104prose; thecraig_search::rewritemodule docs. -
U2b:
configuration-reference.adoc(the key var on the mode; the owner DSN); deployment guide § "Field-scheme rewrite (#1399)" — quiesce →--dry-run→ run → gate → roll; key = serving’s secret mount; owner DSN; mid-run rollback = resume or PITR;field_lineage.rs:108-113names the command; CHANGELOG (the process mode, the schema-exact requirement). -
U3: ADR-049 § Amendment — #1399 (the mode as the SECOND owner-role writer; the ledger; the four-layer fence;
:397-400/:418-419superseded) and ADR-063 § Amendment — #1399 (a second process-mode CLASS: key-bearing, owner DSN, offline, NOT a deploy phase; thepre_applyseam; argv / env; dispatch order; the N−1 gap) Proposed at U0 → Accepted; ADR-048 note (:695reversed; OQ3 unchanged);local-dev.adoc(D8 + the wrapper);cli.adoc(the wrapper); ssa-digest repoint;.claude/CLAUDE.md:311-312,:324,:432; the plan archived.
Units — each Relates to #1399; U3 Closes #1399; U0 → U1 → U2a → U2b → U3
| MR | Issue | Scope | W |
|---|---|---|---|
U0 |
#1399 |
This page (Active nav), ADR-049 / ADR-063 § Amendment — #1399 Proposed + the ADR-048 note, epic + children
+ follow-ups (the ssa-digest docs |
1 |
U1 |
new |
THE FENCE: craig-db |
3 |
U2a |
new |
THE KERNEL: |
2 |
U2b |
new |
THE TOOL: |
3 |
U3 |
new |
|
2 |
Weight 11 against the issue’s 5 — a program split, recorded; the page runs past the ~300-line advisory for the same reason
(the &96 precedent), accepted. Every MR is green alone (U1 fences a tool that does not exist yet; U2a has no caller); each
carries its CHANGELOG.adoc == Unreleased entry; every new test carries its // @axis: tag.
Test matrix (by risk) — services/craig-cases/tests/api/scheme_rewrite.rs (keyed harness) unless noted
Every keyed-harness leg first inserts the per-test key’s crypto_key_lineage row (the tests/api/boot_verify.rs:60-72
shape) — the preflight refuses ciphertext without lineage — and enters the fenced path through a fixture that closes the
harness’s router pool first. Erratum (2026-09-21, U2b #1958): the U2b keyed-harness legs live in
tests/api/scheme_rewrite_tool.rs (evil + sad) and tests/api/scheme_rewrite_tool_live.rs (concurrency + happy); U1’s
legs stay in scheme_rewrite.rs.
-
Evil: (U1)
runtime_role_cannot_write_the_rewrite_ledger(devstack DB, the:427-440shape);a_non_participant_write_on_persons_is_refused_by_the_trigger_while_a_row_is_live(a second role over raw sqlx — the throwaway DB grants itpersonsDML first, thetests/api/field_lineage.rs:431-434shape);eager_connect_refuses_by_name_while_the_exclusive_lock_is_heldanda_reconnect_during_a_rewrite_never_hands_out_a_connection_and_times_out_the_acquire(craig-db,Participantvs a held exclusive, a short acquire bound);gate_connect_fails_while_the_tool_holds_the_exclusive_lock; (U2b)rewrite_refuses_while_any_participant_connection_lives(zero writes, no ledger row);rewrite_refuses_while_another_client_backend_is_attached_and_names_it;plaintext_cell_under_required_refuses_before_any_write;undecryptable_cell_refuses_the_run_and_names_one_row(incl. the substituted-sibling pre-state);writer_bound_wrong_digest_refuses_in_both_directions;wrong_key_refuses_at_preflight_before_any_read;resume_with_a_different_key_kcv_refuses;marker_moved_underneath_makes_the_swap_cas_refuse_and_the_row_stays_verifying;tool_output_never_contains_a_plaintext_a_key_or_a_second_row_id; real binary (services/craig-cases/tests/ rewrite_scheme_binary.rs, themigrate_postgres_only.rsshape):rewrite_scheme_extra_argv_fails_before_env,rewrite_scheme_without_the_field_key_refuses_naming_the_var. -
Sad: (U1)
boot_verify_refuses_while_a_rewrite_ledger_row_is_running_or_verifying;gate_pre_apply_refuses_while_a_rewrite_ledger_row_is_live_before_any_migration;pre_apply_treats_a_missing_ledger_table_as_no_live_row(the gate that applies U1 itself);n_minus_1_gap_is_named_in_the_deployment_guide(a grep gate over the U1 runbook sentence); (U2b)resume_adopts_the_live_row_only_under_its_db_user;tool_refuses_when_the_schema_is_not_exact;optional_mode_refuses_the_rewrite;dry_run_classifies_and_writes_nothing;pass1_refusal_on_a_fresh_run_closes_the_row_aborted;refuse_during_a_resume_keeps_the_row_running_never_aborted;abort_is_refused_once_a_row_was_mutated(direction A);crash_after_a_batch_containing_only_heals_then_abort_is_refused(direction B,RederiveSiblingonly);abort_closes_a_live_row_when_nothing_was_mutated;config_reverted_mid_rewrite_refuses_naming_the_forward_target;tool_stops_before_the_next_batch_when_its_exclusive_lease_session_dies;second_run_after_completion_is_a_noop_and_prints_the_lineage;heal_counts_are_printed_per_kind;orphan_sibling_heal_cas_matches_a_null_base;verify_failure_keeps_the_marker_and_the_row_verifying. -
Concurrency: (U2b)
two_concurrent_tool_runs_serialize_on_the_exclusive_lease_and_the_loser_refuses;crash_after_n_batches_then_resume_converges_to_the_same_plaintext_sibling_and_marker_state(RewriteHooks::after_batch; ciphertext bytes differ by nonce, stated);a_participant_reconnect_racing_the_tool_loses_at_connect_not_on_timing. -
Happy: (U2b)
blind_to_opaque_clears_every_sibling_the_override_router_reads_200_and_default_boot_verify_refuses(build_router_with_registries,tests/api/keyed_harness.rs:495-502; rawSELECT ssn_last_four, ssn_hmac,tests/api/persons_search.rs:377-388;count(ssn_hmac) = 0by raw SQL);opaque_to_blind_binds_siblings_the_default_router_reads_200_and_the_override_router_500s;equality_filter_hits_after_opaque_to_blind;gate_case1_noops_and_boot_verify_accepts_after_the_rewrite;real_binary_rewrite_scheme_then_migrate_both_exit_0_over_a_scratch_clone(direction B, GA build). -
Property (DB-free, U2a,
craig_search::rewrite):rewrite_then_inverse_preserves_plaintext_and_blind_index_hits(A∘B and B∘A over random 4-digit strings, row ids and optional stale siblings);classify_is_total_over_arbitrary_cell_bytes_and_never_panics;classify_agrees_with_the_walk_on_every_generated_pre_state;every_heal_and_rewrite_outcome_is_a_write_and_nothing_else_is. -
Live (the U3 wrapper, run at U2b-open and recorded on the MR): both directions on the clone;
verify-seed --expect keyedagainst the clone after each;count(ssn_hmac) = 0after A; the seededcraig_casesuntouched (its marker and_seed_markerbyte-equal before and after).
Verification
-
Per MR: fmt, clippy (the 40-line bound holds for every pass fn and
classify), budgets at their locks (new modules in their own files),contested-census,check-docs,plan-lint, the battery;compose_gates_match_the_registry_structurally(xtask/src/registry.rs:270) extended for the profile service;runtime_role_cannot_write_the_markerunchanged. -
After U2b:
rg -n "UPDATE crypto_field_lineage" services crates xtask→ exactly ONE site (the swap);rg -n "at-rest bytes are identical" crates/craig-cases-fields→ 0;rg -n "migration tooling \(#1399\)" services→ 0;rg -n "craig:scheme-rewrite"→ craig-db’s hook, the tool’s lease, the docs;rg -n "'failed'" services/craig-cases/src/scheme_rewrite→ 0;rg -n "Box<dyn Error" crates/craig-api/src/migrate_mode.rs→ 0. Erratum (2026-09-21, U2b #1958): the marker grep also matches test-side raw moves (the pre-existing runtime-role refusal probe, the MarkerMoved leg’s hook and the direction-B pre-state fixture); ONE PRODUCT site —marker.rs’s `SWAP_SQL— is the invariant. -
Live probe at U2b-open (D8): the U3 wrapper’s steps by hand (the wrapper lands in U3), recorded on the MR.
Rollout + risks
-
Order per environment: roll U1 on EVERY replica first → ship the image whose bundle declares the new scheme → scale cases to ZERO (a straggler cannot reconnect or write — it fails closed) → PITR mark → Job
rewrite-scheme --dry-run→rewrite-scheme→ gatemigrate(case 1) → roll serving. Skipping the tool = the existing case-2 refusal, now naming the command. -
Mid-run rollback is FORWARD (resume) or a restore: a half-rewritten table under the old marker is unreadable by any binary; the live ledger row refuses every U1+ boot / gate / non-owner write until the run completes; an N−1 (pre-U1) image is NOT guarded — never roll below U1 while a ledger row is live (runbook + the grep pin).
-
Pre-1.0
Changed: every craig-db pool connection takes a shared advisory lock at connect and fails closed while a rewrite holds the exclusive lock; a per-statement trigger onpersons; boot / gate refuse on a live rewrite; a new process mode; the tool requires anExactschema. After A,promote_ssn’s hmac arm (`store/persons.rs:112-123) never lands for existing rows (B restores it); the partialidx_persons_ssn_hmacempties under A (no DDL). Cost: three AEAD passes per row, 1 000-row transactions — minutes per million rows; one advisory-lock round trip per new connection fleet-wide; one index lookup per write statement onpersons. -
A transaction-pooling pgbouncer between any participant or the tool and Postgres defeats session advisory locks: the guide requires a direct connection (DSN-class note).
Rulings (approved 2026-09-20, rev 3)
-
R0 — timing: now, U0–U3 (the one-way-door argument; the "post-1.0" note in ADR-048 and the field-aad plan is reversed).
-
R1 — the fence: the four layers — the per-connection shared lock in craig-db, the tool’s exclusive lock, the
personswrite trigger, the ledger refusals in boot /pre_apply— as pre-1.0Changed. -
R2 — provenance: the
crypto_field_rewritesledger withrunning | verifying | completed | aborted, nofailed,abortedonly atrows_mutated = 0. -
R3 — anomaly policy: refuse plaintext / undecryptable / a wrong digest in either direction; heal derived siblings with counts.
-
R4 — devstack: the guard keeps wipe + reseed; the wrapper is a clone rehearsal, round trip.
-
R5 — flags: no
--to(target from config, source from the marker);--dry-runand--abortthe only flags. -
R6 — the split: five MRs at weight 11.
-
R7 — the N−1 gap: additive migration, no floor bump; the gap a runbook constraint + a grep pin.
-
R8 — the compose one-shot: a
craig-cases-rewriteprofile service (image fromCRAIG_CASES_REWRITE_IMAGE) in the typed registry, used only by the wrapper.
Review log
Round |
Vendor |
Resolved model |
Verdict |
1 |
Anthropic — three fresh contextless lens subagents (conventions, implementability, readability + risk) + an anchor verifier, the four plan-lifecycle questions, over the plan + the rules |
Claude Fable 5.1 |
no-ship — 10 blockers + 20 observations, folded into rev 2 |
gate |
maintainer (plan mode, rev 2 → rev 3) |
— |
rev 2 no-ship — 17 findings + 3 mismatches (the per-process lease is not a
connection-level fence; the gate applies before its fence; non-participating writers; heals not covered by the abort
counter; wrong digests accepted in A; the stale-sibling heal impossible as specified; the orphan CAS; no schema verdict;
the wrapper on the seeded DB; the runner API vs the fence order; a false default-router pin; the probe’s bundle
activation; U1’s grep pin; the verify-seed key; the Opaque-sibling oracle; ledger-before-no-op; the historical migration
header; lifetimes; the allowlist claim; |
2 |
open — run by the maintainer through another vendor’s model |
open |
open |