Skip to content

Submit found blocks to the node before accounting and keep the submitter alive under DB saturation (1.x.x) - #113

Merged
djh58 merged 11 commits into
1.x.xfrom
fix/prism-submit-first-liveness
Aug 12, 2026
Merged

djh58 merged 11 commits into
1.x.xfrom
fix/prism-submit-first-liveness

Conversation

@Anatolie

@Anatolie Anatolie commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Found blocks were being lost because the PRISM coordinator did durable Postgres accounting before offering the block to qbitd. When production Postgres saturated, the submitblock RPC sat behind a database write long enough for the tip to move, and the coordinator then abandoned a real block as stale-job. The same unbounded database wait wedged the block_submitter thread entirely, tripping the liveness watchdog and restarting the process.

This branch makes the node offer the fast lane — it happens before any accounting — bounds every blocking call the submitter can make, moves accounting onto its own thread so it can never convoy later block submissions, and adds per-phase heartbeats so a future watchdog firing names the exact call that stopped progressing.

Incident that motivated this (production, 2026-08-11)

  • The pool found 5+ real blocks between 00:44 and 01:43 UTC.
  • Three candidates were abandoned in two hours, e.g. 01:50:52 block candidate abandoned reason=stale-job: tip moved before submit — the tip had moved ~80s earlier, meaning the submit had been stuck in the pipeline that entire time.
  • The submitter then stopped entirely: last heartbeat ~01:50:19, and at 01:55:18 the watchdog fired with unresponsive subsystems=['block_submitter'] timeout=300s, restarting the process and causing a paging outage.
  • Postgres was saturated at the time (a separate fix); qbitd itself was healthy throughout — tips flowing, CreateNewBlock instant.
  • The log gave no indication of which call had wedged for 300 seconds, only the thread name.

Root cause: _submit_next_block_candidate_writer called _mark_block_candidate_attempted (a durable Postgres write) before submit_block_candidate (the submitblock RPC), and nothing on that path — lock acquisition, Postgres statements, or the RPC — had a timeout. A delayed submit is a lost block; a duplicate submit is harmless, since the node rejects blocks it already knows.

What changed

1. Submit-first ordering (c18a661)

_submit_block_candidate_to_node now offers the durable candidate to qbitd before the attempt-marker write, writer admission, audit construction, or payout publication. The node result plus the same-hash disposition lease then transfer to the accounting tail.

Crash-point analysis for the new ordering (duplicate submits are acceptable, double accounting is not — everything is deduped by block hash):

Crash point Durable state Replay behaviour
Before submitblock outbox row pending Replay resubmits the same bytes; nothing was accounted.
After submitblock, before attempt marker outbox row pending Replay resubmits; qbitd's accepted-duplicate response is treated as a successful landing signal. Block-hash-keyed ledger persistence keeps accounting exactly once.
After attempt marker, before finalize outbox row pending + attempt marker The existing finalize-only retry registry completes the terminal update; the accounting tail is not re-run.
After finalize submitted / abandoned An exact resubmission observes the terminal state inside the same durable pre-submit transaction — submitted coalesces to success, abandoned stays rejected — before any new node offer is made.

The at-most-once terminal-accounting guarantee that the old mark-before-submit ordering provided is preserved via the finalize-retry registry rather than by delaying the submit. Exact share replays now return the original row as not newly inserted (BlockCandidateIntentPersistResult), so process-local worker and vardiff counters are not credited twice.

A short in-memory prospective-payout barrier is installed before qbitd can observe a candidate, so startup prewarm cannot issue child work from the stale balance base — without falsely claiming the block landed.

2. Bounded blocking calls and phase heartbeats (c18a661)

  • Postgres: every statement the submitter touches (outbox read/replay, mark-attempted, finalize) gets a fresh deadline via new SingleWriterShareLedger.operation_timeout / statement_timeout scopes, which set both the client-side budget and SET LOCAL statement_timeout. Expiry raises LedgerOperationTimeout; the row stays pending and enters the ordinary candidate backoff. Direct outbox reads/mutations additionally go through a single-flight wrapper so a driver that ignores its deadline cannot accumulate retry threads.
  • RPC: submitblock runs under an explicit hard deadline.
  • Locks: bare with self.lock on this path is replaced by a bounded acquire-loop that heartbeats in slices and periodically logs which lock is contended and the current phase.
  • Heartbeats: _record_block_submitter_phase tags liveness with the active phase — replay-outbox-query, submitblock-rpc, fast-lane-admission, accounting-queue, and so on. A watchdog firing now reports block_submitter:replay-outbox-query instead of just the thread name, which is exactly the diagnostic the 2026-08-11 log was missing.
  • Poison detection: at most two timeout-ignoring RPC workers and two timeout-ignoring ledger workers may stay detached. If either bounded pool remains exhausted for PRISM_BLOCK_SUBMIT_STUCK_CALL_EXIT_SECONDS, the coordinator requests shutdown and exits nonzero so the supervisor replaces the poisoned process; durable outbox rows remain pending for replay.

