Repository navigation
Fix the found-block landing livelock: O(recipients) balances, landing-class deadlines, degradable barrier, replay hardening (1.x.x) - #120
Conversation
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]>
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]>
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]>
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]>
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]>
72700d7 to
430efb2
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72700d768e
ℹ️ 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".
430efb2 to
f70683e
Compare
_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]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9a518c4c1
ℹ️ 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".
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]>
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]>
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]>
_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]>
Summary
Layered fix for the found-block landing livelock that forced the rollback of the
1.x.xmainnet deploy on 2026-08-14 (pin4e66520). On the first found block, the post-acceptance landing ran an O(history) prior-balances aggregate under the 1-second submitter statement deadline introduced by #113. The aggregate could no longer finish inside that budget at production carry-forward volume (~1.4M rows for ~13 miners), so the landing was statement-canceled on every attempt (13 observed), the accepted-parent payout barrier from #50 blocked template refreshes for over four minutes, and job issuance collapsed while the mainnet node itself accepted the block in ~1s. Durable outbox replay after restart re-entered the same structurally doomed path.Implements the full layered re-deploy gate from the incident review: fixes 1 + 2 + 3 + the replay portions of 4 + 5 + 6, one commit per fix.
Everything the deploy proved out is preserved: the #113 submit-first fast lane, #112 sub-second payout anchors, #111 fast lease release, and #115
trust_blockedelimination are untouched.Commit 1 — Make the current prior-balances read O(active recipients)
qbit_current_carry_forward_balances()recomputedSUM(gross - onchain)over every activeqbit_payout_carry_forwardrow on each call. That read crossed the one-second line silently as the table grew and wedged the landing.Design decision. The incident review's preferred index-backed latest-row-per-recipient query is provably not an exact replacement: the existing Postgres ledger test pins reorg semantics in which a mid-history reversal leaves later rows' recorded
carry_forward_balance_satsstale until reconciliation (recorded 1250 vs. correct active balance 250, with the integrity report flagging exactly that state) while the recomputed aggregate stays correct. The incident review anticipates this: "Treat a transactionally maintained current-balance table as a separate schema/invariant design if the index-backed form is insufficient." That is what this implements:qbit_payout_carry_forward_current— one row per(miner_id, payout_order_key, p2mr_program)partition holding the active-row balance and count, maintained by row-level triggers onqbit_payout_carry_forwardandqbit_pool_blocksinside the same transaction as every write that changes the active carry set. Readers get snapshot-consistent results under concurrent settlement; exactness holds by construction, including through the mid-history-reversal state that defeats recorded-balance reads.qbit_current_carry_forward_balances()now reads the summary. Identity selection, program-level alias aggregation,HAVING <> 0, and ordering are byte-identical;qbit_current_owed_balances()inherits the fast path.qbit_recomputed_carry_forward_balances();qbit_carry_forward_current_drift()cross-checks the two, and the integrity report now exposescurrent_drift_count/current_driftso any drift is an alertable signal in production.qbit_rebuild_carry_forward_current_balances()as the ops resync hook, and TRUNCATE triggers for completeness. The delta helper is update-first becauseINSERT ... ON CONFLICTevaluates theactive_row_count >= 0CHECK on the proposed tuple before conflict resolution.Measured (scale fixture, 1M carry rows): old recompute ~1.2s — past the very deadline that caused the outage — vs. ~6ms warm / ~11ms cold for the summary read.
Commit 2 — Split submitter DB deadlines by call class
PRISM_BLOCK_LANDING_DB_TIMEOUT_SECONDS(default 30s) now governs every landing-class statement — accepted-block persist, prior balances, confirmation, and prepared-state rejection of a terminal candidate — starting with the first attempt. A landing-class operation never begins at the poll budget.PRISM_BLOCK_LANDING_DB_TIMEOUT_MAX_SECONDS(default 120s). Escalation state clears with the candidate retry state; retries stay paced by the existing backoff; the stuck-call and coordination watchdogs remain the overall bound.SET LOCALscopes roll back with the transaction) and the subprocess backend's exit drops the session — no timed-out query continues invisibly. The scale fixture proves this against a live database.Commit 3 — Decouple job issuance from slow landing bookkeeping
Not a timing bypass — the change builds on the invariants the barrier already enforces:
PRISM_ACCEPTED_PARENT_UNRESOLVED_DEPTH_MAX(default 8) bounds how many landed-but-unresolved transitions may stack prospective balance chains; beyond it, job builds fail closed with an explicitTemplateRefreshBlocked. The durable outbox bound remains the wider backstop.The bounded preview wait and withdrawn/invalidated semantics are unchanged.
Commit 4 — Close startup and replay hazards
state: "starting"503 while the cold aggregate (minutes on a grown ledger) runs in the background loop — no more connection-refused window, and the readiness delay is no longer conflated with writer-lease recovery.Commit 5 — Observability and pre-deadline signals
New
/metricsseries so query growth becomes a ticket instead of an outage: per-call-class ledger call counts / timeouts / current (escalated) budget / last & max duration; unresolved accepted-parent transition count and oldest age; preview-wait timeout counter; prior-balances read count / last / max duration; startup phase gauges.docs/prism-ledger-ops.mddocuments the series and alert thresholds (prior-balances latency at ~20% of budget, any landing-class timeout, unresolved-parent age beyond the preview wait).Commit 6 — Production-scale fixture with plan and budget gates
Every latent charge in this incident was invisible on the empty databases ordinary tests run against.
test/test-prism-postgres-scale.sh(make test-prism-postgres-scale, wired into CI) seeds a named, reusable fixture — configurable scale with skewed miner distribution; CI defaults 120k carry / 200k share rows, env knobs raise it to the ~5M/~50M production shape — and asserts:pg_stat_activityis polled to prove nothing keeps running invisibly, and the next read succeeds cleanly;The in-memory acceptance shape for a padded landing (jobs keep flowing on the immutable preview, publication stays gated, unresolved age tracked, confirmed reads resume on completion) is pinned in
JobBundleCacheTests.test_job_issuance_continues_during_padded_landing.Verification
1.x.xbase (the only failures in the dev sandbox are pre-existing docker-dependent lifecycle tests, verified identical on the base commit).shellcheck -xandbash -nclean on the new script.Acceptance criteria mapping
pg_stat_activityassertion; retries stay paced.Out of scope
Deploy-tooling follow-ups (previous-image retention, wrapper-only recreation, environment interpolation guard, sustained deploy health gate) belong to the deploy-tooling repository per the incident review. The full N→N-1 cross-build replay gate needs the previous release's build; the durable outbox format contract test covers the payload shape it depends on. The three-blocks-landed promotion criterion is a post-deploy soak gate, not CI.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.