Repository navigation
3.x.x: wait, within a bound, for the failover standby to flush a found block's reservation before submitblock (#529) - #570
Merged
Conversation
…d block's reservation before submitblock (#529) Under asynchronous D3 the replication gap can hold a found block's candidate row and offer reservation as well as shares. A block offered to the node whose rows are then lost with the primary is on chain with no candidate, audit or pool-blocks record on the promoted primary, and no code path lands an on-chain block without its candidate row (#529 item c). After the offer reservation commits, the offering frontend now reads the primary's pg_current_wal_flush_lsn(), which covers the candidate row and the reservation, and polls pg_catalog.pg_stat_replication until the named standby's flush_lsn (state streaming) reaches it, then calls submitblock. It runs before the strictly-live renewal, so the token fence stays immediately before the send. flush_lsn is what synchronous_commit=on would wait for; sent_lsn or write_lsn would not survive a promotion. - PRISM_OFFER_STANDBY_APPLICATION_NAME (unset = off) and PRISM_OFFER_STANDBY_FLUSH_WAIT_MS (default 250, 0 = off, at most 10000), parsed into Config, printed by check-config, wired through Compose and .env.example, and listed in the settings inventory. - The wait never holds the block: a standby that is not streaming is not waited for (absent); at the bound the block is offered anyway (lagging); a database error or a writer role without pg_read_all_stats is reported at once (failed). Every outcome but confirmed logs the block hash at WARN for post-failover reconciliation. Each poll takes and returns a pooled connection; one timeout covers every checkout and read. - synchronous_standby_names stays empty: no commit waits, shares and their ACKs are unchanged. D3 is unchanged. - qbit_prism_block_offer_standby_wait_total{outcome} (all four series start at zero) and a PrismBlockOfferStandbyUnconfirmed warning (any non-confirmed outcome in 30 minutes, no dwell, never pages), generated into the migration table and the qbit-tools patch, with seven promtool scenarios. - self-check refuses a configured wait when the writer role cannot read replication positions (GRANT pg_monitor) or the name matches no single streaming standby, and reports what it read. - Docs: the HA reference gains a found-block section (behaviour, grant, measurements, the amended accepted-loss statement) and promotion step 6, reconciling the logged hashes after a failover; the ledger operations guide points to it. Next to #291's sync experiment it records that PostgreSQL disables statement_timeout before the COMMIT's sync-rep wait: with the standby down a SET LOCAL synchronous_commit COMMIT blocked for 18.7 minutes despite statement_timeout=2s, so a statement timeout cannot be the duration guard. Tests (all gated, listed in test/prism-gated-tests.txt): - live_regtest offer_standby drill on the #531 fixture: a 400 ms lagging replication link, cut the moment the found block reaches the node, then fence, stop, promote and move the endpoint. The promoted primary holds the reservation and the block lands once. - postgres_failover offer_standby_flush on a disposable primary/standby pair with a non-superuser writer: fails fast without pg_monitor (and self-check refuses), confirms after the grant, returns at the bound with the lag while the standby's WAL receiver is suspended, confirms after it resumes, does not wait for a stopped standby (self-check refuses), and ignores another application name. - coordinator offer_standby_tests: an absent standby lets the block go at once (counted absent, landed once); with the wait off nothing is counted. - Config parsing unit test. Mutants caught: no wait (drill, absent test); sent_lsn instead of flush_lsn (drill, pair test); an absent standby waited for until the bound (pair test, absent test); no privilege check (pair test); counter not recorded (absent test); alert without lagging, with a 5 m window, counting confirmed, or with a 3 m dwell (promtool scenarios). Closes #529 Refs #291 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Member
Author
|
@cursor review |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 3b0228a. Configure here.
…ushed, and document the reserved-but-unsent window (#529 review) From the #570 review lanes: - A second standby sharing the application_name, or a lingering walsender from a dropped connection, could confirm the wait for the standby that had not flushed (ORDER BY flush_lsn DESC LIMIT 1). The wait now confirms only when every connected standby under the name has flushed through the target, so such a row can delay it to the bound but never confirm it falsely. Runtime and self-check read the same rows (one STANDBY_ROWS predicate), and self-check refuses a name matching more than one standby or one that has not reported a flush position yet. - A standby in state catchup after a reconnect counted as absent and got no wait; connected standbys in streaming or catchup are now waited for. - The wait widens the window in which a crash or a lost claim leaves a block reserved but never sent, from one round trip to at most the bound. That is the price of keeping the reservation on the standby; it is now stated at the call site, in the module and in the HA doc's accepted-loss list. - StandbyWait { waited, durability } replaces the per-variant waited field; durability.outcome() returns the metric label, so the second four-case label mapping and the nested result go away, and the coordinator logs one INFO or one WARN (fields and message prefix unchanged). - The poll's read ceiling (bound / 1 ms) is documented, and the HA doc no longer claims write_lsn is tested. The postgres_failover pair test adds a second standby under the same name whose WAL receiver is suspended: the wait lags to the bound although the first standby flushed, and self-check refuses the name. A mutant that confirms when any same-named row flushed (bool_or) fails it; the earlier mutants (no wait, sent_lsn, absent waited to the bound, no privilege check, no counter) still fail their tests. Refs #529 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Member
Author
|
deep-review ledger (head Stakes: high, because the change sits on the found-block submission path (block rewards). Lanes run:
The second, cross-provider adversarial lane was not run: this work is limited to Claude models. No review bots commented on this PR.
Verification on
|
This was referenced Sep 29, 2026
Closed
djh58
added a commit
that referenced
this pull request
Sep 29, 2026
…cenario manifest (#560) (#584) The manifest check added by #560 fails on 3.x.x (tests/test_check_e2e_scenarios.py::test_the_checked_in_manifest_passes): two live_regtest tests in the PR gated list are cited by no running scenario. Both belong to existing #521 scenarios: - pg_failover_tests::offer_standby::a_found_block_offered_after_the_standby_flush_survives_a_replication_cut_at_submitblock (#570, #529 item c) runs on the #521 scenario 3 failover fixture; its criteria gain the standby flush wait's claim. - node_outage_tests::node_restarted_into_warmup_before_submitblock_lands_the_block_once (#566) is a #521 scenario 4 node-outage drill. scripts/check_e2e_scenarios.py and its tests pass. Refs #560, #570, #566. Co-authored-by: Claude Opus 5.5 <[email protected]>
djh58
added a commit
that referenced
this pull request
Sep 29, 2026
…abase answers, finish an offer in flight at shutdown, and record a recovered reservation's outcome as unknown (#529, #578) (#585) * 3.x.x: retry a failed candidate attempt's claim release until the database answers, finish an offer in flight at shutdown, and record a recovered reservation's outcome as unknown (#529, #578) A PostgreSQL failover while a found block is mid-landing delayed the landing by up to the 120 s candidate lease (#529 item b). The offering frontend's attempt failed on the old primary's dead connections, its claim release failed on the same connections, and no frontend could take the row until the lease expired. The submit loop now keeps a failed attempt whose release did not reach the database, and retries the same token- and lease-fenced release (the one retry_candidate runs, split out as release_candidate_claim) about once a second until the database answers or the lease's local end passes. At shutdown it tries each once more through release_recovery_claim. - Structural, not by convention: claim_release::Attempt owns the claim, the future of Attempt::run borrows it, and the only ways to release it (Attempt::failed, and at shutdown Attempt::hand_back_at_shutdown, which is #573's hand-back moved there unchanged: same release, reason, bound and logs) consume it, so the borrow checker drops the work first. Nothing this process started under the claim, submitblock included, can still run once the row is released. - The release is fenced on the token and the live lease, so it changes nothing once another frontend has taken the row or the lease expired. Offer-state rows are never offered again by the recovery, as before. - Retries keep their schedule while the loop processes other rows; before each claim the loop waits for at most one bounded retry (the lease's 5 s bound, never past the lease's local end). - The lease's local end comes from the heartbeat itself (the start of the last successful renewal plus the lease), never later than the database's own expiry. - WARN logs when a release is deferred and when it succeeds or expires. - A holder that died with the old primary still leaves its claim to the lease. A takeover keyed on the promotion (a timeline-stamped claim) would cover it, but needs a migration and preempts every healthy holder after a promotion; it stays a documented option in #529. A graceful shutdown between the offer reservation's commit and submitblock dropped the attempt, leaving an offer_reserved row that was never sent and that recovery never offers again, so a restart could lose a found block; #570's standby wait sits inside that window (#578). The offer path now holds an offer section from just before the reservation until the node's answer is recorded or the unsent reservation is returned to pending. A shutdown that finds one open keeps driving the attempt until it closes, within the send's deadline, the standby wait's bound and the lease's bound for the reservation and the recording, logs that it waits, and only then stops; the landing after it is left to the next claim, which lands the offered row without another offer. Pre-dispatch failures still return the reservation through release_unsent_offer. A crash in the window is unchanged: recovery reconciles the reservation as delivery unknown. A recovered offer_reserved row whose call's answer was never recorded landed submitted with offer_outcome NULL (#529 item a). finish_candidate now records unknown for an offer-state row without an outcome, as the reconciliation and orphan dispositions already do; pending rows keep none. Tests (gated, listed in test/prism-gated-tests.txt): - claim_release_tests, a third frontend reaching PostgreSQL through a TCP relay the test cuts and heals, with a 30 s lease: the claim is released 0.3 s after the database answers and only after the attempt's work was dropped, then another frontend recovers the reservation and lands it with outcome unknown and no submitblock; a deferred release leaves a claim another frontend took after expiry untouched; shutdown releases a deferred claim. - offer_shutdown_tests: a shutdown with the attempt parked right after the reservation (before the standby wait) or right before the send waits for the offer; the block is sent once, recorded accepted, and landed once. - The live async failover drill now asserts landing within 30 s of the promotion (2.3 s here; 119.8 s with the retry removed) and the unknown outcome. Docs: the ledger operations guide describes the deferred release, the shutdown mid-offer and the recorded outcome, and the HA reference's promotion step 5 says when a mid-landing block lands. Closes #529. Closes #578. Co-Authored-By: Claude Opus 5.5 <[email protected]> * 3.x.x: bound the submit loop's shutdown by one 20 s budget, give the offer section the renewal's allowance, and classify the moved pool checkouts (#529, #578) Review of #585 found two ways the shutdown path could run out of time. - The offer-section bound allowed the lease's bound twice, for the reservation and the recording, but a section has three database steps: the strictly-live renewal before submitblock is the third. A slow but live database could end the wait during the send and drop a reserved block, the loss #578 prevents. It now allows the lease's bound three times. - After the shutdown signal the loop could spend the section wait, the claim hand-back and one bounded attempt per deferred release in series, past the server's 30 s join of its tasks, which then aborts the loop and leaves its claims to the lease. Everything after the signal now shares one 20 s budget (SHUTDOWN_BUDGET), leaving room for one bounded retry already running when the signal came, and a signal that arrives during the pre-claim retry claims no new row. scripts/prism_pool_acquires.json follows the moves: the heartbeat's checkout is now in with_tracked_heartbeat, retry_candidate's BEGIN in release_candidate_claim, and Attempt::run is classified non-database (a name collision, like the server's runtime run), which the Python shard's pool-acquire check requires. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Oct 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #529 (item c). Refs #291.
Why
Under asynchronous D3 the replication gap can hold a found block's candidate row and offer reservation as well as shares. The #531 drills showed a block found in the gap loses its outbox row with the primary. If that block was already offered, it is on chain with no candidate, audit or
qbit_pool_blocksrecord on the promoted primary, and no code path lands an on-chain block without its candidate row. The #529 prototype comment measured the narrowest fix; this PR turns it into a production feature.What
After a found block's offer reservation commits, the offering frontend reads the primary's
pg_current_wal_flush_lsn()(which covers the candidate row and the reservation) and pollspg_catalog.pg_stat_replicationuntil theflush_lsnof every standby connected under that name (streaming, orcatchupafter a reconnect) reaches it. Only then does it callsubmitblock. The wait runs before the strictly-live renewal, so the token fence stays immediately before the send. It targetsflush_lsn, whatsynchronous_commit=onwould wait for;sent_lsnorwrite_lsnwould not survive a promotion.PRISM_OFFER_STANDBY_APPLICATION_NAMEapplication_name, at most 63 printable ASCII bytesPRISM_OFFER_STANDBY_FLUSH_WAIT_MS0turns the wait off; at most 10000It never holds the block.
confirmedwaited_usabsentlagginglag_bytesfailedpg_read_all_statssynchronous_standby_namesstays empty. No commit waits for the standby, so share appends and their ACKs are unchanged and D3 is unchanged. Block-only proofs are the one exception: their ACK already waits for their candidate's disposition, so a lagging standby delays those ACKs by the bound.qbit_prism_block_offer_standby_wait_total{outcome}counts every wait (all four series start at zero).PrismBlockOfferStandbyUnconfirmedis a warning (never pages) on any non-confirmedoutcome in the last 30 minutes, with no dwell, gated on a fresh snapshot. It is generated into the migration table and the qbit-tools patch.GRANT pg_monitor), or whose name does not match exactly one connected standby reporting its flush position, and reports what it read underoffer_standby. check-config prints the effective setting.${PRISM_OFFER_STANDBY_APPLICATION_NAME:-}, so off by default),.env.exampleand the server README.candidates recoverrefuses a hash with no row. The ledger operations guide points to it.statement_timeoutbefore the COMMIT's synchronous-replication wait (finish_xact_command()→disable_statement_timeout()→CommitTransactionCommand()). With the standby down, aSET LOCAL synchronous_commit=onCOMMIT blocked for 18.7 minutes despitestatement_timeout=2s, untilpg_cancel_backend. So a statement timeout cannot be the duration guard.With the wait on, the accepted asynchronous loss is:
Tests
All gated and listed, sorted, in
test/prism-gated-tests.txt:live_regtest::pg_failover_tests::offer_standby::a_found_block_offered_after_the_standby_flush_survives_a_replication_cut_at_submitblockaccepted, and the block lands once with one audit bundle, is confirmed, offered exactly once, and passes carry-forward integritypostgres_failover::offer_standby_flush::offer_standby_wait_confirms_the_flush_returns_at_the_bound_and_never_waits_for_a_stopped_standbypg_monitorit reportsfailedat once and self-check refuses it. After the grant it confirms. With the standby's WAL receiver suspended it returnslaggingat the bound (≥ bound, < bound + 2 s) with the lag, and confirms again after resume. A second standby under the same name whose WAL receiver is suspended keeps the wait from confirming (it lags to the bound although the first standby flushed) and self-check refuses the name. A stopped standby isabsentat once and self-check refuses it. Another application name is not waited forcoordinator::candidate_lease_tests::offer_standby_tests::a_found_block_is_offered_at_once_when_the_configured_standby_is_not_streamingabsentcoordinator::candidate_lease_tests::offer_standby_tests::with_the_standby_wait_off_a_found_block_is_offered_without_a_waitconfig::tests::offer_standby_wait_needs_a_name_and_a_positive_bound(unit)Seven promtool scenarios cover: fires at once, holds for the 30-minute window, clears after it, confirmed offers never warn, lagging and failed warn per frontend, a counter reset alone does not warn, and a stale snapshot defers to the snapshot rules.
Mutants (each fails at least one test)
offered before the standby held its reservation (standby row: None)), absent testsent_lsninstead offlush_lsnConfirmed { waited: 475µs }while the standby flushed nothing)the offer took 10.1s)Absentinstead offailed)bool_or)laggingdropped / 5 m window /confirmedcounted / 3 m dwellVerification
1fb74b79(3.x.x: offer again a won block whose submitblock qbitd answered from its warmup, instead of losing it as unknown (#526) #566, which also changes the offer path); the targeted suites below were re-run there.cargo fmt --all --checkandcargo clippy -p qbit-prism-server --all-targets -- -D warningsare clean.PRISM_TEST_REQUIRE_INTEGRATION=1:--libbinary passed 578/579; the one failure wascommit_reconcile_block_only_poll_errors_are_retried_then_unknown, which hit 5 s statements under host load and passed 3/3 alone;observability,config_cliandpostgres_failoverpass;live_regtest pg_failover_testspasses 3/3, including the two 3.x.x: live PostgreSQL primary failover with a found block mid-landing (#521 scenario 3) #531 drills with the shared relay change; on the rebased tree the new drill and the 3.x.x: offer again a won block whose submitblock qbitd answered from its warmup, instead of losing it as unknown (#526) #566 node-outage drills pass (6 passed, 1 pre-existing ignored);test_prism_alert_promql.py(promtool 3.14.0): 160 scenarios passed.generate_prism_alerts.py --check,generate_prism_metrics.py --check,test_prism_alert_deployment.py(78 original / 74 proposed rules),check_prism_settings.py,check_prism_pool_acquires.pyandcheck_gate_env_reads.pyall pass.Share ACK A/B
The load harness (
qbit-prism-load) ran with its managed asynchronous standby (application_name=prism_standby_1,synchronous_standby_names='') and one debug frontend. Each arm had 100 sessions, 50 shares/s and 10 scheduled own blocks in a 60 s steady state. The feature was on (PRISM_OFFER_STANDBY_APPLICATION_NAME=prism_standby_1, 250 ms bound) or off. There were eight interleaved arms, each under the exclusive timing lock on a quiet host (1-minute load 0.5 to 1.4). These are example artifacts (debug build, dirty tree), so read them as a relative A/B.confirmed, 0.7–2.6 ms (p50 about 1.9 ms)Share ACK latency is unchanged. The rare ACKs of about 3.6 s appear in both arms (one off run, two on runs) and never in a window with a block offer's wait above 2.6 ms. They come from the harness host, not the wait. On a healthy standby the wait adds 1 to 3 ms before each found block's
submitblockand nothing to share ACKs. The prototype's lagging-standby arm (every offer held for the bound, and block-only proof ACKs with it) is in the #529 comment.Per-PR CI runtime added
About 10 s in total, all inside existing test binaries, with no new binary to link:
Shared-code changes (additive)
offer_standby: Noneadded to everyConfigliteral in tests and test support: one line each, as 3.x.x: An own block found 9 s after the previous landing was refusedunknown-joband never reached the node #478 did for its setting.tests/support/live_pg_failover.rs:Relaygains an optional per-connection delay on the target-to-client direction (default 0, unchanged path) and setsTCP_NODELAYon relayed sockets, since without it small replies waited about 40 ms. It declares the new child module.#[path] modline each inpostgres_failover.rsandcandidate_lease_tests.rs; the observability census counts (+1 family, +4 series).Accepted trade-off
The wait sits between the durable reservation and
submitblock. That widens the window in which a crash or a lost claim leaves a block reserved but never sent, from one round trip to at most the bound (250 ms by default, 10 s at most). Recovery treats such a block as delivery unknown and never offers it. This is the price of keeping the reservation on the standby, which lets a held attempt record its outcome on the promoted primary. It is stated at the call site, in the module and in the HA accepted-loss list.Not covered
This is a disposable fixture. It does not qualify the operator's real standby, fencing or endpoint (#291). It does not address #529 (a), the recovered outcome record, or (b), the 120 s lease delay after a mid-landing failover.
🤖 Generated with Claude Code