Skip to content

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
3.x.xfrom
orca/313-hint-idle-timeout
Open

kiwidream wants to merge 3 commits into
3.x.xfrom
orca/313-hint-idle-timeout

Conversation

@kiwidream

@kiwidream kiwidream commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

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_timeout on 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 its ROLLBACK never reached the server. The transaction stayed idle in transaction until 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 held ACCESS SHARE on the ledger and every partition. DETACH PARTITION ... CONCURRENTLY waits for every such holder with no timeout, so share-archive detach waited for it while holding the archive lifecycle lock, and every other share-archive command 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:
    • The hint's existing BEGIN batch now also sets the idle timeout for the transaction alone, in the same single round trip and before synchronous_commit:
      BEGIN; SET LOCAL statement_timeout = N; SET LOCAL idle_in_transaction_session_timeout = Y; SET LOCAL synchronous_commit = local
    • Y = max(the write's bound, 1 s), in whole milliseconds rounded up, clamped to PostgreSQL's int maximum and never 0. A new hint_idle_in_transaction_timeout computes it once, into HintDeadline (new field idle), and begin_statement now takes it as a second argument.
    • PostgreSQL restarts the timer at every 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.
    • When it fires, the server ends the session with SQLSTATE 25P03 (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 warns error 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.
    • Doc comments now describe the idle bound. Item 6: the "a statement with less than a millisecond left is not sent" wording now states the real rule (half the margin under the timeout in force, or a new timeout of at least 1 ms once the margin and the setting's round trip are taken off).
  • 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:
    • The difficulty-hint entry describes the idle bound and the 3.1.2 behaviour, and carries the item 6 wording fix.
    • The 3.x.x: PostgreSQL warns there is already a transaction in progress on the share-append path under commit-deadline cancellations #482 section quotes the new BEGIN.
    • The rejected session-wide idle_in_transaction_session_timeout paragraph gains one sentence on why a transaction-local one on the hint differs.
    • New runbook section If share-archive detach waits. It states the privileges its queries need (pg_read_all_stats, and pg_signal_backend to end a session); without them, the operator escalates. Three queries, each kept to the current database, show:
      • the waiting detach and the transactions it waits for now (blocked_by);
      • transactions idle in a transaction for over 30 s, with their xact_start;
      • every relation lock and advisory lock each one holds, with the advisory keys of ORDER_LOCK and SETTLEMENT_LOCK.
    • A transaction counts as a stalled hint only if all five conditions hold:
      1. the detach waits for it;
      2. it has been idle in a transaction for 30 s;
      3. it holds no advisory lock;
      4. it locks only hint relations (a relation lock with no name is not a hint's);
      5. its last statement is one only a hint runs: a share probe, the hint row's INSERT or UPDATE, or its read-back.
    • The advisory-lock condition exists so that a stalled settlement or landing transaction is never matched. Such a transaction runs the same write guard and, stalled right after it, locks only hint relations, but it holds ORDER_LOCK or SETTLEMENT_LOCK as an advisory lock, which a relation-only query never shows. Ending it would roll back settlement work and, with ORDER_LOCK, release a lock that every share append waits for.
    • A session whose last statement is the write guard or the set_config re-arm is escalated, because other ledger transactions run those too.
    • The detach waits on its holders one at a time, and blocked_by names 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.
    • Each end is a guarded pg_terminate_backend that matches pid, state and xact_start, so only the classified transaction can be ended. The runbook says what its result means.
    • The section also gives the full command that finalizes an interrupted detach, says what to escalate (any other holder, in particular one holding ORDER_LOCK or SETTLEMENT_LOCK), and offers an optional operator action: role-level server-side keepalives plus tcp_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_difficulty is local to each database and not synced.

  • The setting is transaction-local on the 3.1.3 frontend's own connections to its own database. Nothing is persisted, and it touches no wire format, schema or peer-sync contract, so the two versions interoperate unchanged.
  • A 3.1.3 node's database is protected from its own frontend's stalled hints. A 3.1.2 node's database keeps the old exposure from its 3.1.2 frontend, in a mixed pair and after rolling a node back to 3.1.2. The new runbook section covers that case: it identifies a 3.1.2 hint holder and says to end it.
  • Rolling a node forward or back restarts its frontend, which closes its sockets cleanly and leaves no stalled transaction behind.
  • Miners see no change.

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 cmp against the saved source:

Test Kind What it pins Caught
T1 ledger::difficulty::tests::a_hint_transactions_idle_bound_is_its_write_bound_and_at_least_a_second unit Y(500 ms) = 1000, Y(1 ms) = Y(0) = 1000, Y(2 s) = 2000, rounded up (1.500001 s → 1501), clamped to i32::MAX, never 0, always ≥ the bound Y = 0; floor removed; Y = bound less the margin; clamp removed; setting dropped
T2 difficulty_hint_bound::a_hint_write_is_one_checkout_and_its_statements_are_counted_on_the_wire (extended writes_only_the_hint_row) PG, wire proxy the BEGIN ends ; SET LOCAL idle_in_transaction_session_timeout = 300000; SET LOCAL synchronous_commit = local; statement counts unchanged setting dropped; session SET; setting sent as its own statement (one more statement on the wire)
T3 ledger::difficulty::tests::postgres_a_stalled_hint_transaction_is_ended_by_the_server_and_lets_a_detach_finish (new) PG-gated Steps below the table setting dropped (the pin's behaviour): "the stalled hint's session outlived its idle bound"; Y = 0: same; Y = bound less the margin: "ended 1.809801348s after the hint idled, under a 2s idle bound"
T4 ledger::difficulty::tests::postgres_a_stalled_hint_releases_its_row_to_the_next_hint (new) PG-gated Steps below the table setting dropped: "the next hint did not commit" (57014); Y = 0: same; floor removed: "the next hint did not wait for the stalled row"
T5 postgres_a_custom_begin_that_completes_returns_its_connection_at_the_pool_timeout and postgres_a_committed_hint_leaves_its_connection_at_the_pools_settings (extended) PG-gated the idle setting is in force inside the hint's transaction and back at the pool's value (0) on the next checkout setting dropped: "1234ms 0 local"; session SET leaking into the pool: "15s 5s remote_apply, not the pool's 15s 0 remote_apply"
T6 ledger::difficulty::tests::the_runbook_tells_a_hint_by_statements_only_a_hint_runs (new) unit every statement a hint can stall after (both probes, RECORD_SQL, LOWER_SQL, READ_SQL) starts with a prefix the runbook lists as hint-only; the write guard and the re-arm do not a hint statement edited so the runbook's prefix no longer matches

The 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_lock on ORDER_LOCK shows classid 1347570003, objid 1291845634.

T3 steps.

  1. Open the hint's transaction with a 2 s bound, so Y is 2 s. That leaves a slow machine time for the checks while the hint is held. The 1 s floor is pinned by T1 and T4.
  2. Run both evidence probes for a share the ledger does not hold.
  3. Hold the transaction open and send nothing. (Dropping it instead would let the release ping deliver the ROLLBACK.)
  4. Check that the backend is idle in transaction with AccessShareLock on qbit_share_ledger and qbit_share_ledger_p0, and that it meets the runbook's lock and last-statement conditions.
  5. Start DETACH PARTITION qbit_share_ledger_p0 CONCURRENTLY and check that it waits on virtualxid with the hint's pid in pg_blocking_pids.
  6. Check that the hint's backend ends no earlier than Y less 100 ms and no later than Y + 3 s after the hint went idle, then that the detach completes and the partition is detached.

T4 steps. This is EP-STATE's out-of-order pair.

  1. The row starts at 64.
  2. A hint with a 300 ms bound (so Y is 1 s) runs its guard and LOWER_SQL to 32, and stalls uncommitted. It meets the runbook's lock and last-statement conditions.
  3. The next hint for that worker (a decrease to 48, 3 s bound) waits on the row, and commits once the server ends the stalled session.
  4. The read-back and the committed row are 48: the stalled write's 32 was rolled back, and the earlier write loses.

Ran locally on the final head (d814db8), against a private PostgreSQL 16.16 cluster set up the way test/prism-native-tests.sh sets one up (127.0.0.1 over TCP, the gate's pg_hba, fsync on):

  • cargo test -p qbit-prism-server --lib --test difficulty_hint_bound --locked --offline --no-fail-fast -- --test-threads=4 difficulty a_hint_ the_runbook (with PRISM_TEST_DATABASE_URL and PRISM_TEST_REQUIRE_INTEGRATION=1): 44 passed in the lib binary (every ledger::difficulty::tests test, the stratum::difficulty_hint_tests suite including its PostgreSQL test, and two other matches) and 2 passed in difficulty_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-wide MIGRATION_LOCK (canceling statement due to lock timeout on SELECT 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.
  • With PRISM_TEST_GATE_MANIFEST set, both new tests recorded executed under ids identical to the new lines in test/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.
  • Pre-push reviews: /code-review xhigh before each push found no correctness bug in the code change.
    • On the first commit it found a comment that wrongly described the pool's behaviour across a dropping path (the pool behaviour itself predates this PR), a flake risk in T3's 600 ms check, and wording nits in the ops entry and the runbook; the second commit fixes them.
    • On the third commit, two passes before it was pushed found that the runbook must repeat one blocker at a time and use a guarded terminate, plus the privilege, query and test points addressed above; the pushed commit includes those fixes.

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

  • EP-ERRORS.
    • One deadline still governs the whole write. Y derives from the same bound, and the server now cleans up the idle gaps the client cannot cover once it stalls.
    • Unknown outcomes are kept: a bound that passes during COMMIT stays timed_out, and a killed session is a definite rollback.
    • No retry is added.
    • Verified by T4, which injects the stall after the side effect (the UPDATE succeeded, uncommitted) and checks the rollback and the next write's commit, and by T3.
  • EP-STATE. Publication is unchanged: the writer caches only a committed read-back. T4 runs two writes out of order, and the stalled earlier one does not overwrite the later one. No lock or guard is added.
  • EP-COMPAT. Nothing persisted or shared with the peer changes. The mixed pair and rollback are analysed above. A 3.1.2 node keeps the old behaviour, which the runbook covers.

What is unverified

  • Production's keepalive settings, kernel keepalive values and any proxy idle timeouts in front of the databases are not known, so the "about 2 h 11 min" is the stock figure, not a production measurement. Also not checked: whether any backend in production is idle in a transaction right now (the new runbook queries answer that).
  • That a transaction aborted by an error holds no locks (so the reverted SET LOCAL does not matter in idle in transaction (aborted)) rests on PostgreSQL's documented abort semantics. No test exercises it.
  • The runbook's role-level keepalive option uses example values. It was not tested here, including that the role-level values reach the socket.
  • A true network black-hole cannot be produced by the test proxy. T3 keeps the client silent instead, which the server sees the same way.
  • T3 gives its checks up to 2 s while the hint is held, and T4's checks only get easier on a slower machine. Both passed in CI, but their margins were not measured there.
  • The runbook procedure was not rehearsed end to end against a stalled 3.1.2 hint on a production-like pair. Its SQL was run on PostgreSQL 16, and T3 and T4 check its conditions against a stalled hint.

Release note

A stalled difficulty-hint transaction no longer holds the share ledger for hours (#930).

Since 3.1.2, a hint reads the share ledger inside its own transaction. If a frontend stopped sending in the middle of a hint (a lost or paused host, a network path dropping packets, or a hung process), that transaction stayed idle in transaction until PostgreSQL's TCP keepalive ended the session. That took about two hours with stock settings, and never for a hung process. Until then it held ACCESS SHARE on qbit_share_ledger and its partitions, and its hint row if it had written one, so share-archive detach on that node's database waited for it.

The hint's transaction now sets idle_in_transaction_session_timeout for itself only: to the hint's bound, and at least 1 s. PostgreSQL ends such a session within the hint's bound, and at least a second (1 s at the default 500 ms bound), and logs terminating connection due to idle-in-transaction timeout. The frontend replaces the connection, logging one SQLx warning. No setting, schema, metric or alert changes.

A 3.1.2 frontend keeps the old behaviour on its own node's database, in a mixed pair or after a rollback. Other transactions on a stalled connection, including a share append holding the append order lock, still last until their session ends. The share-archive runbook ("If share-archive detach waits") says how to find and end a stalled hint.

Follow-ups not done

  • The append's ORDER_LOCK, which remains exposed. A share append holds ORDER_LOCK between its qbit_prism_append_share call and its COMMIT. If its connection stalls there, every append on that node's database fails at its lock timeout, and share-archive detach waits, 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.
  • 3.x.x: follow-ups from the last review of the difficulty-hint statement timeout (#905) #930 items 2, 3, 5 and 7 to 12 wait for a later release. Item 4 is dropped: the hint's bound overriding a lower PRISM_DATABASE_STATEMENT_TIMEOUT_MS is documented as deliberate.
  • Mapping SQLSTATE 25P03 to timed_out was not done. A kill can only follow the writer's own bound passing, so the writer has normally already counted timed_out.
  • doc/release-notes-3.1.2.md needs two corrections (that file is outside this PR):
    • The 3.x.x: follow-ups from the last review of the difficulty-hint statement timeout (#905) #930 known-issue entry (near lines 979-981) still advises ending any idle in transaction backend. That would include a stalled settlement or share append; it should point to the runbook section above.
    • The upgrade step near line 758 offers moving a verify-ca URL with no sslrootcert to verify-full. Without a root certificate, verify-full trusts only the public roots, so a database behind a private CA passes startup and then fails at connect. This is most likely on PRISM_PEER_DATABASE_URL_FALLBACK.

🤖 Generated with Claude Code

kiwidream and others added 2 commits December 2, 2026 17:16
…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>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T00:06:42.057363Z d814db8 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qbit-reviewer qbit-reviewer 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.

1 finding posted inline.

Not posted: 3 nits. Reviews post bugs and security points only; the rest stay in Sixth Man's ledger.

Reviewed by Claude Opus 5.5.

Comment thread docs/prism-ledger-ops.md Resolved
…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>

@qbit-reviewer qbit-reviewer 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.

No bugs or security points found.

Not posted: 3 nits. Reviews post bugs and security points only; the rest stay in Sixth Man's ledger.

Reviewed by Claude Opus 5.5.

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.

1 participant