Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1c31207
Release the quote and the idempotency record on pre-charge faults
claude Nov 1, 2026
7efe93c
Return the enterprise use when the generic pre-charge abandon frees t…
claude Nov 1, 2026
d22d7a0
Return the enterprise use for contention that escapes before the reserve
claude Nov 1, 2026
b852652
Return the enterprise use when the reserve itself is contended
claude Nov 1, 2026
ab5283a
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 5, 2026
7b55190
Release the record for an unexpected ValueError and use a real ledger…
claude Nov 5, 2026
1f9a61d
Correct the tool_price_invalid comment for the permitted invoke path
claude Nov 5, 2026
27a4e4e
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 5, 2026
2144a15
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 5, 2026
6d3bcc6
Build the abandon guard test records from real governed calls
claude Nov 5, 2026
e2bcb43
Patch service methods on the class in the contention tests
claude Nov 5, 2026
317f72b
Merge remote-tracking branch 'origin/main' into claude/release-pre-ch…
Nov 5, 2026
3e0ed2f
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 6, 2026
2e72a63
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 24, 2026
4592ddd
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 24, 2026
4ba9119
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 25, 2026
3ca938d
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 25, 2026
a71caa0
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 25, 2026
75fc2b0
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 26, 2026
2402e5c
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 26, 2026
57e6440
Merge remote-tracking branch 'origin/main' into fleet-1126-ramp/am-27…
PetrefiedThunder Nov 26, 2026
d992c93
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 27, 2026
fc7fec4
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Nov 27, 2026
30f0797
Reword two comments about handing a reservation back
claude Nov 29, 2026
69bb7bc
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Dec 3, 2026
bbc78ae
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Dec 3, 2026
47f820a
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Dec 3, 2026
32c9b0b
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Dec 5, 2026
7feada2
Merge branch 'main' into claude/release-pre-charge-resources
PetrefiedThunder Dec 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 116 additions & 12 deletions gateway/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
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:
Expand All @@ -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")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
or isinstance(exc, PermitWriteContendedError)
):
Comment thread
PetrefiedThunder marked this conversation as resolved.
Resolved
# 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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)


Expand Down
88 changes: 88 additions & 0 deletions gateway/tests/test_iga_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand Down
Loading
Loading