Repository navigation
3.x.x: PostgreSQL ends a stalled difficulty hint's transaction once it has waited its bound, at least a second, for the frontend's next statement - #956
Open
kiwidream wants to merge 3 commits into
Conversation
…its bound, at least a second, for the frontend's next statement (#930) A hint whose frontend stopped sending mid-transaction (a lost or paused host, a network path dropping packets, a hung process) stayed idle in transaction until TCP keepalive ended its session, about 2 h 11 min at stock settings or never for a hung process. An evidence hint holds ACCESS SHARE on qbit_share_ledger and every partition by then, so share-archive detach waited for it. The hint's BEGIN batch now also sets idle_in_transaction_session_timeout = max(bound, 1 s), transaction-local, in the same round trip. Also corrects the "less than a millisecond left" wording (#930 item 6) and adds the share-archive runbook for a waiting detach. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t is told apart and what a dropping path still holds (#930 review) - A frontend across a path that drops packets still holds a pool slot while its release ping waits on TCP retransmission; the server side has already ended. Said so in the doc comment and the ops entry. - The ops entry keeps "a hint ended so" about the statement timeout and moves the idle-bound text after it; the timer starts at each ReadyForQuery; durations name the default bound. - The runbook tells a stalled hint by every relation it locks as well as its last statement (the write guard and the set_config re-arm are shared with other ledger transactions), gives the full finalize command, notes the ~15 min retransmission case and adds tcp_user_timeout to the optional role settings. - T3 runs a 2 s bound and checks the session ends no earlier than the idle bound, instead of a presence check at 600 ms; T3 and T4 check the stalled hint's locks match the runbook's relation list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codex Review Summary: ✅ CompletedThis 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. |
…ds no advisory lock and last ran a hint-only statement, one blocker at a time (#930 review) qbit-reviewer: a settlement or landing transaction stalled right after the shared write guard locks only qbit_prism_cluster and qbit_ledger_writer_lease, both on the hint list, and its ORDER_LOCK or SETTLEMENT_LOCK is advisory, so the relation join never showed it. The runbook would have called it a hint and said to terminate it. A transaction the detach waits for now counts as a stalled hint only if it has idled 30 s, holds no advisory lock, locks only hint relations (an unnamed relation lock is not a hint's), and last ran a statement only a hint runs (a share probe, the hint row's write or its read-back); a guard or set_config last statement is escalated. The detach's virtualxid wait names one holder at a time, so the procedure repeats after each terminate and leaves the detach running. The terminate is guarded by pid, state and xact_start and says what no row means; the lock query lists advisory locks with the ORDER_LOCK and SETTLEMENT_LOCK keys; the session queries keep to the current database; the privileges the queries need are stated. T3 and T4 read the stalled hint in one query and check its locks (unnamed ones included), its advisory locks and its last statement. A unit test pins that every hint statement starts with a prefix the runbook lists and that the write guard and the re-arm do not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
Refs #930 (items 1 and 6). This PR targets
3.x.x, so merging it does not close the issue: close #930's first item by hand, and keep the issue open for the items listed under "Follow-ups not done".What was wrong
Since 3.1.2 (#905), a difficulty hint runs its share-ledger probes, its write guard, its write and its read-back in one transaction on one pooled connection. #872 put a server-side
statement_timeouton every statement, but nothing on the server bounded the transaction while it idled between statements. When the frontend stopped sending mid-transaction (a lost or paused host, a network path dropping packets, or a hung process whose host still answers), the writer's bound dropped the write, but itsROLLBACKnever reached the server. The transaction stayedidle in transactionuntil TCP keepalive ended the session. With stock settings that is 7200 + 9 × 75 s, about 2 h 11 min. For a hung process on a host that still answers, it is never.An evidence hint's probes read
qbit_share_ledger, so the stalled transaction heldACCESS SHAREon the ledger and every partition.DETACH PARTITION ... CONCURRENTLYwaits for every such holder with no timeout, soshare-archive detachwaited for it while holding the archive lifecycle lock, and every othershare-archivecommand waited behind that. A stalled hint that had already written also kept its hint row locked.What changed
crates/qbit-prism-server/src/ledger/difficulty.rs:BEGINbatch now also sets the idle timeout for the transaction alone, in the same single round trip and beforesynchronous_commit:BEGIN; SET LOCAL statement_timeout = N; SET LOCAL idle_in_transaction_session_timeout = Y; SET LOCAL synchronous_commit = localintmaximum and never 0. A newhint_idle_in_transaction_timeoutcomputes it once, intoHintDeadline(new fieldidle), andbegin_statementnow takes it as a second argument.ReadyForQuery, so it fires only when one wait for the writer's next statement outlasts Y. Since Y ≥ the bound, the writer has given up on the write (timed_out) by then, so a write that could still succeed is never ended.terminating connection due to idle-in-transaction timeout). That rolls the hint back and releases its locks and xid. A frontend that can still reach the server finds the connection closed at the pool's release ping (SQLx warnserror occurred while testing the connection on-release) and opens a new one. Across a path that drops packets, that ping still waits on TCP retransmission and holds a pool slot meanwhile; that is 3.x.x: ledger connections have no TCP keepalive or user timeout, so an unclean primary loss can wedge a frontend's pool for minutes #886's, unchanged here, but the server-side locks are already released.crates/qbit-prism-server/src/stratum/difficulty_hints.rs: the EP-ERRORS comment no longer says a stalled connection holds the transaction until the session ends. Comment only.docs/prism-ledger-ops.md:there is already a transaction in progresson the share-append path under commit-deadline cancellations #482 section quotes the newBEGIN.idle_in_transaction_session_timeoutparagraph gains one sentence on why a transaction-local one on the hint differs.share-archive detachwaits. It states the privileges its queries need (pg_read_all_stats, andpg_signal_backendto end a session); without them, the operator escalates. Three queries, each kept to the current database, show:blocked_by);xact_start;ORDER_LOCKandSETTLEMENT_LOCK.INSERTorUPDATE, or its read-back.ORDER_LOCKorSETTLEMENT_LOCKas an advisory lock, which a relation-only query never shows. Ending it would roll back settlement work and, withORDER_LOCK, release a lock that every share append waits for.set_configre-arm is escalated, because other ledger transactions run those too.blocked_bynames only the current one. So the operator ends one stalled hint, runs all three queries again and repeats, until the detach finishes or names a holder that is not a stalled hint.pg_terminate_backendthat matches pid, state andxact_start, so only the classified transaction can be ended. The runbook says what its result means.ORDER_LOCKorSETTLEMENT_LOCK), and offers an optional operator action: role-level server-side keepalives plustcp_user_timeout. That option is clearly marked as needing the production settings read first.test/prism-gated-tests.txt: the two new PostgreSQL-gated tests, sorted.Not changed: configuration, schema, metrics, alerts,
connect.rs, the pool's after-connect statement,CustomBegin, vendored sqlx and the lock files. No statement or round trip is added, and the healthy path behaves as before, because the timer never fires there. The pool-acquire inventory is unchanged.Mixed 3.1.2/3.1.3 pair and rollback
Each node of the pair writes its own database, and peer sync copies rows between them.
qbit_worker_difficultyis local to each database and not synced.Tests
New and extended tests, and the mutation each was seen to catch. Each mutation was applied, run and restored, and the restore was confirmed with
cmpagainst the saved source:ledger::difficulty::tests::a_hint_transactions_idle_bound_is_its_write_bound_and_at_least_a_secondi32::MAX, never 0, always ≥ the bounddifficulty_hint_bound::a_hint_write_is_one_checkout_and_its_statements_are_counted_on_the_wire(extendedwrites_only_the_hint_row)BEGINends; SET LOCAL idle_in_transaction_session_timeout = 300000; SET LOCAL synchronous_commit = local; statement counts unchangedSET; setting sent as its own statement (one more statement on the wire)ledger::difficulty::tests::postgres_a_stalled_hint_transaction_is_ended_by_the_server_and_lets_a_detach_finish(new)ledger::difficulty::tests::postgres_a_stalled_hint_releases_its_row_to_the_next_hint(new)postgres_a_custom_begin_that_completes_returns_its_connection_at_the_pool_timeoutandpostgres_a_committed_hint_leaves_its_connection_at_the_pools_settings(extended)SETleaking into the pool: "15s 5s remote_apply, not the pool's 15s 0 remote_apply"ledger::difficulty::tests::the_runbook_tells_a_hint_by_statements_only_a_hint_runs(new)RECORD_SQL,LOWER_SQL,READ_SQL) starts with a prefix the runbook lists as hint-only; the write guard and the re-arm do notThe runbook's rule, against a real stalled hint. T3 and T4 read the stalled hint's state in one query: its last statement, its relation locks (an unnamed one included) and its advisory-lock count. They check the runbook's conditions 3 to 5 on it: no advisory lock, only hint relations, and a hint-only last statement. T3 also checks condition 1: the detach waits for that pid. A temporary test-only edit that stalled a hint right after its write guard failed the last-statement check, as the runbook intends ("the runbook would not tell this hint by its last statement: SELECT c.fatal_error,..."). The tests restate the conditions rather than run the runbook's SQL, whose queries list only sessions idle for 30 s. That SQL was run by hand on PostgreSQL 16 without error, and the advisory keys it prints were confirmed live:
pg_advisory_xact_lockonORDER_LOCKshows classid 1347570003, objid 1291845634.T3 steps.
ROLLBACK.)idle in transactionwithAccessShareLockonqbit_share_ledgerandqbit_share_ledger_p0, and that it meets the runbook's lock and last-statement conditions.DETACH PARTITION qbit_share_ledger_p0 CONCURRENTLYand check that it waits onvirtualxidwith the hint's pid inpg_blocking_pids.T4 steps. This is EP-STATE's out-of-order pair.
LOWER_SQLto 32, and stalls uncommitted. It meets the runbook's lock and last-statement conditions.Ran locally on the final head (d814db8), against a private PostgreSQL 16.16 cluster set up the way
test/prism-native-tests.shsets one up (127.0.0.1 over TCP, the gate's pg_hba,fsyncon):cargo test -p qbit-prism-server --lib --test difficulty_hint_bound --locked --offline --no-fail-fast -- --test-threads=4 difficulty a_hint_ the_runbook(withPRISM_TEST_DATABASE_URLandPRISM_TEST_REQUIRE_INTEGRATION=1): 44 passed in the lib binary (everyledger::difficulty::teststest, thestratum::difficulty_hint_testssuite including its PostgreSQL test, and two other matches) and 2 passed indifficulty_hint_bound.cargo test -p qbit-prism-server --lib --locked --offline -- --test-threads=4 ledger::difficulty::tests::postgres, nine times: eight runs passed 10 of 10. In one, an existing test (postgres_a_hint_statement_sent_late_gets_only_what_is_left_of_the_write_bound) failed before it ran any hint code. Its fixture's migration timed out on the database-wideMIGRATION_LOCK(canceling statement due to lock timeoutonSELECT pg_advisory_xact_lock($1)in the server log) while other test schemas migrated concurrently on a loaded host. Loops on this PR's earlier commits passed every run.PRISM_TEST_GATE_MANIFESTset, both new tests recordedexecutedunder ids identical to the new lines intest/prism-gated-tests.txt.cargo fmt --all --check;cargo clippy -p qbit-prism-server --all-targets --locked --offline -- -D warnings.python3 scripts/check_prism_pool_acquires.py,scripts/check_gate_env_reads.py,scripts/check_toolchain_pin.py,scripts/check_deleted_test_map.py: all pass. No test was deleted or renamed./code-review xhighbefore each push found no correctness bug in the code change.CI on d814db8: every job passes except
signed-landing, which stays red until the PR is landed. That includes the four PostgreSQL and multi-instance shards, the proof that every gated Rust test executed, and the dual-writer fast lane.Engineering lessons checked against the diff
COMMITstaystimed_out, and a killed session is a definite rollback.UPDATEsucceeded, uncommitted) and checks the rollback and the next write's commit, and by T3.What is unverified
SET LOCALdoes not matter inidle in transaction (aborted)) rests on PostgreSQL's documented abort semantics. No test exercises it.Release note
Follow-ups not done
ORDER_LOCK, which remains exposed. A share append holdsORDER_LOCKbetween itsqbit_prism_append_sharecall and itsCOMMIT. If its connection stalls there, every append on that node's database fails at its lock timeout, andshare-archive detachwaits, until the session ends. The server-side keepalive session settings in the keepalive PR cover the dead-network case. A hung frontend process on a live host is still uncovered, and an idle bound on the append transaction needs its own analysis of unknown share outcomes.PRISM_DATABASE_STATEMENT_TIMEOUT_MSis documented as deliberate.timed_outwas not done. A kill can only follow the writer's own bound passing, so the writer has normally already countedtimed_out.doc/release-notes-3.1.2.mdneeds two corrections (that file is outside this PR):idle in transactionbackend. That would include a stalled settlement or share append; it should point to the runbook section above.verify-caURL with nosslrootcerttoverify-full. Without a root certificate,verify-fulltrusts only the public roots, so a database behind a private CA passes startup and then fails at connect. This is most likely onPRISM_PEER_DATABASE_URL_FALLBACK.🤖 Generated with Claude Code