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 DEFINER functions whose proconfig bakes 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 Drop backstop, compensating_drop and sweep primitive, the measurement records for construct and release, the opt-outs, unit and live tests, the testing.adoc section, this page.

  • U2: the post-battery and manual sweeps report per-run pool state and collect stale registries; cargo xtask perf ephemeral-schema gains --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_parts and raw CREATE SCHEMA in crates/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 -p with 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 canopy_test_pool_<sha8> where sha8 is the first eight hex digits of sha256(registry.sql); it never matches the sweep’s test_% or %\_<run16>\_% patterns. It holds leases(schema_name PK, service, run_id, pool_key, fingerprint, seeds jsonb, ledger_rows int, ledger_head bigint, state free|leased, leased_at, leased_by uuid, created_at, use_count), an index on (service, run_id, pool_key, state), and the plpgsql functions wipe(nsp), is_pristine(nsp), snapshot_seeds(nsp), fingerprint(nsp), drop_if_owner(nsp, ticket). The DDL is crates/canopy-test-lib/src/db_pool/registry.sql (new, include_str!); ensure_registry applies it with CREATE … IF NOT EXISTS under pg_advisory_xact_lock(9997) — idempotent, no upgrade path, because a different SQL is a different registry. Two checkouts with different test-lib versions therefore share nothing; the sweep collects a registry whose rows are all older than the evidence floor and none leased (U2). 9997 is registered in the lock-number comment of crates/canopy-db/src/idempotency_schema.rs (1, 2, 9998 retired, 9999 in use).

D2

Pool key = the invalidation rule. pool_key = sha256("canopy-test-pool/v1" ‖ sha256(registry.sql) ‖ sha256(canopy_db::idempotency_schema::ddl_text()) ‖ CANOPY_TEST_SCHEMA_REUSE_SALT ‖ for every migration in version order: version, description, type, no-tx flag, sqlx checksum). sqlx’s checksum is Sha384(sql bytes), so any byte of any migration file, of the idempotency DDL or of the wipe/fingerprint SQL changes the key; a row with another key is never leased and ages out through the sweep. The salt (empty by default) lets a test-lib test own a private pool inside the ambient run, so the battery’s own sweep collects it. The Migrator and the key are computed once, before the constructor branches, and the same Migrator is passed to the replay (run_migrations_with(pool, &Migrator)).

D3

Lease is one statement, scoped by run (listing below). run_id is the ambient run16 or local, the value the COMMENT stamp already carries, so a battery leases only schemas it minted and a concurrent local run never touches them. FOR UPDATE SKIP LOCKED on the picked row means two processes cannot obtain one schema, and a sweep that holds the row lock (D8) is skipped rather than raced.

D4

A leased row is never reclaimed by a lessee. A crashed or killed test leaves state='leased'; only the sweep (D8) drops such a schema. No TTL, no zombie-owner race; the cost is one extra create per crashed test, which is today’s cost.

D5

Release is one fenced transaction, on the admin connection. BEGIN; SELECT leased_by FROM leases WHERE schema_name = $1 FOR UPDATE — absent row → NoRow; leased_by <> $ticket → NotOwner, ROLLBACK, walk away; owned → SET LOCAL session_replication_role = replica; SET LOCAL search_path = pg_catalog, pg_temp; SELECT wipe($1) (DELETE from every base table except _sqlx_migrations, order-independent: with the role set to replica every trigger whose tgenabled = 'O' is skipped, which is all 30 user triggers including the append-only redaction_keys and action_signals guards and every RI trigger; no migration declares ENABLE ALWAYS or ENABLE REPLICA; then pg_clear_relation_stats / pg_clear_attribute_stats for analyzed tables; then the seed rows restored from leases.seeds), then fingerprint($1) compared with the stored value and the ledger checked (count(*) and max(version) of _sqlx_migrations equal ledger_rows/ledger_head), then the straggler rule (D7); all equal and clean → UPDATE … SET state='free', leased_at=NULL, leased_by=NULL, COMMIT → Freed; otherwise DROP SCHEMA … CASCADE; DELETE FROM leases …; COMMIT → Dropped(reason). The row lock is held from the owner check through the commit, so the wipe never touches a schema this ticket does not own, and a cancelled cleanup rolls back to the leased state. DELETE, never TRUNCATE: a truncate allocates a new relfilenode per relation, which is the file churn being removed. The lease then runs is_pristine (one EXISTS per non-ledger table, jsonb equality on the seed tables, the ledger check; ~3–6 ms) and wipes again only if dirt is found.

D6

