Repository navigation
fix(refunds): release a dispatch attempt's permit reservation once - #468
PetrefiedThunder wants to merge 3 commits into
Conversation
The operator refund retry decremented the permit's spent_credits without reading or setting the dispatch attempt's budget_released_at. When the live path, the dispatch reconciler or the budget-only sweep had already released the same reservation through release_dispatch_budget_once, or released it after the retry, one refunded upstream call gave its reservation back twice and the permit admitted one call's cost past max_credits (issue #434 part 1). For an item that has a dispatch attempt, the retry now locks the attempt before the permit and releases through the same guarded budget_released_at IS NULL update as release_dispatch_budget_once, in its own transaction. If the reservation is already back, it resolves the item without a decrement and without the budget conflict check, so the item does not stay pending. Items with no dispatch attempt (local tools) keep the old behavior. The budget conflict guard and the clamp at zero are unchanged. Tests reproduce each route from the issue with forced order: lost refund acknowledgement with sweep then retry and retry then sweep, reconciler release before the live pending item, and a reconcile that refunds after the pending item exists (both orders) or misses a late receipt. Each checks spent_credits after every step, one refund row, and that the permit then refuses spend at max_credits. Refs #434 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GyhDYGi5fpiBGFHez9fhbH Signed-off-by: Claude <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 32 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
Generated by Claude Code |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 328687d346
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 328687d. Configure here.
The operator retry now claims the dispatch attempt's budget_released_at, which stops every later release of that attempt. But it gave back only spent_credits. release_dispatch_budget_once also gives back the max_calls_per_tool slot of an attempt that reserved one and never dispatched. So when the retry was the release for a pre-dispatch failure, that slot stayed consumed for good (review findings on #468). Move the release body of release_dispatch_budget_once into PermitService.release_claimed_dispatch_reservation, which gives back credits_authorized (clamped at zero) and, for a reserved slot that never dispatched, decrements tool_call_counts_json under its compare and swap. release_dispatch_budget_once and the operator retry both call it after winning the once-only claim, in the same transaction. The slot read now refreshes the permit row, because the retry's session already holds it. A contended slot update in the retry rolls the whole retry back, claim included, and the item stays pending. Tests: a pre-dispatch failure with a lost refund acknowledgement and max_calls_per_tool 1, retried before the sweep: the slot count goes from 1 to 0 with the credits, stays 0 after the sweep, and one more call is admitted before permit_max_calls_exceeded. Control: a dispatched failure keeps its slot consumed after the retry and the sweep. Refs #434 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GyhDYGi5fpiBGFHez9fhbH Signed-off-by: Claude <noreply@anthropic.com>
|
READY FOR QA 079f987 This is a readiness marker, not a QA verdict. I post no verdict. Head:
This head is 0 commits behind main What CI on this head: as read at 11:27 UTC on 2026-12-05, all 35 check runs are complete: 26 success, 3 skipped, 1 neutral, 1 cancelled, 4 failure. Local check on this head's tree (
Bots and reviews:
What the PR description claims and I did not check myself: the before and after numbers per route, and a PostgreSQL 16 run of the new test file and two existing refund reconciliation test files with a local test plugin that is not committed. Not tested, as the description says: real concurrency between the retry and a sweep on separate connections, the signer window that #434's last comment describes on the #330 and #331 heads, and the same-key retry entry into the reconciler. Other open PRs: #331 ( Payment path: this PR changes how the operator refund retry gives back a permit reservation and a call slot. No maintainer yes is recorded on this PR. Under Main: as read at 11:27 UTC on 2026-12-05, main is I merge nothing. Generated by Claude Code |