3. Priority isolation: node offers vs. accounting (bf7bf61)

Adversarial review of the first commit found that a stalled accounting tail could still convoy later block submissions. Accounting now runs on its own block_accounting thread behind a height-prioritized queue:

  • The submitter hands off (node result, lease) and immediately returns to the next candidate.
  • A full primary handoff spills into a result-preserving overflow queue — an already-offered block is never converted back into a raw-submit retry. Once spillover starts, later handoffs queue behind it so older spill entries can't starve.
  • block_submitter and block_accounting expose independent phase heartbeats, so slow accounting neither delays node offers nor disguises which phase stopped.
  • Recovery restores pending outbox rows in batches into a separate, lower-priority replay queue with no per-row database accounting, so live discoveries always outrank restart work while an older stalled replay cannot hide newer durable rows.
  • Fast-lane capacity reservations (_reserve_block_fast_lane_slot) keep PRISM_MAX_BLOCKS / stop-after-block semantics correct now that admission and accounting are decoupled.
  • Abandonment is counted only after any prepared payout state is rejected and the false disposition is fixed; if cleanup fails the candidate stays pending and can still converge to submitted on later chain evidence.

4. Startup replay no longer crash-loops on a slow ledger (e082971)

Review caught a P0 regression introduced by the two commits above: routing the startup outbox replay through the new 1s database deadline meant a slow-but-healthy Postgres raised BlockSubmitterDatabaseTimeout / LedgerOperationTimeout out of serve() → main(), exiting nonzero ~1s after boot and crash-looping — in precisely the conditions this branch exists to survive, including after the branch's own fail-stop exits.

_run_startup_block_candidate_replay now catches TimeoutError (covering both subclasses) at the startup boundary, logs the phase and configured budget, and continues boot so listeners open and the submitter/accounting threads start. This is safe because block_submit_loop already calls replay_pending_block_candidates() every iteration with paced backoff, and every durable candidate remains pending in qbit_block_candidate_outbox; the pre-listener pass only gives durable candidates a head start over fresh miner wakeups.

Deliberate scope limits in that fix:

  • Non-timeout database errors at startup replay stay fatal, matching base behaviour — a hard error is a real failure, not backpressure.
  • ShutdownInProgress handling and the drain_threads clean-stop path are unchanged.
  • replay_recovered_shares runs on the main thread with no timeout scope armed, so its behaviour is untouched.
  • The single-flight wrapper deliberately leaves a timed-out call registered under its key, so the loop's next retry reuses the still-running worker; the startup fix preserves that reuse.

Configuration

New knobs, all with production-safe defaults wired through .env.example and compose.yaml:

Variable Default Purpose
PRISM_BLOCK_SUBMIT_RPC_TIMEOUT_SECONDS 1 Hard deadline on the fast-lane submitblock RPC.
PRISM_BLOCK_SUBMIT_DB_TIMEOUT_SECONDS 1 Fresh deadline for each submitter Postgres statement and local ledger gate.
PRISM_BLOCK_SUBMIT_LOCK_WAIT_LOG_SECONDS 5 Cadence for logging the contended lock and current phase.
PRISM_BLOCK_SUBMIT_STUCK_CALL_EXIT_SECONDS 30 Exit nonzero when a timeout-ignoring RPC/DB worker pool stays exhausted this long.

docs/prism-ledger-ops.md is updated to describe the fast lane, the accounting handoff, best-effort startup replay, the phase-tagged heartbeats, and the revised exactly-once accounting story.

Testing

python3 -m unittest tests.test_prism_coordinator_vardiff tests.test_prism_share_ledger — 487 tests, OK (run locally on this branch). The 5 pre-existing failures in tests.test_prism_coordinator_job_cache are unchanged from base 6c00d6e and are untouched here.