Fingerprint = the migrated-shape guarantee. fingerprint(nsp) is md5(string_agg(row ORDER BY row)) over, for the namespace: pg_class (name, kind, persistence, owner, acl, options, relrowsecurity, relforcerowsecurity, relreplident, relispartition), pg_attribute (+ defaults via pg_attrdef, attidentity, attgenerated, attcompression, attacl), pg_constraint (pg_get_constraintdef, validity), pg_index (pg_get_indexdef, validity), pg_trigger (tgenabled, pg_get_triggerdef), pg_policy (polcmd, polpermissive, roles, pg_get_expr of qual and check), pg_rewrite rules, pg_proc via pg_get_functiondef (the whole definition: strictness, volatility, parallel safety, security, SET config, body) plus owner and acl, enum labels, domain constraints, composite attributes, view definitions, pg_statistic_ext, pg_inherits, and the namespace owner/acl; _sqlx_migrations excluded; run with search_path = pg_catalog. Computed once after a fresh replay and stored; compared at release. A fault-injection test that adds a constraint, a poison trigger or an index, renames a column, creates a table, or changes metadata only (ALTER FUNCTION … STRICT, ENABLE ROW LEVEL SECURITY, ALTER COLUMN … SET DEFAULT, DISABLE TRIGGER) fingerprints differently → Dropped. ~5–10 ms.

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 PgConnection::connect with search_path only, as the TANF and security chain suites do). At release, after a 100 ms re-check (the process’s own just-closed backends can linger for milliseconds), any client backend in this database other than the releaser that either carries this schema’s name in application_name or is untagged (application_name not of the form canopy-test:<service>:<schema> nor canopy-test-admin:<purpose>) and whose backend_start >= leased_at → Dropped("straggler"). Service containers' pools started before any lease; other tests' fixture pools are tagged with their own schema; so the rule costs a reuse only for tests that open raw connections during their own run.

D8

Every destructive path is fenced. drop_if_owner(nsp, ticket) is one transaction: SELECT leased_by … FOR UPDATE; absent row → plain DROP SCHEMA IF EXISTS … CASCADE (an unpooled or legacy schema); leased_by = ticket (or ticket IS NULL and state = 'free', the sweep’s form) → DROP + DELETE the row; any other owner → no-op. The Drop backstop (impl Drop for SchemaGuard), compensating_drop and the cleanup fallback call it with the guard’s ticket when one exists and behave exactly as today otherwise. drop_schemas (the sweep primitive in db.rs) calls it per schema with ticket = NULL and additionally refuses a leased row unless the caller is the current run’s unconditional pass (which runs after every lane) or the row’s lessee has no live backend and the row is older than the sweep’s threshold; a lessee blocked on the row lock finds the row gone. This closes the lost-acknowledgement drop, the cancelled-cleanup drop and the manual --older-than sweep race.

D9

Seeds and ledger. Right after a fresh replay every non-empty table except _sqlx_migrations is snapshotted into leases.seeds ({table: [rows]}) and the ledger’s row count and head version into ledger_rows/ledger_head; today the seeds are only canopy-security’s nist_control_mappings (11), detection_rules (6) and the audit_archive_schedule singleton. Restored verbatim on every wipe, so ids are stable across reuses (a fresh replay gives different random ids each time, so nothing can depend on them) and next_due_at ⇐ now() still means "due now". The ledger is never wiped, restored or snapshotted; it is validated by count and head.

D10

Hit path arms ownership first; opt-outs fall back loudly. On a lease hit the SchemaGuard is constructed with the ticket before ensure_pristine runs, so a probe or wipe failure takes compensating_drop (fenced) and returns the error; a register failure on the miss path does the same. ensure_registry returns false when current_setting('is_superuser') is off (the replica role setting is superuser-only) and the constructor takes today’s path after one eprintln!("[canopy-test] schema reuse off: role is not a superuser") per process; CANOPY_TEST_SCHEMA_REUSE=0 does the same fleet-wide with its own line. POOL_MAX_USES = 256 and POOL_MAX_AGE = 5 h bound heap bloat and age: past either, release drops.

D11

Measurement on both ends. The measure!("ephemeral_schema", …) record keeps create_ms and replay_ms and gains reused=<bool> and use_count=<n>; on a hit replay_ms is the lease + probe time. A new measure!("ephemeral_schema_release", service, schema, outcome, wipe_ms, fingerprint_ms, total_ms) is emitted by cleanup_within, so release work cannot hide from the numbers. EphemeralSchema::provenance() → Provenance::{Fresh, Reused{use_count}} is public. Names stay test_<run16>_<hex12> so every existing grep, stamp and sweep rule holds.

