Test-lib migration replay — lock only the global-DDL migrations (#1392, epic &76)

Status: Done (2026-09-09) — !1365
Epic: &76
Issues: #1392 (closure) · #1806 U-MIG-B (w3) · #1807 U-MIG-C (w3) · #1808 U-MIG-A (w5) — stream weight 11
Branches: chore/1392-migration-lock-split-plan (frame) → one MR per unit in the order B → C → A; the gate lands before the runner activates unlocked replay, and the harness lands first so the "before" numbers come from main.

This is a Design + Scope plan under the v2026.5 plan rule: GitLab owns tracking, the child issues carry the implementer detail, and the plan freezes when U-MIG-B starts — a deviation is a one-line erratum under the Review log.

Context

EphemeralSchema::new_for_<service> (crates/canopy-test-lib/src/db.rs, run_service_migrations → new_for_service) replays a service’s whole migration set into a per-test schema with sqlx::migrate::Migrator::new(dir).run(pool). sqlx-postgres 0.8.6 derives the migration advisory lock from current_database() alone (pg_advisory_lock(0x3d32ad9e * crc32(dbname)), session-level), so every concurrent replay in one service database serializes: 335 constructor call sites, infra lanes at 12 threads (.config/nextest.toml) — the convoy the validate-unit profile comment names. #1377 bounded the symptom; #1392 asks for the structural split.

What the lock protects (inventory re-verified against main on 2026-09-09, replacing the rotted 2026-08-26 note):

  • CREATE EXTENSION IF NOT EXISTS btree_gist|pg_trgm WITH SCHEMA public — persons 20260604000000, 20260623000000, 20260624000000, 20260819000000; applications 20261216000000; enrollment 20261222000000. Racy only on first creation (pg_extension unique violation). All six select public explicitly.

  • Cluster-global CREATE ROLE inside DO bodies whose handler catches duplicate_object OR unique_violation — security 20260910000000, 20261010000000; tanf and medicaid 20260910000000; reporting 20261111000000.

  • GRANT CONNECT ON DATABASE %I — security/tanf/medicaid 20260910000000, reporting 20261111000000; reporting’s ALTER ROLE canopy_reporting_app IN DATABASE %I SET search_path = public, pg_temp; GRANT <owner role> TO current_user (security 20260910000000, 20261010000000, 20261015000000; tanf/medicaid 20260910000000, 20261010000000; reporting 20261111000000); GRANT canopy_chain_verify TO canopy_security_verify; fail-closed RAISE reconciles over pg_roles / pg_authid / pg_auth_members (owner role and test\_% members exempt).

  • Applications 20260601000001 takes a transaction-scoped pg_advisory_xact_lock(51776): not global, but it still serializes that one migration per database.

Why the obvious shapes are out. A physical directory split is blocked by sqlx’s immutable applied history (VersionMissing), 19 sqlx::migrate! embeds, two runtime arms (crates/canopy-api/src/bootstrap.rs, xtask/src/cmd/migrate.rs) and the ADR-039 generator, for zero production benefit. A persistent per-database bootstrap schema with a _sqlx_migrations ledger as marker fails twice: re-executing GRANT|REVOKE …​ ON DATABASE / ALTER ROLE …​ IN DATABASE …​ SET from unlocked concurrent replays updates the same pg_database / pg_db_role_setting row without an object lock (PostgreSQL 18 ExecGrant_common, AlterSetting: unconditional catalog tuple update, the second writer gets ERROR: tuple concurrently updated), so security, tanf, medicaid and reporting would have to stay fully locked; and a pinned ledger breaks #1380’s invariant that the SQL on disk always runs. Role-membership grants are safe (AddRoleMems locks the role and skips an unchanged membership with a NOTICE) but are treated as global anyway.

Rulings in force: never raise timeouts or retries (#1311, 2026-08-04); do not drop the lock before the split (#1392); do not cap the per-schema pool (db.rs, the #1207 pin); nextest is process-per-test, so no in-process state coordinates tests; the three production migration arms and every migration file stay byte-identical.

Scope

In scope

  • U-MIG-B (#1806): cargo xtask perf ephemeral-schema, the parallel-replay measurement harness, with the "before" numbers from main on its MR.

  • U-MIG-C (#1807): the canopy_test_lib::global_ddl lexer + classifier and the migrations-lint global-DDL contract with exact-file grandfathering.

  • U-MIG-A (#1808): the per-migration-locking runner in test-lib, the schema-scoped idempotency lock, the live locking / history / concurrency tests, the "after" numbers; closes #1392.

Out of scope (each owned elsewhere or dropped)

  • #1311’s template-once / CREATE DATABASE … TEMPLATE — a program (new topology, sweep and lifecycle); file an issue only if wanted.

  • #1614’s rejected "drop ,public" alternative stays rejected.

  • A LOCKED_REPLAY_SERVICES fallback, a bootstrap schema and its sweep flag, throwaway databases in tests — all made unnecessary by the design.

Design

Decisions

# Decision

D1

Per-migration locking, no persistent state. run_service_migrations(pool, service) keeps its signature and delegates to a runner that mirrors Migrator::run_direct on one acquired connection but takes sqlx’s own per-database lock (sqlx::migrate::Migrate::lock() / unlock(), the id the production arms and a booting service use) only around migrations classified as global-DDL. Every other migration applies unlocked, in parallel across schemas. Mutual exclusion with a concurrently booting service replica is preserved for exactly the statements that need it.

D2

One lexer, one classifier, two consumers. canopy_test_lib::global_ddl provides lex(sql) (PostgreSQL lexical rules: -- line comments, nested /* / block comments, '…' strings with '' escapes and E'…' backslash escapes, "…" identifiers with "" escapes, $tag$…$tag$ bodies with tag = [A-Za-z_][A-Za-z_0-9] or empty so bare $$ and tagged forms both work; words lowercased, quoted identifiers kept verbatim without quotes) and classify over token sequences with object targets, never substrings. A -- global-ddl: <reason> marker anywhere in the file forces the locked path. The runner and cargo xtask migrations-lint consume the same report, so lock policy and lint contract cannot drift.

D3

Operation matrix (below), normalized: USER/GROUP → ROLE; "public" → public. Forbidden means the lint fails regardless of marker and the runner treats the migration as Always locked.

D4

Guard association. A role CREATE is guarded iff it lies inside the dollar body of a DO statement, within a BEGIN … EXCEPTION … END block whose EXCEPTION clause names both duplicate_object and unique_violation, and that block is the innermost BEGIN block enclosing the CREATE (a sibling handler does not count). Unguarded → violation and Always locked.

D5

Lock policy. Always when the report holds any locked-class kind, a forbidden kind, or a marker. IfExtensionAbsent(names) when the only global kind is a conforming CREATE EXTENSION IF NOT EXISTS … WITH SCHEMA public: probe SELECT 1 FROM pg_extension WHERE extname = $1 on the same connection and lock only when absent — a committed extension is visible to the migration’s IF NOT EXISTS too, and D3 forbids the only mutations that could invalidate the probe. Steady-state persons/applications/enrollment replays never lock.

D6

Error path. apply_locked: lock() → apply() → always attempt unlock(); the apply error is primary. new_for_service keeps closing the pool before the compensating DROP. No Dirty handling beyond sqlx’s own; the tree has no -- no-transaction migrations.

D7

Idempotency lock. canopy_db::ensure_idempotency_schema keeps pg_advisory_xact_lock(9999) (bigint) unchanged for the production arms. canopy-db gains ensure_idempotency_schema_scoped(pool) (same DDL, lock pg_advisory_xact_lock($1::int4, hashtext(current_schema())) with $1 = 9999), used only by the test-lib runner: per-schema replays serialize per schema; production semantics and cross-version behaviour are untouched.

D8

Regrowth gate. cargo xtask migrations-lint (already a fixed validate gate id) gains the D3 contract over services//migrations/.sql. Grandfathering is by exact file: GRANDFATHERED_GLOBAL_DDL_FILES lists the workspace-relative paths of today’s global-DDL-bearing files, pinned by a unit test that every listed file exists and is classified global; those files are exempt from the marker/guard requirements (applied history is immutable), every other file is held to the contract from its first commit. No version cutoff — migration ordering is per service.

D9

Measurement. cargo run --release -p xtask — perf ephemeral-schema --service <svc> --parallel N --reps R [--quick] [--max-slowdown X] reports per-constructor wall (min/median/p95/max), total, and advisory-lock waiters sampled every 50 ms from pg_locks joined to pg_stat_activity, scoped to this database and to this run (the harness mints its own CANOPY_TEST_RUN_ID, so its schemas and application_name = canopy-test:<svc>:<schema> carry it), grouped by lock key. Debug builds print a "not evidence-grade" warning; recorded numbers always come from the release invocation, on the MR, never in the plan; the verdict threshold is pinned from the MR’s baselines.

Operation matrix (D3)

Object class Operation Treatment

role (ROLE, USER, GROUP)

CREATE

must be guarded (D4) else violation; locked

role

ALTER (incl. IN DATABASE … SET)

marker required; locked

role

membership GRANT / REVOKE (GRANT a, b TO c, REVOKE a FROM c)

marker required; locked

role

DROP, REASSIGN OWNED, DROP OWNED

forbidden

extension

CREATE

must be IF NOT EXISTS … WITH SCHEMA public; runner fast path (D5); no marker needed

extension

ALTER, DROP

forbidden (keeps D5 sound: extensions are never dropped or relocated by a migration)

database

GRANT / REVOKE … ON DATABASE

marker required; locked

database

CREATE, ALTER, DROP

forbidden

schema

CREATE / ALTER / DROP SCHEMA; GRANT / REVOKE … ON SCHEMA; any statement whose object target is public.<name> (dot-separated qualified name in any spacing or quoting)

forbidden (not isolated by the constructor’s search path)

non-schema global objects (CAST, LANGUAGE, ACCESS METHOD, FOREIGN DATA WRAPPER, SERVER, USER MAPPING, TRANSFORM, TABLESPACE, PUBLICATION, SUBSCRIPTION, EVENT TRIGGER)

CREATE, ALTER, DROP, GRANT, REVOKE, COMMENT ON

forbidden

ALTER DEFAULT PRIVILEGES, ALTER SYSTEM

any

forbidden (SET / SET LOCAL of a GUC stays local)

session advisory locks (pg_advisory_lock, pg_advisory_lock_shared, pg_try_advisory_lock, pg_try_advisory_lock_shared)

call

marker required; locked (xact forms are local)

everything else

—

local, unlocked

Expected residual serialization (quantified by D9): security 3 locked migrations (20260910000000, 20261010000000, 20261015000000), tanf and medicaid 2, reporting 1, persons/applications/enrollment 0 global in steady state (applications keeps its one xact-lock migration) — each serialized for its own apply only.

Units

Detail, signatures and the full test lists live on the child issues; each is the implementer brief.

U-MIG-B (weight 3) — measurement harness (#1806)

xtask/src/cmd/perf.rs gains PerfCmd::EphemeralSchema (mod ephemeral_schema;, block_on_mt promoted to pub(super)), xtask/src/cmd/perf/ephemeral_schema.rs (new): --service, --parallel (12), --reps (3), --quick, --max-slowdown (verdict = p95 parallel wall / serial wall, pinned from the MR baselines). serial_baseline, run_rep (a JoinSet of EphemeralSchema::new_for_service + cleanup()), sample_waiters (50 ms; pg_locks non-granted advisory locks in this database joined to pg_stat_activity rows whose application_name carries this run’s id, grouped by (classid, objid, objsubid)). URL via canopy_test_lib::topology::service_database_url (requires a running devstack; stated in the doc comment). docs/modules/ROOT/pages/tooling/xtask-catalog.adoc perf row. The MR records the "before" numbers for security, medicaid, tanf, reporting, persons from the release invocation. MR Relates to #1392, Closes #1806.

U-MIG-C (weight 3) — classifier + lint contract (#1807)

crates/canopy-test-lib/src/global_ddl.rs (new; pub mod global_ddl;): lex, marker, classify/scan, GlobalDdl { class, op, detail }, Treatment, GlobalDdlReport { items, marker } with is_global, lock_policy, violations(grandfathered); statements split on top-level ;, aliases normalized, object targets resolved as qualified names across any spacing/quoting, guard association per D4 (a DO body re-lexed with BEGIN/END depth). Unit tests for comments, strings and quoted identifiers, extension conformance, guard association (tagged and bare $$, sibling handler), aliases, membership lists, public targets in any form, the non-schema global objects, advisory-lock forms, marker, lock policy; property tests (proptest): lexer never panics, report invariant under comment/whitespace insertion and keyword case, dollar bodies round-trip; a floor pin over db::migrations_dir(svc) that the inventory files are global and rules/notices/web have none. xtask/src/cmd/migrations_lint.rs: GRANDFATHERED_GLOBAL_DDL_FILES, collect_migration_files, check_v4_defaults (existing logic extracted), check_global_ddl; rules per D3/D8; unit tests incl. every_grandfathered_file_exists_and_is_global. xtask-catalog.adoc gains a migrations-lint row; testing.adoc names the lint as the contract the unlocked replay relies on. MR Relates to #1392, Closes #1807.

U-MIG-A (weight 5) — runner + scoped idempotency lock + live tests (#1808)

crates/canopy-test-lib/src/db.rs: run_service_migrations (unchanged signature) → ensure_idempotency_schema_scoped → migrations_dir → run_migrations_from(pool, dir) (#[doc(hidden)] pub); pending_migrations (strict: VersionMissing / VersionMismatch, skip applied, skip down), apply_one (policy dispatch via global_ddl::scan), extension_absent, apply_locked; migrations read only through iter(); sqlx 0.8.6 pinned in the doc comment. crates/canopy-db/src/idempotency_schema.rs: additive ensure_idempotency_schema_scoped. crates/canopy-test-lib/tests/db_replay_test.rs (new; in-body infrastructure_available() under CANOPY_TEST_INFRA=required): helpers temp_migrations, side_lock (holds Migrate::lock()), await_advisory_waiter (observes a non-granted advisory lock on the expected key in pg_locks — no sleep-then-!is_finished() assertions); locking tests (global waits on the key, local does not, extension fast path both branches incl. an unavailable extension, failed locked migration releases the lock); history tests (repeat replay, checksum mismatch, missing version, down skipped, dirty refused, failed migration rolls back); concurrency tests (12 concurrent security and reporting constructors all succeed; the scoped idempotency lock serializes per schema, both directions). testing.adoc §EphemeralSchema gains "Replay locking (#1392)" and §lifecycle rewords the advisory-lock sentence. The MR records the "after" numbers. MR Closes #1808, Closes #1392.

Files touched

Area Files

test-lib

crates/canopy-test-lib/src/global_ddl.rs (new), crates/canopy-test-lib/src/db.rs, crates/canopy-test-lib/src/lib.rs, crates/canopy-test-lib/tests/db_replay_test.rs (new)

canopy-db

crates/canopy-db/src/idempotency_schema.rs (additive fn)

xtask

xtask/src/cmd/migrations_lint.rs, xtask/src/cmd/perf.rs, xtask/src/cmd/perf/ephemeral_schema.rs (new)

docs

docs/modules/ROOT/pages/testing.adoc, docs/modules/ROOT/pages/tooling/xtask-catalog.adoc, docs/modules/ROOT/nav.adoc, this page, CHANGELOG.adoc

Must not change

every services/<service>/migrations/*.sql; the 19 sqlx::migrate! embeds; crates/canopy-api/src/bootstrap.rs; xtask/src/cmd/migrate.rs; xtask/src/cmd/outbox_migrations.rs; the existing ensure_idempotency_schema and its bigint lock; .config/nextest.toml thread caps; the per-schema pool width

Verification

Property Layer

Lexer: no panic on arbitrary input; report invariant under comments, whitespace, keyword case; dollar bodies round-trip

proptest in global_ddl.rs

Classifier: the D3 matrix, guard association, aliases, public targets in any spacing/quoting

unit tests in global_ddl.rs

Lint: contract, exact-file grandfathering, marker semantics; the grandfather list exists and is global

unit tests in migrations_lint.rs; cargo xtask migrations-lint green on main

Runner: global migrations wait on the sqlx key (observed), local ones do not, extension fast path both branches, a failed locked migration releases the lock

live tests (infra lane)

Runner: history compatibility (repeat, mismatch, missing, down, dirty, rollback)

live tests

12 concurrent security / reporting constructors all succeed; the scoped idempotency lock serializes per schema

live tests

Measured (AC3): parallel replay no longer serializes per database

release-build perf ephemeral-schema --parallel 12 --reps 3 before (U-MIG-B MR) and after (U-MIG-A MR)

Production arms unchanged

git diff --stat on the must-not-change list per MR

Per commit

cargo fmt --all, cargo clippy --all-targets — -D warnings, unit lanes, the flagless cargo xtask quality-budgets, rustdoc -D warnings on the touched crates; the pre-push battery

Documentation Updates

testing.adoc (§EphemeralSchema, §lifecycle), xtask-catalog.adoc (perf, migrations-lint), a CHANGELOG.adoc == Unreleased entry per MR, this page’s Status on start and completion.

Review log

round vendor resolved model verdict

1

Anthropic

claude-fable-5-1

no-ship — four in-plan blockers (classifier rules under-specified; lint missed REVOKE ON DATABASE, membership REVOKE, non-schema global objects; the D5 test unimplementable as written; SHA and MR number in the body, non-imperative frame subject) — fixed the same day

2

OpenAI (run by the maintainer; read-only review against the repo, sqlx 0.8.6 and the PostgreSQL docs)

gpt-6-astra

no-ship — 4 P1 (version cutoff exempts new per-service migrations; token stripping defeated by block comments and strings; public targets and schema grants escaped the check; extension namespace unrequired) + 10 P2 (aliases and operation matrix, guard association, production idempotency-lock regression, extension fast path vs mutations, gate-after-runner sequencing, missing history-compat / absent-branch / waiter-observation tests, unscoped waiter sampling, debug-build evidence) — all fixed in-plan

Erratum (2026-09-09): D2 — string literals, and the dollar-quoted body of an EXECUTE, are shadow-scanned one level so dynamic SQL via EXECUTE format('…') cannot hide global DDL; a dynamic site may demand the lock but never a rewrite (its Forbidden softens to marker-required, except a role CREATE); CREATE FUNCTION bodies stay opaque. The grandfather list is the 14 inventory files as built. D8 as built is stricter than written: grandfathered files are exempt only from the marker requirement; forbidden and unguarded statements fail regardless.

Edit this page · default