Coverage added for each acceptance property:

  • test_submitter_offers_block_before_writer_admission_with_rpc_deadline — the RPC precedes writer admission and carries a deadline.
  • test_sixty_second_attempt_mark_stall_does_not_delay_rpc_or_heartbeat — with a database that stalls 60s, the candidate still reaches the node RPC promptly and the submitter keeps heartbeating.
  • test_crash_after_submit_before_attempt_mark_replays_duplicate_once — crash between submit and mark-attempted; replay resubmits and accounting lands exactly once.
  • test_accounting_saturation_does_not_convoy_node_offers, test_replay_batch_reaches_node_while_oldest_accounting_stalls — accounting stalls do not block later node offers.
  • test_overdue_submitter_heartbeat_names_the_stuck_phase — watchdog output includes the phase label.
  • test_startup_block_replay_timeout_starts_submitter_and_converges, test_startup_block_replay_catches_psql_server_timeout, test_startup_block_replay_keeps_hard_database_errors_fatal, test_startup_block_replay_preserves_shutdown_stop — the boot regression and its intentional limits.
  • test_stuck_rpc_worker_pool_requests_nonzero_restart, test_stuck_ledger_worker_pool_requests_nonzero_restart, test_one_stuck_ledger_call_does_not_restart_with_spare_capacity — poisoned-pool fail-stop only fires with no spare capacity.
  • test_synchronous_waiter_joins_finalize_only_registry, test_restart_resubmit_coalesces_terminal_submitted_outbox, test_restart_resubmit_honors_terminal_abandoned_outbox, test_exact_share_replay_does_not_repeat_process_credit — exactly-once accounting across replay and same-hash races.
  • Ledger-level: test_operation_timeout_bounds_local_writer_lock_admission, test_statement_timeout_refreshes_for_each_database_step, test_subprocess_operation_timeout_sets_client_and_server_deadlines, test_native_operation_timeout_is_transaction_local, and the matching server-deadline/hard-error cases.

Risks and rollout notes

  • Duplicate submits are now expected on the crash/replay path. This is intended — qbitd rejects blocks it already knows, and accepted-duplicate is treated as a landing signal. Accounting is deduped by block hash.
  • The 1s database default is aggressive by design. Under sustained saturation the submitter will time out and back off rather than block; rows stay pending and converge on retry. If a deployment has a genuinely slower ledger, raise PRISM_BLOCK_SUBMIT_DB_TIMEOUT_SECONDS — note this budget also covers TCP connect + auth on a cold connection.
  • New fail-stop path: an exhausted, timeout-ignoring worker pool now exits nonzero on purpose. That requires a supervisor that restarts the process; durable rows are safe across that restart.
  • The accounting overflow queue is unbounded process-local, bounded in practice by max-block admission on unresolved real offers.
  • Postgres saturation itself is being addressed separately; this branch only makes the block-submit path immune to it.

🤖 Generated with Claude Code


Note

High Risk
Changes found-block submission ordering, crash/replay semantics, and fail-stop behavior on the critical path that lands pool blocks and drives payout accounting.

Overview
Found blocks are now offered to qbitd before any durable accounting, so a saturated Postgres can no longer delay submitblock long enough to lose the tip race or wedge block_submitter.

The node result hands off to an independent height-prioritized block_accounting lane; a full primary queue spills into a result-preserving overflow instead of turning an already-offered block back into a raw retry. Live discoveries outrank restart replay, and startup outbox recovery is best-effort so a slow ledger no longer crash-loops boot.

Every submit-path RPC, DB statement, and lock wait is freshly deadline-bounded, with phase-tagged heartbeats and a poisoned-worker fail-stop. New knobs (PRISM_BLOCK_SUBMIT_*) are wired through .env.example / compose.yaml, and docs/prism-ledger-ops.md documents the fast lane, accounting isolation, and revised exactly-once replay story.

Reviewed by Cursor Bugbot for commit 223d2a0. Bugbot is set up for automated code reviews on this repo. Configure here.


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

Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
@Anatolie
Anatolie force-pushed the fix/prism-submit-first-liveness branch from cec4e91 to 223d2a0 Compare August 12, 2026 07:15
Anatolie and others added 7 commits August 12, 2026 17:03
Rebasing the submit-first fast lane onto the 1.x.x landing fences left
the accounting decision unsynchronized with fenced predating appends:
the fast lane no longer holds the fence across submitblock, so a landing
could verify a pre-bump epoch while a predating row's durable commit was
still in flight and persist a payout window omitting that row.

