Repository navigation
3.x.x: time candidate claim leases on the taker's monotonic clock, label database refusals truthfully, and page a PostgreSQL outage on its own rule (#581) - #646
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1604a754fd
ℹ️ 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".
…own monotonic clock, as recover does (#581) Codex on #646: abandon still treated `claim_expires_at` before the database clock as proof that a claim had ended. Since 021 a holder's writes are fenced on its token alone, so after a forward step that estimate says nothing about the holder: the command would terminalize a pending row and clear the token under a live holder, whose offer reservation then fails, and the block it was about to offer is lost. abandon now decides a claim as the recovery claim does. It watches the claim's version (token, renewals) for the whole lease on its own clock and abandons by compare and set on that version; a claim that changes meanwhile, renewed or taken over, is live and refuses it with exit 5. The CLI waits once per version and announces the wait, and the wait loop is shared with recover's. --unsafe-database-clock-expiry restores the pre-021 rule, for an operator who knows the holder is gone and the clock has not stepped. Tests: a clock-step test (a forward step no longer lets abandon take a live claim; a holder that stops renewing is abandoned one watched lease later) and CLI tests for the wait, the renewal refusal and the flag. Both fail under the old rule with their headline assertions. The ops doc and the gated-test manifest are updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bel database refusals truthfully, and page a PostgreSQL outage on its own rule (#581) #586's nightly variants showed two gaps. Every outbox deadline was the database clock, so a clock step moved it by the step. Forward, a second frontend took a live claim whose block was still being offered. Backward, the reconciliation row that takeover left waited two hours, and a dead holder's claim would have waited lease + step. Separately, a PostgreSQL outage held only PrismBlockCandidateMetricsUnavailable: the share-refusal rules were gated on a snapshot whose freshness flaps while the publisher waits on the database, and their counters were frozen in it. Database stalls were refused backend-rpc-unavailable, blaming a healthy node. Leases (option B, operator-chosen): migration 021 adds claim_renewals and claim_lease_seconds, a partial index over claimed rows, and the candidate_claim_observed_lease capability (offline, as 018). A frontend times each claim version (token, renewals) on its own monotonic clock from the reply that first shows it, and takes the row over only after the whole lease, by compare and set on that version, whatever the row's schedule unless it is parked. Holders fence on their token; their heartbeat deadline is never extended from the database clock. A row last written later than the clock proves a backward step and is due at once. candidates recover waits out an observed lease (--unsafe-database-clock-expiry keeps the old rule) and its release keeps a schedule within the row's own backoff. candidates abandon times a claim the same way and abandons by compare and set on the version it watched, so a forward step no longer lets it take a pending row from a live holder (Codex on #646); the same flag keeps the old rule. The pool-acquire inventory classifies the revocation helper. Attribution and alerting: backend-database-unavailable for session allocation, the payout reads, job persistence and resume when a SQLx error is in the chain, and stale readiness when the latest refresh failed on the database. rejections_total and accepted_shares_total render at scrape time, the two share-refusal rules drop the snapshot gate, and PrismDatabaseUnavailable (database collector unavailable for 2 m, paging) is added, with the qbit-tools patch regenerated. #586's nightly tests now assert the new behaviour. Three adversarial verifications: leases and labels requested changes (a renewal after a backward step stranding a dead holder's row; stale readiness during an outage still blamed the node), both fixed with regression tests; the re-verification approved. Rebased onto 3.x.x 90327e8 as one commit (PR #646's series eb5f65e, 1604a75, 5ce263d), past #642 and #645: the cardinality pins are 77 families, 306 startup and 957 populated series; the stratum normalization pin stays 15. Co-Authored-By: Claude Opus 5.5 <[email protected]>
5ce263d to
4de0297
Compare
…bel database refusals truthfully, and page a PostgreSQL outage on its own rule (#581) #586's nightly variants showed two gaps. Every outbox deadline was the database clock, so a clock step moved it by the step. Forward, a second frontend took a live claim whose block was still being offered. Backward, the reconciliation row that takeover left waited two hours, and a dead holder's claim would have waited lease + step. Separately, a PostgreSQL outage held only PrismBlockCandidateMetricsUnavailable: the share-refusal rules were gated on a snapshot whose freshness flaps while the publisher waits on the database, and their counters were frozen in it. Database stalls were refused backend-rpc-unavailable, blaming a healthy node. Leases (option B, operator-chosen): migration 021 adds claim_renewals and claim_lease_seconds, a partial index over claimed rows, and the candidate_claim_observed_lease capability (offline, as 018). A frontend times each claim version (token, renewals) on its own monotonic clock from the reply that first shows it, and takes the row over only after the whole lease, by compare and set on that version, whatever the row's schedule unless it is parked. Holders fence on their token; their heartbeat deadline is never extended from the database clock. A row last written later than the clock proves a backward step and is due at once. candidates recover waits out an observed lease (--unsafe-database-clock-expiry keeps the old rule) and its release keeps a schedule within the row's own backoff. candidates abandon times a claim the same way and abandons by compare and set on the version it watched, so a forward step no longer lets it take a pending row from a live holder (Codex on #646); the same flag keeps the old rule. The pool-acquire inventory classifies the revocation helper. Attribution and alerting: backend-database-unavailable for session allocation, the payout reads, job persistence and resume when a SQLx error is in the chain, and stale readiness when the latest refresh failed on the database. rejections_total and accepted_shares_total render at scrape time, the two share-refusal rules drop the snapshot gate, and PrismDatabaseUnavailable (database collector unavailable for 2 m, paging) is added, with the qbit-tools patch regenerated. #586's nightly tests now assert the new behaviour. Three adversarial verifications: leases and labels requested changes (a renewal after a backward step stranding a dead holder's row; stale readiness during an outage still blamed the node), both fixed with regression tests; the re-verification approved. Rebased onto 3.x.x eedf331 as one commit (PR #646's series eb5f65e, 1604a75, 5ce263d), past #642, #645 and #643: the cardinality pins are 79 families, 313 startup and 964 populated series; the stratum normalization pin stays 15. ReadinessState keeps #643's poll fields and refresh_failed_on_database, whose comment now says that a guarded tip poll (#622) decides whether readiness ages during a database outage and this flag decides the label once it does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
4de0297 to
8687163
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 86871631e8
ℹ️ 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".
…resh lock, so an older refresh cannot overwrite a newer one's (#581) Codex on #646: refresh_once wrote refresh_failed_on_database after refresh_once_inner had returned and dropped refresh_lock. Two overlapping refreshes run serialized under that lock, but the older one could record its outcome after the newer one had: a success overwriting the database failure that followed it. If readiness then aged out, the refusal would blame the node although the latest refresh failed on PostgreSQL. The work under the lock moves to refresh_locked, and refresh_once_inner records the outcome before the lock guard drops, so outcomes land in the order the refreshes ran. The lock order (refresh lock, then readiness) is the one the refresh already takes. Test: a refresh paused in its revision read fails on the database while the test holds readiness, so it cannot record yet. The refresh lock must still be held, and the newer, successful refresh's outcome is the one left. On the old code the lock was already free (the headline assertion fails). The stale-readiness test's comment now names #643's guarded tip poll. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…database's, whichever of the deadline and the statement failed first (#581) CI shard 0 on 0b21539 failed compact_runtime_e2e's issued_expiry_during_sql_wait test: a persistence queued on a database lock past its 1 s deadline was refused backend-database-unavailable when the statement its shortened statement_timeout cancelled failed first, and backend-rpc-unavailable when the deadline fired first (a plain string error). The label depended on which future completed first. Persistence waits on the ledger alone (its clock and revision reads, the batch transaction and its row locks, the compact repair it writes), so an expiry is the database not answering in time. save_issued_record, the one place that knows the persistence's own deadline, now marks a failure that outlived it with a typed IssuedPersistenceExpired, and persist_issued_job labels that backend-database-unavailable before the SQLx-chain rule. A failure inside the deadline keeps that rule (a statement error is the database's; an authority refusal stays backend-rpc-unavailable). The full error chain is logged. Tests: a unit test forces both orderings on the fake ledger (a statement failing inside the deadline; the deadline elapsing while the save still waits, its statement failing afterwards), both backend-database-unavailable; without the classification the second is labelled the node's, as in CI. The e2e test now runs both orderings on PostgreSQL (the waiting statement cancelled inside the deadline; the lock held past it) and expects the database label for each. A sweep of other backend-rpc-unavailable assertions found none on a database-wait path. prism-rejections.md names the case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd label session timeouts and hung refreshes by the dependency they wait on (#654, #655) (#667) * 3.x.x: time CTV fanout claim leases on the taker's monotonic clock, so a database clock step neither double-claims nor strands a fanout (#654) #646 moved candidate claims onto an observed lease (#581), but CTV fanout claims still compared `claim_expires_at` and `next_broadcast_attempt_at` with `clock_timestamp()`. A forward database clock step, which a failover can cause, made a live claim look expired: a second frontend took the fanout over and broadcast it again, and the holder's settlement write was refused. A backward step left a dead holder's claim waiting lease + step, and an attempt or confirmation check scheduled before it waiting its delay + step. Migration 022 (offline, as 021) adds `claim_renewals` and `claim_lease_seconds` to `qbit_ctv_fanout_artifacts`, a partial index over claimed fanouts and the `fanout_claim_observed_lease` capability. Fanout claims now follow #581's contract: - Every fanout claim poll surveys the claimed fanouts and times each version (token, renewals) on the frontend's own monotonic clock, through the same ClaimObserver, now shared in ledger/claim_observer.rs with one instance per kind of claim. It takes a fanout over only after watching the same version for the whole lease, by compare and set on that version, before the lane, which takes only unclaimed due fanouts. A claimed fanout is taken over whatever its schedule unless held at infinity. - The holder is fenced on its token alone. Its lease is its own monotonic deadline: the broadcaster's 90 s attempt deadline is below the 120 s lease every renewal takes, now named constants with a compile-time check. - The survey makes due, at once, every unclaimed fanout whose last write is later than the database clock (a backward step), and a shutdown release keeps its schedule but never later than the clock. - Every statement that clears a fanout claim clears its lease and version. - `ledger::revoke_fanout_claims` replaces the tests' ad hoc `claim_expires_at` rewrites. The lane's claimable predicate is unchanged in meaning, written once and shared by the lane, the takeover and the survey. EXPLAIN on 100k settled fanouts: the survey is two index scans (0.3 ms); the lane's plan and cost are the same as before. Tests: five ledger clock-step tests (forward on a live claim and its holder's writes; backward on a dead holder, on a retry, after one renewal, and on a shutdown release) and a broadcaster test with a forward step in the middle of an attempt. All six fail on b8aeb29 with their headline assertion and pass here. The fanout tests that expired a claim by rewriting `claim_expires_at` now revoke it, and assert that only a takeover fences the old holder. Migration pins, the recovery-evidence script, the pool-acquire inventory and the gated-test list include 022. * 3.x.x: label a session timeout and a hung refresh by the dependency they were waiting on, so a database stall no longer reads as the node's (#655) #646 labelled database refusals backend-database-unavailable but left two paths blaming the node during a database stall. The Stratum session's own timeouts (session allocation, job persistence, job resume, initial job delivery) could not tell what the backend was waiting on, and a template refresh that hung on the database, rather than failing, recorded no database failure, so the stale-readiness refusal that followed named the node. A new crate::waiting module lets work name the steps it waits on the ledger database, into a tracker its timer reads when the deadline passes, while the work is still pending (dropping the work ends its marks). The tracker reaches the work through a task-local, as READ_DEADLINE does, so the MiningBackend trait and its implementations are unchanged. The coordinator marks the ledger allocation, the whole issued persistence (consistent with IssuedPersistenceExpired, so the label never depends on which deadline passes first), each ledger step of resume and of the issuance-authority reads, and every ledger step of a refresh. Node calls, CPU work and admission stay unattributed and keep backend-rpc-unavailable. Marks are never placed inside work shared between tasks: a waiter marks its own await of a shared read, and the resume flight's shared reconstruction keeps its own tracker, which each waiting session follows. The session runs each backend call under waiting::timeout and labels an expiry with StratumError::timed_out. The coordinator registers the refresh in flight with its start and tracker; a submit refused for aged-out readiness is the database's when the latest refresh failed on it (#646), or when the refresh in flight has outlived its deadline, the health timeout, and is still waiting on the database. Tests: allocation, persistence and resume stalled on the database through the real coordinator; a refresh held in its first ledger read past its deadline; controls for a refresh held on the node or inside its deadline, and for a backend stall it does not name; a third-party backend naming its step; the tracker's own semantics. The four regressions fail on 3.x.x b8aeb29 with backend-rpc-unavailable. Docs: the rejection registry, the stratum admission note, the metric inventory and the load harness's counted classes. * 3.x.x: revoke a dead fanout owner's claim in the live lost-reply tests, mark the replacement-lease payout read, and tighten the revocation hook (#654, #655) CI shard 0 on aca451e: live_regtest's two fanout lost-reply tests waited 60 s for a survivor that, since #654, takes a dead owner's fanout over only after watching its claim for the whole 120 s lease. Their shared expire_dead_lease helper revoked candidate claims but only backdated claim_expires_at for fanouts, which no longer ends a fanout claim. It now revokes both kinds. Both tests pass locally against the pinned qbitd 1.0.0. /code-review high on #667: - prove_published_lease's payout_state read was unmarked, so an issuance under a replacement lease that stalled there still read as the node's. It is now an on_database step. - revoke_fanout_claims touches only claimed fanouts and no schedule. A takeover does not wait for a schedule, and its due_now option could only make held (infinity) fanouts due. - The survey reply decoding and the takeable-claim filter are shared in claim_observer.rs by the candidate and fanout claim polls. - refresh_once_inner's failure flag no longer shadows on_database. - Docs: a claimed fanout is held only at infinity (its own schedule is no hold); push a dead holder's fanout with broadcast-ctv by revoking its claim first; issued-job persistence counts as one database step as a whole, as IssuedPersistenceExpired does. * 3.x.x: mark a persistence's ledger writes rather than the whole persistence, so a session timeout in its repair's encoding or admission is not the database's (#655) Codex on #667 (P2), and /code-review high: persist_issued_job marked the whole issued persistence as a database step. On the compact repair path that includes the repair lock, build-slot admission and the blocking encode, so a session deadline passing during CPU work or admission read as the database's although no statement was pending. The two writes in save_with_dependency are now the marked steps: the issued batcher's save, whose batcher does nothing but write batches, and the compact repair's save. The clock, revision, window and payout reads were already marked where they run. A persistence that outlives the issued job's own deadline stays the database's, as #581 decided (IssuedPersistenceExpired), and docs/prism-rejections.md now says which persistence steps are marked. Test: a persistence whose repair is held in its encode at a session deadline reads Unattributed. With the whole persistence marked it read Database (the test fails); the batch-write stall test still reads the database's. --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Closes #581.
#575's nightly variants (#586) found two gaps. Safety held in every run; both are liveness and attribution problems.
Problem
1. A database clock step moved every outbox deadline by the step.
qbit_block_candidate_outbox.next_attempt_atandclaim_expires_atwereclock_timestamp()plus a backoff or lease. Every claim lane and every holder write compared them withclock_timestamp().2. A PostgreSQL outage was alerted only through
PrismBlockCandidateMetricsUnavailable, and database stalls were blamed on the node.SETTLEMENT_LOCKholder, PostgreSQL atmax_connections) was refused asbackend-rpc-unavailable. So the reason-labelled counters andPrismRejectRatioByReasonHighpointed at the node while it was healthy.Decision
Option B, chosen by the operator: leases are timed on the taker's own monotonic clock. The alternatives were a bounded clamp on the database clock, which cannot stop a forward step from ending a live claim early, and a forward-step guard, which misses steps across a restart.
Change
Migration 021 (
candidate_claim_observed_lease)claim_renewals: 0 at a claim, +1 per renewal.claim_lease_seconds: 1–600; NULL for a pre-021 claim, timed as 600 s; 0 revokes a claim.candidate_claim_observed_lease = 1.Takeover.
(claim_token, claim_renewals). The frontend starts its own monotonic clock at the reply that first shows a version.FOR UPDATE SKIP LOCKED).infinity) row is left to the operator.Holder.
Retries. A row last written later than
clock_timestamp()proves a backward step. Each claim poll makes such a row's retry due at once, so a step delays a retry by less than its own backoff, never by the step.candidates recover.--unsafe-database-clock-expiryrestores the old rule and is documented as unsafe during a clock step.candidates abandon.recoverdoes: by default it waits out an observed lease and abandons by compare and set on the version it watched. A claim that changes meanwhile (renewed, or taken over) refuses it with exit 5.pendingrow whose live holder was about to offer the block.--unsafe-database-clock-expiryrestores the old rule, documented as unsafe during a clock step.Revocation hook.
ledger::revoke_candidate_claimsreplaces the ad hocclaim_expires_atrewrites in the lease tests.backend-database-unavailable, a new rejection reason.save_issued_recordmarks it with a typedIssuedPersistenceExpired, andpersist_issued_joblabels it before the SQLx-chain rule.backend-rpc-unavailable.Live counters.
qbit_prism_rejections_totalandqbit_prism_accepted_shares_totalare rendered at scrape time.PrismShareAppendFailuresandPrismRejectRatioByReasonHighno longer require a fresh snapshot.New rule
PrismDatabaseUnavailable.qbit_prism_collector_available{collector="database"} == bool 0for 2 minutes. Critical, paging, gated only onup == 1.#586's nightly tests.
PrismDatabaseUnavailableand at least one more rule to hold on every server.Docs.
prism-ledger-ops.mdcovers the lease and retry contract, revocation and the upgrade. Also updated:prism-rejections.md,prism-native-metrics.mdandprism-b4-stratum-admission.md.Migration notes (D5)
021 is an offline upgrade, like 018:
qbit_prism_instancesrow reportsstoppedordrained. The migrator refuses any other instance before applying 021, and holds the registration lock through the commit.Mixed versions are not supported. A pre-021 frontend takes claims over by the database clock and never writes the columns a post-021 frontend times. The capability refuses older binaries at every later connect.
Tests
New tests:
ledger_postgres::clock_stepstests: forward and backward steps on live and dead claims, retries, renewal after a step, the recovery claim and release, andcandidates abandon.candidates abandon's observed wait, its refusal of a renewing holder, and the unsafe flag.backend-database-unavailable.The clock-step, abandon CLI, forward-step coordinator and stale-readiness tests were run against the code before their fix: they fail there with their headline assertions and pass now. The stall and lease-proof tests assert
backend-database-unavailable, which the old code never produced.Run on this branch as one commit on
3.x.x(90327e8, past #645; the suites below marked † were re-run on d7812be, past #643, and the rollups lib tests on eedf331), against a private PostgreSQL 16, one test binary at a time:--test ledger_postgres -- --test-threads=4†--test candidate_storm†--test candidate_storm_restart--test landing_metrics--test offer_lifecycle†--test postgres_failover†--test observability†--test observability_database -- --include-ignored†--test candidate_dispatch_probe--test b619_gap_work_after_promotion--test candidate_window_switch--test audit_body_normalization--test compact_runtime_e2e(×5 after the expiry fix; its expiry test alone ×10)--test stratum_protocol†--test metrics_allocation†--lib -- --test-threads=4 coordinator:: ledger:: metrics:: stratum:: tools::†--test readiness_rpc†--test work_refresh_metric†--test b478_stale_revision_block†-p qbit-prism-load --test harnessBefore the rebase, a full
cargo test --locked --no-fail-fast -p qbit-prism-server --all-targets -- --test-threads=4run gave 1858 passed and 1 failed (a column pin, since fixed), with 965 gated tests executed and 27 skipped (live_regtest).Also clean:
cargo fmt --all -- --checkcargo clippy --locked -p qbit-prism-server -p qbit-prism-load --all-targets -- -D warningspython3 scripts/generate_prism_metrics.py --checkpython3 scripts/generate_prism_alerts.py --check --snapshot <qbit-tools a007a142>python3 scripts/test_prism_alert_deployment.py --snapshot <…>: 78 original / 78 proposed rulespython3 scripts/test_prism_alert_promql.py --promtool <3.14.0>: 44 expressions, 179 scenarios, 378 expression and 273 alert assertionspython3 scripts/check_e2e_scenarios.pypython3 scripts/check_deleted_test_map.pyThree adversarial verifications:
backend-rpc-unavailable. Fixed.candidates abandonstill trusted the database clock's expiry. Fixed as above, with a clock-step test and CLI tests; both fail on the old rule with their headline assertions.compact_runtime_e2e::issued_expiry_during_sql_wait…labelled an expired persistence by whichever of its deadline and the cancelled statement failed first. Fixed in 4aeb8b2 as above; a unit test forces both orderings, and the e2e test runs both on PostgreSQL.Not run here and why
The build host has no
qbitdand no docker, solive_regtestdid not run. That includes the two #586 nightly tests this PR updates:clock_jump_testsanddisk_exhaustion_tests. The fuzz seed replay was not run either.Follow-ups
backend-rpc-unavailable. Nothing has recorded a database failure yet. 3.x.x: renew readiness from a guarded tip poll so a slow rebuild no longer refuses current work as 'tip polling stale' (#622) #643 mostly closes this, because a guarded tip poll keeps readiness fresh while the published work is current.job resume timed out,job persistence timed out,session allocation timed out) are stillbackend-rpc-unavailable. The session's timer cannot tell the database from the node.Merge notes
ReadinessStatekeeps its fields andrefresh_failed_on_database, whose comment now says that a guarded tip poll decides whether readiness ages during a database outage and this flag decides the label once it does. The label is decided like this:backend-database-unavailablebackend-database-unavailablebackend-rpc-unavailablebackend-rpc-unavailable3.x.xeedf331, past 3.x.x: answer a session's submits while its own job rebuild is built and persisted, and measure what still waits for it (#621) #642 (3.x.x: a session's share acks wait behind its own queued job rebuild (the request loop reads nothing while deliver_job runs) #621), 3.x.x: refuse a block on work from a lost replication gap before its offer, and stop issuing that work after an async promotion (#619) #645 (3.x.x: after an async promotion, a block on a job issued in the replication gap is offered and lands on chain but can never be landed in the pool (window range incomplete) #619) and 3.x.x: renew readiness from a guarded tip poll so a slow rebuild no longer refuses current work as 'tip polling stale' (#622) #643 (3.x.x: new-tip job delivery misses a 30 s bound with ~3,000 sessions at a 1 s reanchor in release ('tip polling stale' deferrals) #622), so the cardinality pins are 79 families / 313 startup / 964 populated series. The stratum normalization pin stays at 15, andtools.rskeeps bothlanding_trimand the recoverytakeoverargument.🤖 Generated with Claude Code