Skip to content

fix(refunds): release a dispatch attempt's permit reservation once - #468

Open
PetrefiedThunder wants to merge 3 commits into
mainfrom
claude/permit-release-once
Open

PetrefiedThunder wants to merge 3 commits into
mainfrom
claude/permit-release-once

Conversation

@PetrefiedThunder

@PetrefiedThunder PetrefiedThunder commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

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_locked in gateway/app/services/refund_reconciliation.py) decremented spent_credits without reading or setting the dispatch attempt's budget_released_at. The live path, the dispatch reconciler and the budget-only sweep all release through release_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_once uses.

  • 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 answers refund_reconciliation_linkage_invalid.

  • What a release gives back is decided in one place, PermitService.release_claimed_dispatch_reservation (moved out of release_dispatch_budget_once). It gives back credits_authorized and, for an attempt that reserved a max_calls_per_tool slot and never dispatched, that slot. release_dispatch_budget_once and 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 set budget_released_at but kept the slot consumed for good.

Unchanged: items with no dispatch attempt (local tools), the refund_reconciliation_budget_conflict guard, and the clamp at zero.

Routes, before and after

All cases use max_credits 4, call cost 2, and one good call before the failed one. Each test checks spent_credits after every step, one refund row, and then spends until the permit refuses.

Route main 38da347 this branch
1. Reconciler refunds and releases, then live path writes the pending item, then operator retry spent_credits 2, then 0 after retry. 2 more calls admitted. Wallet paid 6 2, still 2 after retry. 1 more call admitted. Wallet paid 4
2. Lost acknowledgement, sweep then retry 4, 2 after sweep, 0 after retry. Paid 6 4, 2, 2. Paid 4
2. Lost acknowledgement, retry then sweep 4, 2 after retry, 0 after sweep. Paid 6 4, 2, 2. Paid 4
3A. Reconcile refunds after the pending item exists, raises before release; sweep then retry 4, 4, 2, 0. Paid 6 4, 4, 2, 2. Paid 4
3A. Same, retry then sweep 4, 4, 2, 0. Paid 6 4, 4, 2, 2. Paid 4
3B. Receipt lands after the reconcile's lookup; reconcile refunds and releases, then retry 4, 2, 0. Paid 6 4, 2, 2. Paid 4

One refund row in every run, before and after.

Two more tests:

  • No other spend: the reservation is already back. On main the retry answers 409 refund_reconciliation_budget_conflict and the item stays pending. Now it resolves and spent_credits stays 0.
  • Control: the refund checkpoint rolled back, so only the retry releases. The retry releases once and now sets budget_released_at, and a later sweep releases nothing.

Call slots (max_calls_per_tool), lost refund acknowledgement, operator retry before the sweep:

Case before 079f987 after
Pre-dispatch failure, cap 1 slot count 1 after the retry and the sweep; the next call refused with permit_max_calls_exceeded 1, then 0 after the retry, 0 after the sweep; one call admitted, then refused
Dispatched failure, cap 2 (control) 1 after the retry and the sweep 1 after the retry and the sweep (the call used its slot)

On 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

  • I identified the repository area changed by this PR. (gateway)
  • I understand that spec/, verifier/, sdk/python/, sdk/typescript/, integrations/, and examples/ are Apache-2.0.
  • I understand that gateway/ contributions are under FSL-1.1-ALv2 (Fair Source).
  • This PR does not include proprietary hosted-service code or secrets.

Spec changes

  • This PR does not change normative spec behavior.
  • If it changes normative spec behavior, I opened or linked an RFC issue.

Validation

  • Tests at 079f987, run from 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 in test_action_database_guard.py (the nested pytest saw test.db change) 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.
    • New tests without the fix: 8 failed (SQLite and PostgreSQL 16).
  • PostgreSQL 16: tests/test_permit_release_once.py, tests/test_refund_reconciliation.py and tests/test_refund_reconciliation_contention_surface.py on a disposable database migrated with alembic 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 a NullPool. Without it the generic fixtures fail with a cross-event-loop error from the connection pool, unrelated to this change.
  • Other checks: ruff 0.17.6 check and format --check clean, mypy 2.4.1 clean (mypy app/ and mypy . with mypy.ini).

Risk and compatibility

Contributor checklist

  • I added or updated tests for behavior changes, or explained why tests are not applicable.
  • I updated relevant documentation and examples. (No documentation describes this release order.)
  • Every commit in this PR is signed off under the Developer Certificate of Origin.
  • I agree to submit this contribution under the license applicable to the files I changed.

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 decremented spent_credits without setting the attempt's budget_released_at—allowing spend past max_credits.

release_claimed_dispatch_reservation centralizes what a claimed release returns: clamped credit decrement and optional max_calls_per_tool slot decrement for pre-dispatch failures. release_dispatch_budget_once now 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 same budget_released_at NULL → set gate; otherwise it resolves the item without touching budget. Local-tool items still use the clamped permit update.

