diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 16c1d24b..920fd84e 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1156,6 +1156,42 @@ async def _assert_replay_iga_access(*, auth: AuthContext, tool_name: str) -> Non ) +# Typed outcomes that hold or finalize the idempotency record deliberately: a +# denial or failure that already wrote its terminal answer, an in-progress or +# conflict answer about a record this call does not own, and the approval and +# terminal-write signals. The wrapper's generic pre-charge abandon skips them. +# A bare ValueError is not listed: library and driver errors subclass it too, +# so it is kept only when the pipeline raised it on purpose +# (``_is_record_keeping_error``). +_RECORD_KEEPING_ERRORS: tuple[type[BaseException], ...] = ( + GovernedToolError, + PermissionError, + HTTPException, + IdempotencyInProgressError, + IdempotencyConflictError, + HumanApprovalPendingSignal, + ToolExecutionError, + TerminalRecordContendedError, +) + + +def _is_record_keeping_error(exc: BaseException) -> bool: + """True for an outcome that keeps or finalizes its own idempotency record. + + A ``ValueError`` counts only when ``_value_error_jsonrpc_code`` recognises + its text, which is the set the pipeline raises on purpose (each of those + finalizes or releases its record before raising, or never owned one). Any + other ``ValueError`` (a ``json.JSONDecodeError`` or a driver error, for + example) is an unexpected fault and takes the generic pre-charge release + like any other. + """ + if isinstance(exc, _RECORD_KEEPING_ERRORS): + return True + return ( + isinstance(exc, ValueError) and _value_error_jsonrpc_code(str(exc)) is not None + ) + + async def _execute_registered_tool( *, tool_name: str, @@ -1235,11 +1271,33 @@ async def _execute_registered_tool( transport_key=idempotency_key, ) raise - except ( - AuditChainContendedError, - ReceiptWriteContendedError, - PermitWriteContendedError, - ): + except Exception as exc: + # The three contention types are provably pre-effect wherever they + # escape. Any other fault is only proven pre-charge while it is still in + # the span before the reserve: nothing there takes a reservation, a + # prepared attempt, a quote or a charge, so the owned record is all that + # is left holding. Past it, the inner branches own their cleanup. + # Deliberate typed outcomes keep their record on purpose and are never + # swept up here. + if not isinstance( + exc, + ( + AuditChainContendedError, + ReceiptWriteContendedError, + PermitWriteContendedError, + ), + ) and ( + owned_record.get("past_precharge_span") or _is_record_keeping_error(exc) + ): + raise + generic_precharge = not isinstance( + exc, + ( + AuditChainContendedError, + ReceiptWriteContendedError, + PermitWriteContendedError, + ), + ) record_id = owned_record.get("record_id") record_key = owned_record.get("key", idempotency_key) if record_id and wallet_id and record_key: @@ -1261,14 +1319,37 @@ async def _execute_registered_tool( idempotency_key=record_key, expected_record_id=record_id, ) - if abandoned and record_endpoint == "/mcp/action/v1": + if abandoned and ( + record_endpoint == "/mcp/action/v1" + or generic_precharge + or not owned_record.get("past_precharge_span") + or isinstance(exc, PermitWriteContendedError) + ): # Only confirmed deletion proves this invocation's use # unaccepted. Inner cleanup may already have released # it; in that case abandon returns False, not a refund. + # A generic pre-charge fault has no inner handler, and + # the use was recorded before the gates that can raise, + # so a max_uses=1 principal would otherwise meet the + # advised retry as iga_max_uses_exceeded. A contention + # type that escapes before the reserve is the same + # case: no inner branch has run to release the use. + # So is a contended reserve: it is the only place the + # permit type escapes the inner function, because both + # post-charge budget releases absorb their own. Past + # the reserve, the other contention types on a + # non-action record stay with the inner branches, which + # release their own use. await _release_iga_use( owned_record.get("iga_granted_use"), tool_name, - reason="preacceptance_write_contended", + reason=( + "precharge_fault" + if generic_precharge + or not owned_record.get("past_precharge_span") + or isinstance(exc, PermitWriteContendedError) + else "preacceptance_write_contended" + ), ) except Exception: logger.exception( @@ -2167,7 +2248,7 @@ async def _execute_registered_tool_inner( iga_decision.policy_id, iga_decision.reservation, ) - if action_identity is not None and owned_record is not None: + if owned_record is not None: owned_record["iga_granted_use"] = iga_granted_use except IGAError as exc: # Catches verification failures for bearers routed to the IGA layer @@ -2506,6 +2587,13 @@ async def _execute_registered_tool_inner( ) dispatch_attempt = None + # Past this line a reservation, a prepared attempt, a consumed quote or a + # charge may exist, so the wrapper may no longer abandon the record for an + # arbitrary fault: it could not also hand those back without risking a + # second release. Every fault before it provably held none of them. + if owned_record is not None: + owned_record["past_precharge_span"] = True + # Linearize authorization as late as possible. For a remote call, reserve # permit budget and create the recoverable prepared checkpoint in the same # transaction; a durable reservation can therefore never exist without an @@ -2886,6 +2974,19 @@ async def _repair_pre_dispatch(exc: BaseException) -> Any: await _release_iga_use( iga_granted_use, tool_name, reason="ledger_write_contended" ) + # The quote was consumed just above the debit and the debit rolled back + # whole, so the price lock was never spent. Hand it back on the same + # proof as the use above, or the retry this answer advises meets + # quote_already_consumed. The generic branch below does not do this: an + # unclassified fault there cannot prove the debit did not commit. + if quoted is not None and quote_id: + try: + await get_quote_service().release(quote_id) + except Exception: + logger.exception( + "mcp_contended_quote_release_failed", + extra={"quote_id": quote_id}, + ) try: await _audit_mcp_invocation( effects_committed=False, @@ -4103,10 +4204,13 @@ def _registered_tool_cost( ) -> Decimal: # Shared with the quote endpoint so a locked quote and the charge that # honors it are computed from one definition of price. A price that is - # not finite and non-negative raises ValueError("tool_price_invalid") - # here, before idempotency, policy, permit or ledger state is touched; it - # is deliberately not a classified ValueError, so the caller gets the - # opaque internal_error and the operator gets the logged traceback. + # not finite and non-negative raises ValueError("tool_price_invalid"). + # At the quote endpoint that happens before any idempotency state exists. + # On a permitted invoke it happens after the idempotency record is granted + # and before the permit reserve, so the wrapper's pre-charge release frees + # the key. It is deliberately not a classified ValueError, so the caller + # gets the opaque internal_error and the operator gets the logged + # traceback. return tool_price(service, category) diff --git a/gateway/tests/test_iga_policy.py b/gateway/tests/test_iga_policy.py index be75de6f..d818bd2b 100644 --- a/gateway/tests/test_iga_policy.py +++ b/gateway/tests/test_iga_policy.py @@ -1254,6 +1254,94 @@ async def _always_contended(self, **_kwargs): registry.unregister_local(E2E_TOOL) +@pytest.mark.parametrize( + "fault", + ["generic", "value_error", "json_decode", "audit_contended", "reserve_contended"], +) +async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( + iga_config, clean_database, rsa_key, client, monkeypatch, fault +): + """A fault after the use is recorded and before the reserve hands it back. + + The enterprise use is consumed ahead of the wallet policy check, so a + one-shot fault there must give it back along with the abandoned key, or a + ``max_uses=1`` principal is refused the retry the key now permits. + """ + import json + + from app.routers import mcp as mcp_router + from app.services.audit_chain import AuditChainContendedError + from app.services.permits import PermitService, PermitWriteContendedError + + calls: list[dict] = [] + registry = _register_e2e_tool(calls) + try: + setup = await _provision_for_e2e(client, idem_key=f"iga-e2e-precharge-{fault}") + bundle_wallet = await _make_wallet() + policy_id = await _make_bundle(bundle_wallet, allowed_tools=[E2E_TOOL]) + iga_config( + _okta_issuers(rsa_key), + {"payments-ops": {"policy_id": policy_id, "max_uses": 1}}, + ) + token = _mint(rsa_key, extra={"groups": ["payments-ops"]}) + headers = {**setup["agent_headers"], "Authorization": f"Bearer {token}"} + + real = mcp_router.evaluate_wallet_policy + state = {"calls": 0} + + async def one_shot(*args, **kwargs): + state["calls"] += 1 + if state["calls"] == 1: + if fault == "audit_contended": + raise AuditChainContendedError("head contended") + if fault == "value_error": + raise ValueError("stored value could not be read") + if fault == "json_decode": + raise json.JSONDecodeError("Expecting value", "", 0) + raise RuntimeError("policy backend down") + return await real(*args, **kwargs) + + if fault == "reserve_contended": + real_reserve = PermitService.authorize_and_reserve + + async def one_shot_reserve(self, *args, **kwargs): + state["calls"] += 1 + if state["calls"] == 1: + raise PermitWriteContendedError() + return await real_reserve(self, *args, **kwargs) + + monkeypatch.setattr( + PermitService, "authorize_and_reserve", one_shot_reserve + ) + else: + monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", one_shot) + first = await _invoke_tool_call( + client, + wallet_id=setup["agent_wallet_id"], + permit_id=setup["permit_id"], + idem_key=f"iga-e2e-precharge-{fault}-1", + headers=headers, + ) + assert "error" in first, first + assert state["calls"] == 1 + assert calls == [] + assert oidc_iga._lifetime_uses == {} + assert oidc_iga._window_calls == {} + + retry = await _invoke_tool_call( + client, + wallet_id=setup["agent_wallet_id"], + permit_id=setup["permit_id"], + idem_key=f"iga-e2e-precharge-{fault}-1", + headers=headers, + ) + assert "result" in retry, retry + assert calls == [{"message": "hello"}] + assert sum(oidc_iga._lifetime_uses.values()) == 1 + finally: + registry.unregister_local(E2E_TOOL) + + async def test_a_contended_remote_charge_keeps_the_use_it_cannot_prove_unspent( iga_config, clean_database, rsa_key, client, monkeypatch ): diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index c3f5c16f..f5f397aa 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -40,12 +40,18 @@ from app.db.models import McpDispatchAttemptModel from app.main import app from app.schemas.billing import ServiceCategory +from app.services.agent_money import AgentMoney from app.services.billing_engine import BillingEngine -from app.services.idempotency import get_idempotency_service +from app.services.idempotency import ( + GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, + IdempotencyService, + get_idempotency_service, +) from app.services.mcp_dispatch_reconciliation import ( get_mcp_dispatch_reconciliation_service, ) from app.services.permits import get_permit_service +from app.services.quotes import QuoteService from app.services.service_registry import get_service_registry from tests.test_mcp_upstream_governed import FakeUpstreamExecutor from tests.test_trust_helpers import ( @@ -688,3 +694,476 @@ async def test_a_capped_permit_can_still_spend_its_call_after_contention( body = retry.json() assert "error" not in body, body assert runs["count"] == 1 + + +# --------------------------------------------------------------------------- +# Pre-charge faults must release the quote, the reservation and the record. +# +# These faults are injected at the exact call that raises (the debit, the wallet +# policy, the daily-spend read), one shot each, so the retry runs against the +# state the first call left behind. Reservation counters are read from storage: +# a status code alone cannot tell a release from a double release. +# --------------------------------------------------------------------------- + + +def _one_shot(error: BaseException, real: Any) -> tuple[Any, dict[str, int]]: + """Wrap ``real`` so its first call raises ``error`` and later calls pass.""" + state = {"calls": 0} + + async def wrapper(*args: Any, **kwargs: Any) -> Any: + state["calls"] += 1 + if state["calls"] == 1: + raise error + return await real(*args, **kwargs) + + return wrapper, state + + +def _fail_once_on( + monkeypatch: Any, cls: type, name: str, error: BaseException +) -> dict[str, int]: + """Make the first call to ``cls.name`` raise ``error``, then pass through. + + Patched on the class, never on a singleton instance. ``monkeypatch`` puts an + instance attribute back by assigning the saved bound method, which on some + pytest releases leaves a shadow behind; a later test that patches the class + would then be bypassed on that instance. A class attribute restores exactly. + """ + real = cls.__dict__[name] + state = {"calls": 0} + + async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: + state["calls"] += 1 + if state["calls"] == 1: + raise error + return await real(self, *args, **kwargs) + + monkeypatch.setattr(cls, name, wrapper) + return state + + +async def _capped_governed_call( + client: AsyncClient, tool_name: str, *, with_quote: bool, idem_key: str +) -> tuple[dict[str, Any], dict[str, Any], str, str | None]: + from tests.test_permit_reservation_unwind import _create_capped_permit + + ctx = await provision_agent_wallet(client) + permit_id = await _create_capped_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=tool_name, + max_calls=1, + idem_key=f"{idem_key}-permit", + ) + body = _call_body( + tool_name=tool_name, + wallet_id=ctx["agent_wallet_id"], + permit_id=permit_id, + idempotency_key=idem_key, + ) + quote_id: str | None = None + if with_quote: + from app.services.quotes import get_quote_service + + quote = await get_quote_service().create_quote( + wallet_id=ctx["agent_wallet_id"], + tool=tool_name, + quoted_credits=Decimal(str(TOOL_COST)), + category=ServiceCategory.AGENT_COMMS.value, + ) + quote_id = quote.quote_id + body["params"]["mcpContext"]["quote_id"] = quote_id + return ctx, body, permit_id, quote_id + + +async def _quote_status(quote_id: str) -> str: + from app.services.quotes import get_quote_service + + quote = await get_quote_service().get_quote(quote_id) + assert quote is not None + return str(quote.status) + + +async def _record(ctx: dict[str, Any], key: str) -> Any: + return await get_idempotency_service().get_record( + wallet_id=ctx["agent_wallet_id"], + endpoint=GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, + idempotency_key=key, + ) + + +@pytest.mark.anyio +async def test_quote_is_released_when_the_debit_is_contended_once( + client: AsyncClient, clean_database: None, governed_tool, monkeypatch +) -> None: + """The retry the contention answer advises must keep its locked price.""" + from app.services.billing_engine import LedgerWriteContendedError + from tests.test_permit_reservation_unwind import _calls_made + + tool_name, runs = governed_tool + ctx, body, permit_id, quote_id = await _capped_governed_call( + client, tool_name, with_quote=True, idem_key="prefault-quote-1" + ) + assert quote_id is not None + state = _fail_once_on( + monkeypatch, AgentMoney, "charge", LedgerWriteContendedError() + ) + + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "ledger_write_contended", first.text + assert state["calls"] == 1 + # Nothing moved, and everything the call held is back: the quote, the + # credits, the per-tool use and the key. + assert await _quote_status(quote_id) == "active" + assert await _spent_credits(permit_id) == Decimal("0") + assert await _calls_made(permit_id, tool_name) == 0 + assert await _record(ctx, "prefault-quote-1") is None + assert runs["count"] == 0 + + second = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert second.status_code == 200, second.text + assert "error" not in second.json(), second.text + assert second.json()["result"]["receipt"]["outcome"] == "success" + assert await _quote_status(quote_id) == "consumed" + assert ( + await _debit_count( + client, ctx["agent_wallet_id"], ctx["agent_headers"], tool_name + ) + == 1 + ) + assert await _spent_credits(permit_id) == Decimal(str(TOOL_COST)) + assert await _calls_made(permit_id, tool_name) == 1 + assert runs["count"] == 1 + + +@pytest.mark.anyio +async def test_the_reservation_goes_back_exactly_once_on_a_contended_debit( + client: AsyncClient, clean_database: None, governed_tool, monkeypatch +) -> None: + """Adding the quote release must not add a second reservation release.""" + from app.routers import mcp as mcp_router + from app.services.billing_engine import LedgerWriteContendedError + + tool_name, _ = governed_tool + ctx, body, _permit_id, _quote_id = await _capped_governed_call( + client, tool_name, with_quote=True, idem_key="prefault-once-1" + ) + _fail_once_on(monkeypatch, AgentMoney, "charge", LedgerWriteContendedError()) + real_release = mcp_router._release_local_permit_reservation + releases: list[str] = [] + + async def counted(*args: Any, **kwargs: Any) -> None: + releases.append(str(kwargs.get("reason"))) + await real_release(*args, **kwargs) + + monkeypatch.setattr(mcp_router, "_release_local_permit_reservation", counted) + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "ledger_write_contended", first.text + assert releases == ["ledger_write_contended"] + + +@pytest.mark.anyio +@pytest.mark.parametrize("failing", ["evaluate_wallet_policy", "get_daily_spend"]) +async def test_the_key_is_freed_when_the_wallet_policy_raises_once( + client: AsyncClient, + clean_database: None, + governed_tool, + monkeypatch, + failing: str, +) -> None: + """A generic fault after the record begins and before any charge.""" + from app.routers import mcp as mcp_router + from tests.test_permit_reservation_unwind import _calls_made + + tool_name, runs = governed_tool + key = f"prefault-policy-{failing}" + ctx, body, permit_id, _ = await _capped_governed_call( + client, tool_name, with_quote=False, idem_key=key + ) + if failing == "evaluate_wallet_policy": + wrapper, state = _one_shot( + RuntimeError("policy backend down"), mcp_router.evaluate_wallet_policy + ) + monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", wrapper) + else: + state = _fail_once_on( + monkeypatch, + AgentMoney, + "get_daily_spend", + RuntimeError("spend read failed"), + ) + + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "internal_error", first.text + assert state["calls"] == 1 + assert await _record(ctx, key) is None + # The reserve comes after the policy check, so nothing was ever held. + assert await _spent_credits(permit_id) == Decimal("0") + assert await _calls_made(permit_id, tool_name) == 0 + + second = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert second.status_code == 200, second.text + assert "error" not in second.json(), second.text + assert second.json()["result"]["receipt"]["outcome"] == "success" + assert await _spent_credits(permit_id) == Decimal(str(TOOL_COST)) + assert await _calls_made(permit_id, tool_name) == 1 + assert runs["count"] == 1 + + +@pytest.mark.anyio +async def test_a_fault_after_the_charge_keeps_the_record_and_the_quote( + client: AsyncClient, clean_database: None, governed_tool, monkeypatch +) -> None: + """Negative: once the debit committed, nothing may be handed back.""" + tool_name, runs = governed_tool + key = "postcharge-keep-1" + ctx, body, permit_id, quote_id = await _capped_governed_call( + client, tool_name, with_quote=True, idem_key=key + ) + assert quote_id is not None + state = _fail_once_on( + monkeypatch, IdempotencyService, "mark_charged", RuntimeError("checkpoint lost") + ) + + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "internal_error", first.text + assert state["calls"] == 1 + monkeypatch.undo() + + assert ( + await _debit_count( + client, ctx["agent_wallet_id"], ctx["agent_headers"], tool_name + ) + == 1 + ) + assert await _quote_status(quote_id) == "consumed" + assert await _record(ctx, key) is not None + assert await _spent_credits(permit_id) == Decimal(str(TOOL_COST)) + assert runs["count"] == 0 + + +@pytest.mark.anyio +async def test_abandon_never_deletes_a_record_with_a_response_or_a_ledger_entry( + client: AsyncClient, clean_database: None, governed_tool, monkeypatch +) -> None: + """Negative: the backstop every pre-charge release relies on. + + Both records come from the real governed path. The answered one is an + insufficient-funds denial: a stored response and no debit. The charged one + is a call whose debit committed and whose response then failed to persist: + a ledger entry and no response. Each is refused on its own evidence. + """ + from tests.test_permit_reservation_unwind import _set_balance + + tool_name, runs = governed_tool + idem = get_idempotency_service() + ctx = await provision_agent_wallet(client) + wallet = ctx["agent_wallet_id"] + permit = await create_tool_permit( + client, + wallet_id=wallet, + key_id=ctx["key_id"], + tool_name=tool_name, + max_credits=50, + idem_key="guard-permit", + ) + + await _set_balance(wallet, "1") + denied = await client.post( + "/mcp/messages", + json=_call_body( + tool_name=tool_name, + wallet_id=wallet, + permit_id=permit["permit_id"], + idempotency_key="guard-answered", + ), + headers=ctx["agent_headers"], + ) + assert denied.json()["error"]["message"] == "insufficient_funds", denied.text + await _set_balance(wallet, "1000") + + async def response_lost(self: Any, **_kwargs: Any) -> None: + raise RuntimeError("checkpoint lost") + + monkeypatch.setattr(IdempotencyService, "complete", response_lost) + charged_call = await client.post( + "/mcp/messages", + json=_call_body( + tool_name=tool_name, + wallet_id=wallet, + permit_id=permit["permit_id"], + idempotency_key="guard-charged", + ), + headers=ctx["agent_headers"], + ) + monkeypatch.undo() + assert charged_call.json()["error"]["message"] == "internal_error" + assert runs["count"] == 1 + + answered = await _record(ctx, "guard-answered") + charged = await _record(ctx, "guard-charged") + assert answered is not None and charged is not None + # Each record carries exactly one of the two pieces of evidence. + assert answered.response_json is not None + assert not answered.ledger_entry_id + assert charged.response_json is None + assert charged.ledger_entry_id + for key, record in (("guard-answered", answered), ("guard-charged", charged)): + assert ( + await idem.abandon( + wallet_id=wallet, + endpoint=GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, + idempotency_key=key, + expected_record_id=record.record_id, + ) + is False + ) + assert await _record(ctx, key) is not None + + +@pytest.mark.anyio +async def test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reservation( + client: AsyncClient, clean_database: None, governed_tool, monkeypatch +) -> None: + """Negative: the generic abandon stops at the reserve. + + Past the reserve the call holds a permit reservation that this wrapper cannot + hand back without risking a second release, so freeing the key there would + let the retry reserve a second time on top of the first. The record stays, + as it did before. + """ + from tests.test_permit_reservation_unwind import _calls_made + + tool_name, runs = governed_tool + key = "afterreserve-keep-1" + ctx, body, permit_id, quote_id = await _capped_governed_call( + client, tool_name, with_quote=True, idem_key=key + ) + state = _fail_once_on( + monkeypatch, QuoteService, "consume", RuntimeError("quote store down") + ) + + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "internal_error", first.text + assert state["calls"] == 1 + monkeypatch.undo() + + assert await _record(ctx, key) is not None + assert await _spent_credits(permit_id) == Decimal(str(TOOL_COST)) + assert await _calls_made(permit_id, tool_name) == 1 + assert runs["count"] == 0 + + +def _unexpected_value_error(kind: str) -> ValueError: + """The unexpected ValueError shapes a library or driver can raise.""" + if kind == "json_decode": + import json + + return json.JSONDecodeError("Expecting value", "", 0) + return ValueError("stored value could not be read") + + +@pytest.mark.anyio +@pytest.mark.parametrize("failing", ["evaluate_wallet_policy", "get_daily_spend"]) +@pytest.mark.parametrize("kind", ["value_error", "json_decode"]) +async def test_an_unexpected_value_error_before_the_reserve_frees_the_key( + client: AsyncClient, + clean_database: None, + governed_tool, + monkeypatch, + failing: str, + kind: str, +) -> None: + """ValueError subclasses are not all deliberate outcomes. + + A ``json.JSONDecodeError`` or a driver error is a ValueError too. Raised + after the record is granted and before the reserve, it must free the key + like any other pre-charge fault, with the quote untouched and nothing + debited, or the retry meets ``idempotency_in_progress`` forever. + """ + from app.routers import mcp as mcp_router + from tests.test_permit_reservation_unwind import _calls_made + + tool_name, runs = governed_tool + key = f"prefault-valueerror-{kind}-{failing}" + ctx, body, permit_id, quote_id = await _capped_governed_call( + client, tool_name, with_quote=True, idem_key=key + ) + assert quote_id is not None + error = _unexpected_value_error(kind) + if failing == "evaluate_wallet_policy": + wrapper, state = _one_shot(error, mcp_router.evaluate_wallet_policy) + monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", wrapper) + else: + state = _fail_once_on(monkeypatch, AgentMoney, "get_daily_spend", error) + + first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert first.json()["error"]["message"] == "internal_error", first.text + assert state["calls"] == 1 + assert await _record(ctx, key) is None + assert await _quote_status(quote_id) == "active" + assert ( + await _debit_count( + client, ctx["agent_wallet_id"], ctx["agent_headers"], tool_name + ) + == 0 + ) + assert await _spent_credits(permit_id) == Decimal("0") + assert await _calls_made(permit_id, tool_name) == 0 + assert runs["count"] == 0 + + second = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert second.status_code == 200, second.text + assert "error" not in second.json(), second.text + assert await _quote_status(quote_id) == "consumed" + assert ( + await _debit_count( + client, ctx["agent_wallet_id"], ctx["agent_headers"], tool_name + ) + == 1 + ) + assert runs["count"] == 1 + + +@pytest.mark.anyio +async def test_a_deliberate_value_error_keeps_its_own_cleanup( + client: AsyncClient, clean_database: None, monkeypatch +) -> None: + """A classified ValueError still takes the path it always took. + + "Tool not found" on a permitted call releases its own record before it + raises; the wrapper must neither change that answer nor touch the record + again. + """ + from tests.test_permit_reservation_unwind import _create_capped_permit + + absent_tool = "contention-absent-tool" + ctx = await provision_agent_wallet(client) + permit_id = await _create_capped_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=absent_tool, + max_calls=1, + idem_key="prefault-absent-permit", + ) + body = _call_body( + tool_name=absent_tool, + wallet_id=ctx["agent_wallet_id"], + permit_id=permit_id, + idempotency_key="prefault-absent-1", + ) + abandons: list[str] = [] + real_abandon = IdempotencyService.abandon + + async def counted_abandon(self: Any, **kwargs: Any) -> bool: + abandons.append(str(kwargs.get("idempotency_key"))) + return await real_abandon(self, **kwargs) + + monkeypatch.setattr(IdempotencyService, "abandon", counted_abandon) + resp = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) + assert resp.json()["error"]["code"] == -32001, resp.text + # Released once by the branch that raised, never again by the wrapper. + assert abandons == ["prefault-absent-1"] + assert await _record(ctx, "prefault-absent-1") is None