Repository navigation
3.x.x: keep a ledger future cancelled inside BEGIN from leaving its transaction on the pooled connection (#482) - #515
Conversation
…ransaction on the pooled connection (#482) Every D1 run of #447 logged PostgreSQL's "there is already a transaction in progress" on the share-append path. Reproduced deterministically: SQLx 0.8.6 counts a transaction only once the reply to BEGIN is read, and its cancellation guard rolls back nothing before that, so a persist task aborted at the share-commit deadline (or dropped by a miner disconnect), the metrics collector's deadline, or the subscribe timeout around session allocation, dropped between the BEGIN write and its reply, returned the connection to the pool with the server still in a transaction. The release ping consumed the reply, the next checkout's BEGIN landed inside the leftover, and the same backend pid served it. No advisory lock can be held across it (every later await is at depth 1 and queues ROLLBACK, flushed by the pool return), but a statement run on a directly acquired connection inside the leftover would be reported durable without being so. Guard, one per form of BEGIN: - `ledger::shielded_begin` runs the BEGIN round trip in a task of its own and joins it. `Ledger::begin`, the startup transaction and the metrics collector use it; a cancelled caller detaches, the task reads the reply and the transaction it drops queues the ROLLBACK the pool return flushes. - `AppendConnection::begin` records completion; when BEGIN did not complete, the guard's drop detaches the connection from the pool synchronously and closes it on the captured runtime, so the pool opens a replacement and can never offer that connection again, even at shutdown. The successful path is unchanged: an append is the same ten statements on one connection, verified on the wire. Tests: `ledger_cancelled_begin` holds one BEGIN reply at the execution proxy (new `pause_statement`), cancels the future there by abort and by drop, and asserts from `pg_stat_activity`, `pg_locks`, the proxy's execution log and a warning-capturing subscriber that no backend is left idle in transaction, no ORDER_LOCK or SETTLEMENT_LOCK is held, and the next transaction starts without the warning. Against the base both tests fail on the idle-in- transaction backend and the BEGIN, BEGIN wire. Docs: `docs/prism-ledger-ops.md` records the trigger paths, the argument, the guard and the rejected `after_release` alternative with its cost. Co-Authored-By: Claude Fable 5.1 <[email protected]>
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. |
kiwidream
left a comment
There was a problem hiding this comment.
Adversarial verification by a delegated agent (Opus) of the Fable-authored change, on behalf of workstream A, at head dc5a63ec. Posted by the coordinator.
I adversarially verified dc5a63e against 6575f59 by reading sqlx 0.8.6's begin, rollback, drop, detach and release-ping code and running every requested command. I also ran the new tests against the base source tree in an isolated target dir. Verdict: APPROVE. There are no blocking findings, only four low-severity nits listed below. What's left is optional: the two test/doc nits and the rare unshielded partition-ensure path, which the doc already names as a residual.
FINDINGS (most severe first, none blocking)
- Low: crates/qbit-prism-server/src/ledger/append_admission.rs:139-142. The retire branch runs Connection::close(raw) with no timeout, and the admission permit is held until that close returns. sqlx's own close_on_drop bounds its close with CLOSE_ON_DROP_TIMEOUT (5 s). In practice it is bounded: close writes a Terminate of a few bytes and then shuts the socket down. Scenario: a peer stalls with the socket send buffer full, so one of the pool's max-1 append permits stays held until TCP errors out. No test covers it. Optional fix: wrap the close in tokio::time::timeout.
- Low: crates/qbit-prism-server/src/ledger/connect.rs:639. shielded_begin's tokio::spawn does not carry the caller's tracing span or subscriber into the BEGIN task. A server notice relayed during a shielded BEGIN is therefore logged without the caller's span, and a with_subscriber capture would miss it. The test avoids this by running the next transaction with pool.begin(). This only affects logs; production uses a global subscriber.
- Low (test): tests/ledger_cancelled_begin.rs, in cancel_inside_begin near pause.release(). The comment says the backend is already in a transaction while the reply is held, but nothing asserts pg_stat_activity is 'idle in transaction' at that point. Coverage still holds: on the base, the post-settle 'idle' check, the no-notice check and the wire check all fail, as shown below.
- Nit (doc): docs/prism-ledger-ops.md:1478. The Residual paragraph says BatchConnection is safe only because it is cancelled at shutdown. In fact its Drop (ledger/jobs/compact_issued_batch.rs:86-108) runs an explicit ROLLBACK through execute(). execute() first waits until ready, which reads the held BEGIN reply, so it is safe even when cancelled mid-BEGIN.
Q1 DROP-PATH TABLE
shielded_begin (the task owns the PoolConnection; tokio::spawn is detach-on-drop):
(a) Caller dropped before the task is polled: the task still runs BEGIN and reads the reply. Because no join handle remains, the harness drops the output on a worker thread. Transaction::drop queues ROLLBACK (depth 1). PoolConnection::drop then calls rt::spawn(return_to_pool), whose ping writes Sync and waits until ready, flushing ROLLBACK and reading both replies before release(). The connection returns clean.
(b) Caller dropped while the task awaits the reply: same as (a). The task is not cancelled, reads the reply and drops the Transaction; ROLLBACK is flushed by the ping before release. Proven by the session test: wire BEGIN,ROLLBACK,BEGIN, same pid and same proxy connection.
(c) Task done, caller dropped before taking the Transaction: dropping the JoinHandle drops the stored output on the dropping thread (a runtime thread, as before). Same ROLLBACK and ping path.
Runtime shutdown (JoinError cancelled): the BEGIN future is dropped at depth 0. PoolConnection::drop floats the connection eagerly. The spawn onto a closed runtime drops that future, which closes the socket and decrements the pool size, so no dirty connection is released. Panics are re-raised with resume_unwind.
AppendConnection with began=false (abort or drop during BEGIN, or BEGIN error): detach() is synchronous. Floating::detach drops the DecrementSizeGuard, so size-1 and the pool semaphore release happen immediately. The ledger pool sets no min_connections (grep), so PoolConnection::drop inside detach spawns nothing and needs no ambient runtime. runtime.spawn goes through the captured Handle and does not panic after shutdown; the future is dropped instead, which drops raw (socket closed, server aborts) and drops the admission permit. The permit is released in both branches: after close, or with the dropped future. The began=true branch is unchanged from the base. Evidence: after the retirement, the next append in the test needs the pool's only admission permit (capacity max(2-1,1)=1) and it succeeded.
began is set in the same poll that returns the Transaction, so no cancellation point lies between them.
Q2 NOTHING WORSE: Transaction<'static> owns its MaybePoolConnection, is Send, and moves out through the JoinHandle; it compiles and clippy is clean. The only runtime assumption is ambient tokio, and every caller is under a tokio runtime (main and tools use runtime.block_on). current_thread works. The READ_DEADLINE task-local is read only in API handlers, not inside BEGIN. On timeout (session allocation, the collector's 3 s deadline), the BEGIN task alone keeps running until the reply, then ROLLBACK and ping. On the base, the release task's ping also blocked on the same BEGIN reply, so the slot is not occupied materially longer; the cancel path adds only one ROLLBACK round trip. No path now frees a slot more slowly than before, except the retire path, which opens a replacement (one reconnect per cancel-in-BEGIN).
Q3 SUCCESS PATH: in code, AppendConnection::begin is the same Transaction::begin plus a bool store, and shielded_begin is the same Transaction::begin plus a task hop, not a round trip. On the wire, the --nocapture trace of the post-retirement append shows 10 executions (BEGIN, pg_advisory_xact_lock, ..., COMMIT) and 0 new connections. The session test shows the next Ledger-pool transaction as BEGIN, SELECT, COMMIT only. The base run failed before printing its normal-append trace, so the before/after 10-statement equality rests on the code reading.
Q4 TESTS: the pause holds the reply from CommandComplete on, so BEGIN has been written and executed and the client is blocked reading its reply. That is between the write and the reply, not before or after. Run against the 6575f59 source tree plus the new test files, both tests FAIL for the right reasons: settled backend 'idle in transaction' with query BEGIN; wire [BEGIN, BEGIN, SELECT pg_backend_pid(), COMMIT]; the notice 'there is already a transaction in progress'; the next transaction on the same pid. On the head both pass: the session case shows BEGIN,ROLLBACK,BEGIN on the same pid; the append case shows wire [BEGIN], the pid gone, a new pid and proxy connection, and the connection count increased. The pg_locks check for ORDER_LOCK and SETTLEMENT_LOCK is empty. The gate manifest shows both tests 'executed' (PRISM_TEST_REQUIRE_INTEGRATION set by the script), so they did not pass by skipping. There are no timeout-based passes: settled_backends errors on timeout. The append replacement assertion checks pid, proxy connection and count together. Both ids are in test/prism-gated-tests.txt, sorted under both C and locale sort -c. check_prism_pool_acquires.py passes with the shielded-begin class.
Q5 UNSHIELDED BEGIN SITES (non-test src):
- partitions.rs:53 ensure_with_metrics. Reachable from a cancellable future: YES. Abortable persist task via window.rs:641, missing-partition retry only (rare). Also the ensure loop at partitions.rs:103 (select with shutdown) and startup at server.rs:58. This is the real residual, and the doc names it.
- rollups.rs:59 advance_with_metrics: cancellable only by the shutdown select (rollups.rs ~95). Low.
- ledger/jobs/compact_issued_batch.rs:183: cancellable, but safe, because BatchConnection::drop sends an explicit ROLLBACK after waiting until ready.
- ledger/migration/online.rs:288 and migration/partition.rs:286: a dedicated connection that is closed and never returned to the pool (online.rs ~137-150). Safe.
- ledger/window.rs:671: the AppendConnection guard. Covered.
- Every Ledger::begin caller (self.begin() / ledger.begin() across candidates, fanout, blocks, archive, etc.): shielded.
There is no pool.begin()/begin_with in non-test src.
Q6: miner_submit.rs changes only /// doc-comment lines (4 lines, 3 added). No code change.
COMMAND LOG (minidev-alex1, head dc5a63e)
- cargo build --locked -p qbit-prism-server: exit 0
- cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings: exit 0
- python3 scripts/check_prism_pool_acquires.py: exit 0
- test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --test ledger_cancelled_begin -- --nocapture: 17 passed, both gated tests executed. Run twice, the second time after the base experiment.
- test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --test ledger_deadline_atomicity --test ledger_single_execution -- --test-threads=4: 7 + 22 passed, 14 gated tests executed. I added --test-threads=4 per the host quirk.
- cargo test --locked -p qbit-prism-server --test observability: 17 passed
- Base experiment: git archive 6575f59 into the scratchpad, with the head's test, proxy support and gated list overlaid, and CARGO_TARGET_DIR isolated. The new tests FAIL 2/2 as described in Q4. A first attempt that shared the head's target dir was invalid, because archive mtimes let cargo reuse the head library; I discarded it. I removed the temporary target and tree. No repo file was changed.
Brings in #470, #512, #513, #514 and #515. #515 opens the share append's transaction through AppendConnection::begin, which records BEGIN completion so that a future cancelled before the reply retires the connection instead of returning it to the pool; this branch opens the same transaction with "BEGIN; SET LOCAL plan_cache_mode = force_generic_plan" so the share_id probe is planned once per connection. Resolution keeps both: AppendConnection::begin takes the opening statement and the append passes APPEND_TRANSACTION_BEGIN. SQLx reads every reply of that simple query through its ReadyForQuery before begin returns, so the guard records completion only once the whole batch is in. ledger_cancelled_begin now cancels the append on the custom BEGIN, and a new case holds only the batch's closing ReadyForQuery (the execution proxy gains pause_statement_ready) and proves the connection is still retired. The pool-acquire inventory, the gated-test manifest and the #482 ops notes follow the new call sites. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #482 (workstream A, #261; evidence from #447's D1 runs, mechanism from #324). Ledger connection handling on the share-append and owned-transaction paths; no change to what an append writes, locks or commits.
The defect. PostgreSQL's
WARNING: there is already a transaction in progressappeared 10,303 times across #447's 33 runs, almost all inslow_databaseand its drain, once in asteady_statephase. Reproduced deterministically here (tests/ledger_cancelled_begin.rs): hold the reply toBEGINat the execution proxy and cancel the future there. sqlx 0.8.6 counts a transaction only after theBEGINreply is read, and its cancellation guard rolls back nothing at depth 0, so a persist task aborted atshare_commit_timeout, a persist task dropped by a miner disconnect, the metrics collector's 3 s deadline, or session allocation under the subscribe timeout can return a connection to the pool whose server side is inside a transaction. On the base the cancelled backend satidle in transactionin the pool, the wire showedBEGIN,BEGINwith noROLLBACK, and the next transaction ran on the same pid.What it could and could not do. No advisory lock can be held across it:
ORDER_LOCK/SETTLEMENT_LOCKare taken afterBEGINcompletes, at depth 1, where a drop queuesROLLBACKthat the pool return flushes; a transaction cancelled insideBEGINhas run nothing butBEGIN. The share path was never affected and every run reconciled exactly. The hazard was a directly acquired statement (heartbeat, session-reservation delete, difficulty record, landed-audit-bits update) running inside the leftover: reported successful but neither durable nor visible until the connection's next transaction user ended the block, row locks held while idle in the pool, and one error poisoning that connection for up to sqlx's 30-minute lifetime. Guarded rather than only documented for that reason.The guard.
ledger::shielded_begin:Transaction::beginon the already checked-out connection runs in a task of its own and is joined, so a cancelled caller lets the task read the reply and the transaction it then drops queues theROLLBACKthe pool return flushes. Used byLedger::begin, the startup begin andmetrics/collectors.rs. Wire after cancellation:BEGIN,ROLLBACK,BEGINon the same pid.AppendConnection::beginrecords completion and, whenBEGINdid not complete,Dropdetaches the connection from the pool synchronously and closes it on the captured runtime instead of returning it. Retirement over a drop-time rollback: a drop must never block and must never return a connection whose server side may be in a transaction, including at runtime shutdown. Cost: one reconnect per append cancelled insideBEGIN, around three hundred per D1 run inslow_database, none in steady state.Rejected alternative (recorded in
docs/prism-ledger-ops.md): a poolafter_releasehook. sqlx exposes no client-side transaction status for this case (its own depth is exactly the number that is wrong), so detection needs a statement round trip on every release, paid as connection occupancy in the pool-boundslow_databasephase.idle_in_transaction_session_timeoutwas rejected too: it reaps only after its timeout and does nothing under load.Tests. Two new gated tests in
tests/ledger_cancelled_begin.rs(ids added totest/prism-gated-tests.txt): the share append cancelled insideBEGINretires its connection (no idle-in-transaction backend, no lock key inpg_locks, the retired connection carried only the cancelledBEGIN, the next transaction warns nothing); session allocation dropped insideBEGINreturns the connection clean (BEGIN,ROLLBACK,BEGINon that connection). The execution proxy gainedpause_statement, which holds one statement's reply without severing the connection.Residual.
partitions::ensure_with_metricsand the rollup writer still use a plainTransaction::beginon a fresh checkout; the former is reachable from the persist task's missing-partition retry path. Named in the doc section for a follow-up.Verification.
cargo fmt --all --check;cargo clippy --locked --workspace --all-targets -- -D warnings;scripts/check_gate_env_reads.py;scripts/check_prism_settings.py;scripts/check_prism_pool_acquires.py(newshielded-beginclass);test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server --test ledger_cancelled_begin --test ledger_deadline_atomicity --test ledger_single_execution(manifest: all executed);cargo test --locked -p qbit-prism-server --test observability;cargo test --locked -p qbit-prism-server --lib ledger::. Written by a delegated worker, re-verified by the coordinator; an independent adversarial verification of the drop paths is in progress and any finding will be posted here.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.