Skip to content

3.x.x: Give each integration fixture its own database - #410

Merged
kiwidream merged 5 commits into
3.x.xfrom
kiwidream/isolate-ledger-test-databases
Sep 16, 2026
Merged

kiwidream merged 5 commits into
3.x.xfrom
kiwidream/isolate-ledger-test-databases

Conversation

@kiwidream

@kiwidream kiwidream commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Parallel integration fixtures used separate schemas inside one PostgreSQL database, so they competed for database-scoped advisory locks — migration, order and settlement. The interference was reproduced while qualifying the contract-coverage work in this group: audit_body_normalization timed out on the migration lock because every fixture's migration queued behind the same database-scoped key.

Give each fixture its own database in the targets where that interference was reproduced. A shared helper owns setup and cleanup and preserves the original error across failed setup, cancellation and an unknown CREATE outcome. Schemas and search paths, pool sizes, concurrency, interleavings, timeouts and assertions are all unchanged; production lock and timeout behaviour is untouched.

The supplied test role needs CREATEDB on a disposable PostgreSQL instance.

Verification

Manifest goes 358 → 359 on this base for the new independence regression; combined with the other two branches in this group it is 366.

  • Independent review covers the conversions, cancellation, collision and cleanup failures. A lost-CREATE-reply probe reproduced a leak in an earlier version of the helper and confirms its correction; that earlier version was rejected in review for aliasing the helper's single-connection maintenance pool.
  • After conversion, audit_body_normalization passes 15/0/1 at default concurrency in 69.9 s, with sampled migration-key holds spread across 12 distinct fixture databases and zero waiters, and nothing left behind.
  • ledger_postgres passes 112/0 at default concurrency, with zero leftover fixture databases or backends.
  • A new gated regression proves independence between fixtures and contention within a fixture.
  • The expensive measurement stays opt-in; its pg_locks watcher remains cluster-wide and unfiltered as before, and a bounded 4,000-share control through the new pool still observes a nonzero settlement hold.
  • Rust 1.98.1 cargo fmt --all --check and cargo clippy --locked --workspace --all-targets -- -D warnings: clean.

Superseded commit

15bafb7f fixed a second failure found during qualification: pg_restore's SQL clears the session search_path, and returning that connection to the fixture pool could break a later schema-qualified DELETE whose trigger body resolves unqualified ledger tables. #391 landed a fix for the same root cause first, restoring search_path inside the transaction, so this branch's merge takes the upstream version and support/recovery.rs does not appear in this diff. The commit is kept in history as a superseded attempt.

Worth a separate issue: pg_restore also emits SET statement_timeout = 0, SET lock_timeout = 0 and SET idle_in_transaction_session_timeout = 0, which the upstream fix still returns to the pool. lock_timeout = 0 is the one that could matter, since these fixtures set a lock timeout.

Residual risk

Other upstream targets that still use shared-schema fixtures — audit_completeness and compact_issued_repair among them — did not reproduce advisory-lock interference in either full native run, so they were left unconverted.

