Skip to content

3.x.x: Keep one-shot operator commands out of frontend heartbeat registration - #412

Merged
Anatolie merged 3 commits into
3.x.xfrom
tool-heartbeat-registration
Sep 16, 2026
Merged

Anatolie merged 3 commits into
3.x.xfrom
tool-heartbeat-registration

Conversation

@Anatolie

@Anatolie Anatolie commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Closes #381. Part of #260; follows #360 (audited fatal-state recovery) and #362 (heartbeat writers).

Problem

self-check, import-audits, backfill-ctv and broadcast-ctv connected through the frontend constructors, so every invocation registered a starting heartbeat that nothing ever attested stopped. With PRISM_INSTANCE_ID unset each run generated a UUID and left a row that fatal-state clear refuses, with no process left to follow the recovery runbook. With a configured ID the registration overwrote the live frontend's status and session-owner token.

Change

  • Ledger::connect_tool and Coordinator::new_tool: a third registration mode beside the frontend (connect/new) and the recovery operator (connect_operator). The startup gates are unchanged: schema version, declared capabilities, migration source, the halt guard (writable) and the cluster fingerprint. The only difference is that no heartbeat is written. The private Registration enum in ledger/connect.rs makes the three modes explicit.
  • The four commands in tools.rs use the new constructors. broadcast-ctv keeps its token-fenced claims; claim_instance_id still names the process. Command outputs are unchanged.
  • No stale-row deletion, no heartbeat-age override, no change to fatal-state triggers, no repair of existing rows: a starting row left by an earlier 3.x.x build is still refused and the runbooks say so.

Tests

  • ledger_postgres::fatal_state::one_shot_tools_register_no_heartbeat_and_keep_the_halt_guard (new, gated, listed in test/prism-gated-tests.txt): runs the four commands with a generated ID and with a live frontend's ID, asserts the row count and the frontend's row (status, session-owner token, heartbeat time) are unchanged after each, asserts all four still refuse a halted cluster, then stops the real frontend and clears the halt with its audit record. Reverting the four call sites to the registering constructors makes it fail at import-audits registered a row.
  • self_check_cli::postgres_self_check_samples_before_local_startup_and_reports_missing_table: the assertion that the diagnostic overwrote the seeded legacy health payload with starting is inverted. The row is byte-identical afterwards, and a generated ID leaves no row.

Runbooks

docs/prism-ledger-ops.md (fatal-state "stop every frontend" step and the CTV section), docs/prism-ha-reference-architecture.md (self-check sample), docs/prism-rust-migration.md (import/backfill) and doc/release-notes-3.0.0.md.

Verification

Local, against a disposable PostgreSQL 16 (fsync and full_page_writes on), with PRISM_TEST_PG_BIN_DIR set and the gate manifest enabled:

  • cargo test --locked -p qbit-prism-server --all-targets --no-fail-fast -- --test-threads=4: 793 passed. The 9 live_regtest tests fail locally by design (no QBITD_BIN), and 5 tests in compact_issued_repair, compact_prepared_storage, offer_lifecycle and window_reference hit the migrate advisory-lock timeout under parallel load; all 5 pass on rerun (window_reference at one thread). None of those binaries touch the changed constructors.
  • scripts/check_gate_manifest.py: 347 of 359 gated tests executed; the missing 12 are the 9 live_regtest tests, the 2 observability_database tests and the #[ignore] stratum_admission_postgres soak, the known local baseline.
  • ledger_postgres fatal_state:: (12 tests, including the new one) and self_check_cli (5 tests) pass. migration_rollback, which drives the import-audits CLI, passes.
  • Non-vacuity: with the four call sites reverted to Coordinator::new / Ledger::connect, the new regression fails at import-audits registered a row (left: 2, right: 1) and the self-check test fails at self-check changed the live frontend's row.
  • cargo fmt --all --check and cargo clippy --locked --workspace --all-targets -- -D warnings are clean.

🤖 Generated with Claude Code


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

Anatolie and others added 3 commits September 16, 2026 09:44
…n (3.x.x)

self-check, import-audits, backfill-ctv and broadcast-ctv connected through
the frontend constructors, so every invocation registered a starting
heartbeat that nothing ever attested stopped: a generated instance ID left
a row fatal-state clear refuses, and a configured one overwrote the live
frontend's status and session-owner token.

Add Ledger::connect_tool and Coordinator::new_tool, a third registration
mode beside the frontend and the recovery operator: the same startup gates
(schema version, declared capabilities, migration source, halt guard and
cluster fingerprint) with no heartbeat write. Claims a tool takes remain
fenced by their own tokens.

Part of #260, follows #360 (fatal-state recovery) and #362 (heartbeat
writers). Refs #381.
…n-registering tools

The self-check CLI test asserted the leftover starting heartbeat the old
constructor wrote over the seeded legacy health payload. It now proves the
opposite: the frontend's row, session-owner token included, is byte-identical
after the diagnostic ran under its ID, and a generated ID leaves no row at
all. The slow-cadence sample stops the fixture frontend first, since the
diagnostic no longer re-registers over its row.

Runbooks: the fatal-state recovery and CTV sections, the HA reference's
self-check description, the migration guide's import/backfill notes and the
3.0.0 release notes state that the one-shot commands keep every startup gate
but write no heartbeat, and that rows left by earlier builds still need the
documented investigation. Refs #381.
Cover the four one-shot commands (self-check, import-audits, backfill-ctv,
broadcast-ctv) against a real PostgreSQL cluster: a generated instance ID
leaves no qbit_prism_instances row on success or on failure, a live
frontend's row (status with its session-owner token, heartbeat_at and
started_at) is byte-identical after each tool runs under its instance ID,
the halt guard still refuses every tool with "cluster halted", and
fatal-state clear succeeds once the real frontend stops because no tool
row is left to refuse.

With the registering constructors restored in tools.rs the test fails at
the first row-count assertion, so it guards the fix rather than the setup.

Refs #381.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@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-16T14:22:46.347521Z 5d73fc4 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.

@Anatolie
Anatolie merged commit 9a4b4af 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]>
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