Skip to content

2.x.x: abandon proven-orphan block candidates at once and release the landed barrier (#414) - #420

Merged
djh58 merged 2 commits into
2.x.xfrom
djh58/page-284-2xx-orphan-verdict
Sep 16, 2026
Merged

djh58 merged 2 commits into
2.x.xfrom
djh58/page-284-2xx-orphan-verdict

Conversation

@djh58

@djh58 djh58 commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Fixes #414 (parent #413).

Problem

A PRISM block that loses a same-height tip race probes "unknown" forever: the abandon path defers it as accepted-pending-finalization behind the 300 s observed-tip window while its landed payout transition fences reconciliation, payout publication and every job build. On mainnet this stalled all job delivery for ~307 s per own-orphan (4 times in the preceding 24 h) and a valid solve found during one hold was discarded.

Change

  • Definitive orphan verdict. _block_candidate_chain_probe returns False when the node holds the candidate's header off the active chain (getblockheader confirmations == -1) and getblockhash at the candidate's height names a different block. Either statement missing, contradictory, or failing over RPC keeps the view unknown, so the lost-ack protection inside PRISM_OBSERVED_TIP_ACCEPT_WINDOW_SECONDS is unchanged (the constant is untouched). The header is fetched once via the new block_candidate_chain_header helper, shared with active_block_candidate_height.
  • Seal and barrier release. The verdict seals under coordinator.lock alone: it drops the tip observation, the retained-offer stash and the hash's outstanding registration, so a late blockwait observation cannot re-arm the defer. The existing withdrawal in record_abandoned releases the landed barrier on the same pass, and the abandon nudges the pending tip refresh instead of waiting for its next wave.
  • Client-thread crash. PayoutStatePublicationBlocked raised by the share-driven vardiff retarget's paired job build no longer escapes note_accepted: the retarget is skipped, counted under qbit_prism_vardiff_retargets_skipped_total{reason="payout_publication_blocked"}, and logged once per connection.
  • Observability. qbit_prism_block_candidate_orphan_verdicts_total counts proven orphans once per candidate at the verdict, separating them from window-expiry abandonments. Abandon reason id and every existing series are unchanged.

Tests

  • New: first-pass abandonment with barrier released and refresh woken; unknown probe inside the window still defers (lost-ack guard); window expiry leaves the verdict counter at zero; probe verdict semantics (both statements required); late observation vs. verdict race; both vardiff paths (service and coordinator level, client stays connected, log once, counter).
  • python -m compileall -q lab tests OK; targeted unittest set 666 tests OK; full shard run_python_test_shard.py --shard-index 0 --shard-count 1: 3721 tests, 54 gated skips, 0 failures attributable to this change (the 14 test_prism_public_dashboard_api failures were the build host's HTTPS proxy returning 403 to the local test server; the module passes 116/116 with the proxy unset and is untouched here).

Companion 3.x.x work (regression pin + terminal orphan disposition) is tracked in #415.

🤖 Generated with Claude Code

On mainnet (2026-09-16), a PRISM block that lost a same-height tip race probed
"unknown" forever, so the abandon path deferred it as accepted-pending
behind the 300 s observed-tip window while its landed payout transition
fenced reconciliation, payout publication, and every job build. The
coordinator delivered no work for ~307 s per orphan and a valid solve
found during the hold was discarded.

- Definitive orphan verdict: `_block_candidate_chain_probe` now returns
  False when the node holds the candidate's header off the active chain
  (`getblockheader` confirmations == -1) AND `getblockhash` at the
  candidate's height names a different block. Either statement missing,
  contradictory, or failing over RPC keeps the view unknown, so the
  lost-ack protection (defer inside the window) is unchanged. The
  header is fetched once through the new `block_candidate_chain_header`
  helper, which `active_block_candidate_height` now shares.
- The verdict seals under `coordinator.lock` alone: it drops the tip
  observation, the retained-offer stash, and the hash's outstanding
  registration, so a late blockwait observation cannot re-arm the
  accept-pending defer; the existing withdrawal in `record_abandoned`
  then releases the landed barrier and the writer pops the tombstone
  once the outbox row is terminal. The abandon nudges the pending tip
  refresh instead of leaving it to its next wave.
- Client-thread crash: `PayoutStatePublicationBlocked` raised by the
  share-driven vardiff retarget's paired job build no longer escapes
  `note_accepted`; the retarget is skipped, counted under
  `qbit_prism_vardiff_retargets_skipped_total{reason=
  "payout_publication_blocked"}`, and logged once per connection.
- Observability: `qbit_prism_block_candidate_orphan_verdicts_total`
  counts proven orphans once per candidate at the verdict, separating
  them from window-expiry abandonments; the abandonment reason id and
  every existing series are unchanged.

Tests cover the page-#284 interleaving end to end (first-pass
abandonment, barrier released, refresh woken, late observation refused),
the unknown-probe regression guard, the expiry path leaving the verdict
counter at zero, the probe verdict semantics, the out-of-order
observation-versus-verdict race, and both vardiff paths.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@djh58
djh58 force-pushed the djh58/page-284-2xx-orphan-verdict branch from 0795aa1 to 495e8f0 Compare September 16, 2026 15:31
@djh58

djh58 commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

Automated deep review of this PR (8 review angles, 13 candidates verified individually, 4 refuted). Findings, most severe first; a follow-up commit is in progress for 1–3 and the smaller items.

  1. Tie-later-won loses the block reward (lab/prism/block_candidates.py ~L8074). confirmations == -1 plus getblockhash(H) != candidate is also the state of a live same-height tie, yet the verdict is sealed terminally on the first pass and the prepared payout rows are rejected; nothing revives a rejected pool block if the chain later reorgs back to our block (the reconciler scans only confirmed/inactive). The base code kept a 300 s re-probe window; this PR shrinks it to 0. Proposed: release the landed barrier on the verdict (the actual stall fix) but keep the ledger row prepared until the competitor has at least one child (or the verdict has aged past the window), then reject.
  2. TemplateRefreshSuperseded still kills the client thread (lab/prism/job_delivery.py ~L2166). The reorg-phase except TemplateRefreshBlocked: raise ignores raise_on_reorg_failure while the build phase honours it, so a sibling exception from the same reconcile pass escapes note_accepted exactly like PayoutStatePublicationBlocked did. Minimum: catch both in the vardiff path (as tip_refresh.py already does); better: make the reorg clause symmetric so the share-driven retarget takes retarget_locked's existing restore path.
  3. The probe became stateful (block_candidates.py ~L4405). _resolve_unreplayable_ancestor_transition calls _block_candidate_chain_probe as a read-only check; a confirmed-then-reorged ancestor now increments the orphan counter and leaves a verdict entry that is never retired. Proposed: return the verdict and seal only inside record_abandoned's terminal section, or no-op the recorder when the hash is not outstanding.
  4. Under initial convergence a fenced retarget is counted both as initial_retargets_total{outcome="failed"} and as a skip (vardiff_service.py ~L2427).
  5. _block_candidate_proven_orphaned probes getblockhash at the caller's expected_height rather than the header's own height, so a corrupt-intent height makes the second statement vacuous (block_candidates.py ~L8075).
  6. The tip-refresh wake is attached to one abandonment branch instead of the barrier release itself; other landed-clearing paths still wait for the ~2 s poller holdoff (payout_state.py ~L3792).
  7. The "proven orphaned" log line prints on every re-probe (the counter is deduped, the print is not), and the closed-pool path probes twice per pass (block_candidates.py ~L8156).
  8. _block_candidate_orphan_verdicts stores a height nobody reads; a set (or the probe's return value) would remove the descriptor/state-map/eviction plumbing (block_candidates.py ~L1520).

@kiwidream

Copy link
Copy Markdown
Member

Independent review of 495e8f0 against origin/2.x.x. I read the diff plus the abandon, finalization, ledger, reconciler, tip-refresh and vardiff paths, ran compileall and the named modules (219 + 61 OK), and applied eleven single-point mutations to see which named test catches each.

Verdict. The fail-closed direction is sound for every node reply the tests model: an RPC failure on either statement, a missing or unparseable confirmations, an unknown header, confirmations of 0 or positive, and a getblockhash that still names the candidate all leave the view unknown, and the observed-tip window then defers exactly as on origin/2.x.x with the constant untouched. Two gaps are worth fixing before merge, and one of them is a question for #415 rather than for this PR.

1. A non-hash getblockhash reply is accepted as proof of a different block

lab/prism/block_candidates.py:8085-8098. The second statement is str(self._coordinator.rpc.call("getblockhash", [height])).lower(), compared for inequality against the candidate hash. There is no check that the reply is a block hash, and rpc.call returns payload["result"] verbatim on a success envelope. So a {"result": null, "error": null} reply stringifies to "none", which is "a different block", and the seal runs: evidence dropped, registration discarded, counter incremented, candidate abandoned on that pass.

Driving the probe with a fake RPC (header confirmations: -1, expected height 10):

getblockhash result probe verdict counter
None False 1
"" False 1
0 False 1
candidate hash, upper-case None 0

qbitd shouldn't answer getblockhash with a null result — an out-of-range height is a JSON-RPC error, which correctly stays unknown — so this needs a misbehaving node or an intermediary. It's still the one path where a reply that proves nothing becomes an irreversible disposition. Requiring a 64-character hex string before comparing, and returning None otherwise, closes it locally.

Related, same function: int(header.get("confirmations")) accepts "-1" and truncates -1.5 to -1. A node won't send those, but "exactly the integer -1" is the intended rule and is cheap to state.

2. confirmations == -1 isn't pinned by any test

Replacing if confirmations != -1: return None with a no-op leaves the module green at 219/219. The semantics test's "header without a usable confirmations field" case uses {"height": 10}, so int(None) raises before the check is reached — the only value it proves is absent. The confirmations: 1 case returns True on the pre-existing rule before the orphan helper runs, so it doesn't constrain this either. Under the mutation, a header with confirmations: 0 plus a competitor at the height is a proven orphan and nothing notices.

A case with a known header whose confirmations is 0 and the competitor active, asserting None and an untouched counter, would pin it — and could cover the null-reply case above and the height disagreement below at the same time.

3. Once proven, the block can't come back, and the comment says otherwise

lab/prism/block_candidates.py:8317-8321 justifies never re-probing a False verdict partly on "the reorg reconciler owns any later reactivation of the block". On the incident path (lab/prism/block_finalization.py:1147-1157) the abandon runs before persist-accepted-block, so no pool-block row exists, the outbox row becomes abandoned, and the in-memory terminal outcome fences the hash. But reactivate_pool_block acts only on an inactive row in the in-memory backend and requires chain_state = 'confirmed' in the SQL backend, and stranded_prepared_blocks only on prepared rows. There is nothing for the reconciler to reactivate.

End to end with this PR's own scaffolding: after the first-pass orphan abandon the recording ledger holds zero persisted, rejected or confirmed rows; flipping the fake node back to the pool's block makes the probe answer True and retires the in-memory verdict, but the hash is no longer outstanding, the terminal outcome is still False, and re-offering is refused without a submitblock. On origin/2.x.x the same flip-back inside the 300 s window was rescued.

Ending the stall is clearly worth more than that rescue, so this reads as a deliberate trade — but it's undocumented, the comment claims the opposite, and the abandonment is recorded under submitblock-rejected, a reason that says the node refused a block it in fact accepted. Suggest fixing the comment and, separately, the reason id.

4. The height cross-check ignores the header's own height

lab/prism/block_candidates.py:8077-8081. When expected_height is supplied the header's height is not consulted. With header {"height": 11, "confirmations": -1}, expected height 10, a competitor active at 10 and the candidate active at 11, the probe issues only getblockhash [10] and returns a verdict "orphaned at height 10" for a block the node holds active. The outcome is False either way, because the pre-existing wrong-height rule also abandons it, so no won block is lost — but the verdict registry and the new counter mislabel a wrong-height candidate as an orphan.

Lower-confidence notes

  • The verdict counter increments at the probe (block_candidates.py:8131-8152), so the ancestor re-drive at block_candidates.py:4405 and the closed-pool probe at block_finalization.py:1752 also count, and a flip-flop counts twice. A hash never registered as a candidate produced probe=False, counter=1. The HELP text at lab/prism/metrics.py:582 says "once per candidate at the verdict. Such candidates abandon on that pass". Counting at the terminal commit in record_abandoned, where the abandonment counter already dedupes per candidate, would match the text.
  • The seal's docstring (block_candidates.py:8107-8124) says it is never nested inside the payout-balance mutation lock; on the incident path that RLock is held for the whole stretch and instrumenting the seal shows it owned when the seal runs. Both locks are reentrant and the order already existed, so no inversion was found — the docstring just misleads.
  • test_proven_orphan_abandons_first_pass_and_releases_landed_barrier still passes with the preview withdrawal removed from record_abandoned, because the finalize step withdraws the transition again before the assertions. The release is pinned by six pre-existing tests and by the direct late-observation test; the headline test doesn't distinguish "released on the abandon pass" from "released at finalize".
  • "Logged once per connection" is once per ClientState lifetime and never reset, so a long-lived connection spanning two holds logs only the first.

Mutations that were caught

For the record, these all failed a named test: removing the contradiction guard, turning a getblockhash RPC failure into a verdict, keeping the tip observation, keeping the outstanding registration, keeping the retained stash, never retiring the verdict on a True re-probe, counting per probe, and removing the refresh nudge. The seal's atomicity and the vardiff fix both hold up: retarget_locked restores every speculative client mutation before re-raising, note_accepted catches only PayoutStatePublicationBlocked so other failures still propagate, and the label set is a fixed tuple guarded by ValueError.

For #415

Since the same semantics land natively, four things to tighten rather than inherit:

  1. Validate the boundary — confirmations exactly the integer -1, and a well-formed block hash before the comparison; anything else unknown.
  2. Anchor the height — require the header's own height to equal the candidate's intended height and cross-check at that height; a disagreement is not an orphan.
  3. Decide what the row becomes. In 2.x.x a proven orphan ends as outbox abandoned under submitblock-rejected, with no pool-block row and no path back if the chain reorgs to it. 3.x.x: lost-race regression test and a terminal orphan disposition for reconciliation rows #415 should either give the proven orphan its own terminal disposition that keeps enough durable evidence to reactivate on a flip-back, or state explicitly that a proven orphan forfeits one — and not inherit "rejected by the node" as the reason for a block the node accepted.
  4. Count once per candidate at the commit, not per probe.

Not verified here: the full Python shard this PR's body cites (the targeted modules are green), behaviour against a live qbitd — specifically whether it can ever report confirmations: 0 or a null getblockhash result — and an exhaustive lock-inversion search across every taker of the payout-balance mutation lock, which was read rather than executed.

…rg fences, read-only probe

Addresses the PR #420 review findings (deep review items 1-8 and the
independent review) for #414 (parent #413).

1. A same-height tie is not a settled orphan. The orphan verdict still
   releases the landed payout barrier on its first pass and wakes the tip
   refresh (the stall fix), but the prepared payout rows are rejected only
   once the competitor block has PRISM_CANDIDATE_ORPHAN_TERMINAL_CONFIRMATIONS
   confirmations (default 2) or the first verdict is older than
   PRISM_OBSERVED_TIP_ACCEPT_WINDOW_SECONDS, whichever comes first. Until
   then the candidate defers under orphan-confirmation-wait with its ledger
   row prepared, and a chain that flips back fully restores it: verdict
   retired, tip observation re-registered, landed barrier re-armed and its
   tombstone popped. The verdict registry keeps hash -> first-verdict
   monotonic time because that stamp is the window clock. An RPC failure
   during the wait keeps waiting on the standing clock and is never a
   terminal step; the verdict is retired at terminal finalization rather
   than at the seal, so a failed prepared-row rejection retry neither
   restarts the wait nor counts the verdict twice. The withdrawn
   transition's tombstone keeps failing the orphan's own descendants closed
   but no longer fences unrelated builds on the competitor's chain while
   the verdict stands.
2. A TemplateRefreshBlocked subclass raised at the reorg reconciliation
   boundary (TemplateRefreshSuperseded, PayoutStatePublicationBlocked) no
   longer escapes a non-raising caller: the clause is symmetric with the
   build boundary, so the share-driven retarget skips the job, keeps its
   client, and the share acknowledgement is still written. The vardiff
   path catches the whole family as a second line of defence (new
   template_refresh_blocked skip reason), and the skip log re-arms after an
   applied retarget: once per hold, not once per connection lifetime.
3. _block_candidate_chain_probe is a read. It returns a typed
   BlockCandidateChainVerdict; the verdict counter, the wait clock and the
   seal live in record_abandoned, so the ancestor re-drive sweep and the
   closed-pool gate mutate no candidate state.
4. A fenced initial-convergence retarget counts as superseded, not failed.
5. The orphan proof anchors on the header's own height (a disagreement
   with the intent's height is unknown, not an orphan) and validates the
   boundary: confirmations must be exactly the integer -1, a boolean is
   never a confirmation count or height on the active path either, and
   getblockhash must return a well-formed 64-hex hash before it counts as
   a different block.
6. The tip-refresh wake is attached to the barrier release itself, so
   every landed-clearing path resumes delivery on the same wave; the
   wake's docstring states the real lock nesting (callers may hold the
   payout-balance mutation lock, which is already ordered before the
   runtime lock).