Summary
Fixes part 1 of #434: one refunded upstream call could give its permit reservation back twice, so the permit admitted one call's cost past
max_credits.Cause: the operator refund retry (
_retry_lockedingateway/app/services/refund_reconciliation.py) decrementedspent_creditswithout reading or setting the dispatch attempt'sbudget_released_at. The live path, the dispatch reconciler and the budget-only sweep all release throughrelease_dispatch_budget_once, which sets that flag. So the retry and any one of them released the same reservation twice, in either order.Change, for an item that has a dispatch attempt:
The retry locks the attempt before the permit. This is the order
release_dispatch_budget_onceuses.It releases through the same guarded update (
budget_released_at IS NULL, set in the same transaction). A later sweep or reconcile then releases nothing.When the reservation is already released, the retry resolves the item without a decrement and skips the budget conflict check, so the item does not stay pending (third comment on Permit reservation can be released twice for one refunded upstream call, so a permit admits spend past max_credits; and the replay contract docs misstate revoked-permit replay #434).
The attempt must match the item's idempotency record, the receipt's
dispatch_attempt_id, permit, wallet and charge. Otherwise the retry answersrefund_reconciliation_linkage_invalid.What a release gives back is decided in one place,
PermitService.release_claimed_dispatch_reservation(moved out ofrelease_dispatch_budget_once). It gives backcredits_authorizedand, for an attempt that reserved amax_calls_per_toolslot and never dispatched, that slot.release_dispatch_budget_onceand the retry both call it after winning the once-only claim, in the same transaction. Added in 079f987 after review: before it, a retry that was the release for a pre-dispatch failure setbudget_released_atbut kept the slot consumed for good.Unchanged: items with no dispatch attempt (local tools), the
refund_reconciliation_budget_conflictguard, and the clamp at zero.Routes, before and after
All cases use
max_credits4, call cost 2, and one good call before the failed one. Each test checksspent_creditsafter every step, one refund row, and then spends until the permit refuses.38da347spent_credits2, then 0 after retry. 2 more calls admitted. Wallet paid 6One refund row in every run, before and after.
Two more tests:
refund_reconciliation_budget_conflictand the item stays pending. Now it resolves andspent_creditsstays 0.budget_released_at, and a later sweep releases nothing.Call slots (
max_calls_per_tool), lost refund acknowledgement, operator retry before the sweep:permit_max_calls_exceededOn main the retry did not give back the slot either, but the sweep released the attempt later (with the double credit release this PR fixes).
The first 8 new tests fail on main and pass on this branch, on SQLite and on PostgreSQL 16. The pre-dispatch slot test fails at c3448b7 and passes at 079f987.
Related issues
Refs #434
Part 2 of #434 (the replay contract docs sentence) is not in this PR. The proposed text replaces one sentence with three, so it is left for a separate change.
Area and license
spec/,verifier/,sdk/python/,sdk/typescript/,integrations/, andexamples/are Apache-2.0.gateway/contributions are under FSL-1.1-ALv2 (Fair Source).Spec changes
Validation
gateway/as CI runs them (Python 3.12, pytest 9.2.0):pytest -q --ignore=tests/judge_e2e -m "not production_trust" -n auto --timeout 300: 6735 passed, 105 skipped, 1 xfailed. A first run had one failure intest_action_database_guard.py(the nested pytest sawtest.dbchange) while a PostgreSQL run used the same directory; that file passed alone (37 passed) and the full leg passed when rerun alone.TRUST_MODE_ENABLED=true ALLOW_LEGACY_UNPERMITTED_MCP=false ENABLE_PROOF_SURFACES=false pytest -q --ignore=tests/judge_e2e -m production_trust --timeout 300: 12 passed.tests/test_permit_release_once.py,tests/test_refund_reconciliation.pyandtests/test_refund_reconciliation_contention_surface.pyon a disposable database migrated withalembic upgrade head(ENVIRONMENT=test,AMW_TEST_DB_DISPOSABLE=1): 28 passed, 2 skipped at 079f987. Both skips are existing tests marked SQLite-only. This run loaded a local, uncommitted test plugin that gives the engine aNullPool. Without it the generic fixtures fail with a cross-event-loop error from the connection pool, unrelated to this change.checkandformat --checkclean, mypy 2.4.1 clean (mypy app/andmypy .withmypy.ini).Risk and compatibility
release_dispatch_budget_oncenow reads the permit'stool_call_counts_jsonwithpopulate_existing, so the slot compare and swap uses a fresh value. Its behavior is otherwise unchanged; the body moved into the shared method.PermitWriteContendedError, which rolls the retry back (claim included) and answers 503refund_reconciliation_failed; the item stays pending for another retry.release_dispatch_budget_once. The only path that locks an attempt before its idempotency record isabandon_effect_free_prepared_attempt, which acts on a prepared attempt with no charge and so never on an attempt that has a refund item.release_dispatch_budget_once._compensate_returned_errorstate as the tested routes.Contributor checklist
Note
High Risk
Changes permit budget and call-slot release on the operator refund path and ties it to dispatch-attempt claims; incorrect idempotency would either over-release budget (overspend) or leave items stuck pending.
Overview
Fixes double release of permit budget when a refunded upstream MCP call is cleaned up by both the dispatch path (
release_dispatch_budget_once/ sweep / reconciler) and the operator refund retry, which previously decrementedspent_creditswithout setting the attempt'sbudget_released_at—allowing spend pastmax_credits.release_claimed_dispatch_reservationcentralizes what a claimed release returns: clamped credit decrement and optionalmax_calls_per_toolslot decrement for pre-dispatch failures.release_dispatch_budget_oncenow delegates to it after the guarded claim.Refund reconciliation retry for governed upstream calls now locks the dispatch attempt (before the permit), validates linkage via
_dispatch_attempt_for_item, and only releases when it wins the samebudget_released_atNULL → set gate; otherwise it resolves the item without touching budget. Local-tool items still use the clamped permit update.Adds
test_permit_release_once.pywith eight scenarios (sweep vs retry ordering, reconciler races, pre-dispatch slots, and already-released reservations).Reviewed by Cursor Bugbot for commit 079f987. Bugbot is set up for automated code reviews on this repo. Configure here.
Generated by Claude Code