Re-check the live append-invalidation epoch under the landing fence lock
after a completed fast-lane offer, immediately before accounting: the
fence can no longer gate the node offer, but it still gates accounting.
The fallback (not-yet-offered) path keeps the base behavior of holding
the fence across submitblock itself.

Adapt the 1.x.x fence tests to submit-first semantics: the node offer
now always goes out, so their assertions move from "submitblock must not
run" to "accounting must abandon with append_epoch_stale", matching the
pattern the durable-descendant fast-lane test already uses.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Anatolie
Anatolie force-pushed the fix/prism-submit-first-liveness branch from 223d2a0 to c74fd00 Compare August 12, 2026 17:06
Comment thread lab/prism/prism_coordinator.py Resolved
djh58 and others added 2 commits August 12, 2026 13:39
A retryable candidate failure inside the block_accounting task (for
example an attempt-marker statement timeout) slept out the exponential
backoff while still holding accepted_block_handling writer admission and
the disposition lease. That stalled every queued accounting task and kept
an armed payout barrier blocking balance mutation for up to the 30s
backoff cap — the exact convoy this branch exists to prevent, in its
target saturation conditions.

Record a per-hash not-before deadline instead (same escalation state) and
honor it at both dequeue sites. The submitter-thread path keeps its
existing heartbeating backoff wait, and replay_pending_block_candidates
already short-circuits while the retained candidate occupies the retry
slot, so a parked candidate adds no outbox churn during its backoff.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
… the accounting queue

A successful submitblock followed by a retryable failure (for example an
attempt-marker statement timeout) dropped the fresh node result, so the
in-process retry re-offered and read "duplicate" — classifying against
the moved live tip and leaning on chain probes that may be unavailable
under the same saturation, which could terminally abandon a block the
node had already accepted. Retention now stashes a definitive acceptance
and every offer site reuses it instead of re-asking the node, rerunning
the landing tail exactly as if the first pass had continued past the
failure. Ambiguous or rejected offers are never reused, and a process
crash still converges through the durable replay path.

Separately, the primary accounting handoff queue was constructed
unbounded, so the documented result-preserving spillover ordering could
never engage in production. It is now bounded (default depth 8,
attribute-overridable); the overflow queue stays unbounded by design.

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

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5a563ca. Configure here.

Comment thread lab/prism/prism_coordinator.py Resolved
The stash for definitive submitblock successes was written only at three
retention sites, so retention paths that did not stash (the
defer-accounting handoff failures among them) dropped a popped result on
the floor, and even covered paths consumed the stash on a retry that
then failed again — both re-opening the duplicate-reclassification
hazard the stash exists to prevent.

Record the entry once, in the universal post-offer hook, read it without
consuming, and clear it only when the candidate reaches a terminal
outcome. Every present and future retention path is covered without
having to remember, and repeated retryable failures keep reusing the
same known acceptance. The regression test now fails the attempt marker
twice to pin survival across a consumed-and-failed retry.

Co-Authored-By: Claude Fable 5 <[email protected]>
@djh58
djh58 merged commit 7b2405d into 1.x.x Aug 12, 2026
12 checks passed
Anatolie added a commit that referenced this pull request Aug 14, 2026
The 1s PRISM_BLOCK_SUBMIT_DB_TIMEOUT_SECONDS budget from #113 covered every
submitter ledger statement, including the post-acceptance landing tail. A
structurally slow landing under that ceiling is statement-canceled on every
attempt and can never complete: mainnet block 42743's landing was canceled
13 times while Postgres was otherwise idle.

- New PRISM_BLOCK_LANDING_DB_TIMEOUT_SECONDS (default 30s) applies to each
  landing-class statement — accepted-block persist, prior balances,
  confirmation, and the prepared-state rejection of a terminal candidate —
  starting with the first attempt; a landing-class operation never begins
  at the poll budget.
- After an observed landing timeout, the next attempt for the same block
  hash doubles its budget up to PRISM_BLOCK_LANDING_DB_TIMEOUT_MAX_SECONDS
  (default 120s). Escalation state clears with the candidate retry state.
  Retries stay paced by the existing candidate backoff; per-attempt wall
  clock is bounded by the escalated budget; the stuck-call and coordination
  watchdogs remain the overall bound.
- Cheap outbox polls, quarantine writes, candidate-intent persistence, and
  terminal outbox updates keep the tight poll-class budget and their
  single-flight guard. Startup replay of a pending candidate re-enters the
  landing-class scope through the accounting tail.