7. The "proven orphaned" log line prints once per verdict. The closed-pool
   path still probes twice per pass: that fix needs block_finalization.py,
   which is out of scope for this follow-up, and with the probe now
   side-effect free the cost is two RPC reads on a rare path.
8. The registry's unread height and its None-backfill guards are gone.

Observability: qbit_prism_block_candidate_orphan_wait_defers_total and
qbit_prism_block_candidate_orphan_terminals_total{trigger} join the
verdict counter; every existing series is unchanged. The setting is
documented in .env.example, compose.yaml and PRISM.md. The terminal
abandon reason id stays submitblock-rejected; the orphan terminals series
attributes proven orphans separately.

Tests: orphan first pass releases the barrier and holds the rows;
competitor confirmations and the setting's bar; window expiry with the
competitor unsettled; tie flip-back before terminal keeps the reward;
RPC failure during the wait keeps waiting until the window; flip-back on
a later probe fully restores the candidate; flip-back after the accepted
tail re-arms nothing; late observation vs verdict ordering both ways;
probe semantics pin exact -1, boolean and string confirmations, non-hash
getblockhash replies and height disagreement; the sweep's probe leaves no
verdict behind; reorg-boundary fences for non-raising and raising
callers; both fence classes keep the client connected and the share
acked end to end through the Stratum dispatcher; fenced initial retarget
counts as superseded; skip log re-arms after an applied retarget; metrics
parity for the new series.

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

