From 1c31207f48134b2c917f9f57c79bea65e170cdec Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 04:02:07 +0000 Subject: [PATCH 1/9] Release the quote and the idempotency record on pre-charge faults A contended debit left the consumed quote spent, so the advised retry met quote_already_consumed. A generic fault between the idempotency begin and the reserve left the key in progress. Release the quote on the contended-debit proof, and abandon the owned record for any fault in the pre-reserve span. Closes #278 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 62 +++- gateway/tests/test_ledger_write_contention.py | 318 +++++++++++++++++- 2 files changed, 374 insertions(+), 6 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index aa36cf180..4cde3af59 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1145,6 +1145,23 @@ 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. +_RECORD_KEEPING_ERRORS: tuple[type[BaseException], ...] = ( + GovernedToolError, + PermissionError, + ValueError, + HTTPException, + IdempotencyInProgressError, + IdempotencyConflictError, + HumanApprovalPendingSignal, + ToolExecutionError, + TerminalRecordContendedError, +) + + async def _execute_registered_tool( *, tool_name: str, @@ -1224,11 +1241,26 @@ 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 isinstance(exc, _RECORD_KEEPING_ERRORS) + ): + raise record_id = owned_record.get("record_id") record_key = owned_record.get("key", idempotency_key) if record_id and wallet_id and record_key: @@ -2494,6 +2526,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 exactly once. 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 @@ -2874,6 +2913,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, diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index c3f5c16f9..a1bfdc532 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -41,7 +41,10 @@ from app.main import app from app.schemas.billing import ServiceCategory from app.services.billing_engine import BillingEngine -from app.services.idempotency import get_idempotency_service +from app.services.idempotency import ( + GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, + get_idempotency_service, +) from app.services.mcp_dispatch_reconciliation import ( get_mcp_dispatch_reconciliation_service, ) @@ -688,3 +691,316 @@ 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 + + +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.agent_money import get_agent_money + 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 + money = get_agent_money() + wrapper, state = _one_shot(LedgerWriteContendedError(), money.charge) + monkeypatch.setattr(money, "charge", wrapper) + + 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.agent_money import get_agent_money + 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" + ) + money = get_agent_money() + wrapper, _ = _one_shot(LedgerWriteContendedError(), money.charge) + monkeypatch.setattr(money, "charge", wrapper) + 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 app.services.agent_money import get_agent_money + 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: + money = get_agent_money() + wrapper, state = _one_shot( + RuntimeError("spend read failed"), money.get_daily_spend + ) + monkeypatch.setattr(money, "get_daily_spend", wrapper) + + 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 + idem = get_idempotency_service() + wrapper, state = _one_shot(RuntimeError("checkpoint lost"), idem.mark_charged) + monkeypatch.setattr(idem, "mark_charged", wrapper) + + 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 +) -> None: + """Negative: the backstop every pre-charge release relies on.""" + idem = get_idempotency_service() + wallet = (await provision_agent_wallet(client))["agent_wallet_id"] + endpoint = "/mcp/messages" + + charged = await idem.begin_with_record( + wallet_id=wallet, + endpoint=endpoint, + idempotency_key="guard-charged", + request_payload={"n": 1}, + ) + await idem.mark_charged( + wallet_id=wallet, + endpoint=endpoint, + idempotency_key="guard-charged", + ledger_entry_id="led-1", + ) + answered = await idem.begin_with_record( + wallet_id=wallet, + endpoint=endpoint, + idempotency_key="guard-answered", + request_payload={"n": 2}, + ) + await idem.complete( + wallet_id=wallet, + endpoint=endpoint, + idempotency_key="guard-answered", + response_reference=None, + response_json={"ok": True}, + ) + for key, begun in (("guard-charged", charged), ("guard-answered", answered)): + assert ( + await idem.abandon( + wallet_id=wallet, + endpoint=endpoint, + idempotency_key=key, + expected_record_id=begun.record_id, + ) + is False + ) + assert ( + await idem.get_record( + wallet_id=wallet, endpoint=endpoint, idempotency_key=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 exactly once, 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 app.services.quotes import get_quote_service + 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 + ) + quotes = get_quote_service() + wrapper, state = _one_shot(RuntimeError("quote store down"), quotes.consume) + monkeypatch.setattr(quotes, "consume", wrapper) + + 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 From 7efe93cc903703f57fa5f3d6fc207dada11b5421 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 04:10:04 +0000 Subject: [PATCH 2/9] Return the enterprise use when the generic pre-charge abandon frees the key The use is consumed before the gates that can raise, but only action records exposed it to the wrapper. Record it for every governed call and release it after a confirmed abandon on the generic path. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 26 ++++++++++++-- gateway/tests/test_iga_policy.py | 61 ++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 4cde3af59..5e9cc7773 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1261,6 +1261,14 @@ async def _execute_registered_tool( or isinstance(exc, _RECORD_KEEPING_ERRORS) ): 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: @@ -1282,14 +1290,26 @@ 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 + ): # 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. The 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 + else "preacceptance_write_contended" + ), ) except Exception: logger.exception( @@ -2188,7 +2208,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 diff --git a/gateway/tests/test_iga_policy.py b/gateway/tests/test_iga_policy.py index be75de6f1..6ee798664 100644 --- a/gateway/tests/test_iga_policy.py +++ b/gateway/tests/test_iga_policy.py @@ -1254,6 +1254,67 @@ async def _always_contended(self, **_kwargs): registry.unregister_local(E2E_TOOL) +async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( + iga_config, clean_database, rsa_key, client, monkeypatch +): + """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. + """ + from app.routers import mcp as mcp_router + + calls: list[dict] = [] + registry = _register_e2e_tool(calls) + try: + setup = await _provision_for_e2e(client, idem_key="iga-e2e-precharge-permit") + 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: + raise RuntimeError("policy backend down") + return await real(*args, **kwargs) + + 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="iga-e2e-precharge-1", + headers=headers, + ) + assert first["error"]["message"] == "internal_error", 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="iga-e2e-precharge-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 ): From d22d7a07914740d8481ebd245f1ef8f09f0c41d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 04:21:49 +0000 Subject: [PATCH 3/9] Return the enterprise use for contention that escapes before the reserve A contention type raised ahead of the reserve frees a non-action key but no inner branch has run to release the use. Release it after the confirmed abandon. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 14 ++++++++++---- gateway/tests/test_iga_policy.py | 14 +++++++++----- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 5e9cc7773..ae23dc4a1 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1291,7 +1291,9 @@ async def _execute_registered_tool( expected_record_id=record_id, ) if abandoned and ( - record_endpoint == "/mcp/action/v1" or generic_precharge + record_endpoint == "/mcp/action/v1" + or generic_precharge + or not owned_record.get("past_precharge_span") ): # Only confirmed deletion proves this invocation's use # unaccepted. Inner cleanup may already have released @@ -1299,15 +1301,19 @@ async def _execute_registered_tool( # 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. The contention - # types on a non-action record stay with the inner - # branches, which release their own use. + # 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. + # Past the reserve, contention on a non-action record + # stays with the inner branches, which release their + # own use. await _release_iga_use( owned_record.get("iga_granted_use"), tool_name, reason=( "precharge_fault" if generic_precharge + or not owned_record.get("past_precharge_span") else "preacceptance_write_contended" ), ) diff --git a/gateway/tests/test_iga_policy.py b/gateway/tests/test_iga_policy.py index 6ee798664..66475ee11 100644 --- a/gateway/tests/test_iga_policy.py +++ b/gateway/tests/test_iga_policy.py @@ -1254,8 +1254,9 @@ async def _always_contended(self, **_kwargs): registry.unregister_local(E2E_TOOL) +@pytest.mark.parametrize("fault", ["generic", "audit_contended"]) async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( - iga_config, clean_database, rsa_key, client, monkeypatch + iga_config, clean_database, rsa_key, client, monkeypatch, fault ): """A fault after the use is recorded and before the reserve hands it back. @@ -1264,11 +1265,12 @@ async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( ``max_uses=1`` principal is refused the retry the key now permits. """ from app.routers import mcp as mcp_router + from app.services.audit_chain import AuditChainContendedError calls: list[dict] = [] registry = _register_e2e_tool(calls) try: - setup = await _provision_for_e2e(client, idem_key="iga-e2e-precharge-permit") + 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( @@ -1284,6 +1286,8 @@ async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( async def one_shot(*args, **kwargs): state["calls"] += 1 if state["calls"] == 1: + if fault == "audit_contended": + raise AuditChainContendedError("head contended") raise RuntimeError("policy backend down") return await real(*args, **kwargs) @@ -1292,10 +1296,10 @@ async def one_shot(*args, **kwargs): client, wallet_id=setup["agent_wallet_id"], permit_id=setup["permit_id"], - idem_key="iga-e2e-precharge-1", + idem_key=f"iga-e2e-precharge-{fault}-1", headers=headers, ) - assert first["error"]["message"] == "internal_error", first + assert "error" in first, first assert state["calls"] == 1 assert calls == [] assert oidc_iga._lifetime_uses == {} @@ -1305,7 +1309,7 @@ async def one_shot(*args, **kwargs): client, wallet_id=setup["agent_wallet_id"], permit_id=setup["permit_id"], - idem_key="iga-e2e-precharge-1", + idem_key=f"iga-e2e-precharge-{fault}-1", headers=headers, ) assert "result" in retry, retry From b8526529676f7dd853d4851683b7e7c86ab2c2b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 1 Nov 2026 04:32:37 +0000 Subject: [PATCH 4/9] Return the enterprise use when the reserve itself is contended The reserve is the only place a permit contention escapes the governed function without an inner release, and release_tool_use is idempotent per reservation, so releasing after the confirmed abandon cannot over-refund. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 11 ++++++++--- gateway/tests/test_iga_policy.py | 18 ++++++++++++++++-- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index ae23dc4a1..d1072f203 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1294,6 +1294,7 @@ async def _execute_registered_tool( 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 @@ -1304,9 +1305,12 @@ async def _execute_registered_tool( # 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. - # Past the reserve, contention on a non-action record - # stays with the inner branches, which release their - # own 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, @@ -1314,6 +1318,7 @@ async def _execute_registered_tool( "precharge_fault" if generic_precharge or not owned_record.get("past_precharge_span") + or isinstance(exc, PermitWriteContendedError) else "preacceptance_write_contended" ), ) diff --git a/gateway/tests/test_iga_policy.py b/gateway/tests/test_iga_policy.py index 66475ee11..eedb4b260 100644 --- a/gateway/tests/test_iga_policy.py +++ b/gateway/tests/test_iga_policy.py @@ -1254,7 +1254,7 @@ async def _always_contended(self, **_kwargs): registry.unregister_local(E2E_TOOL) -@pytest.mark.parametrize("fault", ["generic", "audit_contended"]) +@pytest.mark.parametrize("fault", ["generic", "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 ): @@ -1266,6 +1266,7 @@ async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( """ 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) @@ -1291,7 +1292,20 @@ async def one_shot(*args, **kwargs): raise RuntimeError("policy backend down") return await real(*args, **kwargs) - monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", one_shot) + 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"], From 7b5519044606f02e8f8db5e57ae8d5d9e124c8d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 07:43:08 +0000 Subject: [PATCH 5/9] Release the record for an unexpected ValueError and use a real ledger entry in the guard test An unexpected ValueError (a JSONDecodeError or a driver error) raised after the record is granted and before the reserve kept the record, so the retry met idempotency_in_progress. A ValueError now keeps its record only when the pipeline raised it on purpose, as _value_error_jsonrpc_code classifies it. The abandon guard test now debits the provisioned wallet and checkpoints the returned entry id instead of an invented one. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 24 +++- gateway/tests/test_iga_policy.py | 11 +- gateway/tests/test_ledger_write_contention.py | 134 +++++++++++++++++- 3 files changed, 164 insertions(+), 5 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index daf8186c2..844c0302b 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -1140,10 +1140,12 @@ async def _assert_replay_iga_access(*, auth: AuthContext, tool_name: str) -> Non # 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, - ValueError, HTTPException, IdempotencyInProgressError, IdempotencyConflictError, @@ -1153,6 +1155,23 @@ async def _assert_replay_iga_access(*, auth: AuthContext, tool_name: str) -> Non ) +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, @@ -1248,8 +1267,7 @@ async def _execute_registered_tool( PermitWriteContendedError, ), ) and ( - owned_record.get("past_precharge_span") - or isinstance(exc, _RECORD_KEEPING_ERRORS) + owned_record.get("past_precharge_span") or _is_record_keeping_error(exc) ): raise generic_precharge = not isinstance( diff --git a/gateway/tests/test_iga_policy.py b/gateway/tests/test_iga_policy.py index eedb4b260..d818bd2bb 100644 --- a/gateway/tests/test_iga_policy.py +++ b/gateway/tests/test_iga_policy.py @@ -1254,7 +1254,10 @@ async def _always_contended(self, **_kwargs): registry.unregister_local(E2E_TOOL) -@pytest.mark.parametrize("fault", ["generic", "audit_contended", "reserve_contended"]) +@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 ): @@ -1264,6 +1267,8 @@ async def test_generic_precharge_fault_releases_iga_use_and_frees_the_key( 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 @@ -1289,6 +1294,10 @@ async def one_shot(*args, **kwargs): 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) diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index a1bfdc532..28c28baea 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -930,17 +930,31 @@ async def test_abandon_never_deletes_a_record_with_a_response_or_a_ledger_entry( wallet = (await provision_agent_wallet(client))["agent_wallet_id"] endpoint = "/mcp/messages" + from app.services.agent_money import get_agent_money + charged = await idem.begin_with_record( wallet_id=wallet, endpoint=endpoint, idempotency_key="guard-charged", request_payload={"n": 1}, ) + # A real debit on the provisioned wallet, keyed by the record like the + # governed path keys it, so the checkpoint names an entry that exists. + entry = await get_agent_money().charge( + wallet_id=wallet, + service_category=ServiceCategory.AGENT_COMMS, + units=Decimal(str(TOOL_COST)), + request_path=endpoint, + description="abandon guard debit", + operation_key=charged.record_id, + caller=CallerIdentity.for_wallet(wallet), + ) + assert getattr(entry, "entry_id", None), entry await idem.mark_charged( wallet_id=wallet, endpoint=endpoint, idempotency_key="guard-charged", - ledger_entry_id="led-1", + ledger_entry_id=entry.entry_id, ) answered = await idem.begin_with_record( wallet_id=wallet, @@ -1004,3 +1018,121 @@ async def test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reser 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 app.services.agent_money import get_agent_money + 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: + money = get_agent_money() + wrapper, state = _one_shot(error, money.get_daily_spend) + monkeypatch.setattr(money, "get_daily_spend", wrapper) + + 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] = [] + idem = get_idempotency_service() + real_abandon = idem.abandon + + async def counted_abandon(**kwargs: Any) -> bool: + abandons.append(str(kwargs.get("idempotency_key"))) + return await real_abandon(**kwargs) + + monkeypatch.setattr(idem, "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 From 1f9a61d7476a87c7cb26fa62b9498e1a2ba52e76 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 07:46:32 +0000 Subject: [PATCH 6/9] Correct the tool_price_invalid comment for the permitted invoke path Comment only. On a permitted call the price is computed after the idempotency record is granted and before the reserve, so the wrapper frees the key. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 844c0302b..b22651ba8 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -4180,10 +4180,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) From 6d3bcc6bb6e1fef7bec99fd987f35ca078f74708 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 08:21:20 +0000 Subject: [PATCH 7/9] Build the abandon guard test records from real governed calls The guard test used an invented request payload, an invented response body and a made-up debit description. Its two records now come from the real path: an insufficient-funds denial (a stored response, no debit) and a call whose debit committed and whose response then failed to persist (a ledger entry, no response). Each record is read back and refused on its own evidence. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/tests/test_ledger_write_contention.py | 109 ++++++++++-------- 1 file changed, 61 insertions(+), 48 deletions(-) diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index 28c28baea..121a016ad 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -923,68 +923,81 @@ async def test_a_fault_after_the_charge_keeps_the_record_and_the_quote( @pytest.mark.anyio async def test_abandon_never_deletes_a_record_with_a_response_or_a_ledger_entry( - client: AsyncClient, clean_database: None + client: AsyncClient, clean_database: None, governed_tool, monkeypatch ) -> None: - """Negative: the backstop every pre-charge release relies on.""" - idem = get_idempotency_service() - wallet = (await provision_agent_wallet(client))["agent_wallet_id"] - endpoint = "/mcp/messages" + """Negative: the backstop every pre-charge release relies on. - from app.services.agent_money import get_agent_money + 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 - charged = await idem.begin_with_record( - wallet_id=wallet, - endpoint=endpoint, - idempotency_key="guard-charged", - request_payload={"n": 1}, - ) - # A real debit on the provisioned wallet, keyed by the record like the - # governed path keys it, so the checkpoint names an entry that exists. - entry = await get_agent_money().charge( - wallet_id=wallet, - service_category=ServiceCategory.AGENT_COMMS, - units=Decimal(str(TOOL_COST)), - request_path=endpoint, - description="abandon guard debit", - operation_key=charged.record_id, - caller=CallerIdentity.for_wallet(wallet), - ) - assert getattr(entry, "entry_id", None), entry - await idem.mark_charged( + 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, - endpoint=endpoint, - idempotency_key="guard-charged", - ledger_entry_id=entry.entry_id, + key_id=ctx["key_id"], + tool_name=tool_name, + max_credits=50, + idem_key="guard-permit", ) - answered = await idem.begin_with_record( - wallet_id=wallet, - endpoint=endpoint, - idempotency_key="guard-answered", - request_payload={"n": 2}, + + 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"], ) - await idem.complete( - wallet_id=wallet, - endpoint=endpoint, - idempotency_key="guard-answered", - response_reference=None, - response_json={"ok": True}, + assert denied.json()["error"]["message"] == "insufficient_funds", denied.text + await _set_balance(wallet, "1000") + + async def response_lost(**_kwargs: Any) -> None: + raise RuntimeError("checkpoint lost") + + monkeypatch.setattr(idem, "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"], ) - for key, begun in (("guard-charged", charged), ("guard-answered", answered)): + 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=endpoint, + endpoint=GOVERNED_MCP_IDEMPOTENCY_ENDPOINT, idempotency_key=key, - expected_record_id=begun.record_id, + expected_record_id=record.record_id, ) is False ) - assert ( - await idem.get_record( - wallet_id=wallet, endpoint=endpoint, idempotency_key=key - ) - is not None - ) + assert await _record(ctx, key) is not None @pytest.mark.anyio From e2bcb43d1636a5e9c796eb0c216d8cd015f9d5e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 08:49:03 +0000 Subject: [PATCH 8/9] Patch service methods on the class in the contention tests Patching a singleton service's method on the instance and undoing it leaves a shadow attribute on some pytest releases (CI pins 9.1.1), which bypassed the class-level patch of IdempotencyService.complete in test_mcp_trust.py, test_x402.py and test_acp_bridge.py. Every patch added by these tests now targets the class, which restores exactly on every pytest release. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/tests/test_ledger_write_contention.py | 79 +++++++++++-------- 1 file changed, 48 insertions(+), 31 deletions(-) diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index 121a016ad..cd45ea1b1 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -40,15 +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 ( 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 ( @@ -716,6 +719,29 @@ async def wrapper(*args: Any, **kwargs: Any) -> Any: 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]: @@ -772,7 +798,6 @@ 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.agent_money import get_agent_money from app.services.billing_engine import LedgerWriteContendedError from tests.test_permit_reservation_unwind import _calls_made @@ -781,9 +806,9 @@ async def test_quote_is_released_when_the_debit_is_contended_once( client, tool_name, with_quote=True, idem_key="prefault-quote-1" ) assert quote_id is not None - money = get_agent_money() - wrapper, state = _one_shot(LedgerWriteContendedError(), money.charge) - monkeypatch.setattr(money, "charge", wrapper) + 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 @@ -818,16 +843,13 @@ async def test_the_reservation_goes_back_exactly_once_on_a_contended_debit( ) -> None: """Adding the quote release must not add a second reservation release.""" from app.routers import mcp as mcp_router - from app.services.agent_money import get_agent_money 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" ) - money = get_agent_money() - wrapper, _ = _one_shot(LedgerWriteContendedError(), money.charge) - monkeypatch.setattr(money, "charge", wrapper) + _fail_once_on(monkeypatch, AgentMoney, "charge", LedgerWriteContendedError()) real_release = mcp_router._release_local_permit_reservation releases: list[str] = [] @@ -852,7 +874,6 @@ async def test_the_key_is_freed_when_the_wallet_policy_raises_once( ) -> None: """A generic fault after the record begins and before any charge.""" from app.routers import mcp as mcp_router - from app.services.agent_money import get_agent_money from tests.test_permit_reservation_unwind import _calls_made tool_name, runs = governed_tool @@ -866,11 +887,12 @@ async def test_the_key_is_freed_when_the_wallet_policy_raises_once( ) monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", wrapper) else: - money = get_agent_money() - wrapper, state = _one_shot( - RuntimeError("spend read failed"), money.get_daily_spend + state = _fail_once_on( + monkeypatch, + AgentMoney, + "get_daily_spend", + RuntimeError("spend read failed"), ) - monkeypatch.setattr(money, "get_daily_spend", wrapper) first = await client.post("/mcp/messages", json=body, headers=ctx["agent_headers"]) assert first.json()["error"]["message"] == "internal_error", first.text @@ -900,9 +922,9 @@ async def test_a_fault_after_the_charge_keeps_the_record_and_the_quote( client, tool_name, with_quote=True, idem_key=key ) assert quote_id is not None - idem = get_idempotency_service() - wrapper, state = _one_shot(RuntimeError("checkpoint lost"), idem.mark_charged) - monkeypatch.setattr(idem, "mark_charged", wrapper) + 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 @@ -961,10 +983,10 @@ async def test_abandon_never_deletes_a_record_with_a_response_or_a_ledger_entry( assert denied.json()["error"]["message"] == "insufficient_funds", denied.text await _set_balance(wallet, "1000") - async def response_lost(**_kwargs: Any) -> None: + async def response_lost(self: Any, **_kwargs: Any) -> None: raise RuntimeError("checkpoint lost") - monkeypatch.setattr(idem, "complete", response_lost) + monkeypatch.setattr(IdempotencyService, "complete", response_lost) charged_call = await client.post( "/mcp/messages", json=_call_body( @@ -1010,7 +1032,6 @@ async def test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reser hand back exactly once, 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 app.services.quotes import get_quote_service from tests.test_permit_reservation_unwind import _calls_made tool_name, runs = governed_tool @@ -1018,9 +1039,9 @@ async def test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reser ctx, body, permit_id, quote_id = await _capped_governed_call( client, tool_name, with_quote=True, idem_key=key ) - quotes = get_quote_service() - wrapper, state = _one_shot(RuntimeError("quote store down"), quotes.consume) - monkeypatch.setattr(quotes, "consume", wrapper) + 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 @@ -1061,7 +1082,6 @@ async def test_an_unexpected_value_error_before_the_reserve_frees_the_key( debited, or the retry meets ``idempotency_in_progress`` forever. """ from app.routers import mcp as mcp_router - from app.services.agent_money import get_agent_money from tests.test_permit_reservation_unwind import _calls_made tool_name, runs = governed_tool @@ -1075,9 +1095,7 @@ async def test_an_unexpected_value_error_before_the_reserve_frees_the_key( wrapper, state = _one_shot(error, mcp_router.evaluate_wallet_policy) monkeypatch.setattr(mcp_router, "evaluate_wallet_policy", wrapper) else: - money = get_agent_money() - wrapper, state = _one_shot(error, money.get_daily_spend) - monkeypatch.setattr(money, "get_daily_spend", wrapper) + 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 @@ -1136,14 +1154,13 @@ async def test_a_deliberate_value_error_keeps_its_own_cleanup( idempotency_key="prefault-absent-1", ) abandons: list[str] = [] - idem = get_idempotency_service() - real_abandon = idem.abandon + real_abandon = IdempotencyService.abandon - async def counted_abandon(**kwargs: Any) -> bool: + async def counted_abandon(self: Any, **kwargs: Any) -> bool: abandons.append(str(kwargs.get("idempotency_key"))) - return await real_abandon(**kwargs) + return await real_abandon(self, **kwargs) - monkeypatch.setattr(idem, "abandon", counted_abandon) + 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. From 30f0797966b3a6f635475d17d36f782d90d7b20e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 23:57:22 +0000 Subject: [PATCH 9/9] Reword two comments about handing a reservation back Comment and docstring text only. No code or test change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GyhDYJWYwCDBVvdXWDMRUG Signed-off-by: Claude --- gateway/app/routers/mcp.py | 4 ++-- gateway/tests/test_ledger_write_contention.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index b8c2c2f13..920fd84e2 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -2589,8 +2589,8 @@ async def _execute_registered_tool_inner( # 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 exactly once. Every - # fault before it provably held none of them. + # 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 diff --git a/gateway/tests/test_ledger_write_contention.py b/gateway/tests/test_ledger_write_contention.py index cd45ea1b1..f5f397aa8 100644 --- a/gateway/tests/test_ledger_write_contention.py +++ b/gateway/tests/test_ledger_write_contention.py @@ -1029,8 +1029,9 @@ async def test_a_fault_after_the_reserve_does_not_free_the_key_over_a_held_reser """Negative: the generic abandon stops at the reserve. Past the reserve the call holds a permit reservation that this wrapper cannot - hand back exactly once, 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. + 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