Skip to content

3.x.x: Native candidate recover --apply for already-accepted pending blocks - #439

Merged
Anatolie merged 26 commits into
3.x.xfrom
candidates-recover-apply
Sep 17, 2026
Merged

Anatolie merged 26 commits into
3.x.xfrom
candidates-recover-apply

Conversation

@Anatolie

@Anatolie Anatolie commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Closes #418. Stacked on #425 (candidates list / abandon, the subcommand group,
refusal taxonomy and test module this extends): this branch is #425's head plus the
commits below, so the diff collapses to them once #425 merges.

Adds qbit-prism-server candidates recover --block-hash <hash>... [--apply] [--timeout-seconds N], the third candidate command: the operator path for a
native-era candidate whose block the node already accepted and which the claim lane
cannot finish (the row abandon correctly refuses). Plan-only by default; --apply
lands the listed blocks at the proven chain revision through the coordinator's own
post-offer landing, and never calls submitblock.

What it does

Plan (default). Reads the listed rows on the same read-only one-connection pool
list uses (default_transaction_read_only=on, so a claim is impossible by
construction), loads no payload column (a describe() test proves the projection),
asks the node getblockheader/getblockhash for each hash, and prints the selection
ordered by height, parent before child. Fail-closed on every listed hash: missing row,
abandoned, submitted without proven accounting, not on the active chain, an
unfinished parent that is not listed, a stored height that disagrees with the node,
unsupported storage version, legacy document. Every problem is printed; the first
one's status is the exit status.

