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— persons20260604000000,20260623000000,20260624000000,20260819000000; applications20261216000000; enrollment20261222000000. Racy only on first creation (pg_extensionunique violation). All six selectpublicexplicitly. -
Cluster-global
CREATE ROLEinsideDObodies whose handler catchesduplicate_object OR unique_violation— security20260910000000,20261010000000; tanf and medicaid20260910000000; reporting20261111000000. -
GRANT CONNECT ON DATABASE %I— security/tanf/medicaid20260910000000, reporting20261111000000; reporting’sALTER ROLE canopy_reporting_app IN DATABASE %I SET search_path = public, pg_temp;GRANT <owner role> TO current_user(security20260910000000,20261010000000,20261015000000; tanf/medicaid20260910000000,20261010000000; reporting20261111000000);GRANT canopy_chain_verify TO canopy_security_verify; fail-closedRAISEreconciles overpg_roles/pg_authid/pg_auth_members(owner role andtest\_%members exempt). -
Applications
20260601000001takes a transaction-scopedpg_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 frommainon its MR. -
U-MIG-C (#1807): the
canopy_test_lib::global_ddllexer + classifier and themigrations-lintglobal-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_SERVICESfallback, 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. |
D2 |
One lexer, one classifier, two consumers. |
D3 |
Operation matrix (below), normalized: |
D4 |
Guard association. A role |
D5 |
Lock policy. |
D6 |
Error path. |
D7 |
Idempotency lock. |
D8 |
Regrowth gate. |
D9 |
Measurement. |
Operation matrix (D3)
| Object class | Operation | Treatment |
|---|---|---|
role ( |
|
must be guarded (D4) else violation; locked |
role |
|
marker required; locked |
role |
membership |
marker required; locked |
role |
|
forbidden |
extension |
|
must be |
extension |
|
forbidden (keeps D5 sound: extensions are never dropped or relocated by a migration) |
database |
|
marker required; locked |
database |
|
forbidden |
schema |
|
forbidden (not isolated by the constructor’s search path) |
non-schema global objects ( |
|
forbidden |
|
any |
forbidden ( |
session advisory locks ( |
call |
marker required; locked ( |
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 |
|
canopy-db |
|
xtask |
|
docs |
|
Must not change |
every |
Verification
| Property | Layer |
|---|---|
Lexer: no panic on arbitrary input; report invariant under comments, whitespace, keyword case; dollar bodies round-trip |
proptest in |
Classifier: the D3 matrix, guard association, aliases, |
unit tests in |
Lint: contract, exact-file grandfathering, marker semantics; the grandfather list exists and is global |
unit tests in |
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 |
Production arms unchanged |
|
Per commit |
|
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 |
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; |
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.