Scope of the runtime evidence. The runs cited above were executed on the combined tree built from cff94df5, before #369, #378 and #318 landed. That tree's full native run exited 0 in 906 s with 1,039 passed and all 304 expected gate IDs executed. Every static check has since been re-run on the merged tree — including a full cargo check --all-targets with zero warnings, which matters here because #391 and #401 rewrote parts of readiness_rpc.rs, window_reference.rs, candidate_window_migration.rs and ledger_deadline_atomicity.rs, all files this branch also edits. The native runtime qualification has not yet been repeated on the post-merge tree; CI's gate proof runs it on the real merge.


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Resolve the restore-session overlap in favour of the fix that landed upstream:
pg_restore SQL clears session search_path, and 3.x.x now restores it inside the
same transaction before the connection returns to the pool. Keep both sides of
the ledger_postgres module declarations.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T13:35:33.524556Z cfd6734 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@kiwidream
kiwidream merged commit 54c0f88 into 3.x.x Sep 16, 2026
20 checks passed
kiwidream added a commit that referenced this pull request Sep 17, 2026
…nance (#438)

* Scaffold the native candidate-storm suite and its one cardinality reader (#270)

The storm scenarios split across four targets by the seam each needs, because
`candidates::faults` and `Coordinator::offer_probe` are `#[cfg(test)]` and so
are invisible to an integration test, while `CARGO_BIN_EXE_*` exists only in
an integration target. Two new `#[cfg(test)]` module declarations are the only
production lines this issue adds; the four test files are empty frames their
writers fill.

`PRISM_TEST_STORM_CANDIDATES` sizes every scenario from one reader, so the
reduced cardinality the native PostgreSQL job runs and the incident's 3,120
cannot drift apart. It is not a gate variable: the gate decides whether a test
runs, this decides how large it is, so every storm test executes in both paths
and none is `#[ignore]`d. Values below the CI default are refused rather than
quietly measuring less than CI already proves.

Refs #270

* Re-pin the storm scaffolding and require one database per fixture (#270)

The base moved seven commits. Two of them change this suite's design rather
than its line numbers.

#410 gave each integration fixture its own PostgreSQL database, because
advisory locks are database-scoped and fixtures sharing a database queued on
each other's migration, order and settlement keys. For this suite that is
load-bearing: a drain of thousands of siblings takes one claim each, every
claim touches the ordering and settlement keys, and a per-row cost measured in
a shared database measures other fixtures' lock waits instead of the drain. It
also sharpens the counting invariant over a wall-clock one, since with the
database isolated the claim and statement counts are clean while wall clock
still carries the runner's noise.

#412 added a registration mode that runs every startup gate but writes no
`starting` heartbeat, so the restart frame now says to be deliberate about
which constructor the relaunched child uses and what the instance table should
hold afterwards.

The offer-evidence module records why it is empty: #415 may add a terminal
disposition for a proven orphan, which would change what a reconciliation row
can become, and assertions written before that decision would be written
against a rule that is about to change.

Refs #270

* 3.x.x: pin the lost tip race and settle proven orphans terminal (#415)

Part of #413, the 2026-09-16 mainnet orphan stall: the 2.x.x coordinator
held all job delivery for 307 s after one of its own blocks lost a tip
race. 3.x.x cannot stall that way, because the block becomes a
`reconciliation` row and issuance never reads candidate state. Two gaps
remained, and this closes both.

The pin (tests/lost_race_pin.rs, Postgres-gated). A real Coordinator against
a scripted node reproduces the race exactly: submitblock returns null, our
hash is the best tip, the node reorgs to a same-height competitor inside
100 ms, and the tip advances two further heights. It asserts the row lands
in reconciliation with the not-active reason and its accepted offer, that
submitblock was called exactly once, that the landed audit survives, that
the block-only proof is neither credited nor failed while the block can
still become active, and that new work for each new tip is issued within
2 s of the tip becoming visible while the orphan row is claimed by a live
lease and held under FOR UPDATE (measured at ~60 ms; the incident's number
was 307 s). It passes on the tree that introduces it; it fails only if
issuance is ever coupled to candidate state.

The disposition. Reconciliation rows were retried forever and every
unfinished row counted toward qbit_prism_block_candidates_pending and
qbit_prism_block_candidate_oldest_pending_seconds, so a handful of orphans
kept the migrated pending-candidate alerts firing permanently. After the
post-offer landing, one coherent tip observation that shows a DIFFERENT
block active at the candidate's height with at least
PRISM_CANDIDATE_ORPHAN_CONFIRMATIONS confirmations (new setting, default 6,
1..=1000; confirmations are tip_height - height + 1 from the observed tip)
now settles the row terminal as `orphaned`:

* Ledger::orphan_candidate_at_revision reuses the existing fences and adds
  no lock: settlement and order locks, the payout revision the observation
  was taken at (a reorg reconciler that confirmed the block meanwhile bumped
  it, so a stale "not active" verdict cannot overwrite a newer "active"
  one), the strictly-live claim token, and the block's own qbit_pool_blocks
  row, which must not be confirmed. State, reason, completed_at and the
  block's `inactive` chain state are one transaction. Never from pending.
* The row keeps its document, block bytes, window reference and offer
  record (an operator surface for #268 can show what was offered and why);
  it is never claimed, offered or retried again. The pending gauges use
  CandidateState::UNFINISHED_SQL and stop counting it; the new counter
  qbit_prism_block_candidates_orphaned_total is incremented once the
  settlement committed, never on a failed observation, which still settles
  the row back into reconciliation (unknown stays distinct from zero).
* Reactivation: the block keeps its landed audit and its pool block, so the
  ordinary reorg reconciler (Ledger::reconcile_blocks_in) confirms it and
  credits its deferred share from that preserved evidence if the chain ever
  reactivates it. The terminal row never reopens; tested end to end.
* The block-only acknowledgement path (miner_submit.rs) answers a share on
  an orphaned block `ledger-confirmation-failed`, like an abandoned one.

Migration 015 replaces 011's three lifecycle CHECKs under their own names,
only after deparsing 011's definitions and finding them unchanged, and
declares candidate_orphan_disposition = 1 so a pre-015 binary, which has no
name for the state, refuses the database at connect (mixed-version rollout
is rejected explicitly). Old rows are not rewritten. REQUIRED_SCHEMA_VERSIONS,
NATIVE_MIGRATIONS, NATIVE_CAPABILITIES and the declared-capability gate
learn 15, and so do the test supports (undo helpers, version sets, the
capability restores, the 013 online-migration cases) and the recovery
evidence scripts, which treat `orphaned` as terminal while still exporting
its balance snapshot. The in-flight-registration fixture in
offer_lifecycle.rs polls for the migrator's lock wait for 15 s instead of
3 s: the scratch apply of every native migration is ~12% longer with 015
and the old budget was no longer met with four tests queued on the
migration lock; the assertion is unchanged.

Tests: the four lost_race_pin contracts (the pin, the disposition with its
reactivation, the ordering mirror of
stale_candidate_active_proof_cannot_overwrite_a_newer_reorg, and the failed
observation), the 015 lifecycle shapes and a terminal-orphan ledger contract
in offer_lifecycle, and the migration_rollback offer-recovery fingerprints
extended with the orphaned state (its evidence stays visible to a restore
and it no longer counts as unfinished). All are listed in
test/prism-gated-tests.txt.

Docs: prism-native-metrics.md (regenerated inventory plus the gauge
exclusion and counter contract), prism-alert-migration.md (pending-candidate
rule guidance), prism-rejections.md, prism-ledger-ops.md (the state table)
and the crate README setting row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* 3.x.x: Prove drain cost and admission at storm cardinality (#270)

The 2026-08-20 testnet4 incident left 3,120 durable block candidates behind
one decided height. 2.x.x measured that sibling set with a Python instrument
#244 deleted; this fills the native target with the properties, not the
harness.

Four gated scenarios, every asserted quantity an integer from a counter the
test owns:

- the clean baseline drain: N siblings at one decided height, one of them the
  block the node reports active, through the real claim path. Chain calls are
  exactly six per drained row (`CHAIN_PROBES_PER_SIBLING`, derived from the
  native pre-offer path and pinned with what each call is), `submitblock` is
  exactly once for each hash offered and zero for every hash that was not, the
  dispatch-sequence delta and `SUM(attempt_count)` both equal the claims made,
  and the abandoned set *is* the sibling set while the decided height's own
  block stays pending without offer evidence. Brand-new work is admitted,
  offered and landed three times while the backlog is still owed;
- statements per drained row on the wire, through
  `support/ledger_execution_proxy.rs`, asserted equal at the baseline
  cardinality and at the run's own in one process against one schema, then
  against a pinned 26 whose comment names all four transactions. That equality
  is what makes the reduced-N CI path prove what a local run at 3,120 proves;
- the two claim lanes and the dispatch probe keep their partial indexes over N
  *unfinished due* rows beside 50,000 retained ones, with no `Seq Scan` and no
  `Sort`, EXPLAINing the statements `Ledger` returns rather than a copy; and
  one claim under `ANALYZE, BUFFERS` reads one row and discards none, so
  per-claim work does not walk the siblings;
- admission against a backlog of N: the fresh lane returns the block just
  found, by hash, for thirty-two rounds, and the oldest-due lane still serves
  both an old never-attempted row and a due retry, so neither lane starves the
  other.

The fixture takes its own PostgreSQL database through
`support/ledger_database.rs` (#410). That is load-bearing rather than
hygienic: a drain of N siblings is N claims, each touching the ordering and
settlement keys, so a per-row cost measured in a shared database would be
measuring other fixtures' lock waits.

Nothing asserts a duration. Wall clock, microseconds per row, the plan's
shared buffer counts and both cardinalities are recorded under
`storm_scale::record` and never asserted. Cardinality comes from the one
shared reader; its first consumer also proves its floor, ceiling and malformed
refusals in a plain test that needs no database and is therefore not gated.

No production code, schema or metric family changes.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Record the dispatch probe's plan instead of asserting it at storm size (#270)

The incident-cardinality run found what the reduced-N run cannot: at 3,120
unfinished rows PostgreSQL stops using 011's partial index for the dispatch
probe and takes a sequential scan, and it does so even when nothing is due.

The probe compares `next_attempt_at` against `clock_timestamp()`, which is
volatile, so no histogram applies and the planner falls back to roughly a third
of the indexed rows: about 1,035 estimated matches at 3,120 unfinished rows. It
concludes an `EXISTS` will hit one almost at once and charges the scan's startup
cost as near zero. At 24 or 100 rows the same estimate is small enough that the
index wins, which is why the original assertion passed in the required job and
failed only here.

When rows really are due the gamble pays. The damaging case is a pool left idle
behind a storm, thousands of unfinished rows all backing off and none due, where
that plan reads the whole outbox including retained terminal history on every
poll to prove nothing is due -- a per-poll cost that grows with retained
history, in exactly the state this suite exists to study, and one 011's index
cannot prevent because the planner declines to use it.

That is a finding about the server, not about the test, so the probe's plan is
recorded at the run's cardinality rather than asserted away. The guarantee is
asserted where it holds: trimming the unfinished set to the baseline restores
the index scan over the same table, the same index and freshly analysed
statistics, so the recorded pair is direct evidence that the flip follows
unfinished cardinality and not a missing index. Both claim lanes keep their
index scans at 3,120 and are still asserted at every cardinality.

Per-row drain cost is unaffected and remains independent of N: six chain calls
and twenty-six wire statements per drained row, equal at the baseline and at
3,120.

Refs #270

* Add native candidate restart coverage and map remaining storm gaps (#270)

* Run local database storm scenarios at incident cardinality (#270)

* Forward and validate the candidate orphan confirmation threshold

* Harden orphan settlement, migration safety, and reactivation accounting

* 3.x.x: pin the lost tip race and settle proven orphans terminal (#415)

Part of #413, the 2026-09-16 mainnet orphan stall: the 2.x.x coordinator
held all job delivery for 307 s after one of its own blocks lost a tip
race. 3.x.x cannot stall that way, because the block becomes a
`reconciliation` row and issuance never reads candidate state. Two gaps
remained, and this closes both.

The pin (tests/lost_race_pin.rs, Postgres-gated). A real Coordinator against
a scripted node reproduces the race exactly: submitblock returns null, our
hash is the best tip, the node reorgs to a same-height competitor inside
100 ms, and the tip advances two further heights. It asserts the row lands
in reconciliation with the not-active reason and its accepted offer, that
submitblock was called exactly once, that the landed audit survives, that
the block-only proof is neither credited nor failed while the block can
still become active, and that new work for each new tip is issued within
2 s of the tip becoming visible while the orphan row is claimed by a live
lease and held under FOR UPDATE (measured at ~60 ms; the incident's number
was 307 s). It passes on the tree that introduces it; it fails only if
issuance is ever coupled to candidate state.

The disposition. Reconciliation rows were retried forever and every
unfinished row counted toward qbit_prism_block_candidates_pending and
qbit_prism_block_candidate_oldest_pending_seconds, so a handful of orphans
kept the migrated pending-candidate alerts firing permanently. After the
post-offer landing, one coherent tip observation that shows a DIFFERENT
block active at the candidate's height with at least
PRISM_CANDIDATE_ORPHAN_CONFIRMATIONS confirmations (new setting, default 6,
1..=1000; confirmations are tip_height - height + 1 from the observed tip)
now settles the row terminal as `orphaned`:

* Ledger::orphan_candidate_at_revision reuses the existing fences and adds
  no lock: settlement and order locks, the payout revision the observation
  was taken at (a reorg reconciler that confirmed the block meanwhile bumped
  it, so a stale "not active" verdict cannot overwrite a newer "active"
  one), the strictly-live claim token, and the block's own qbit_pool_blocks
  row, which must not be confirmed. State, reason, completed_at and the
  block's `inactive` chain state are one transaction. Never from pending.
* The row keeps its document, block bytes, window reference and offer
  record (an operator surface for #268 can show what was offered and why);
  it is never claimed, offered or retried again. The pending gauges use
  CandidateState::UNFINISHED_SQL and stop counting it; the new counter
  qbit_prism_block_candidates_orphaned_total is incremented once the
  settlement committed, never on a failed observation, which still settles
  the row back into reconciliation (unknown stays distinct from zero).
* Reactivation: the block keeps its landed audit and its pool block, so the
  ordinary reorg reconciler (Ledger::reconcile_blocks_in) confirms it and
  credits its deferred share from that preserved evidence if the chain ever
  reactivates it. The terminal row never reopens; tested end to end.
* The block-only acknowledgement path (miner_submit.rs) answers a share on
  an orphaned block `ledger-confirmation-failed`, like an abandoned one.

Migration 015 replaces 011's three lifecycle CHECKs under their own names,
only after deparsing 011's definitions and finding them unchanged, and
declares candidate_orphan_disposition = 1 so a pre-015 binary, which has no
name for the state, refuses the database at connect (mixed-version rollout
is rejected explicitly). Old rows are not rewritten. REQUIRED_SCHEMA_VERSIONS,
NATIVE_MIGRATIONS, NATIVE_CAPABILITIES and the declared-capability gate
learn 15, and so do the test supports (undo helpers, version sets, the
capability restores, the 013 online-migration cases) and the recovery
evidence scripts, which treat `orphaned` as terminal while still exporting
its balance snapshot. The in-flight-registration fixture in
offer_lifecycle.rs polls for the migrator's lock wait for 15 s instead of
3 s: the scratch apply of every native migration is ~12% longer with 015
and the old budget was no longer met with four tests queued on the
migration lock; the assertion is unchanged.

Tests: the four lost_race_pin contracts (the pin, the disposition with its
reactivation, the ordering mirror of
stale_candidate_active_proof_cannot_overwrite_a_newer_reorg, and the failed
observation), the 015 lifecycle shapes and a terminal-orphan ledger contract
in offer_lifecycle, and the migration_rollback offer-recovery fingerprints
extended with the orphaned state (its evidence stays visible to a restore
and it no longer counts as unfinished). All are listed in
test/prism-gated-tests.txt.

Docs: prism-native-metrics.md (regenerated inventory plus the gauge
exclusion and counter contract), prism-alert-migration.md (pending-candidate
rule guidance), prism-rejections.md, prism-ledger-ops.md (the state table)
and the crate README setting row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Forward and validate the candidate orphan confirmation threshold

* Harden orphan settlement, migration safety, and reactivation accounting

* Test native candidate cleanup faults and offer provenance

* Map native storm recovery and provenance coverage

* Enforce reader password authentication in native test fixtures

---------

Co-authored-by: Dan Hepworth <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 1, 2026
…rations cannot time out its setup (#603) (#641)

The rollups::tests fixture created a schema in the shared test database and
ran Ledger::connect(.., true) there. Migration takes MIGRATION_LOCK
(0x505249534d000001) with pg_advisory_xact_lock, and advisory locks are
scoped to the database, not the schema, so every fixture in the lib binary
that migrates into that database queues on one key under the ledger pool's
5 s lock_timeout. On a loaded host the queue passed 5 s and setup failed
with a bare "canceling statement due to lock timeout", which is what #603
recorded. The server log of a reproduction showed the timed-out statement
was the rollup fixture's SELECT pg_advisory_xact_lock($1), sixth in a queue
of other fixtures' migrations.

The fixture now opens a per-case database with the shared
FixtureDatabase helper (#410's fix for the same class of contention), keeps
its schema name as the application_name the cases look up in
pg_stat_activity, and attaches setup context to the connect/migrate step.
The test error now keeps any cleanup failure as context instead of dropping
it. No assertion, timeout or production lock_timeout changes.

Holding MIGRATION_LOCK in the gate database from a second session, the
base fails both #603 cases 3/3 with that error; with this change they pass
20/20 and all 11 rollups::tests pass 5/5.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant