Repository navigation
fix(store): prevent late commit of timed-out debit statements - #1336
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Threat model review — advisoryReviewed head Review not completed for this head. Previous findings are superseded, not confirmed resolved. Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging. Coverage: 12/33 source units; cross-file integration pending. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned. Cost this run: $0.3786 reported, $0.0000 reserved with unknown cost; 5 paid request(s), 0 reused batch(es), 80044 provider cache-hit tokens. Saved findings and earlier report · Historical findings are not confirmed resolved. |
Upstream reorganized the coordinator (#1324): the PostgreSQL backend now lives in coordinator/store/postgres and every Go test lives under coordinator/tests. - Re-apply the explicit debit transaction to PostgresStore.Debit in coordinator/store/postgres/ledger.go. The change is the same statement for statement; coordinator/store/postgres.go no longer exists. - Move the cancellation regression test to coordinator/tests/store/postgres/debit_cancellation_test.go on the relocated fixture. The test name, schedule and assertions are unchanged. - Keep both changelog entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CHANGELOG.md conflicted again at the top of the file. Both sides are kept; master's new entries go first so later entries there do not collide with this branch's section. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CHANGELOG.md conflicted at the top of the file again, this time with the entry master gained when #1336 merged. Every entry is kept. This branch's entry now sits after the verification-concurrency section, away from the spot where other open changes insert theirs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
A PostgreSQL debit that is waiting on an account row lock can return a client deadline error before pgx's asynchronous cancellation reaches the server. If the lock is released in that window, the single-statement autocommit can still charge the account, even though the reservation caller has already treated the operation as failed and rejected the request.
This change keeps the standalone
PostgresStore.Debitstatement inside an explicit transaction.COMMITis sent only after a successful statement result and a live operation context; otherwise the transaction is rolled back using a fresh, bounded cleanup context. The transaction-neutraldebitBalancehelper used by promotion and other callers that already own a transaction is unchanged. No schema, API or protocol changes.Linked issue
Related to #342. This is deliberately not
Closes: it fixes one accounting defect found while investigating that issue under contention. It does not address the issue's admission-guard, throughput or routing findings, which remain open.Before
Blue shows database and control flow; red shows the failed request and the late charge.
After
flowchart LR A["BEGIN and debit"] --> B{"Statement result received before deadline?"} B -->|"Yes"| C["COMMIT, then admit request"] B -->|"No"| D["Do not send COMMIT"] D --> E["Rollback or connection cleanup"] E --> F["No durable debit from timed-out statement"] classDef action fill:#1e40af,color:#fff,stroke:#93c5fd; classDef decision fill:#6b21a8,color:#fff,stroke:#d8b4fe; classDef safe fill:#166534,color:#fff,stroke:#86efac; class A,D,E action; class B decision; class C,F safe;Green describes the pre-
COMMITtimeout boundary only. A lostCOMMITacknowledgement remains an uncertain outcome (see limitations).Ported onto the reorganized coordinator (2026-10-04)
Merged current master
c5552d3af7(after #1324, #1338 and #1340) with signed merge commits7d9b7b69andc9caaa1f. The change is the same; only its location moved.coordinator/store/postgres.go,PostgresStore.Debitcoordinator/store/postgres/ledger.go,PostgresStore.Debit— the same statementscoordinator/store/postgres_debit_cancellation_test.go(packagestore)coordinator/tests/store/postgres/debit_cancellation_test.go(packagepostgres_test), on that package's existingnewPostgresWithPoolConfigfixture. Test name, schedule and assertions unchangedCHANGELOG.mdRefactor pass. A dedicated refactor subagent reviewed the ported change against the structure and clean-code rules in
AGENTS.md. Outcome: no change needed. It confirmed the test's place, fixture use and cleanup match its neighbours, that nothing in it depends on the old harness's larger connection pool (it needs three connections; the default pool has at least four), and that the comment and both documentation passages are still true at the new path.Validation on the merged head (Go 1.25.0, PostgreSQL 16, synthetic accounts only):
gofmtclean,go build ./coordinator/...,go vet ./coordinator/....TestCoordinatorTestsAreIsolated.TestPostgresDebitTimeoutDoesNotCommitAfterCancellationDelaypasses with the fix (backend reachesidle in transaction). With master'sledger.gosubstituted throughgo test -overlayit fails:timed-out debit committed after its error: 1 blocked-a ledger rows.go test ./coordinator/tests/store/...— all six packages pass;./coordinator/tests/store/postgresalso passes under-race.python3 scripts/run-coordinator-tests.py --jobs 1 ./coordinator/...: 8,129 passed, 0 failed, 5 skipped. The same five tests skip on master (environment-gated performance and fixture suites).make docs-check(330 files) andmake docs-impact-check BASE=origin/master.golangci-lint, E2E and native suites. CI covers them.Test plan (original head, pre-refactor paths)
Local validation used a disposable PostgreSQL 16 instance on a private Unix socket with synthetic accounts only.
TestPostgresDebitTimeoutDoesNotCommitAfterCancellationDelaydelays only the matching backend's cancel packet through a test-onlyDialFuncwrapper.postgres.goit fails: the original backend reachesidleand a durable charge exists after the returned error.idle in transaction, is cleaned up, and no timed-out charge exists.python3 scripts/run-coordinator-tests.py --jobs 1 ./coordinator/store— 548 test/subtest pass events, 0 failures, 0 skips../coordinator/paymentsthrough the same runner — 50 test/subtest pass events.go test -race -p 1 -count=1 ./coordinator/store -run '^(TestPostgresDebitTimeoutDoesNotCommitAfterCancellationDelay|TestConcurrentCreditDebitLedgerConsistency|TestModelTokenPromotionConcurrentClaimsReservationsAndTerminals)$'— pass.go test ./coordinator/api -run '^TestServiceReservation(DisabledUsesLedgerDebit|ConcurrentAvoidsDebitHotRow|RefundReleasesHoldWithoutCredit|CompletionDebitsActualAndReleasesHold)$'— 4 pass.gofmt -landgo vet ./coordinator/store/clean on Go 1.25.0;git diff --checkclean.make docs-impact-check BASE=48d2be458b3ce511a2a9006238b923295c9c6718— canonical documentation coverage OK.make docs-checkpassed in the validation checkout.Disclosed test history: the first component run reported 13 store failures because the harness passed a keyword-format DSN to tests that need a URL. The rerun with a socket URL is the 548/548 result above. The two baseline reproductions and the deterministic red run are expected failures that demonstrate the defect.
The new regression test skips when
DATABASE_URLis unset and assumes PostgreSQL 16's 16-byteCancelRequestpacket.Components touched
Protocol / interface changes
Documentation impact
docs/architecture/billing.md(new "PostgreSQL debit cancellation" section),docs/architecture/storage.md, and aCHANGELOG.mdtopic entry.Notes for reviewers
BEGINandCOMMITadd two round trips and hold the account row lock until commit. This is a correctness change, not a throughput improvement, and makes no production latency claim. The five-second operation budget now includes those steps; cleanup uses its own bounded context.COMMIThas been sent (for example a lost acknowledgement) still has an uncertain outcome. This PR adds no idempotent reservation identifier and no blind retry or refund, so it does not rule out every duplicate-charge scenario. Callers must not treat every returned error as safe to retry.debitBalancehelper for transaction-owning callers is unchanged.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.