Adds test_permit_release_once.py with 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

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>
@vercel

vercel Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
agent-middleware-web Ready Ready Preview Dec 5, 2026 11:14am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between ae2e721 and 079f987.

Files selected for processing: 3

  • gateway/app/services/permits.py
  • gateway/app/services/refund_reconciliation.py
  • gateway/tests/test_permit_release_once.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

Copy link
Copy Markdown
Collaborator Author

PR Guards / Engine Review Pass is red at c3448b7 because no reviewer engine other than the author has posted a review on this head yet. It needs a review, not a code change. The other checks are running.


Generated by Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 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-05T10:58:11.020428Z 328687d Draft marked ready
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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>

Copy link
Copy Markdown
Collaborator Author

READY FOR QA 079f987

This is a readiness marker, not a QA verdict. I post no verdict.

Head: 079f9877ac0438370d98d809bac2a5bfbb82fd41. The branch has three commits on its own line:

  • 2026-12-05, 09:41 UTC: c3448b7, "fix(refunds): release a dispatch attempt's permit reservation once", by the worker session that opened this PR.
  • 2026-12-05, 10:46 UTC: 328687d, a merge of main ae2e721 (feat(sdk): widen typed-action path, recommended for consequential tools #445), made by this session at the maintainer's request through GitHub's update-branch API. Its tree is identical to a local trial merge I built before the update, and git show --remerge-diff is empty.
  • 2026-12-05, 11:06 UTC: 079f987, "fix(refunds): give back a pre-dispatch call slot when the retry releases", by the same worker session. This session passed it the task at the maintainer's request. It gives this head.

This head is 0 commits behind main ae2e721. The patch against main has 3 files: gateway/app/services/permits.py, gateway/app/services/refund_reconciliation.py and the new gateway/tests/test_permit_release_once.py.

What 079f987 changes: Codex (P2) and Cursor Bugbot (High) both reported on 328687d that the operator retry claimed budget_released_at but gave back only the credits. Unlike release_dispatch_budget_once, it did not give back the max_calls_per_tool slot of an attempt that never dispatched, and once the flag was set no other path released that attempt. The release body is now one method, PermitService.release_claimed_dispatch_reservation. Both release_dispatch_budget_once and the retry call it after winning the once-only claim, in the same transaction. For an item with a dispatch attempt, the retry now gives back the attempt's credits_authorized through that method. Items with no dispatch attempt keep their previous release. The shared method also reads the permit's tool_call_counts_json with populate_existing, so release_dispatch_budget_once now does the call-slot compare and swap against a fresh value. Both review threads have a reply from the worker session and are resolved.

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. CI result, License result and gitleaks are success. The 3 skipped runs are matrix jobs whose names were not expanded: Node, Python licenses and npm licenses. The neutral run is CodeRabbit ("Review rate limited"). The cancelled run and the 4 failures are all runs of Engine Review Pass, whose commit status reads "No passing review from a non-author engine for current head SHA". The branch prefix claude/ makes claude the author engine.

Local check on this head's tree (2612b357), Python 3.12, SQLite:

  • Full leg (-m "not production_trust", -n auto): 6735 passed, 105 skipped, 1 xfailed, 0 failed. Production-trust leg: 12 passed. ruff 0.17.6 and mypy 2.4.1 pass.
  • tests/test_permit_release_once.py alone: 10 passed.
  • With permits.py and refund_reconciliation.py put back to 328687d, the same file gives 1 failed and 9 passed. The failing test is test_retry_gives_back_a_pre_dispatch_call_slot_once.
  • On 328687d I also ran the test file as it is there (8 tests) with only refund_reconciliation.py put back to main's version: all 8 failed.
  • Not run locally: the PostgreSQL jobs and the other Python versions. CI ran them on this head and they are success.

Bots and reviews:

  • Cursor Bugbot reviewed this head and found no issues (check run success).
  • Codex reviewed 328687d, not this head. Its summary comment still names 328687d.
  • CodeRabbit has not reviewed this PR. Its check run on this head is neutral, "Review rate limited".
  • Copilot is assigned, and its copilot check run on this head is success. It has posted no review or comment.
  • Both review threads (the Codex P2 and the Bugbot High above) are resolved. There are no other threads.

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 (3ccfb09) and #279 (32c9b0b) are each 1 commit behind main. The maintainer's plan is to update both after this PR merges. This PR says Refs #434. Part 2 of #434 (a docs sentence) is not in it.

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 AGENTS.md a merge needs QA to pass the exact head, green CI result, License result and gitleaks, a branch up to date with main, and all review threads resolved.

Main: as read at 11:27 UTC on 2026-12-05, main is ae2e721 and this head is 0 commits behind it.

I merge nothing.


Generated by Claude Code

This branch was successfully deployed

1 active deployment
Preview — 079f9877 Deployed Dec 5, 2026 by vercel[bot]
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.

3 participants