diff --git a/gateway/app/services/permits.py b/gateway/app/services/permits.py index 01f5fde74..6b3043794 100644 --- a/gateway/app/services/permits.py +++ b/gateway/app/services/permits.py @@ -1727,100 +1727,9 @@ async def _once() -> bool: # Another caller claimed it first; its transaction owns # the single decrement. return False - # If this attempt holds a call slot, release it by decrementing - # the tool_call_counts_json counter. This happens in the same - # transaction as the budget release, so it's once-only. - permit_update_values: dict[str, Any] = { - "spent_credits": case( - ( - cast( - ColumnElement[bool], - PermitModel.spent_credits - - attempt.credits_authorized - < Decimal("0"), - ), - Decimal("0"), - ), - else_=PermitModel.spent_credits - - attempt.credits_authorized, - ), - "updated_at": now, - } - - original_counts_json = None - if attempt.call_slot_reserved: - # Only release call slot if attempt never dispatched. - # A dispatched attempt consumed its slot even if it later - # errored and was refunded - the slot was used. - if attempt.dispatched_at is None: - # Pre-dispatch failure: release the call slot - permit = await session.get(PermitModel, attempt.permit_id) - if permit is not None: - original_counts_json = permit.tool_call_counts_json - current_counts = _loads_dict( - original_counts_json or "{}" - ) - tool_name = attempt.public_tool_id - if tool_name in current_counts: - current_count = current_counts[tool_name] - if ( - isinstance(current_count, int) - and current_count > 0 - ): - updated_counts = dict(current_counts) - updated_counts[tool_name] = current_count - 1 - permit_update_values[ - "tool_call_counts_json" - ] = json.dumps(updated_counts) - - # Atomic clamped decrement so a concurrent reservation on the - # same permit is not clobbered by a read-modify-write here. - # Add CAS on tool_call_counts_json when releasing a slot to - # prevent concurrent releases from clobbering each other. - where_conditions = [ - cast( - ColumnElement[bool], - PermitModel.permit_id == attempt.permit_id, - ) - ] - if ( - attempt.call_slot_reserved - and "tool_call_counts_json" in permit_update_values - ): - # Add optimistic lock: only succeed if counts haven't changed - if original_counts_json is None: - where_conditions.append( - cast( - ColumnElement[bool], - cast(Any, PermitModel.tool_call_counts_json).is_( - None - ), - ) - ) - else: - where_conditions.append( - cast( - ColumnElement[bool], - PermitModel.tool_call_counts_json - == original_counts_json, - ) - ) - - released = await session.execute( - sa_update(PermitModel) - .where(*where_conditions) - .values(**permit_update_values) - .execution_options(synchronize_session=False) + await self.release_claimed_dispatch_reservation( + session, attempt, now=now ) - if (cast(Any, released).rowcount or 0) == 0: - # CAS failed - either permit doesn't exist or counts changed. - # Check if permit exists to distinguish the cases. - check_permit = await session.get(PermitModel, attempt.permit_id) - if check_permit is None: - raise PermitError("permit_not_found") - # Permit exists but CAS failed - counts changed concurrently. - # Raise a retryable error so _run_with_write_retry retries. - raise PermitWriteContendedError() # budget_released_at was already set by the guarded claim # above; refresh the identity-mapped instance so callers # holding it observe the committed value. @@ -1831,6 +1740,116 @@ async def _once() -> bool: return await self._run_with_write_retry(_once) + async def release_claimed_dispatch_reservation( + self, + session: AsyncSession, + attempt: McpDispatchAttemptModel, + *, + now: datetime, + ) -> None: + """Give back one dispatch attempt's reservation inside ``session``. + + The caller must already own the attempt's once-only claim: in this same + transaction it flipped ``budget_released_at`` from NULL. This is the + single place that decides what a release gives back, so every claimant + (``release_dispatch_budget_once`` and the operator refund retry) gives + back the same thing: ``credits_authorized`` from ``spent_credits``, + clamped at zero, and the per-tool call slot when the attempt reserved + one and never dispatched. + + Raises ``PermitWriteContendedError`` when the call-slot compare and + swap misses; the caller's transaction must then roll back whole, claim + included. + """ + # If this attempt holds a call slot, release it by decrementing + # the tool_call_counts_json counter. This happens in the same + # transaction as the budget release, so it's once-only. + permit_update_values: dict[str, Any] = { + "spent_credits": case( + ( + cast( + ColumnElement[bool], + PermitModel.spent_credits - attempt.credits_authorized + < Decimal("0"), + ), + Decimal("0"), + ), + else_=PermitModel.spent_credits - attempt.credits_authorized, + ), + "updated_at": now, + } + + original_counts_json = None + if attempt.call_slot_reserved: + # Only release call slot if attempt never dispatched. + # A dispatched attempt consumed its slot even if it later + # errored and was refunded - the slot was used. + if attempt.dispatched_at is None: + # Pre-dispatch failure: release the call slot. Read the + # counts fresh: the caller's session may already hold this + # permit from before its claim. + permit = await session.get( + PermitModel, attempt.permit_id, populate_existing=True + ) + if permit is not None: + original_counts_json = permit.tool_call_counts_json + current_counts = _loads_dict(original_counts_json or "{}") + tool_name = attempt.public_tool_id + if tool_name in current_counts: + current_count = current_counts[tool_name] + if isinstance(current_count, int) and current_count > 0: + updated_counts = dict(current_counts) + updated_counts[tool_name] = current_count - 1 + permit_update_values["tool_call_counts_json"] = json.dumps( + updated_counts + ) + + # Atomic clamped decrement so a concurrent reservation on the + # same permit is not clobbered by a read-modify-write here. + # Add CAS on tool_call_counts_json when releasing a slot to + # prevent concurrent releases from clobbering each other. + where_conditions = [ + cast( + ColumnElement[bool], + PermitModel.permit_id == attempt.permit_id, + ) + ] + if ( + attempt.call_slot_reserved + and "tool_call_counts_json" in permit_update_values + ): + # Add optimistic lock: only succeed if counts haven't changed + if original_counts_json is None: + where_conditions.append( + cast( + ColumnElement[bool], + cast(Any, PermitModel.tool_call_counts_json).is_(None), + ) + ) + else: + where_conditions.append( + cast( + ColumnElement[bool], + PermitModel.tool_call_counts_json == original_counts_json, + ) + ) + + released = await session.execute( + sa_update(PermitModel) + .where(*where_conditions) + .values(**permit_update_values) + .execution_options(synchronize_session=False) + ) + if (cast(Any, released).rowcount or 0) == 0: + # CAS failed - either permit doesn't exist or counts changed. + # Check if permit exists to distinguish the cases. + check_permit = await session.get(PermitModel, attempt.permit_id) + if check_permit is None: + raise PermitError("permit_not_found") + # Permit exists but CAS failed - counts changed concurrently. + # Raise a retryable error so _run_with_write_retry retries. + raise PermitWriteContendedError() + async def _consumed_credits(self, session: Any, permit_id: str) -> Decimal: """Credits a permit's receipts prove it actually consumed. diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index c9291cb2f..8edbaa4a4 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -19,6 +19,7 @@ HumanApprovalModel, IdempotencyRecordModel, LedgerEntryModel, + McpDispatchAttemptModel, PermitModel, ReceiptModel, WalletModel, @@ -693,6 +694,15 @@ async def _retry_locked( item.ledger_entry_id, with_for_update=True, ) + # Locked before the permit, the order + # release_dispatch_budget_once takes them in (attempt, then + # permit), so this retry and the sweep cannot deadlock. + attempt = await self._dispatch_attempt_for_item( + session, + record=record, + receipt=receipt, + item=item, + ) permit = await session.get( PermitModel, item.permit_id, @@ -761,7 +771,19 @@ async def _retry_locked( raise RefundReconciliationError( "refund_reconciliation_state_conflict" ) - if permit.spent_credits < item.credits: + # A governed upstream call's reservation is keyed by its + # dispatch attempt, and the live path, the dispatch reconciler + # and the budget-only sweep all give it back through + # release_dispatch_budget_once, which sets budget_released_at. + # When one of them already did, this retry must not decrement + # again: that second release is what let a permit admit one + # call's cost past max_credits (issue #434). It also must not + # refuse the item as a budget conflict, or an item whose + # reservation is already back would stay pending for good. + release_reservation = ( + attempt is None or attempt.budget_released_at is None + ) + if release_reservation and permit.spent_credits < item.credits: raise RefundReconciliationError( "refund_reconciliation_budget_conflict" ) @@ -794,27 +816,69 @@ async def _retry_locked( correlation_id=item.ledger_entry_id, ) session.add(refund) - # Release the permit reservation with a clamped relative UPDATE - # for the same reason: ``permits.py`` guarantees that every - # ``spent_credits`` write is decided by the database, and that - # guarantee is only as good as its weakest caller. This one sat - # outside that module and wrote back a value read earlier. - await session.execute( - sa_update(PermitModel) - .where( - cast( - ColumnElement[bool], - PermitModel.permit_id == permit.permit_id, + if attempt is not None and release_reservation: + # The same once-only gate as release_dispatch_budget_once, + # in this transaction: exactly one caller can flip + # budget_released_at from NULL, on every engine (FOR + # UPDATE is a no-op on SQLite). Setting it here is what + # stops a later sweep or reconcile from releasing this + # reservation a second time. + released_at = utc_now() + claimed = await session.execute( + sa_update(McpDispatchAttemptModel) + .where( + cast( + ColumnElement[bool], + McpDispatchAttemptModel.attempt_id + == attempt.attempt_id, + ), + cast( + ColumnElement[bool], + cast( + Any, McpDispatchAttemptModel.budget_released_at + ).is_(None), + ), ) + .values(budget_released_at=released_at, updated_at=released_at) + .execution_options(synchronize_session=False) ) - .values( - spent_credits=clamped_decrement( - PermitModel.spent_credits, item.credits - ), - updated_at=utc_now(), + if (cast(Any, claimed).rowcount or 0) == 1: + # Give back exactly what release_dispatch_budget_once + # gives back, through the same code: the credits and, + # for an attempt that never dispatched, its + # max_calls_per_tool slot. Once budget_released_at is + # set no other path releases this attempt, so a slot + # skipped here would stay consumed for good. A + # contended slot update raises and rolls the whole + # retry back, claim included; the item stays pending. + await get_permit_service().release_claimed_dispatch_reservation( + session, attempt, now=released_at + ) + elif release_reservation: + # A local tool call has no dispatch attempt; the operator + # retry is its only release. Release the permit + # reservation with a clamped relative + # UPDATE for the same reason: ``permits.py`` guarantees + # that every ``spent_credits`` write is decided by the + # database, and that guarantee is only as good as its + # weakest caller. This one sat outside that module and + # wrote back a value read earlier. + await session.execute( + sa_update(PermitModel) + .where( + cast( + ColumnElement[bool], + PermitModel.permit_id == permit.permit_id, + ) + ) + .values( + spent_credits=clamped_decrement( + PermitModel.spent_credits, item.credits + ), + updated_at=utc_now(), + ) + .execution_options(synchronize_session=False) ) - .execution_options(synchronize_session=False) - ) await session.refresh(permit) resolved_at = utc_now().isoformat() state = cast(dict[str, Any], payload["refund_reconciliation"]) @@ -832,6 +896,53 @@ async def _retry_locked( ) return resolved, False + @staticmethod + async def _dispatch_attempt_for_item( + session: AsyncSession, + *, + record: IdempotencyRecordModel, + receipt: ReceiptModel, + item: RefundReconciliationItem, + ) -> McpDispatchAttemptModel | None: + """Lock the dispatch attempt that holds this item's reservation, if any. + + A local tool call has no dispatch attempt; its reservation is released + only by the operator retry, as before. A governed upstream call has + exactly one, bound to the same idempotency record, and the receipt + names it. Any disagreement between the two fails closed. + """ + attempt = ( + await session.execute( + select(McpDispatchAttemptModel) + .where( + cast( + ColumnElement[bool], + McpDispatchAttemptModel.idempotency_record_id + == record.record_id, + ) + ) + .with_for_update() + ) + ).scalar_one_or_none() + if attempt is None: + if receipt.dispatch_attempt_id is not None: + raise RefundReconciliationError("refund_reconciliation_linkage_invalid") + return None + if ( + ( + receipt.dispatch_attempt_id is not None + and receipt.dispatch_attempt_id != attempt.attempt_id + ) + or attempt.permit_id != item.permit_id + or attempt.wallet_id != item.wallet_id + or ( + attempt.ledger_entry_id is not None + and attempt.ledger_entry_id != item.ledger_entry_id + ) + ): + raise RefundReconciliationError("refund_reconciliation_linkage_invalid") + return attempt + async def _apply_refund( self, session: AsyncSession, diff --git a/gateway/tests/test_permit_release_once.py b/gateway/tests/test_permit_release_once.py new file mode 100644 index 000000000..12737632f --- /dev/null +++ b/gateway/tests/test_permit_release_once.py @@ -0,0 +1,649 @@ +"""One refunded upstream call gives its permit reservation back exactly once. + +Issue #434 part 1. A governed upstream call reserves its cost on the permit +(``spent_credits``). When the call fails and its charge is refunded, the +reservation is released. Three routes on main released it twice: once through +the dispatch attempt (``release_dispatch_budget_once``, via the live path, the +dispatch reconciler or the budget-only sweep) and once more through the +operator refund retry, which decremented ``spent_credits`` without reading or +setting the attempt's ``budget_released_at``. The permit then admitted one +call's cost past ``max_credits``. + +Each test forces one route's order of events with a fault and a hook, checks +``spent_credits`` after every step, checks that the charge was refunded once, +and then spends until the permit refuses, so a call admitted past the cap +fails the test. +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from typing import Any + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import func, select + +from app.core.time import utc_now +from app.db.database import get_session_factory +from app.db.models import LedgerEntryModel, McpDispatchAttemptModel, PermitModel +from app.main import app +from app.routers import mcp as mcp_router +from app.services.agent_money import AgentMoney +from app.services.mcp_dispatch_attempts import ( + DispatchAttemptError, + McpDispatchAttemptService, +) +from app.services.mcp_dispatch_reconciliation import ( + get_mcp_dispatch_reconciliation_service, +) +from app.services.receipts import ReceiptService +from app.services.service_registry import get_service_registry +from tests.test_mcp_upstream_governed import ( + FakeUpstreamExecutor, + _call_body, + _register_upstream, +) +from tests.test_trust_helpers import ( + BOOTSTRAP_HEADERS, + create_tool_permit, + provision_agent_wallet, +) + +CALL_COST = Decimal("2") +MAX_CREDITS = Decimal("4") + + +@pytest.fixture +async def client() -> AsyncClient: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as value: + yield value + + +class _Case: + def __init__( + self, + client: AsyncClient, + provisioned: dict[str, Any], + permit: dict[str, Any], + executor: FakeUpstreamExecutor, + tool_name: str, + start_balance: Decimal, + ) -> None: + self.client = client + self.provisioned = provisioned + self.permit = permit + self.executor = executor + self.tool_name = tool_name + self.start_balance = start_balance + self.calls = 0 + + @property + def wallet_id(self) -> str: + return str(self.provisioned["agent_wallet_id"]) + + @property + def permit_id(self) -> str: + return str(self.permit["permit_id"]) + + async def call(self, mode: str) -> dict[str, Any]: + self.executor.mode = mode # type: ignore[assignment] + self.calls += 1 + response = await self.client.post( + "/mcp/messages", + json=_call_body( + tool_name=self.tool_name, + wallet_id=self.wallet_id, + permit_id=self.permit_id, + idempotency_key=f"{self.tool_name}-call-{self.calls}", + ), + headers=self.provisioned["agent_headers"], + ) + assert response.status_code == 200 + return dict(response.json()) + + async def spent(self) -> Decimal: + factory = get_session_factory() + async with factory() as session: + permit = await session.get(PermitModel, self.permit_id) + assert permit is not None + return Decimal(permit.spent_credits) + + async def tool_calls(self) -> int: + """Calls the permit counts against max_calls_per_tool for this tool.""" + factory = get_session_factory() + async with factory() as session: + permit = await session.get(PermitModel, self.permit_id) + assert permit is not None + counts = json.loads(permit.tool_call_counts_json or "{}") + return int(counts.get(self.tool_name, 0)) + + async def balance(self) -> Decimal: + response = await self.client.get( + f"/v1/billing/wallets/{self.wallet_id}", + headers=self.provisioned["agent_headers"], + ) + assert response.status_code == 200 + return Decimal(response.json()["balance_exact"]) + + async def failed_attempt(self) -> McpDispatchAttemptModel: + factory = get_session_factory() + async with factory() as session: + attempts = ( + ( + await session.execute( + select(McpDispatchAttemptModel).where( + McpDispatchAttemptModel.permit_id == self.permit_id, + McpDispatchAttemptModel.state == "returned_error", + ) + ) + ) + .scalars() + .all() + ) + assert len(attempts) == 1 + return attempts[0] + + async def refund_rows(self, ledger_entry_id: str) -> int: + factory = get_session_factory() + async with factory() as session: + count = await session.scalar( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.correlation_id == ledger_entry_id, + LedgerEntryModel.action == "refund", + ) + ) + return int(count or 0) + + async def backdate_attempt(self, attempt_id: str) -> None: + """Stand in for the 300 seconds the sweep waits on a terminal attempt.""" + factory = get_session_factory() + async with factory() as session: + async with session.begin(): + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + assert attempt is not None + attempt.updated_at = utc_now() - timedelta(minutes=10) + + async def sweep(self, attempt_id: str) -> None: + await self.backdate_attempt(attempt_id) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + async def operator_retry(self, receipt_id: str) -> dict[str, Any]: + response = await self.client.post( + f"/v1/receipts/reconciliation/refunds/{receipt_id}/retry", + headers=BOOTSTRAP_HEADERS, + ) + assert response.status_code == 200, response.text + return dict(response.json()) + + async def spend_until_refused(self) -> int: + """Spend on the permit until it refuses; return the calls it admitted.""" + admitted = 0 + for _ in range(5): + body = await self.call("success") + if "error" not in body: + admitted += 1 + continue + assert "permit_budget_exceeded" in json.dumps(body["error"]) + return admitted + raise AssertionError("permit never refused further spend") + + +async def _start( + client: AsyncClient, + monkeypatch: pytest.MonkeyPatch, + tool_name: str, + *, + other_spend: bool = True, + max_credits: Decimal = MAX_CREDITS, + max_calls: int | None = None, +) -> _Case: + monkeypatch.setattr(mcp_router.settings, "SIMULATION_MODE_HUMAN_APPROVAL", True) + provisioned = await provision_agent_wallet(client) + executor = FakeUpstreamExecutor("success") + _register_upstream(tool_name, executor, credits_per_call=float(CALL_COST)) + if max_calls is None: + permit = await create_tool_permit( + client, + wallet_id=provisioned["agent_wallet_id"], + key_id=provisioned["key_id"], + tool_name=tool_name, + max_credits=float(max_credits), + idem_key=f"{tool_name}-permit", + ) + else: + response = await client.post( + "/v1/permits", + json={ + "issuer_wallet_id": provisioned["agent_wallet_id"], + "subject_wallet_id": provisioned["agent_wallet_id"], + "subject_key_id": provisioned["key_id"], + "allowed_tools": [tool_name], + "scopes": [f"tool:{tool_name}:invoke", "billing:charge"], + "max_credits": float(max_credits), + "max_calls_per_tool": {tool_name: max_calls}, + "expires_at": ( + datetime.now(timezone.utc) + timedelta(minutes=30) + ).isoformat(), + }, + headers={**BOOTSTRAP_HEADERS, "Idempotency-Key": f"{tool_name}-permit"}, + ) + assert response.status_code == 201, response.text + permit = response.json() + case = _Case(client, provisioned, permit, executor, tool_name, Decimal("0")) + case.start_balance = await case.balance() + if not other_spend: + return case + + # Other spend on the permit: one good call. Without it the operator retry + # refuses with refund_reconciliation_budget_conflict and nothing extra is + # admitted, which hides the double release. + good = await case.call("success") + assert "error" not in good + assert await case.spent() == CALL_COST + return case + + +def _failed_receipt(body: dict[str, Any]) -> tuple[str, str]: + assert body["error"]["message"].startswith("refund_failed") + receipt = body["error"]["data"]["receipt"] + assert receipt["outcome"] == "failed_unrefunded" + return str(receipt["receipt_id"]), str(receipt["ledger_entry_id"]) + + +async def _assert_capped(case: _Case, ledger_entry_id: str) -> None: + """One refund, one more call admitted, the wallet paid at most max_credits.""" + assert await case.refund_rows(ledger_entry_id) == 1 + assert await case.spend_until_refused() == 1 + assert await case.spent() == MAX_CREDITS + assert await case.balance() == case.start_balance - MAX_CREDITS + assert await case.refund_rows(ledger_entry_id) == 1 + + +def _lose_refund_ack_once(monkeypatch: pytest.MonkeyPatch) -> None: + """mark_debit_refunded commits, then the live request sees an exception.""" + original = McpDispatchAttemptService.mark_debit_refunded + state = {"fired": False} + + async def lost_ack(self: McpDispatchAttemptService, **kwargs: Any) -> Any: + result = await original(self, **kwargs) + if not state["fired"]: + state["fired"] = True + raise RuntimeError("refund acknowledgement lost") + return result + + monkeypatch.setattr(McpDispatchAttemptService, "mark_debit_refunded", lost_ack) + + +def _fail_refund_once(monkeypatch: pytest.MonkeyPatch) -> None: + """The live refund raises once; later refunds (the reconciler's) succeed.""" + original = AgentMoney.refund_charge + state = {"fired": False} + + async def failing_once(self: AgentMoney, *args: Any, **kwargs: Any) -> Any: + if not state["fired"]: + state["fired"] = True + raise RuntimeError("refund unavailable") + return await original(self, *args, **kwargs) + + monkeypatch.setattr(AgentMoney, "refund_charge", failing_once) + + +@pytest.mark.anyio +@pytest.mark.parametrize("order", ["sweep_then_retry", "retry_then_sweep"]) +async def test_lost_refund_ack_releases_reservation_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, + order: str, +) -> None: + """Route 2: lost acknowledgement, then the sweep and the operator retry.""" + tool_name = f"release-once-lost-ack-{order}" + case = await _start(client, monkeypatch, tool_name) + try: + _lose_refund_ack_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + attempt = await case.failed_attempt() + assert attempt.debit_refunded_at is not None + assert attempt.budget_released_at is None + # Refunded, reservation still held. + assert await case.spent() == MAX_CREDITS + assert await case.balance() == case.start_balance - CALL_COST + assert await case.refund_rows(ledger_entry_id) == 1 + + if order == "sweep_then_retry": + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + else: + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + + assert (await case.failed_attempt()).budget_released_at is not None + await _assert_capped(case, ledger_entry_id) + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_reconciler_release_before_live_pending_item_releases_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Route 1: the reconciler refunds and releases, then the live path stores + the pending item, then the operator retries it.""" + tool_name = "release-once-reconciler-first" + case = await _start(client, monkeypatch, tool_name) + try: + _fail_refund_once(monkeypatch) + reconciler = get_mcp_dispatch_reconciliation_service() + original_finalize = mcp_router._finalize_unrefunded_failure + seen: dict[str, Decimal] = {} + + async def reconcile_first(**kwargs: Any) -> Any: + # The reconciler reaches the attempt before the live receipt and + # pending item exist: it finds no receipt, refunds and releases. + attempt = await case.failed_attempt() + assert attempt.attempt_id == kwargs["dispatch_attempt_id"] + await reconciler._compensate_returned_error(attempt) + seen["spent_after_reconciler"] = await case.spent() + return await original_finalize(**kwargs) + + monkeypatch.setattr(mcp_router, "_finalize_unrefunded_failure", reconcile_first) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + assert seen["spent_after_reconciler"] == CALL_COST + assert await case.spent() == CALL_COST + assert await case.balance() == case.start_balance - CALL_COST + assert await case.refund_rows(ledger_entry_id) == 1 + attempt = await case.failed_attempt() + assert attempt.budget_released_at is not None + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + + await _assert_capped(case, ledger_entry_id) + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +@pytest.mark.parametrize("order", ["sweep_then_retry", "retry_then_sweep"]) +async def test_reconcile_refunds_after_pending_item_releases_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, + order: str, +) -> None: + """Route 3 case A: a reconcile that listed the attempt finds the + failed_unrefunded receipt, refunds anyway and raises before releasing; + the sweep and the operator retry then both reach the reservation.""" + tool_name = f"release-once-reconcile-after-item-{order}" + case = await _start(client, monkeypatch, tool_name) + try: + _fail_refund_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + assert await case.spent() == MAX_CREDITS + assert await case.balance() == case.start_balance - MAX_CREDITS + assert await case.refund_rows(ledger_entry_id) == 0 + + listed = await case.failed_attempt() + with pytest.raises(DispatchAttemptError, match="outcome_conflict"): + await get_mcp_dispatch_reconciliation_service()._compensate_returned_error( + listed + ) + attempt = await case.failed_attempt() + assert attempt.debit_refunded_at is not None + assert attempt.budget_released_at is None + assert await case.spent() == MAX_CREDITS + assert await case.balance() == case.start_balance - CALL_COST + assert await case.refund_rows(ledger_entry_id) == 1 + + if order == "sweep_then_retry": + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + else: + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + + await _assert_capped(case, ledger_entry_id) + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_reconcile_missing_late_receipt_releases_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Route 3 case B: the receipt lands after the reconcile's lookup, so the + reconcile refunds and releases; the operator retry must not release again.""" + tool_name = "release-once-late-receipt" + case = await _start(client, monkeypatch, tool_name) + try: + _fail_refund_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + assert await case.spent() == MAX_CREDITS + + original_lookup = ReceiptService.get_receipt_by_idempotency_record_id + state = {"hidden": False} + + async def lookup_before_receipt( + self: ReceiptService, *args: Any, **kwargs: Any + ) -> Any: + if not state["hidden"]: + state["hidden"] = True + return None + return await original_lookup(self, *args, **kwargs) + + monkeypatch.setattr( + ReceiptService, + "get_receipt_by_idempotency_record_id", + lookup_before_receipt, + ) + listed = await case.failed_attempt() + await get_mcp_dispatch_reconciliation_service()._compensate_returned_error( + listed + ) + attempt = await case.failed_attempt() + assert attempt.budget_released_at is not None + assert await case.spent() == CALL_COST + assert await case.balance() == case.start_balance - CALL_COST + assert await case.refund_rows(ledger_entry_id) == 1 + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + + await _assert_capped(case, ledger_entry_id) + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_lost_refund_ack_without_other_spend_resolves_without_release( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With the reservation already back and no other spend, the retry used to + answer refund_reconciliation_budget_conflict and leave the item pending. + It now resolves the item without touching spent_credits.""" + tool_name = "release-once-lost-ack-no-other-spend" + case = await _start(client, monkeypatch, tool_name, other_spend=False) + try: + _lose_refund_ack_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + attempt = await case.failed_attempt() + assert await case.spent() == CALL_COST + await case.sweep(attempt.attempt_id) + assert await case.spent() == Decimal("0") + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == Decimal("0") + assert await case.refund_rows(ledger_entry_id) == 1 + + assert await case.spend_until_refused() == 2 + assert await case.spent() == MAX_CREDITS + assert await case.balance() == case.start_balance - MAX_CREDITS + assert await case.refund_rows(ledger_entry_id) == 1 + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_rolled_back_refund_checkpoint_is_released_by_the_retry_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Control: the refund commits but mark_debit_refunded does not, so the + sweep skips the attempt and the operator retry is what releases it. The + retry marks the attempt released, so a later sweep releases nothing.""" + tool_name = "release-once-checkpoint-rolled-back" + case = await _start(client, monkeypatch, tool_name) + try: + + async def checkpoint_rolled_back( + self: McpDispatchAttemptService, **kwargs: Any + ) -> Any: + raise RuntimeError("refund checkpoint rolled back") + + monkeypatch.setattr( + McpDispatchAttemptService, "mark_debit_refunded", checkpoint_rolled_back + ) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + attempt = await case.failed_attempt() + assert attempt.debit_refunded_at is None + assert await case.spent() == MAX_CREDITS + assert await case.refund_rows(ledger_entry_id) == 1 + + await case.sweep(attempt.attempt_id) + assert await case.spent() == MAX_CREDITS + assert (await case.failed_attempt()).budget_released_at is None + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == CALL_COST + assert (await case.failed_attempt()).budget_released_at is not None + + await case.sweep(attempt.attempt_id) + assert await case.spent() == CALL_COST + await _assert_capped(case, ledger_entry_id) + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_retry_gives_back_a_pre_dispatch_call_slot_once( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A pre-dispatch failure holds a max_calls_per_tool slot it never used. + When the operator retry is the release, it must give back that slot with + the credits, under the same once-only claim, or the slot stays consumed + for good once budget_released_at is set.""" + tool_name = "release-once-pre-dispatch-slot" + case = await _start(client, monkeypatch, tool_name, other_spend=False, max_calls=1) + try: + _lose_refund_ack_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt( + await case.call("pre_dispatch_failure") + ) + attempt = await case.failed_attempt() + assert attempt.call_slot_reserved is True + assert attempt.dispatched_at is None + assert attempt.budget_released_at is None + assert await case.spent() == CALL_COST + assert await case.tool_calls() == 1 + assert case.executor.dispatch_count == 0 + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == Decimal("0") + assert await case.tool_calls() == 0 + assert (await case.failed_attempt()).budget_released_at is not None + + await case.sweep(attempt.attempt_id) + assert await case.spent() == Decimal("0") + assert await case.tool_calls() == 0 + assert await case.refund_rows(ledger_entry_id) == 1 + + # The slot is back: one call to the tool is admitted, the next is not. + assert "error" not in await case.call("success") + assert await case.tool_calls() == 1 + refused = await case.call("success") + assert "permit_max_calls_exceeded" in json.dumps(refused["error"]) + assert await case.spent() == CALL_COST + assert await case.balance() == case.start_balance - CALL_COST + finally: + get_service_registry().unregister_local(tool_name) + + +@pytest.mark.anyio +async def test_retry_keeps_a_dispatched_call_slot_consumed( + client: AsyncClient, + clean_database: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Control: a call that reached the upstream used its slot even though it + failed and was refunded. The retry gives back the credits only.""" + tool_name = "release-once-dispatched-slot" + case = await _start( + client, + monkeypatch, + tool_name, + other_spend=False, + max_credits=Decimal("10"), + max_calls=2, + ) + try: + _lose_refund_ack_once(monkeypatch) + receipt_id, ledger_entry_id = _failed_receipt(await case.call("returned_error")) + attempt = await case.failed_attempt() + assert attempt.call_slot_reserved is True + assert attempt.dispatched_at is not None + assert await case.spent() == CALL_COST + assert await case.tool_calls() == 1 + + resolved = await case.operator_retry(receipt_id) + assert resolved["item"]["status"] == "resolved" + assert await case.spent() == Decimal("0") + assert await case.tool_calls() == 1 + + await case.sweep(attempt.attempt_id) + assert await case.spent() == Decimal("0") + assert await case.tool_calls() == 1 + assert await case.refund_rows(ledger_entry_id) == 1 + + assert "error" not in await case.call("success") + assert await case.tool_calls() == 2 + refused = await case.call("success") + assert "permit_max_calls_exceeded" in json.dumps(refused["error"]) + assert await case.spent() == CALL_COST + finally: + get_service_registry().unregister_local(tool_name)