Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
219 changes: 124 additions & 95 deletions gateway/tests/test_mcp_upstream_governed.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import hashlib
import json
import logging
from collections.abc import Awaitable, Callable
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from datetime import timedelta
from decimal import Decimal
Expand Down Expand Up @@ -3370,13 +3371,14 @@ async def _backdate_attempt(attempt_id: str) -> None:
await session.commit()


@asynccontextmanager
async def _upstream_refund_failure_with_key_lost(
client: AsyncClient,
*,
suffix: str,
prior_success: bool,
lost_ack: bool = False,
) -> dict[str, Any]:
) -> AsyncIterator[dict[str, Any]]:
"""A real upstream call that errors, whose refund fails, and whose replica
loses its signing key just after the terminal audit event is written.

Expand All @@ -3392,90 +3394,126 @@ async def _upstream_refund_failure_with_key_lost(
tool_name = f"partner-upstream-unsigned-{suffix}"
executor = FakeUpstreamExecutor("success")
_register_upstream(tool_name, executor)
permit = await create_tool_permit(
client,
wallet_id=wallet_id,
key_id=provisioned["key_id"],
tool_name=tool_name,
max_credits=10,
idem_key=f"partner-upstream-unsigned-{suffix}-permit",
)
if prior_success:
ok = await client.post(
"/mcp/messages",
json=_call_body(
tool_name=tool_name,
wallet_id=wallet_id,
permit_id=permit["permit_id"],
idempotency_key=f"partner-upstream-unsigned-{suffix}-ok",
),
headers=provisioned["agent_headers"],
try:
permit = await create_tool_permit(
client,
wallet_id=wallet_id,
key_id=provisioned["key_id"],
tool_name=tool_name,
max_credits=10,
idem_key=f"partner-upstream-unsigned-{suffix}-permit",
)
assert ok.status_code == 200 and "error" not in ok.json(), ok.text
executor.mode = "returned_error"
signing_key = await get_signing_key_service().ensure_active_key()
balance_before, refunds_before = await _wallet_state(wallet_id)
real_audit = mcp_router._audit_mcp_invocation
if prior_success:
ok = await client.post(
"/mcp/messages",
json=_call_body(
tool_name=tool_name,
wallet_id=wallet_id,
permit_id=permit["permit_id"],
idempotency_key=f"partner-upstream-unsigned-{suffix}-ok",
),
headers=provisioned["agent_headers"],
)
assert ok.status_code == 200 and "error" not in ok.json(), ok.text
executor.mode = "returned_error"
signing_key = await get_signing_key_service().ensure_active_key()
balance_before, refunds_before = await _wallet_state(wallet_id)
real_audit = mcp_router._audit_mcp_invocation

async def audit_then_lose_key(**kwargs: Any) -> Any:
event = await real_audit(**kwargs)
if str(kwargs.get("error") or "").startswith("refund_failed"):
await _set_signing_key_status(signing_key.key_id, "disabled")
return event

async def failing_refund(*_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("refund unavailable")

async def failing_ack(*_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("refund checkpoint unavailable")

idempotency_key = f"partner-upstream-unsigned-{suffix}-1"
with pytest.MonkeyPatch.context() as patched:
patched.setattr(mcp_router, "_audit_mcp_invocation", audit_then_lose_key)
if lost_ack:
patched.setattr(
McpDispatchAttemptService, "mark_debit_refunded", failing_ack
)
else:
patched.setattr(
"app.services.agent_money.AgentMoney.refund_charge", failing_refund
)
response = await client.post(
"/mcp/messages",
json=_call_body(
tool_name=tool_name,
wallet_id=wallet_id,
permit_id=permit["permit_id"],
idempotency_key=idempotency_key,
),
headers=provisioned["agent_headers"],
)
error = response.json()["error"]
reconciliation = error["data"]["refund_reconciliation"]
assert reconciliation["status"] == "pending", error
assert reconciliation["receipt_status"] == "unsigned", error
async with get_session_factory()() as session:
attempt = (
await session.execute(
select(McpDispatchAttemptModel)
.join(
IdempotencyRecordModel,
IdempotencyRecordModel.record_id
== McpDispatchAttemptModel.idempotency_record_id,
)
.where(IdempotencyRecordModel.idempotency_key == idempotency_key)
)
).scalar_one()
assert attempt.state == "returned_error"
yield {
"wallet_id": wallet_id,
"tool_name": tool_name,
"permit_id": permit["permit_id"],
"attempt_id": attempt.attempt_id,
"key_id": signing_key.key_id,
"balance_before": balance_before,
"refunds_before": refunds_before,
}

async def audit_then_lose_key(**kwargs: Any) -> Any:
event = await real_audit(**kwargs)
if str(kwargs.get("error") or "").startswith("refund_failed"):
await _set_signing_key_status(signing_key.key_id, "disabled")
return event
finally:
get_service_registry().unregister_local(tool_name)

async def failing_refund(*_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("refund unavailable")

async def failing_ack(*_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("refund checkpoint unavailable")
@pytest.mark.anyio
@pytest.mark.parametrize("failure_step", ["create_tool_permit", "_wallet_state"])
@pytest.mark.parametrize(
"failure_type", [RuntimeError, AssertionError, asyncio.CancelledError]
)
async def test_unsigned_refund_helper_unregisters_tool_when_setup_fails(
client: AsyncClient, clean_database: None, monkeypatch, failure_step, failure_type
) -> None:
suffix = "setup-cleanup"
tool_name = f"partner-upstream-unsigned-{suffix}"
registry = get_service_registry()
assert registry.get_local(tool_name) is None

idempotency_key = f"partner-upstream-unsigned-{suffix}-1"
with pytest.MonkeyPatch.context() as patched:
patched.setattr(mcp_router, "_audit_mcp_invocation", audit_then_lose_key)
if lost_ack:
patched.setattr(
McpDispatchAttemptService, "mark_debit_refunded", failing_ack
)
else:
patched.setattr(
"app.services.agent_money.AgentMoney.refund_charge", failing_refund
)
response = await client.post(
"/mcp/messages",
json=_call_body(
tool_name=tool_name,
wallet_id=wallet_id,
permit_id=permit["permit_id"],
idempotency_key=idempotency_key,
),
headers=provisioned["agent_headers"],
async def fail_setup(*_args, **_kwargs):
assert registry.get_local(tool_name) is not None
raise failure_type("injected setup failure")

monkeypatch.setattr(f"{__name__}.{failure_step}", fail_setup)
try:
with pytest.raises(failure_type, match="injected setup failure"):
async with _upstream_refund_failure_with_key_lost(
client, suffix=suffix, prior_success=False
):
pytest.fail("setup should have failed")
assert registry.get_local(tool_name) is None
assert all(
tool["service_id"] != tool_name for tool in await registry.list_executable()
)
error = response.json()["error"]
reconciliation = error["data"]["refund_reconciliation"]
assert reconciliation["status"] == "pending", error
assert reconciliation["receipt_status"] == "unsigned", error
async with get_session_factory()() as session:
attempt = (
await session.execute(
select(McpDispatchAttemptModel)
.join(
IdempotencyRecordModel,
IdempotencyRecordModel.record_id
== McpDispatchAttemptModel.idempotency_record_id,
)
.where(IdempotencyRecordModel.idempotency_key == idempotency_key)
)
).scalar_one()
assert attempt.state == "returned_error"
return {
"wallet_id": wallet_id,
"tool_name": tool_name,
"permit_id": permit["permit_id"],
"attempt_id": attempt.attempt_id,
"key_id": signing_key.key_id,
"balance_before": balance_before,
"refunds_before": refunds_before,
}
finally:
registry.unregister_local(tool_name)


@pytest.mark.anyio
Expand All @@ -3494,10 +3532,9 @@ async def test_dispatch_reconciler_leaves_an_unsigned_pending_refund_to_its_owne
failed_unrefunded receipt, and the refund is recorded as one ledger entry, through
the operator retry.
"""
case = await _upstream_refund_failure_with_key_lost(
async with _upstream_refund_failure_with_key_lost(
client, suffix=f"owner-{prior_success}", prior_success=prior_success
)
try:
) as case:
await _backdate_attempt(case["attempt_id"])
await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300)