--apply. Runs the plan, connects as a one-shot tool (Coordinator::new_tool, no
heartbeat, every startup gate), then per block in height order:

  1. takes a durable, token-fenced claim by hash through the existing claim
    mechanism (Ledger::claim_candidate_for_recovery: the lane's own RETURNING
    columns and decode; the statement's WHERE is the safety property: unfinished
    state, no live claim, storage_version = 1, the migrator's document-shape test);
    a parked row is claimable, its schedule untouched;
  2. verifies the block against the node (active at its height; header height equals
    the candidate's; previousblockhash equals the parent in the block bytes);
  3. a pending row is adopted into reconciliation first, exactly as the pre-offer
    probe adopts an active pending block, so from that commit no frontend can offer it;
  4. runs land_offered (builder admission, rebuild from the as-issued snapshot,
    verification, land_candidate_at_revision) under the ordinary lease heartbeat,
    with the rebuild deadline set to the operator's budget instead of the lane's 60 s;
  5. observes again and finishes with finish_candidate_at_revision.

Already-complete submitted blocks are verified (confirmed pool block, audit row,
active on the node) and skipped, so rerunning the same allowlist is a resume.

Deadline. --timeout-seconds (1..3600, default 600, #259's) is one
tokio::time::Instant carried through the plan, the connection, and each claim,
rebuild and landing. On expiry the in-flight claim is released with a bounded write
(FOR NO KEY UPDATE, compatible with the landing transaction's KEY SHARE), the
row keeps its state, evidence and schedule, and the command exits 11. Any other
stop releases the claim the same way and records the reason in last_error.

Exit statuses

Extends #268's table; shared codes keep their meaning.

Code Outcome
0 plan printed / every listed block recovered or verified complete
1 configuration, database or node failure; halted cluster; live legacy writer lease; an allowlist the command refuses
2 a listed hash has no row
4 terminal and unrecoverable: abandoned, or submitted without proven accounting
5 held by a live claim
7 / 8 unsupported storage version / pre-migration 2.x.x document, evidence preserved
9 not on the active chain: nothing to recover, never offered
10 selection refused: unlisted unfinished parent, or stored height disagrees with the node
11 deadline exceeded; candidate left recoverable, claim released
12 landing refused or the row cannot be authenticated; candidate left recoverable

Codes 3 and 6 do not occur: every unfinished state is recoverable, and a landed audit
is what an idempotent landing reuses.

Configuration

list and abandon still take PRISM_DATABASE_URL and nothing else. recover is the
one command that reads the node: the plan needs the database URL and the QBIT_RPC_*
settings; --apply needs the frontend's full configuration (it rebuilds and signs the
audit and verifies genesis/chain and the cluster fingerprint). Frontends do not need to
be stopped: the claim is the fence. docs/prism-ledger-ops.md documents the asymmetry.

Code

  • ledger/candidates.rs: RecoveryReader (read-only plan reads; sql() public for
    the projection test), Ledger::claim_candidate_for_recovery,
    Ledger::release_recovery_claim, RecoveryClaim, RecoveryRow; the abandon
    diagnosis and the new one share RefusalFacts; the lane's RETURNING list is a
    shared constant; read_only_pool is shared with list.
  • coordinator.rs: process_candidate_with_lease is split into
    with_candidate_heartbeat(claim, lease, work) + process_candidate_inner (no
    behaviour change); recover_candidate drives the post-offer phase for a named row
    under the operator's deadline; RecoveryStop names the three stops.
  • rpc.rs: JSON-RPC error replies are now a downcastable RpcReplyError with the
    same message, so "no such block" can be told from "node unreachable".
  • tools.rs: the Recover subcommand, plan/apply, reporting; render_table and
    claim_text are factored out of the list table.

Tests

Five gated PostgreSQL tests in tests/support/candidates_recover.rs
(ledger_postgres::candidates_recover, added to test/prism-gated-tests.txt), each
running the real binary against a scripted fake node that records every RPC method and
has no submitblock arm, and asserting no instance row was registered:

Criterion Test
plan ordering, no claim, no payload, no dispatch slot, works while halted, only chain reads recover_plan_orders_parent_before_child_without_claiming_or_loading_payloads
fail-closed selection (2/4/9/10/7/8, usage errors before any connection, all problems reported, rows byte-identical) recover_plan_fails_closed_on_missing_terminal_inactive_legacy_and_unlisted_parents
--apply lands a real pending (adopted first) and a real reconciliation candidate through the real rebuild; second run verifies and skips; unlisted row untouched recover_apply_lands_the_listed_blocks_and_verifies_completed_ones_idempotently
live foreign claim refused (5), succeeds once expired; an unauthenticated row is released with the reason, not parked recover_apply_refuses_a_live_foreign_claim_and_leaves_the_row_untouched
landing paused in the database past the deadline exits 11, claim released, nothing committed, same allowlist then succeeds recover_apply_enforces_the_deadline_and_leaves_the_candidate_recoverable

Plus a CLI parsing unit test (tools::configuration_tests::recover_arguments_are_bounded_at_the_entry).

Docs

Validation

Run on this Mac against a disposable Homebrew PostgreSQL 16 cluster (fsync=on,
full_page_writes=on):

  • cargo fmt --all --check and cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings: clean.
  • cargo test --locked -p qbit-prism-server --all-targets --no-fail-fast -- --test-threads=4
    with PRISM_TEST_GATE_MANIFEST and GITHUB_JOB=prism-native-postgres set: 362
    distinct gated tests executed and scripts/check_gate_manifest.py confirms the five
    new candidates_recover entries. The only failures were the ones this machine cannot
    run (9 live_regtest tests without QBITD_BIN; the 2 postgres_failover tests and
    the migration_rollback restore without PRISM_TEST_PG_BIN_DIR) and three
    lock-timeout/deadline flakes under parallel load
    (park_tests::unknown_persisted_offer_outcome_parks_as_lifecycle,
    job_tests::postgres_job_checkouts_start_on_first_poll_and_recover,
    window_switch_tests::the_rebuild_and_landing_never_wait_for_the_order_lock), which
    pass when rerun in isolation.
  • The five new tests and the twelve candidates_cli tests from 3.x.x: Candidate list and abandon operator commands, and the legacy-drain runbook step #425 pass together
    (--test ledger_postgres candidates_).
  • scripts/check_gate_env_reads.py, scripts/check_prism_settings.py and
    tests/test_docs_lab_prism_references.py pass.
  • Not run here: live_regtest (needs a real qbitd), and workspace-wide clippy for the
    untouched crates.

🤖 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.

@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-17T15:31:51.103775Z f08e834 New commits
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2f3bba5577

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/qbit-prism-server/src/tools.rs Resolved
Comment thread crates/qbit-prism-server/src/tools.rs Resolved
@Anatolie
Anatolie force-pushed the candidates-recover-apply branch from 2f3bba5 to 20ddc7c Compare September 17, 2026 13:49

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 20ddc7c1cf

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/qbit-prism-server/src/tools.rs Resolved
Comment thread crates/qbit-prism-server/src/tools.rs Resolved
kiwidream and others added 22 commits September 17, 2026 10:09
`qbit-prism-server` had no way to see or finish a block candidate: a
native-era row that keeps failing was retried forever, and the only way
to inspect or stop it was editing rows by hand.

`candidates list` is an inventory. It opens the read-only pool shape
`fatal-state show` uses, so "takes no claim" is enforced by PostgreSQL
rather than by review, and it keeps working while the cluster is halted.
Neither payload column is projected: the height is extracted to a scalar
server-side, guarded by a digit pattern so a row an unknown writer left
behind reports an unknown height instead of failing the inventory. Rows
print in the oldest-due claim lane's own ordering, so the row a server
works next comes first and parked rows sort last. An empty inventory is a
success, because that is what a cutover runbook waits for.

`candidates abandon` applies to `pending` only, which is the one
unfinished state from which no `submitblock` can yet have been made. The
whole safety property is the statement's `WHERE`: `pending`, no live
claim, and no landed block. It is a predicate and never a preceding
`SELECT`, because a row can move between a check and a write; the
diagnosis that produces the operator's message runs read-only after it,
and gates nothing. The column set is the epoch-supersession path's,
verbatim, with the operator's reason taking `last_error`'s place, and
`next_attempt_at` deliberately untouched so a parked row keeps that
evidence. Each refusal has its own exit status, so a runbook can tell a
row that was never there from one already abandoned, and both from the
two refusals that protect the invariant: a block that may already have
been offered, and a block whose accounting has landed.

Both commands read PRISM_DATABASE_URL and nothing else. Neither builds a
node client, reads a signing key, loads `Config` or starts a listener, so
"never calls submitblock" holds structurally.

Co-Authored-By: Claude Opus 5 <[email protected]>
Six gated tests drive the real binary against a recorder in front of the
fake node and assert it made no RPC call at all, `submitblock` included,
and registered no instance. The child is given a database URL and a node
URL and nothing else, so a command that loaded `Config` or started a
listener could not have succeeded.

`list` is asserted not to claim three ways: it runs to completion while
the cluster is halted, which every write path refuses; every row is
byte-identical afterwards, with `claim_token`, `claim_instance_id`,
`claim_expires_at`, `attempt_count` and the dispatch sequence compared
explicitly; and the statement it issues is described by PostgreSQL, so
the assertion that neither payload column is projected reads the result
columns rather than the SQL text.

`abandon` is asserted to leave an `offer_reserved`, `offered` or
`reconciliation` row byte-identical, to refuse a live foreign claim and
then succeed once that claim has expired, to refuse an already-terminal
row and a pending row whose block has landed, and to refuse while the
cluster is halted or a legacy writer lease is live. On the one row it
does take, the resulting row is compared field by field with a row the
epoch-supersession statement abandoned.

Co-Authored-By: Claude Opus 5 <[email protected]>
`prism-ledger-ops.md` gains a `Candidate commands` subsection three lines
below the state table it explains: the two command lines, a real `list`
output block, what each column means, the parked-versus-retrying
distinction, the refusal table with its exit codes, and the two fences
`abandon` inherits from the ordinary ledger write path — a halted cluster
and a live legacy Python writer lease, which is what stops an operator
abandon racing the 2.x.x writer during a cutover.

`prism-rust-migration.md` gains the native counterpart to the legacy
drain, and says plainly that they are not the same drain. The legacy
instruction is unchanged: every 2.x.x candidate is still drained with the
pinned legacy image before migrating, and the migrator still refuses
while any remains. The native commands act on native-era rows only, and
running them neither satisfies nor bypasses that check.

`prism-deleted-test-map.md` keeps the pending-block-recovery row partial
and its open-gap link intact, adds the six new tests where they genuinely
cover a case, and fills in the per-case mapping the row promised. The
recovery command's plan ordering, fail-closed selection across a plan and
apply idempotence stay open; the cooperative-JSON codec cases stay
retired.

Co-Authored-By: Claude Opus 5 <[email protected]>
The state predicate is the abandon statement's version guard, so two
operator abandons completing out of order are safe without any lock on
top. Prove it end to end: after the successful abandon, a second one with
a different reason exits 4, says the row is already abandoned, and leaves
it byte-identical, so the reason the first operator recorded survives.

Co-Authored-By: Claude Opus 5 <[email protected]>
`abandon` writes an ordinary ledger row, so it belongs in the same bucket
as `import-audits`, `backfill-ctv`, `broadcast-ctv` and `self-check`, not
with recovery and migration: `Registration::Tool` refuses a halted
cluster at connect, exactly as a frontend would, instead of getting as
far as the write guard. The write guard call stays, because it is what
refuses a live legacy Python writer lease, which the connection does not
cover.

`list` keeps the read-only pool. It opens no ledger and writes nothing,
`default_transaction_read_only=on` is a stronger guarantee than a tool
connection would give, and a tool connection would refuse a halted
cluster — which is exactly when an operator needs to inspect candidates.

A new gated test gives `abandon` the four properties a one-shot tool
owes: a generated instance ID leaves no row on success or on a refusal, a
live frontend's row and session-owner token are untouched when the
command runs under that frontend's ID, the halt guard holds and the
halted run changes nothing, and once the real frontend stops no row is
left that the recovery command's instance gate would refuse. Substituting
the registering connection for the tool connection fails all five abandon
tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
home of the unfinished recover work would become dead ends. Row 84's
"not covered" clause and every plan-level case in the per-case table now
link #418 instead. Row 84 stays partial, and the #285 and #270 links are
untouched.

The per-case table also says which revision it enumerates. The file has
seventeen cases at 504846c, the `origin/2.x.x` commit this document pins
throughout; three of them arrived with #258, so a reader who checks
v2.0.1 instead sees fourteen and none of those three. Saying so stops the
next reader concluding the extra rows are invented.

Co-Authored-By: Claude Opus 5 <[email protected]>
The per-case retarget moved every recover link from #268 to #418, but the
header still named #268 as one of the issues those links point at. No link
points there now, so the sentence described the document's previous state.
Land already-accepted blocks for an explicit allowlist of at most 32 candidates
(#418), plan-only by default and never calling submitblock. The plan reads the
listed rows on the inventory's read-only pool, loads no payload column and
proves each block active on the node; --apply takes a token-fenced claim by
hash through the existing claim mechanism, adopts a pending row before anything
lands, and drives the coordinator's own post-offer landing and finish under one
operator deadline, releasing the claim with the reason on any stop. The refusal
taxonomy extends the abandon exit codes (9 not active, 10 selection refused,
11 deadline, 12 landing refused).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Five gated tests drive the real binary against a scripted fake node that
records every RPC method and has no submitblock arm: plan ordering without a
claim or a payload, fail-closed selection for every refusal, a real apply that
lands a pending and a reconciliation candidate and verifies them idempotently
on rerun, a live foreign claim refused and an unauthenticated row released, and
a landing paused inside the database past the deadline. The seeding helpers of
the list and abandon tests are shared with the new module.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The ledger-ops guide gains the third candidate command beside list and abandon,
with the configuration asymmetry, the plan, the apply steps, the deadline, the
exit table and a native runbook; the migration guide names it in the two-drains
section; and the deleted-test map's pending-block-recovery row drops its #418
clause, staying partial only for #285.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Anatolie
Anatolie force-pushed the candidates-recover-apply branch from 20ddc7c to 3b10f52 Compare September 17, 2026 14:17

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b10f526c0

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/qbit-prism-server/src/tools.rs Resolved
Comment thread crates/qbit-prism-server/src/tools.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6eb19a6c37

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28144eee6c

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/qbit-prism-server/src/tools.rs Resolved
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.

2 participants