Skip to content

fix(store): prevent late commit of timed-out debit statements - #1336

Merged
Gajesh2007 merged 3 commits into
masterfrom
fix/store-timed-out-debit-commit
Oct 4, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
fix/store-timed-out-debit-commit

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

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.Debit statement inside an explicit transaction. COMMIT is 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-neutral debitBalance helper 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

flowchart LR
  A["Reserve funds"] --> B["Autocommit debit waits for row lock"]
  B --> C["Client deadline returns error"]
  C --> D["Request rejected before dispatch"]
  B --> E["Lock released before cancellation"]
  E --> F["Charge commits after reported failure"]
  classDef action fill:#1e40af,color:#fff,stroke:#93c5fd;
  classDef failure fill:#991b1b,color:#fff,stroke:#fca5a5;
  class A,B,E action;
  class C,D,F failure;
Loading

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;
Loading

Green describes the pre-COMMIT timeout boundary only. A lost COMMIT acknowledgement 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 commits 7d9b7b69 and c9caaa1f. The change is the same; only its location moved.

Before Now
coordinator/store/postgres.go, PostgresStore.Debit coordinator/store/postgres/ledger.go, PostgresStore.Debit — the same statements
coordinator/store/postgres_debit_cancellation_test.go (package store) coordinator/tests/store/postgres/debit_cancellation_test.go (package postgres_test), on that package's existing newPostgresWithPoolConfig fixture. Test name, schedule and assertions unchanged
CHANGELOG.md Every entry kept; master's newest entries first

Refactor 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):

  • gofmt clean, go build ./coordinator/..., go vet ./coordinator/....
  • Layout guard TestCoordinatorTestsAreIsolated.
  • Regression, green then red: TestPostgresDebitTimeoutDoesNotCommitAfterCancellationDelay passes with the fix (backend reaches idle in transaction). With master's ledger.go substituted through go test -overlay it 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/postgres also passes under -race.
  • Complete coordinator suite at the pushed head, 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) and make docs-impact-check BASE=origin/master.
  • Not run locally: the race-and-coverage configuration of the full suite, 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.

  • Reproduced on unchanged master. Two default-driver contention runs recorded a timed-out debit committing after the row lock was released. The second attributed the ledger entry to the original operation before any recovery call.
  • Deterministic regression, red then green. TestPostgresDebitTimeoutDoesNotCommitAfterCancellationDelay delays only the matching backend's cancel packet through a test-only DialFunc wrapper.
    • On unchanged postgres.go it fails: the original backend reaches idle and a durable charge exists after the returned error.
    • With this fix it passes: the backend reaches idle in transaction, is cleaned up, and no timed-out charge exists.
    • Controls cover unrelated-account success, exact balances, withdrawable funds and ledger sums, a subsequent recovery debit, and insufficient funds.
  • python3 scripts/run-coordinator-tests.py --jobs 1 ./coordinator/store — 548 test/subtest pass events, 0 failures, 0 skips.
  • ./coordinator/payments through 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 -l and go vet ./coordinator/store/ clean on Go 1.25.0; git diff --check clean.
  • make docs-impact-check BASE=48d2be458b3ce511a2a9006238b923295c9c6718 — canonical documentation coverage OK. make docs-check passed in the validation checkout.
  • Full coordinator, E2E and native suites were not run locally; this PR relies on CI for them.

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_URL is unset and assumes PostgreSQL 16's 16-byte CancelRequest packet.

Components touched

  • coordinator (Go)
  • provider (Rust, legacy)
  • provider-swift (Swift CLI)
  • console-ui (Next.js)
  • enclave (Swift)
  • infra / CI / release
  • docs

Protocol / interface changes

  • No protocol/interface changes
  • Yes — described above and matching side updated

Documentation impact

  • Canonical documentation updated: docs/architecture/billing.md (new "PostgreSQL debit cancellation" section), docs/architecture/storage.md, and a CHANGELOG.md topic entry.
  • No documentation needed

Notes for reviewers

  • Cost. BEGIN and COMMIT add 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.
  • Remaining limitation. An error after COMMIT has 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.
  • After refactor(coordinator): reorganize domain ownership and storage backends #1324. The storage code moved; this branch now carries the same transaction boundary and regression test at the new paths (section above). The neutral debitBalance helper for transaction-owning callers is unchanged.
  • An independent code and test review of this exact diff found no blocking defect.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

@vercel

vercel Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 4, 2026 9:33pm UTC
d-inference-console-ui-dev Ready Ready Preview Oct 4, 2026 9:33pm UTC
d-inference-landing Ready Ready Preview Oct 4, 2026 9:33pm UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 4, 2026 9:33pm UTC

Request Review

@jonathan308
jonathan308 marked this pull request as ready for review October 3, 2026 22:11
@jonathan308
jonathan308 requested a review from Gajesh2007 October 3, 2026 22:11
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head c9caaa1ffc80 against base c5552d3af7ae.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
normal spending limit reached; remaining coverage deferred

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.

jonathan308 and others added 2 commits October 4, 2026 12:14
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>
@Gajesh2007
Gajesh2007 merged commit 34f0e6d into master Oct 4, 2026
32 of 33 checks passed
@Gajesh2007
Gajesh2007 deleted the fix/store-timed-out-debit-commit branch October 4, 2026 23:35
jonathan308 added a commit that referenced this pull request Oct 4, 2026
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>

This branch was successfully deployed

4 active deployments
Preview – d-inference-console-ui-dev — c9caaa1f Deployed Oct 4, 2026 by vercel[bot]
Preview – d-inference — c9caaa1f Deployed Oct 4, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — c9caaa1f Deployed Oct 4, 2026 by vercel[bot]
Preview – d-inference-landing — c9caaa1f Deployed Oct 4, 2026 by vercel[bot]
benchmarks — c9caaa1f Deployed Oct 4, 2026 by jonathan308 via E2E Benchmarks #2201
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.

2 participants