- Cancellation cleanup was audited rather than changed: the native psycopg
  backend discards the pooled connection after a deadline error (SET LOCAL
  scopes roll back with the transaction) and the psql backend's subprocess
  exit drops the session, so no timed-out query continues invisibly.
- Both call classes record latency, budget, and timeout counters
  (block_ledger_call_class_metrics) for the observability wiring in the
  follow-up change.

Covered by new PrismCoordinatorReliabilityTests cases: escalation and
clearing, first-attempt landing budget selection, escalated budget after a
timed-out scope, and fast-class timeout metrics.

Co-Authored-By: Claude Fable 5 <[email protected]>
kiwidream pushed a commit that referenced this pull request Aug 15, 2026
…-class deadlines, degradable barrier, replay hardening (1.x.x) (#120)

* Make current prior-balances read O(active recipients)

qbit_current_carry_forward_balances() recomputed SUM(gross - onchain) over
every active qbit_payout_carry_forward row on each call. On mainnet that
read crossed the 1s submitter statement budget at ~1.4M rows and wedged
block landing (the 2026-08-14 livelock).

An index-backed latest-row-per-recipient read cannot replace it exactly:
after a mid-history reversal the recorded carry_forward_balance_sats of
later rows is stale until reconciliation (the postgres ledger test pins
this state: block A reversed under block B leaves B's row recorded at 1250
while the correct active balance is 250, with the integrity report
flagging the stale chain). Per the issue's fallback design, the exact
O(active recipients) form is a transactionally maintained current-balance
table:

- qbit_payout_carry_forward_current holds per
  (miner_id, payout_order_key, p2mr_program) partition the active-row sum
  and count, maintained by row-level triggers on qbit_payout_carry_forward
  and qbit_pool_blocks inside the same transaction as every write that
  changes the active carry set, so readers keep snapshot-consistent
  results under concurrent settlement.
- qbit_current_carry_forward_balances() now reads that summary; identity
  selection, program-level aggregation of aliases, HAVING <> 0, and result
  ordering are unchanged. qbit_current_owed_balances() inherits the fast
  path.
- The original aggregate is retained as
  qbit_recomputed_carry_forward_balances();
  qbit_carry_forward_current_drift() cross-checks the two and the
  integrity report now exposes current_drift_count/current_drift.
- A one-time seed DO block rebuilds the summary when the schema is applied
  to a database that predates it;
  qbit_rebuild_carry_forward_current_balances() is the ops resync hook,
  and TRUNCATE triggers keep the summary consistent for completeness.

The delta helper is update-first: INSERT ... ON CONFLICT would evaluate
the active_row_count >= 0 CHECK on the proposed tuple before conflict
resolution, so negative deltas against existing partitions would fail.

test/test-prism-postgres-ledger.sh gains equivalence assertions between
the summary-backed and recomputed forms at the alias, mid-reversal,
post-cleanup, and reseed checkpoints, drift-count assertions (including
mismatch_count=1 with zero drift in the stale-chain state), and a
migration-seeding test that clears the summary and re-applies the schema.

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

* Split submitter DB deadlines by call class with a landing budget

The 1s PRISM_BLOCK_SUBMIT_DB_TIMEOUT_SECONDS budget from #113 covered every
submitter ledger statement, including the post-acceptance landing tail. A
structurally slow landing under that ceiling is statement-canceled on every
attempt and can never complete: mainnet block 42743's landing was canceled
13 times while Postgres was otherwise idle.

- New PRISM_BLOCK_LANDING_DB_TIMEOUT_SECONDS (default 30s) applies to each
  landing-class statement — accepted-block persist, prior balances,
  confirmation, and the prepared-state rejection of a terminal candidate —
  starting with the first attempt; a landing-class operation never begins
  at the poll budget.
- After an observed landing timeout, the next attempt for the same block
  hash doubles its budget up to PRISM_BLOCK_LANDING_DB_TIMEOUT_MAX_SECONDS
  (default 120s). Escalation state clears with the candidate retry state.
  Retries stay paced by the existing candidate backoff; per-attempt wall
  clock is bounded by the escalated budget; the stuck-call and coordination
  watchdogs remain the overall bound.
- Cheap outbox polls, quarantine writes, candidate-intent persistence, and
  terminal outbox updates keep the tight poll-class budget and their
  single-flight guard. Startup replay of a pending candidate re-enters the
  landing-class scope through the accounting tail.
- Cancellation cleanup was audited rather than changed: the native psycopg
  backend discards the pooled connection after a deadline error (SET LOCAL
  scopes roll back with the transaction) and the psql backend's subprocess
  exit drops the session, so no timed-out query continues invisibly.
- Both call classes record latency, budget, and timeout counters
  (block_ledger_call_class_metrics) for the observability wiring in the
  follow-up change.

Covered by new PrismCoordinatorReliabilityTests cases: escalation and
clearing, first-attempt landing budget selection, escalated budget after a
timed-out scope, and fast-class timeout metrics.

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

* Decouple job issuance from slow landing bookkeeping

The accepted-parent barrier converts a landing failure into a mining
blackout when preview publication itself depends on ledger reads: in the
incident, preparing the payout-state artifact inside
_publish_accepted_block_payout_preview timed out with the wedged writer
gate, so the immutable compact preview never became visible and every tip
refresh re-failed with "accepted parent payout preview is not ready yet".

This change degrades the barrier without weakening payout correctness,
building on the invariants the machinery already enforces:

- Degraded preview publication: if preparing or atomically publishing the
  full payout-state artifact fails (e.g. a ledger timeout while the
  durable landing is slow), fall through to the existing fenced
  local-retention branch instead of raising. Delivery admission is
  force-blocked, waiting children receive the immutable compact preview
  (the payout/carry snapshot from the issued-job summary, cross-checked
  against live balances before this point), and payout-state publication
  itself stays gated behind the landed transition until the landing
  reaches a terminal durable state. No job bound to pre-accept balances
  can land after publication, and no balance is invented: the preview is
  the same snapshot an atomic publication would have installed.
- Unresolved-depth cap: PRISM_ACCEPTED_PARENT_UNRESOLVED_DEPTH_MAX
  (default 8) bounds how many landed-but-unresolved transitions may stack
  prospective balance chains. Beyond the cap, job builds fail closed with
  an explicit TemplateRefreshBlocked instead of extending the chain; the
  durable outbox bound remains the wider backstop.
- Unresolved age tracking: landed transitions record landed_monotonic and
  accepted_parent_unresolved_ages_seconds() exposes their ages for the
  observability wiring (alerts fire well before the barrier could wedge
  delivery again).

The bounded preview wait (5s grace) and the withdrawn/invalidated
semantics are unchanged; double payment and omitted carry remain excluded
by the existing base-drift shutdown check before early publication and by
the publication gate on reconciliation.

New JobBundleCacheTests cover degraded publication delivering the preview
with publication still gated, the depth cap failing closed above the cap
while the ordinary bounded wait applies at or below it, and unresolved-age
bookkeeping across mark/unmark.

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

* Close startup and replay hazards

Startup replay window: before this change, a startup outbox-query timeout
was swallowed and startup continued, leaving pending accepted candidates
unknown and their payout barriers unarmed — a child job built in that
window could pay balances that omit a pending parent's carry. Now:

- Job builds fail closed (TemplateRefreshBlocked) until the durable outbox
  has been enumerated once. _run_startup_block_candidate_replay marks
  enumeration as owed; replay_pending_block_candidates clears it only
  after every pending row has been queued (arming its barrier) or
  quarantined.
- While enumeration is owed, the replay query is correctness-critical: it
  bypasses the live-candidate short-circuits and runs with the
  landing-class budget instead of the 1s poll budget. The steady-state
  poll keeps the tight budget; replayed candidates themselves already land
  under the landing-class accounting scope.

Startup readiness: the 4m28s full-readiness delay conflated audit binding
with the cold accepted-share aggregate. Now the audit/health listener
binds before the warm-up and /healthz reports an explicit
state="starting" 503 while the first snapshot refresh (which seeds the
exact aggregate and can take minutes on a grown ledger) runs in the
background loop instead of blocking the bind path.

Startup phase timing: lease heartbeat start, node RPC readiness, audit
bind, replay enumeration, health snapshot warm-up, first tip template
publication, and first delivered job are recorded separately
(startup_phase_seconds) so a slow phase is attributable; exposition is
wired in the observability change.

_run_block_submitter_ledger_call accepts a per-call timeout override so
the owed enumeration can use the landing budget without loosening any
other poll-class call.

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

* Expose landing-path observability and pre-deadline signals

The prior-balances read grew past the 1s submitter deadline silently over
several weeks; nothing measured landing latency, statement timeouts, or
accepted-parent age. New /metrics series:

- qbit_prism_block_ledger_calls_total / _call_timeouts_total /
  _call_budget_seconds / _call_last_duration_seconds /
  _call_max_duration_seconds, labelled by call_class (fast vs landing),
  fed by the per-class recorder from the deadline split. The budget gauge
  shows the escalated landing budget applied to retries.
- qbit_prism_accepted_parent_unresolved_transitions and
  _unresolved_oldest_seconds from the landed-transition age tracking, and
  qbit_prism_accepted_parent_preview_wait_timeouts_total counting child
  builds that exhausted the preview wait grace.
- qbit_prism_prior_balances_reads_total / _read_last_seconds /
  _read_max_seconds, instrumented inside
  PsqlShareLedger.current_prior_balances.
- qbit_prism_startup_phase_seconds{phase=...} exposing the per-phase
  startup timings recorded by the startup hardening change.

docs/prism-ledger-ops.md documents the series and the pre-deadline alert
thresholds (prior-balances growth at ~20% of budget, any landing-class
timeout, unresolved-parent age beyond the preview wait).

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

* Record the gating startup enumeration under the landing call class

_run_block_submitter_ledger_call recorded every operation as
call_class="fast" even when the caller supplied the landing-class
deadline, so a 30-second startup enumeration timeout never fired the
documented landing-timeout alert and instead reported the fast-call
budget gauge as 30 seconds.

The wrapper now takes the metrics class alongside the deadline, and the
owed startup enumeration passes "landing" to match its budget; every
other caller keeps the fast default. The steady-state outbox poll still
records as fast under the poll budget.

Codex review: #120 (comment)

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

* Add production-scale ledger fixture with plan and budget gates

Every latent charge in the landing livelock was an O(history) pattern
invisible on the empty databases the ordinary tests run against. The new
named, reusable fixture (test/test-prism-postgres-scale.sh, make
test-prism-postgres-scale, wired into CI) seeds qbit_payout_carry_forward
and qbit_share_ledger at configurable scale with 13 skewed miners
(defaults 120k carry / 200k share rows keep CI fast; env knobs raise it to
the ~5M/~50M production shape), using trigger-disabled bulk load plus the
documented qbit_rebuild_carry_forward_current_balances() resync path.

Assertions per hot query class:
- Prior balances: warm-median server-side planning+execution time
  <= 50ms (measured ~1ms, where the old recompute takes ~1.2s at 1M rows —
  the exact silent growth that crossed the 1s deadline on mainnet), cold
  timing recorded, plan shape proven to touch only the summary table, and
  zero drift against the recompute both after bulk load and after a
  mid-history reversal performed with reverse_immature_pool_block's
  statement ordering.
- Outbox poll: pending partial-index plan assertion plus a 50ms budget.
- Window read: qbit_audit_share_window budget at the seeded share volume.
- Timeout cancellation: a deliberately padded statement is cancelled under
  a 0.2s operation budget, pg_stat_activity is polled to prove no query
  keeps running invisibly, and the ledger serves the next read cleanly.
- Durable outbox contract: an intent persisted through the ledger API
  round-trips with its authoritative block-hash key, v1 schema tag, and
  replay-critical fields — the shape a rollback build must digest.

Budgets are enforced on server-side planning+execution time (EXPLAIN
ANALYZE) rather than wall clock: per-call psql and docker-exec transport
overhead on shared CI runners is tens of milliseconds and would flake
wall-clock gates, as the first CI run of this fixture showed. Wall-clock
figures are still printed alongside for the record.

The in-memory acceptance shape for a padded landing (jobs keep flowing on
the immutable preview, payout publication stays gated, unresolved age
tracked, confirmed reads resume on completion) is pinned in
JobBundleCacheTests.test_job_issuance_continues_during_padded_landing.

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

* Keep the startup gate closed until outbox enumeration is untruncated

When a restart found more than MAX_PENDING_BLOCK_CANDIDATES (32) pending
outbox rows, replay_pending_block_candidates restored only the first
batch yet still cleared the enumeration-owed gate, so child job builds
could snapshot balances that omit a hidden pending parent's carry.

An owed enumeration now re-queries with a doubled window whenever a
batch comes back full, until the outbox returns fewer rows than
requested; in-flight dedupe makes re-seen rows free. The window is
capped at MAX_BLOCK_REPLAY_ENUMERATION_ROWS (1024) to bound one pass's
memory: at the cap the gate stays closed while the restored batch
drains and the submitter loop re-enumerates the remainder. Steady-state
polls keep the single-batch behaviour. The single-flight call key now
carries the window so a timed-out query is only reused by an attempt
requesting the same window.

Codex review: #120 (comment)

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

* Count worker-reported ledger deadlines as call-class timeouts

A server-side statement cancellation normally completes the bounded
ledger worker with a LedgerOperationTimeout before the coordinator-side
wait deadline expires, so _run_block_submitter_ledger_call took the
completion path and recorded the call with timed_out=False before
re-raising. A real PostgreSQL cancellation of the gating startup
enumeration therefore never incremented
qbit_prism_block_ledger_call_timeouts_total{call_class="landing"} and
the documented landing-timeout alert stayed silent.

Every operation behind the wrapper is a database call, so a completed
call whose error is a TimeoutError now records timed_out=True under its
call class.

Codex review: #120 (comment)

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

* Restrict landing timeout escalation to ledger-originated deadlines

_block_landing_ledger_statement_timeout_scope wraps the whole landing
tail, which also runs qbit RPCs and audit/build work. Its blanket
except TimeoutError treated a node RPC timeout (e.g. getblockhash) as a
landing database timeout: it incremented the landing-timeout alert
series and doubled the next PostgreSQL budget for the same block hash
even though no database deadline expired.

The scope now escalates and counts only LedgerOperationTimeout and
BlockSubmitterDatabaseTimeout; other timeouts still propagate and the
call duration is still recorded, without the false alert or deadline
widening. Tests that simulated a postgres deadline with a bare
TimeoutError now raise LedgerOperationTimeout, matching what every
ledger backend actually raises.

Codex review: #120 (comment)

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

* Block job issuance at the unresolved accepted-parent depth cap

The depth gate in _await_pending_parent_payout_preview only rejected
job construction once the unresolved depth already exceeded
PRISM_ACCEPTED_PARENT_UNRESOLVED_DEPTH_MAX. A child issued while
exactly depth_cap landed transitions were unresolved could land and
create a (cap + 1)th, so the configured maximum did not actually bound
the prospective balance chain the constant documents.

Issuance now stops at the cap (>=). The default cap of 8 keeps the
issue #188 degradable-barrier behaviour: children continue to flow
against published previews while fewer than eight landings are
unresolved.

Codex review: #120 (comment)

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

* Keep found-block preview publication alive when the window build dies

When _build_payout_ledger_artifact raised (a ledger statement timeout
during the very landing the degraded path exists to tolerate), the
exception aborted candidate preparation, so
_publish_accepted_block_payout_preview fell into fenced local
retention: publication force-blocked, no generation installed, and
build_shared_job_bundle rejecting every job on the global
_payout_state_publication_blocked flag before the compact preview at
_prior_balances_for_job_parent could ever be consumed. The timeout
fallback therefore recreated the landing-coupled issuance outage it
was meant to remove.

The immediate-preview window build now degrades on exception to the
cached armed window (the existing "build_failed" fallback that was
only reachable when the prepare lock was busy), or to no window at
all — the preview itself is the published balance state either way
(_payout_state_artifact_from_balances), so the atomic publication
proceeds, installs a generation, and reopens admission and delivery.
ShutdownInProgress still propagates, and non-preview causes keep
raising. The fenced-retention branch remains as a last resort for
in-memory publication failures.

The new end-to-end test pins the outage: without this change the
publication stays fenced after a window-build timeout; with it, a
child job build is admitted and consumes the verified preview.

Codex review: #120 (comment)

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

* Mark the health refresher running before the audit listener dispatches

A probe retrying connection-refused queues in the kernel accept backlog
the moment the audit listener binds, so a handler thread can reach
cached_health_payload before start_audit_server sets
_health_refresh_loop_running. That request took the legacy inline path
and ran the cold accepted-share aggregate synchronously on the handler
thread -- timing out the probe and racing the background refresher with
a duplicate minutes-long query -- instead of returning the documented
starting state (issue #188 fix 4).

start_audit_server now marks and starts the nonblocking refresher
before constructing the HTTP server. The refresher does not depend on
the listener, and the legacy inline fallback remains for embedders that
serve the audit handler without start_audit_server.

Codex review: #120 (comment)

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

---------

Co-authored-by: Claude Fable 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.

2 participants