Expand Down Expand Up @@ -3533,8 +3570,6 @@ async def test_dispatch_reconciler_leaves_an_unsigned_pending_refund_to_its_owne
assert permit is not None
# Only the paid earlier call (if any) still counts against the permit.
assert permit.spent_credits == (Decimal("2") if prior_success else 0)
finally:
get_service_registry().unregister_local(case["tool_name"])


@pytest.mark.anyio
Expand All @@ -3548,10 +3583,9 @@ async def test_unsigned_item_is_never_signed_after_a_refund_landed_elsewhere(
refunded while the unsigned item still lists it as owed. Signing must
refuse, leaving no failed_unrefunded receipt claiming a debt that is gone.
"""
case = await _upstream_refund_failure_with_key_lost(
async with _upstream_refund_failure_with_key_lost(
client, suffix="landed-elsewhere", prior_success=False
)
try:
) as case:
reconciler = get_mcp_dispatch_reconciliation_service()
attempt = await get_mcp_dispatch_attempt_service().get_context(
case["attempt_id"]
Expand All @@ -3578,8 +3612,6 @@ async def test_unsigned_item_is_never_signed_after_a_refund_landed_elsewhere(
or 0
)
assert receipts == 0
finally:
get_service_registry().unregister_local(case["tool_name"])


@pytest.mark.anyio
Expand All @@ -3597,13 +3629,12 @@ async def test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_re
because a refund row exists. Signed, the operator retry finds the refund
row, refunds nothing more, and releases the reservation in that retry.
"""
case = await _upstream_refund_failure_with_key_lost(
async with _upstream_refund_failure_with_key_lost(
client,
suffix=f"lost-ack-{prior_success}",
prior_success=prior_success,
lost_ack=True,
)
try:
) as case:
# The money is already back, and the reservation is still held.
assert await _wallet_state(case["wallet_id"]) == (
case["balance_before"],
Expand Down Expand Up @@ -3653,5 +3684,3 @@ async def test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_re
permit = await get_permit_service().get_permit(case["permit_id"])
assert permit is not None
assert permit.spent_credits == (Decimal("2") if prior_success else 0)
finally:
get_service_registry().unregister_local(case["tool_name"])
21 changes: 15 additions & 6 deletions gateway/tests/test_refund_reconciliation_contention_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ def __init__(
self._state = state
self._retirements = retirements
self._rotate = rotate
self._rotation_base_key_id = real._key_id

def __getattr__(self, name: str) -> Any:
return getattr(self._real, name)
Expand All @@ -187,9 +188,10 @@ async def ensure_active_key(self) -> Any:
# A real rotation to a fresh key id: the resolved key is
# retired and the process signs under the new id from the next
# resolution on, as the replica that rotated would.
await self._real.rotate_active_key_metadata(
f"{key.key_id}-rotated-{self._state['resolved']}"
)
suffix = f"-r{self._state['resolved']}"
key_id_limit = SigningKeyModel.__table__.c.key_id.type.length
base = self._rotation_base_key_id[: key_id_limit - len(suffix)]
await self._real.rotate_active_key_metadata(f"{base}{suffix}")
self._state["retired"] += 1
else:
self._state["retired"] += await _retire_active_keys()
Expand All @@ -207,11 +209,12 @@ def _retire_key_after_resolution(
# service, so the process-wide one is never mutated and is back in place
# when the test ends.
_install_signing_service(monkeypatch, _copy_of_signing_service())
service = _KeyRetiredAfterResolution(
real_get_signing_key_service(), state, retirements, rotate
)

def patched_get_signing_key_service():
return _KeyRetiredAfterResolution(
real_get_signing_key_service(), state, retirements, rotate
)
return service

monkeypatch.setattr(
reconciliation_module,
Expand Down Expand Up @@ -645,6 +648,12 @@ async def test_a_key_rotated_under_every_attempt_exhausts_like_contention(

# One resolution per attempt, and not one more than the documented budget.
assert state["resolved"] == WRITE_CONFLICT_MAX_ATTEMPTS, state
async with get_session_factory()() as session:
key_ids = (await session.scalars(select(SigningKeyModel.key_id))).all()
assert len(key_ids) == WRITE_CONFLICT_MAX_ATTEMPTS + 1
# SQLite does not enforce VARCHAR lengths; PostgreSQL does.
key_id_limit = SigningKeyModel.__table__.c.key_id.type.length
assert all(len(key_id) <= key_id_limit for key_id in key_ids)
assert resp.status_code == 200, resp.text
error = resp.json()["error"]
assert error["code"] != -32005, error
Expand Down
Loading