djh58 commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

Follow-up commit ab0a491 addresses both reviews. Dispositions per finding:

Deep review

  1. Tie-later-won loses the block reward — fixed. The orphan verdict now only releases the landed barrier and wakes the tip refresh (the stall fix). The prepared rows are rejected once the competitor block has PRISM_CANDIDATE_ORPHAN_TERMINAL_CONFIRMATIONS confirmations (default 2, documented in .env.example/compose.yaml/PRISM.md) or the first verdict is older than PRISM_OBSERVED_TIP_ACCEPT_WINDOW_SECONDS, whichever comes first. Until then the candidate defers under orphan-confirmation-wait with its row prepared; a chain that flips back restores it fully (verdict retired, tip observation re-registered, landed barrier re-armed, tombstone popped). An RPC failure during the wait keeps waiting on the standing clock and is never a terminal step; the verdict is retired at terminal finalization, so a failed rejection retry neither restarts the wait nor double-counts. Pinned end to end: competitor-confirmed, the setting's bar, window expiry with the competitor unsettled, flip-back before terminal keeps the reward, RPC failure during the wait, and the observation-vs-verdict ordering in both directions.
  2. TemplateRefreshSuperseded kills the client thread — fixed. The reorg-phase clause is now symmetric with the build boundary: non-raising callers get False plus a coalesced retry, only raise_on_reorg_failure=True re-raises. The vardiff path catches the whole TemplateRefreshBlocked family as a second line of defence (new template_refresh_blocked skip reason). Pinned at the job-delivery boundary, at the service level, and end to end through the Stratum dispatcher (share ack written, connection kept) for both fence classes.
  3. The probe became stateful — fixed. _block_candidate_chain_probe returns a typed BlockCandidateChainVerdict and mutates nothing; the verdict counter, wait clock and seal live in record_abandoned. New ancestor re-drive test: a confirmed-then-reorged ancestor leaves no verdict entry and no count.
  4. Fenced initial retarget double-counted — fixed; a fence from the paired send counts superseded, not failed (pinned for both fence classes).
  5. Probe at the caller's expected height — fixed; the proof anchors on the header's own height, a disagreement with the intent is unknown, and the boundary is validated (exactly the integer -1, 64-hex getblockhash reply).
  6. Wake attached to one branch — fixed; the wake lives in the barrier release itself (_clear_accepted_block_payout_preview for landed drops and _unmark_accepted_block_payout_landed), and its docstring now states the real lock nesting.
  7. Log per re-probe / closed-pool double probe — log fixed (once per candidate at the first verdict). The closed-pool double probe is deferred: removing it needs block_finalization.py to hand its verdict to the abandon path, and with the probe now side-effect free the cost is two RPC reads on a rare path. Happy to take it as a small follow-up.
  8. Registry stores an unread height — fixed with a deviation: the registry stays a dict, of hash → first-verdict monotonic time, because that stamp is now the window clock; the unread height and the None-backfill guards are gone.

