Ephemeral-schema reuse — lease, wipe and fingerprint instead of a migration replay per test (#1938, epic &76)
Status: Done (2026-09-19) — !1450
Epic: &76
Issues: #1938 (parent, closed by U2) · #2181 U1 (w8) · #2182 U2 (w2)
Branches: chore/1938-schema-reuse-lib (U1, carries this page) → chore/1938-schema-reuse-xtask (U2)
This is a Design + Scope plan: GitLab owns tracking, the child issues carry the implementer brief, and the plan freezes when U1 starts.
Context
Every EphemeralSchema::new_for_<service> (17 generated constructors in crates/canopy-test-lib/src/db_constructors.rs; one funnel, EphemeralSchema::new_for_service in crates/canopy-test-lib/src/db.rs) creates a schema named test_<run16>_<hex12>, opens a pool scoped by search_path=<schema>,public, and replays the service’s whole migration set through the runtime sqlx::migrate::Migrator (#1380) under the per-migration lock policy of #1392. nextest runs one process per test, so nothing survives a test and a pre-push battery does this about 1,140 times: applications 238 schemas of ~135 relations, security 180 of ~112. The #1922 record measured it on the 2026-09-18 validate lane: replay p50 178 ms, p95 357 ms, 252 s of replay inside the lane; schema creation is a flat ~55 ms.
The cost is not the time. Each replay inserts, and the drop later deletes, thousands of pg_attribute, pg_depend and pg_constraint rows and creates and unlinks ~135 relation files per schema, and the shared catalogs of canopy_applications have grown to fifty times their pristine size. Autovacuum keeps truncating those catalogs under AccessExclusiveLock; under IO pressure one truncation holds the lock for seconds and every statement in the database queues at parse time. That one mechanism failed four batteries in four disguises (#1938’s notes): the replay’s own 3 s lock_timeout, the service pool’s 5 s acquire timeout surfacing as 503s, transport errors from starved connections, and a 10 s projection deadline.
Three shapes were weighed against the tree:
-
Reuse in place — keep migrated schemas alive for the battery and hand each test a wiped one. Everything the migrations build stays valid because nothing moves: the 48
SECURITY DEFINERfunctions whoseproconfigbakes in the literal schema name (security 28, reporting 11, medicaid 5, tanf 5), the NOLOGIN-role ownership of the chain tables, 21 views, 30 triggers and 3 enums. Chosen. -
Template copy — a schema-to-schema copy loses or mispoints exactly those objects and performs the same catalog inserts as a replay;
CREATE DATABASE … TEMPLATE(#1311) keeps them but copies 300+ files per test, forbids connections to the template while copying, changes the connection topology every caller assumes, and was ruled a program by the #1392 plan. -
Transaction rollback per test — the callers commit (outbox drainers, schedulers, in-process axum apps, multi-connection holders, advisory locks keyed on
current_schema()); a wrapping transaction changes behaviour for the ~360 call sites. Rejected.
Rulings in force (docs/modules/ROOT/pages/plans/archive/test-lib-migration-lock-split.adoc): never raise timeouts or retries; do not cap the per-schema pool width; nextest is process-per-test, so all coordination lives in the database; every services//migrations/.sql, the 19 sqlx::migrate! embeds, crates/canopy-api/src/bootstrap.rs and xtask/src/cmd/migrate.rs stay byte-identical; the ,public search_path fallback stays (1614); infrastructure tests carry no [ignore] and report their own dependency miss (#2162, #2168); the database reachability probe (#2069) precedes the first admin acquire on every constructor path.
Scope
In scope
-
U1: the versioned registry, the lease, the pristine probe, the fenced release (wipe, seeds, statistics, fingerprint, free-or-drop), the fenced
Dropbackstop,compensating_dropand sweep primitive, the measurement records for construct and release, the opt-outs, unit and live tests, thetesting.adocsection, this page. -
U2: the post-battery and manual sweeps report per-run pool state and collect stale registries;
cargo xtask perf ephemeral-schemagains--reuse on|off, complete-round timing (construct + cleanup) and a hit/miss tally, and tears its run down on every path; the "after" numbers on #1938 and in this page’s Done flip;xtask-catalog.adoc; CHANGELOG.
Out of scope
-
The bare-schema harnesses that bypass the funnel (
from_partsand rawCREATE SCHEMAincrates/canopy-test-lib/tests/db_replay_test.rs,crates/canopy-api/tests/migration_phase_test.rs,crates/canopy-api/tests/idempotency_schema_test.rs,crates/canopy-mq/tests/inbox_parking_test.rs,services/canopy-applications/tests/scan_quarantine_test.rs,services/canopy-reporting/tests/report_runs_substrate_test.rs,services/canopy-security/tests/audit_archive_test.rs) keep today’s create/drop. -
Cross-battery reuse: the post-battery sweep still drops every current-run schema, so a pool lives for one battery (a bare
cargo nextest run -pwith no run id reuses across local runs, under the sweep’s 6 h floor). -
Migrations, the production migration arms, nextest thread counts, the devstack PostgreSQL flags, the Keycloak event-loop stall (a separate defect).
-
Converting tests that open raw, untagged connections (the TANF and security chain suites) to a tagged helper: this plan keeps them correct by refusing to reuse their schemas (D7); tagging is a follow-up.
Design
Decisions
| # | Decision |
|---|---|
D1 |
Versioned registry per service database. Schema |
D2 |
Pool key = the invalidation rule. |
D3 |
Lease is one statement, scoped by run (listing below). |
D4 |
A leased row is never reclaimed by a lessee. A crashed or killed test leaves |
D5 |
Release is one fenced transaction, on the admin connection. |
D6 |
Fingerprint = the migrated-shape guarantee. |
D7 |
Straggler rule. Closing the fixture pool does not close connections a test opened itself, and some of those carry no schema tag (a raw |
D8 |
Every destructive path is fenced. |
D9 |
Seeds and ledger. Right after a fresh replay every non-empty table except |
D10 |
Hit path arms ownership first; opt-outs fall back loudly. On a lease hit the |
D11 |
Measurement on both ends. The |
-- $1 service, $2 run_id, $3 pool_key, $4 ticket
WITH pick AS (
SELECT schema_name FROM leases l
WHERE l.service = $1 AND l.run_id = $2 AND l.pool_key = $3 AND l.state = 'free'
AND l.use_count < 256 AND l.created_at > now() - interval '5 hours'
AND EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = l.schema_name)
ORDER BY l.use_count LIMIT 1 FOR UPDATE SKIP LOCKED)
UPDATE leases l
SET state = 'leased', leased_at = now(), leased_by = $4, use_count = l.use_count + 1
FROM pick WHERE l.schema_name = pick.schema_name
RETURNING l.schema_name, l.use_count;
BEGIN;
SELECT leased_by, leased_at, fingerprint, ledger_rows, ledger_head
FROM leases WHERE schema_name = $1 FOR UPDATE; -- none → NoRow; other ticket → NotOwner (ROLLBACK)
SET LOCAL session_replication_role = replica; SET LOCAL search_path = pg_catalog, pg_temp;
SELECT wipe($1); -- DELETE all but the ledger; stats; seeds
SELECT fingerprint($1) = $fp
AND (SELECT count(*), max(version) FROM <nsp>._sqlx_migrations) = ($rows, $head)
AND NOT EXISTS (SELECT 1 FROM pg_stat_activity a
WHERE a.datname = current_database() AND a.pid <> pg_backend_pid()
AND a.backend_type = 'client backend'
AND (a.application_name LIKE '%' || $1 || '%'
OR (a.application_name !~ '^canopy-test(-admin)?:' AND a.backend_start >= $leased_at)));
-- true → UPDATE leases SET state='free', leased_at=NULL, leased_by=NULL WHERE schema_name=$1; COMMIT; (Freed)
-- false → DROP SCHEMA IF EXISTS <nsp> CASCADE; DELETE FROM leases WHERE schema_name=$1; COMMIT; (Dropped)
-- drop_if_owner($1, $ticket): same FOR UPDATE; DROP + DELETE only when owned (or free, for the sweep); else no-op.
Invalidation rule and isolation argument (#1938 AC 1)
Invalidation. A schema is leased only when its pool_key equals the key computed from the migration files on disk at construct time (D2). Editing any migration byte, the idempotency DDL or the registry SQL changes the key; the old rows are never leased again and their schemas are dropped by the post-battery sweep. A different registry SQL is a different registry schema (D1), so no version ever rewrites another’s bookkeeping.
Isolation. A leased schema is held by exactly one process: the row lock and leased_by ticket make the lease exclusive (D3), every destructive path re-checks that ticket under the same row lock (D5, D8), a released schema was wiped and fingerprint-verified by its owner after its own pool closed with no straggler attached (D5–D7), and the lessee re-verifies emptiness before use (D5). Sibling tests hold different schemas; the only shared state is the immutable migrated shape (proved equal by D6) and the cluster-global objects — roles and public extensions — that every schema already shared today. Everything session-scoped (temp tables, prepared statements, SET ROLE) dies with the test process because the pool is per process.
What a reused schema can still differ in
Planner statistics are reset (D5); seed-row timestamps are older than a fresh replay’s (D9; semantics preserved); _sqlx_migrations.installed_on is the schema’s creation time (read only by the bare-schema replay tests); physical row order without ORDER BY after free-space reuse is theoretically observable on multi-page tables (the wipe leaves tables empty; none of the ~360 callers asserts on unordered reads). Dead tuples accumulate between autovacuum passes on the schema’s own tables, never on shared catalogs.
Errata
-
Erratum (2026-09-18, U1 as built): D7’s untagged-backend clause reads "an untagged client backend that started during the lease". In a parallel lane that also matches sibling test processes' own helper connections, which would drop most schemas instead of freeing them, and no client-side accounting can distinguish a raw connection from a test’s own helper pool growing after the schema exists — Docker’s userland proxy hides this process’s ports from the server. As built, the release counts as stragglers a backend tagged with the schema (other than the pool’s own connections) or one holding a lock on the schema’s relations (a writer mid-transaction, which also makes the release fail loudly within a 3 s
lock_timeoutwith the row still leased); the suites that opensearch_path-scoped connections of their own are excluded from reuse by name (db_pool::RAW_CONNECTION_SUITES, pinned against the tree by a unit test) until #2184 tags those connections — the "exclude affected schemas" arm the round-2 review allowed. The intent — a raw connection the releasing test opened itself never survives into a lessee — is unchanged. -
Erratum (2026-09-19, U1 as built): D5 says "
DELETE, neverTRUNCATE". ADELETEwipe leaves heap and index pages behind (noVACUUMinside the release transaction), and at a schema’s seventh reuse in U1’s first battery the planner priced renewals' bloated keyset index above the status index and anEXPLAINpin flipped. As built, the wipeTRUNCATEs — in one statement,CASCADE— only the tables that hold rows (the ones the test wrote to, plus the seed tables; their FK-referencing tables are empty or already listed), leaves every other table alone, and restores seeds after clearing statistics. The file andpg_classchurn is bounded by what one test used, not by the schema’s ~135 relations; thepg_attribute/pg_depend/pg_constraintchurn D5 targets is unchanged. -
Erratum (2026-09-19, #2184): the "exclude affected schemas" arm of the 2026-09-18 erratum is retired for the chain suites — a test’s own raw connection now goes through
EphemeralSchema::connect_raw/connect_raw_as, taggedcanopy-test:<service>:<schema>:<purpose>, so the release counts it precisely (still open →Dropped("straggler"), closed →Freed);db_pool::RAW_CONNECTION_SUITESkeeps only the bare-schema harnesses anddb_replay_test(whose concurrency pin needs the replay), and the tree pin fails on any new untaggedsearch_pathconnection.
Units (weights by complexity) — U1 → U2
U1 (w8) — chore(test-lib): reuse released ephemeral schemas through a fenced per-database lease registry
Files: crates/canopy-test-lib/src/db_pool.rs (new), crates/canopy-test-lib/src/db_pool/registry.sql (new), crates/canopy-test-lib/src/db.rs, crates/canopy-test-lib/src/lib.rs, crates/canopy-test-lib/Cargo.toml (sha2, a workspace dependency), crates/canopy-db/src/idempotency_schema.rs (pub fn ddl_text() + the 9997 registry line), crates/canopy-test-lib/tests/db_pool_test.rs (new), crates/canopy-test-lib/tests/db_cleanup_test.rs (one pin), docs/modules/ROOT/pages/testing.adoc, docs/modules/ROOT/nav.adoc, this page, CHANGELOG.adoc.
db_pool.rs (every fallible function returns Result<_, sqlx::Error>): pool_key(&Migrator, salt: &str) → PoolKey (pure); reuse_enabled() → bool; registry_schema() → &'static str (canopy_test_pool_<sha8>); ReuseTicket { service: String, run_id: String, key: PoolKey, ticket: Uuid } built before mint or lease; ensure_registry(&PgPool) → bool (D1; false = not a superuser); lease(&PgPool, &ReuseTicket) → Leased::{Hit { name, use_count }, Miss}; ensure_pristine(&PgPool, &str) (is_pristine, then wipe if dirty); register(&PgPool, &ReuseTicket, &str) (seeds, ledger, fingerprint, INSERT … state='leased'); release(base_url: &str, name: &str, &ReuseTicket) → Released::{Freed, Dropped(&'static str), NotOwner, NoRow} (D5); drop_if_owner(base_url: &str, name: &str, Option<&ReuseTicket>) (D8); purge_orphan_rows(base_url: &str, run_id: Option<&str>) → PoolReport { purged, free, leased, foreign_leased } and collect_stale_registries(base_url: &str) (consumed by U2); Provenance. CANOPY_TEST_SCHEMA_REUSE_FAULT=probe|wipe|register makes the named step fail (read once; used only by the failure-injection tests).
db.rs:
-
Every constructor path starts with
probe_database_reachable(#2069) exactly as today, before the admin pool. -
create_schema_poolkeeps its public signature for the bare harnesses and becomesmint_schema(admin, service) → namefollowed byopen_scoped(base_url, service, name, reuse: Option<ReuseTicket>) → (PgPool, Arc<SchemaGuard>), the factored-out scoped-pool-plus-guard opener;SchemaGuard::new(name, base_url, reuse)takes the ticket at construction (no interior mutability); theafter_connecthook is unchanged. -
new_for_service: probe →Migrator::new(dir)andpool_keyonce → admin pool →ensure_registry(false, or reuse off → today’s path with the loud line) →lease. -
Hit:
open_scoped(…, Some(ticket))first, thenensure_pristine; a probe or wipe error →pool.close(),compensating_drop(fenced), return the error.measure!withreused=true. -
Miss:
mint_schema→open_scoped(…, Some(ticket))→run_service_migrations(&pool, service, &migrator)(run_migrations_frombecomes a wrapper overrun_migrations_with) →register; a replay or register failure → today’spool.close()+compensating_drop(fenced) + error. -
cleanup_within: afterclose_pool_or_panic, whenguard.reuseis set callrelease()and emit the release record:Freed,Dropped,NotOwner→ setreleased, returnOk;NoRowor anErr→drop_if_ownerwith the ticket (today’s drop, fenced).impl Drop for SchemaGuardandcompensating_dropcalldrop_if_ownerwith the guard’s ticket when one exists; without a ticket they are byte-for-byte today’s behaviour.drop_schemas(the sweep primitive) callsdrop_if_owner(…, None)per schema with the leased-row rule of D8.
Tests. db_pool_test.rs follows the tree’s live-test convention, not the synced digest’s #[ignore] recipe: every test opens with infrastructure_available() and routes any dependency miss through canopy_test_lib::skip_or_panic (#2162 ruling: the battery never passes --run-ignored; kind(test) runs directly under CANOPY_TEST_INFRA=required). Each test sets a unique CANOPY_TEST_SCHEMA_REUSE_SALT so its pool is private inside the ambient run and the battery’s own sweep collects it; each test ends with drop_if_owner over the schemas it created, inside a catch_unwind wrapper so the failure path tears down too. Unit, in db_pool.rs: pool_key_is_deterministic, pool_key_changes_with_any_migration_byte (two temp dirs one byte apart), pool_key_changes_with_the_registry_sql_the_idempotency_ddl_or_the_salt, registry_schema_name_is_derived_from_the_sql_hash. Live: second_constructor_reuses_the_released_schema_with_the_migrated_shape (same name, same information_schema.tables set and ledger count, the first test’s row gone, provenance() == Reused{1}), a_ddl_mutated_schema_is_dropped_on_release_not_reused (ADD CONSTRAINT … CHECK (false)), a_metadata_only_mutation_is_dropped_on_release (ALTER FUNCTION … STRICT, ENABLE ROW LEVEL SECURITY, DISABLE TRIGGER, ALTER COLUMN … SET DEFAULT, each its own case), a_tampered_ledger_is_dropped_on_release, a_stale_pool_key_is_never_leased, a_leased_row_is_never_reused (drop the guard without cleanup(); the fenced backstop drops it), seed_rows_are_restored_with_stable_ids (security), twelve_concurrent_constructors_never_share_a_schema, reuse_disabled_by_env_creates_and_drops_as_before, a_tagged_straggler_forces_drop_instead_of_release, an_untagged_raw_connection_forces_drop_instead_of_release (a PgConnection::connect with options=-c search_path= only, held across cleanup(), the TANF helper’s shape), a_probe_failure_on_a_hit_drops_the_schema_and_its_row and a_register_failure_on_a_miss_drops_the_schema (via CANOPY_TEST_SCHEMA_REUSE_FAULT), a_stale_ticket_cannot_drop_or_wipe_a_schema_another_ticket_holds (lease, release, re-lease from a second constructor, then call drop_if_owner and release with the first ticket → NotOwner, schema and rows intact), the_sweep_does_not_drop_a_free_schema_that_a_concurrent_lease_takes (a drop_schemas pass holding the row lock while a constructor leases → exactly one wins, no dangling lease), a_non_superuser_role_bypasses_reuse_loudly (a throwaway LOGIN role created and dropped by the test; the stderr line asserted). Mutation control per pin is recorded on the MR. The re-pin: db_cleanup_test.rs cleanup_synchronously_drops_the_schema becomes cleanup_releases_or_drops_per_mode — with reuse on and a superuser role it asserts the row is free with leased_by IS NULL and the schema present; with CANOPY_TEST_SCHEMA_REUSE=0 it asserts the schema is gone; in both modes a retained pool clone gets PoolClosed. The other four lifecycle pins pass unchanged.
Acceptance. Every EphemeralSchema::new_for_* caller compiles and passes unchanged; in the integration lane of U1’s own pre-push battery at least 80 % of the [canopy-measure] ephemeral_schema records for applications, security and enrollment carry reused=true (misses are bounded by the 12-thread peak plus fingerprint and straggler drops); the ephemeral_schema_release records show total_ms p50 under 40 ms; cargo xtask check-docs and migrations-lint unchanged; the numbers go in the MR description.
U2 (w2) — chore(xtask): per-run pool report and stale-registry collection in the sweep; perf ephemeral-schema complete rounds; the after numbers
Files: xtask/src/schema_sweep.rs, xtask/src/cmd/perf/ephemeral_schema.rs, docs/modules/ROOT/pages/tooling/xtask-catalog.adoc, this page, CHANGELOG.adoc.
sweep_after_battery_async calls purge_orphan_rows(url, Some(run_id)) per database after its drop passes and prints pool(run=<id>): surviving_leased=0 purged=N — the assertion is on the completed run only; foreign_leased=M (other runs, and crashed runs retained under D4) is reported separately and never fails the battery; manual_sweep prints the same without a run filter and calls collect_stale_registries. perf ephemeral-schema gains --reuse on|off (default on; off sets CANOPY_TEST_SCHEMA_REUSE=0 in its run scope), times complete rounds (construct + cleanup()), discards a warm-up round when reuse is on, tallies provenance() per round, and tears its run down through drop_schemas on every exit path including error and panic. Acceptance. The battery log shows the per-run pool line with surviving_leased=0; perf ephemeral-schema --service applications --parallel 12 --reps 3 reports construct, cleanup and complete-round wall for both modes; the validate lane’s records give the after numbers (recipe under Verification); Closes its child and #1938.
Files touched
| Area | Files |
|---|---|
test-lib |
|
canopy-db |
|
xtask |
|
docs |
|
Must not change |
every |
Verification
| Property | Layer |
|---|---|
The key changes on any migration, idempotency-DDL, registry-SQL or salt byte and on nothing else; the registry name follows the SQL hash |
unit tests in |
Reuse yields the migrated shape; DDL, metadata-only and ledger mutations are dropped; a stale key is never leased; a leased row is never reclaimed; seeds restore with stable ids; twelve concurrent constructors get twelve schemas; env opt-out and non-superuser bypass are loud; tagged and untagged stragglers force a drop; hit-path probe and miss-path register failures compensate; a stale ticket can neither drop nor wipe; the sweep and a concurrent lease never both win |
live tests in |
Every existing lifecycle pin except the one re-pinned still passes; the re-pin asserts per mode |
|
The ~360 callers behave identically; ≥ 80 % reuse on the three largest services; release p50 under 40 ms |
the integration lane of U1’s battery, unchanged tests, the construct and release records |
The after numbers (AC 2) |
|
Catalog churn actually fell |
|
Per push |
the pre-push battery; never |
Filed separately
-
chore(test-lib): a tagged raw-connection helper for the TANF and security chain suites, so their schemas become reusable (today D7 drops them); and a follow-up converting suites that rely on theDropbackstop to an awaitedcleanup()if U1’s hit rate is below the bound (sites that callcleanup().await.ok()do release — the.ok()discards the result after the awaited release).
GitLab
Epic &76 gains two children linked by epic_id: U1 chore(test-lib): reuse released ephemeral schemas through a fenced per-database lease registry (#1938) (w8) and U2 chore(xtask): per-run pool report, stale-registry collection, perf complete rounds and the #1938 after numbers (w2); labels type::chore, priority::high, service::devstack, program::infrastructure, planning::has-plan, workflow::ready, milestone T3. #1938 gets planning::has-plan and a comment linking this page. MR titles match the unit titles. U1’s MR: Closes #2181, Relates to #1938; Status → In progress when it merges. U2’s MR: opened as Draft: first so its !N exists; Closes #2182, #1938; its completion commit sets Done (YYYY-MM-DD) — !N, moves this page into docs/modules/ROOT/pages/plans/archive/ and repoints the nav line, and runs cargo xtask plan-lint --done with --allow-open 2182 --allow-open 1938 — the two issues that MR itself closes, named in the commit message; no other open issue is referenced from this page by number. The MR then leaves draft and merges.
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 (2026-09-18) |
Anthropic (agent-side: a fresh four-question reviewer given only the plan and the rules) |
claude-fable-5-1 |
no-ship — five Q2 blockers (live-test gating convention; registry bootstrap; the ticket reaching the guard, the hit-path opener and the register failure path; the release contract’s |
2 (2026-09-18) |
the maintainer |
maintainer review against the plan and the tree |
no-ship as written — fourteen findings: four P1 (a freed schema could still be dropped by the old guard after a lost acknowledgement or a cancelled cleanup; the wipe ran before the owner check; untagged raw connections escaped the straggler rule; a manual |