Lease (D3), run on the admin connection in autocommit
-- $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;
Release (D5, D7) and fenced drop (D8) — the row lock is taken before anything destructive
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_timeout with the row still leased); the suites that open search_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, never TRUNCATE". A DELETE wipe leaves heap and index pages behind (no VACUUM inside 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 an EXPLAIN pin flipped. As built, the wipe TRUNCATEs — 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 and pg_class churn is bounded by what one test used, not by the schema’s ~135 relations; the pg_attribute/pg_depend/pg_constraint churn 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, tagged canopy-test:<service>:<schema>:<purpose>, so the release counts it precisely (still open → Dropped("straggler"), closed → Freed); db_pool::RAW_CONNECTION_SUITES keeps only the bare-schema harnesses and db_replay_test (whose concurrency pin needs the replay), and the tree pin fails on any new untagged search_path connection.

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_pool keeps its public signature for the bare harnesses and becomes mint_schema(admin, service) → name followed by open_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); the after_connect hook is unchanged.

  • new_for_service: probe → Migrator::new(dir) and pool_key once → admin pool → ensure_registry (false, or reuse off → today’s path with the loud line) → lease.

  • Hit: open_scoped(…, Some(ticket)) first, then ensure_pristine; a probe or wipe error → pool.close(), compensating_drop (fenced), return the error. measure! with reused=true.

  • Miss: mint_schema → open_scoped(…, Some(ticket)) → run_service_migrations(&pool, service, &migrator) (run_migrations_from becomes a wrapper over run_migrations_with) → register; a replay or register failure → today’s pool.close() + compensating_drop (fenced) + error.

  • cleanup_within: after close_pool_or_panic, when guard.reuse is set call release() and emit the release record: Freed, Dropped, NotOwner → set released, return Ok; NoRow or an Err → drop_if_owner with the ticket (today’s drop, fenced). impl Drop for SchemaGuard and compensating_drop call drop_if_owner with the guard’s ticket when one exists; without a ticket they are byte-for-byte today’s behaviour. drop_schemas (the sweep primitive) calls drop_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

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, crates/canopy-test-lib/tests/db_pool_test.rs (new), crates/canopy-test-lib/tests/db_cleanup_test.rs

canopy-db

crates/canopy-db/src/idempotency_schema.rs (additive ddl_text(), registry comment)

xtask

xtask/src/schema_sweep.rs, xtask/src/cmd/perf/ephemeral_schema.rs

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//migrations/.sql; the 19 sqlx::migrate! embeds; crates/canopy-api/src/bootstrap.rs; xtask/src/cmd/migrate.rs; ensure_idempotency_schema and its bigint lock; .config/nextest.toml; docker-compose.yml; every service test; the reachability probe’s position; the after_connect hook

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 db_pool.rs

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 crates/canopy-test-lib/tests/db_pool_test.rs

Every existing lifecycle pin except the one re-pinned still passes; the re-pin asserts per mode

crates/canopy-test-lib/tests/db_cleanup_test.rs

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)

grep -ho '\[canopy-measure\] ephemeral_schema[^<]*' test-results/validate/results.xml → per service: construct replay_ms p50/p95, release total_ms p50/p95, reused=true share; the integration lane’s wall from test-results/validate-report.json for U1’s battery against the last pre-U1 battery on the same host; cargo run --release -p xtask — perf ephemeral-schema --service applications --parallel 12 --reps 3 --reuse off vs --reuse on complete-round wall

Catalog churn actually fell

pg_stat_sys_tables.n_tup_ins on pg_attribute/pg_depend/pg_constraint in canopy_applications before and after one battery (recorded on #1938)

Per push

the pre-push battery; never --no-verify

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 the Drop backstop to an awaited cleanup() if U1’s hit rate is below the bound (sites that call cleanup().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 leased_by reset, no-row arm and delete owner; a numeric U1 acceptance) fixed in-plan, plus the straggler re-check, the per-mode re-pin, the .ok() correction, loud fallbacks and U1’s weight

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 --older-than sweep could drop a schema a concurrent constructor leased) and ten P2 (fingerprint missed function strictness/volatility, RLS and policies; registry upgrades raced other versions; the hit path leased before arming cleanup; the seed snapshot included the migration ledger; the reachability probe moved behind the admin acquire; the Migrator was built after branching; private-salt tests and the perf harness left schemas behind; release work escaped the measurement; the database-wide leased=0 gate; the completion gate and a non-repo-relative path) — all resolved: fenced single-transaction release and drop_if_owner on every destructive path including the Drop backstop, the untagged-backend rule, hash-versioned registries, pg_get_functiondef/policy/rule coverage, ledger exclusion and validation, probe-first ordering, hoisted key, salted private pools with teardown, release records and complete-round timing, per-run reporting, and the --allow-open completion sequence; no round 3

Edit this page · default