Independent review

  1. Non-hash getblockhash reply / int() coercion — fixed: only a well-formed 64-hex hash counts as a different block (None, "", 0, "none", malformed and short replies pinned unknown) and confirmations must be exactly the integer -1.
  2. confirmations == -1 unpinned — fixed: 0, "-1" and True with the competitor active are pinned unknown with untouched counters and evidence; a boolean is rejected on the active path too.
  3. Once proven, the block can't come back — substance fixed by item 1 above (the rows stay prepared for the wait and a flip-back restores the candidate), and the comment about the reconciler now states what it covers and does not. The reason id is deferred: submitblock-rejected is a stable, documented, bounded identifier consumed by dashboards and ledger fixtures that this PR commits to leaving unchanged, and the new qbit_prism_block_candidate_orphan_terminals_total{trigger} series attributes proven orphans separately. A dedicated terminal disposition goes to 3.x.x: lost-race regression test and a terminal orphan disposition for reconciliation rows #415 as you suggested.
  4. Height cross-check ignores the header's own height — fixed (deep review 5).
  • Counter at the probe — fixed (counted once per candidate in the abandon path; the terminal trigger is counted at the commit, after the rows are rejected).
  • Seal docstring vs the payout-balance lock — fixed (the seal is gone with the rewrite; the wake docstring states the nesting).
  • Headline test doesn't distinguish release-at-abandon from release-at-finalize — fixed (the first-pass test asserts the release on a deferred pass, before any finalize).
  • "Once per connection" is once per lifetime — fixed (the skip log re-arms after an applied retarget, so it is once per hold; pinned).

Verification: compileall clean; the targeted modules 700 tests OK; full shard 3736 tests, 54 gated skips, and the only failures are the 14 test_prism_public_dashboard_api cases caused by the build host's HTTPS proxy returning 403 (116/116 with the proxy unset).

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