diff --git a/gateway/app/main.py b/gateway/app/main.py index d2bfca547..e36c2ab3c 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -299,6 +299,9 @@ async def periodic_cleanup(): # reserve and the receipt write (only touches idle permits). if settings.DATABASE_URL: from .services.idempotency import get_idempotency_service + from .services.refund_reconciliation import ( + get_refund_reconciliation_service, + ) from .services.mcp_dispatch_attempts import ( MAX_UPSTREAM_CALL_TIMEOUT_SECONDS, MAX_UPSTREAM_CONNECT_TIMEOUT_SECONDS, @@ -392,6 +395,19 @@ async def periodic_cleanup(): idempotency_records_needing_review=needs_review, ) + # Pending refunds recorded while this or another replica + # could not sign get their receipt from a replica that can. + ( + refund_receipts_signed, + refund_receipts_unsigned, + ) = await get_refund_reconciliation_service().sign_unsigned_pending() + if refund_receipts_signed or refund_receipts_unsigned: + logger.info( + "cleanup_completed", + refund_receipts_signed=refund_receipts_signed, + refund_receipts_still_unsigned=refund_receipts_unsigned, + ) + except asyncio.CancelledError: logger.info("cleanup_task_stopped") break diff --git a/gateway/app/routers/mcp.py b/gateway/app/routers/mcp.py index 16c1d24b4..69c8102a8 100644 --- a/gateway/app/routers/mcp.py +++ b/gateway/app/routers/mcp.py @@ -3186,7 +3186,18 @@ async def _repair_pre_dispatch(exc: BaseException) -> Any: ok=False, error="refund_failed", metadata={ - "receipt_id": receipt_payload["receipt_id"], + "receipt_id": ( + receipt_payload["receipt_id"] + if receipt_payload is not None + else None + ), + # Only an unsigned receipt adds a key, so the + # signed case keeps its existing audit shape. + **( + {"receipt_status": "unsigned"} + if receipt_payload is None + else {} + ), "permit_id": permit_model.permit_id, "ledger_entry_id": charge_result.entry_id, "credits": str(credits_charged), @@ -4543,9 +4554,14 @@ async def _finalize_unrefunded_failure( response_hash_override: str | None = None, approval_id: str | None = None, counterparty: str | None = None, -) -> tuple[dict[str, Any], dict[str, Any]]: +) -> tuple[dict[str, Any] | None, dict[str, Any]]: """Persist the signed failure and its exact-once operator work item. + The receipt payload is ``None`` when the receipt could not be signed (the + signing key became unusable after the call was admitted). The work item is + recorded all the same, marked ``receipt_status: unsigned``, and a replica + whose key can sign signs the receipt later. + Both call sites reach here having already charged the caller, run the tool and failed the refund, so this is unconditionally a post-effects site -- unlike ``_finalize_governed_denial``, which serves both sides of the charge @@ -4587,6 +4603,13 @@ async def _finalize_unrefunded_failure( # losses at the other post-effects sites, and it still may not be # called retryable: the charge stands and the tool already ran. raise _receipt_contention_after_effects() from exc + if receipt is None: + logger.error( + "mcp_refund_reconciliation_receipt_unsigned ledger_entry_id=%s wallet_id=%s", + ledger_entry_id, + wallet_id, + ) + return None, reconciliation receipt_payload = _receipt_response_payload(receipt) return receipt_payload, reconciliation diff --git a/gateway/app/services/mcp_dispatch_attempts.py b/gateway/app/services/mcp_dispatch_attempts.py index fd3780b49..a6652c97f 100644 --- a/gateway/app/services/mcp_dispatch_attempts.py +++ b/gateway/app/services/mcp_dispatch_attempts.py @@ -15,7 +15,7 @@ from typing import Any, cast from urllib.parse import urlsplit -from sqlalchemy import func, select, update as sa_update +from sqlalchemy import func, not_, or_, select, update as sa_update from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement @@ -42,6 +42,7 @@ get_permit_service, ) from app.services.signing_keys import canonical_json, sha256_hex +from app.services.refund_reconciliation import UNSIGNED_RECEIPT_KEY logger = logging.getLogger(__name__) @@ -2143,6 +2144,29 @@ async def list_unfinalized_terminal_contexts( ColumnElement[bool], cast(Any, ReceiptModel.receipt_id).is_(None), ), + # A pending refund recorded without a receipt ID + # (RefundReconciliationService.create_pending) is + # owned by sign_unsigned_pending and the operator + # retry, exactly as a signed failed_unrefunded receipt + # is: compensating it here as well could refund money + # that the unsigned item still lists as owed. Only a + # charged record with no receipt reference can be such + # an item, so no other attempt is left out, whatever + # text its stored response contains. Each test stands + # alone so that a NULL response_json keeps the attempt + # listed. + or_( + cast(Any, IdempotencyRecordModel.response_json).is_(None), + cast(Any, IdempotencyRecordModel.response_reference).is_not( + None + ), + cast(Any, IdempotencyRecordModel.ledger_entry_id).is_(None), + not_( + cast( + Any, IdempotencyRecordModel.response_json + ).contains(f'"{UNSIGNED_RECEIPT_KEY}"', autoescape=True) + ), + ), ) .order_by( cast(ColumnElement[Any], McpDispatchAttemptModel.updated_at) diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index c9291cb2f..404e8c6c2 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -6,9 +6,10 @@ from datetime import datetime, timezone from decimal import Decimal, InvalidOperation import json +import logging from typing import Any, Literal, cast -from sqlalchemy import select, update as sa_update +from sqlalchemy import and_, or_, select, update as sa_update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement @@ -19,6 +20,7 @@ HumanApprovalModel, IdempotencyRecordModel, LedgerEntryModel, + McpDispatchAttemptModel, PermitModel, ReceiptModel, WalletModel, @@ -28,12 +30,45 @@ from app.schemas.trust import ReceiptResponse from app.services.permits import get_permit_service from app.services.receipts import get_receipt_service -from app.services.signing_keys import SigningKeyError, get_signing_key_service +from app.services.signing_keys import ( + SigningKeyError, + get_signing_key_service, + sha256_hex, +) + +logger = logging.getLogger(__name__) RECONCILIATION_KIND = "mcp_failed_refund" RECONCILIATION_VERSION = 1 +# Top-level key of a stored response whose failed_unrefunded receipt could not +# be signed yet. It holds the inputs a replica with a usable key needs to sign +# that receipt later (``sign_unsigned_pending``). It is never replayed to a +# caller: replay reads only named keys of the stored response. +UNSIGNED_RECEIPT_KEY = "unsigned_receipt" +UNSIGNED_RECEIPT_VERSION = 1 + + +def _unsigned_marker(record: IdempotencyRecordModel) -> dict[str, Any] | None: + """Return the unsigned-receipt marker of ``record``'s stored response.""" + if record.response_json is None: + return None + try: + payload = json.loads(record.response_json) + except (json.JSONDecodeError, TypeError): + return None + if not isinstance(payload, dict): + return None + marker = payload.get(UNSIGNED_RECEIPT_KEY) + if ( + not isinstance(marker, dict) + or marker.get("version") != UNSIGNED_RECEIPT_VERSION + or not isinstance(marker.get("inputs"), dict) + ): + return None + return marker + class RefundReconciliationError(RuntimeError): """Fail-closed reconciliation state or linkage error.""" @@ -80,7 +115,7 @@ def __init__(self) -> None: def build_pending_refund_reconciliation( *, - receipt_id: str, + receipt_id: str | None, wallet_id: str, permit_id: str, ledger_entry_id: str, @@ -164,7 +199,7 @@ async def create_pending( permit_id: str, key_id: str | None, tool_name: str, - request_payload: dict[str, Any], + request_payload: dict[str, Any] | None, ledger_entry_id: str, credits_authorized: Decimal, credits_charged: Decimal, @@ -175,8 +210,23 @@ async def create_pending( response_payload: dict[str, Any] | None = None, response_hash_override: str | None = None, counterparty: str | None = None, - ) -> tuple[ReceiptResponse, dict[str, Any]]: - """Atomically insert the signed receipt and durable pending work item.""" + request_hash: str | None = None, + _from_unsigned: bool = False, + ) -> tuple[ReceiptResponse | None, dict[str, Any]]: + """Atomically insert the receipt ID and durable pending work item. + + When the receipt cannot be signed (any ``SigningKeyError`` that is not + the one restart reason, for example a key retired or disabled after + the call was admitted), the debt is still recorded: the stored + response carries the pending work item with ``receipt_id`` ``None`` + and an ``unsigned_receipt`` marker holding everything needed to sign + the receipt later. The receipt is then ``None`` in the return value. + ``sign_unsigned_pending`` signs it from a replica whose key can sign, + through this same method with ``_from_unsigned=True``, which accepts + that marker as the checkpoint instead of an empty response. + """ + if (request_payload is None) == (request_hash is None): + raise RefundReconciliationError("refund_reconciliation_request_invalid") async def validated_checkpoint( session: AsyncSession, @@ -203,12 +253,22 @@ async def validated_checkpoint( if ( record is None or record.ledger_entry_id != ledger_entry_id - or record.response_json is not None or record.response_reference is not None ): raise RefundReconciliationError( "refund_reconciliation_checkpoint_invalid" ) + # A fresh checkpoint has no stored response yet; signing an + # unsigned pending item later starts from its marker instead. + if _from_unsigned: + if _unsigned_marker(record) is None: + raise RefundReconciliationError( + "refund_reconciliation_checkpoint_invalid" + ) + elif record.response_json is not None: + raise RefundReconciliationError( + "refund_reconciliation_checkpoint_invalid" + ) permit = await session.get(PermitModel, permit_id) if permit is None: raise RefundReconciliationError( @@ -303,6 +363,7 @@ def finalize_record( key_id=key_id, tool=tool_name, request_payload=request_payload, + request_hash=request_hash, response_payload=response_payload or {"error": reason}, ledger_entry_id=ledger_entry_id, credits_authorized=credits_authorized, @@ -352,12 +413,319 @@ def retired_under_the_attempt(exc: BaseException) -> bool: "signing_key_not_active" ) + try: + return await run_with_write_conflict_retry( + attempt, + on_exhausted=lambda exc: RefundReconciliationContendedError(), + restart_on=retired_under_the_attempt, + ) + except SigningKeyError as exc: + if _from_unsigned: + # Signing later on a replica that still cannot sign: leave the + # unsigned item in place for the next pass. + raise + effective_payload = response_payload or {"error": reason} + inputs: dict[str, Any] = { + "wallet_id": wallet_id, + "endpoint": endpoint, + "idempotency_key": idempotency_key, + "permit_id": permit_id, + "key_id": key_id, + "tool_name": tool_name, + "request_hash": ( + request_hash + if request_hash is not None + else sha256_hex(cast(dict[str, Any], request_payload)) + ), + "ledger_entry_id": ledger_entry_id, + "credits_authorized": str(credits_authorized), + "credits_charged": str(credits_charged), + "audit_event_id": audit_event_id, + "reason": reason, + "dispatch_attempt_id": dispatch_attempt_id, + "approval_id": approval_id, + "response_payload": effective_payload, + "response_hash_override": response_hash_override, + "counterparty": counterparty, + } + reconciliation = await self._record_unsigned_pending( + validated_checkpoint=validated_checkpoint, + inputs=inputs, + response_hash=sha256_hex(effective_payload), + signing_error=str(exc), + ) + return None, reconciliation + + @staticmethod + async def _refund_landed_and_budget_released(inputs: dict[str, Any]) -> bool: + """Whether this charge was refunded *and* its reservation released. + + Only that combination makes the unsigned item wrong to sign. A refund + row with the reservation still held is the lost acknowledgement case: + the live path refunded the charge, then failed to checkpoint it on the + dispatch attempt (``mark_debit_refunded``), and went down the + refund-failed path. Nothing else releases that reservation (the + dispatch sweep skips an attempt whose refund was never checkpointed + while its debit stands), so the item is signed as usual and the + operator retry, finding the refund row, releases the reservation once + without refunding again. + + The reservation counts as released when the dispatch attempt says so. + Without a dispatch attempt nothing but the operator retry releases it. + """ + ledger_entry_id = inputs["ledger_entry_id"] + factory = get_session_factory() + async with factory() as session: + refund = ( + await session.execute( + select(cast(Any, LedgerEntryModel.entry_id)) + .where( + cast( + ColumnElement[bool], + LedgerEntryModel.correlation_id == ledger_entry_id, + ), + cast( + ColumnElement[bool], + LedgerEntryModel.action == "refund", + ), + ) + .limit(1) + ) + ).scalar_one_or_none() + if ( + refund is None + and (await session.get(LedgerEntryModel, f"refund-{ledger_entry_id}")) + is None + ): + return False + attempt_id = inputs.get("dispatch_attempt_id") + if not attempt_id: + return False + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + released = attempt is not None and attempt.budget_released_at is not None + if not released: + logger.warning( + "refund_reconciliation_unsigned_refund_unacknowledged", + extra={ + "ledger_entry_id": ledger_entry_id, + "dispatch_attempt_id": attempt_id, + }, + ) + return released + + async def _record_unsigned_pending( + self, + *, + validated_checkpoint: Any, + inputs: dict[str, Any], + response_hash: str, + signing_error: str, + ) -> dict[str, Any]: + """Store the pending refund without a receipt, in one transaction. + + The work item names no receipt yet (``receipt_id`` ``None``) and the + marker beside it keeps the receipt inputs. ``response_hash`` is the hash + of the response payload as it was handed in, so signing later can + refuse a payload the JSON round trip changed instead of signing a + different hash. The record is completed with status 500, so a replay + of the same key never runs the tool again; it is refused or given + the stored answer (docs/failure-semantics.md). + """ + factory = get_session_factory() + + async def attempt() -> dict[str, Any]: + async with factory() as session: + async with session.begin(): + record = await validated_checkpoint(session, lock=True) + reconciliation = build_pending_refund_reconciliation( + receipt_id=None, + wallet_id=inputs["wallet_id"], + permit_id=inputs["permit_id"], + ledger_entry_id=inputs["ledger_entry_id"], + credits=Decimal(inputs["credits_charged"]), + ) + reconciliation["receipt_status"] = "unsigned" + record.response_json = json.dumps( + { + "content": [], + "isError": True, + "error": inputs["reason"], + "receipt": None, + "refund_reconciliation": reconciliation, + UNSIGNED_RECEIPT_KEY: { + "version": UNSIGNED_RECEIPT_VERSION, + "signing_error": signing_error, + "recorded_at": utc_now().isoformat(), + "response_hash": response_hash, + "inputs": inputs, + }, + }, + default=str, + ) + record.status_code = 500 + session.add(record) + await session.flush() + return reconciliation + return await run_with_write_conflict_retry( attempt, on_exhausted=lambda exc: RefundReconciliationContendedError(), - restart_on=retired_under_the_attempt, ) + @staticmethod + async def _unsigned_page( + *, after: tuple[Any, str] | None, limit: int + ) -> list[IdempotencyRecordModel]: + """One page of unsigned pending refunds, oldest first, after ``after``. + + Keyset order on ``(created_at, record_id)``, so a caller that advances + past every record it has seen never reads the same one twice in a pass, + whether or not that record could be signed. + + An unsigned pending refund is only ever recorded on a charged record + with no receipt reference (``create_pending`` validates that checkpoint + first), so the page asks for exactly that before it looks at the stored + text. The text alone is not enough: a caller chooses text that other + stored responses repeat, for example the tool name in a ``Tool not + found`` denial, which the shipped trust flags record at no charge. The + match is escaped because ``_`` is a LIKE wildcard. + + The lower bound on ``created_at`` repeats what the keyset condition + already implies. It lets the database seek into the ``created_at`` + index instead of reading it from the oldest record on every page. + """ + created = cast(Any, IdempotencyRecordModel.created_at) + record_id = cast(Any, IdempotencyRecordModel.record_id) + conditions = [ + cast(Any, IdempotencyRecordModel.response_reference).is_(None), + cast(Any, IdempotencyRecordModel.ledger_entry_id).is_not(None), + cast(Any, IdempotencyRecordModel.response_json).contains( + f'"{UNSIGNED_RECEIPT_KEY}"', autoescape=True + ), + ] + if after is not None: + conditions.append(created >= after[0]) + conditions.append( + or_( + created > after[0], + and_(created == after[0], record_id > after[1]), + ) + ) + factory = get_session_factory() + async with factory() as session: + return list( + ( + await session.execute( + select(IdempotencyRecordModel) + .where(*conditions) + .order_by(created, record_id) + .limit(limit) + ) + ) + .scalars() + .all() + ) + + async def sign_unsigned_pending(self, *, limit: int = 50) -> tuple[int, int]: + """Sign the receipts of pending refunds recorded without one. + + Runs from the periodic cleanup on every replica. A replica whose key + cannot sign leaves each item as it is; one whose key can sign writes + the ``failed_unrefunded`` receipt and turns the item into an ordinary + pending work item (the same shape ``create_pending`` writes when it + can sign), which the operator list and ``retry`` then see. Concurrent + signers are safe: the checkpoint is re-read under a row lock and the + second signer finds it already signed. + + Every unsigned item is visited once per pass, in pages of ``limit``. + An item that is refused or cannot be signed stays unsigned and the scan + moves past it, so items that can never be signed (a refund that already + landed and was released, a payload that no longer matches its hash) + cannot keep newer items from being signed. + + Returns ``(signed, still_unsigned)`` for the whole pass. + """ + if limit < 1: + raise ValueError("limit must be positive") + signed = 0 + still_unsigned = 0 + after: tuple[Any, str] | None = None + while True: + records = await self._unsigned_page(after=after, limit=limit) + if not records: + break + after = (records[-1].created_at, records[-1].record_id) + for record in records: + marker = _unsigned_marker(record) + if marker is None: + continue + inputs = dict(marker["inputs"]) + if await self._refund_landed_and_budget_released(inputs): + # The money already came back and the permit reservation was + # already given back, by another path (for example a dispatch + # reconciler pass that ran before it learned to leave these + # items alone). A failed_unrefunded receipt would then claim a + # debt that no longer exists, and the operator retry would + # release the permit budget a second time. Leave it for an + # operator, loudly. + logger.error( + "refund_reconciliation_unsigned_already_refunded", + extra={ + "record_id": record.record_id, + "ledger_entry_id": inputs["ledger_entry_id"], + }, + ) + still_unsigned += 1 + continue + if sha256_hex(inputs["response_payload"]) != marker.get( + "response_hash" + ): + # The stored payload no longer hashes to what the caller's + # response was; signing it would sign a different response. + logger.error( + "refund_reconciliation_unsigned_payload_mismatch", + extra={"record_id": record.record_id}, + ) + still_unsigned += 1 + continue + try: + await self.create_pending( + wallet_id=inputs["wallet_id"], + endpoint=inputs["endpoint"], + idempotency_key=inputs["idempotency_key"], + permit_id=inputs["permit_id"], + key_id=inputs["key_id"], + tool_name=inputs["tool_name"], + request_payload=None, + request_hash=inputs["request_hash"], + ledger_entry_id=inputs["ledger_entry_id"], + credits_authorized=Decimal(inputs["credits_authorized"]), + credits_charged=Decimal(inputs["credits_charged"]), + audit_event_id=inputs["audit_event_id"], + reason=inputs["reason"], + dispatch_attempt_id=inputs["dispatch_attempt_id"], + approval_id=inputs["approval_id"], + response_payload=inputs["response_payload"], + response_hash_override=inputs["response_hash_override"], + counterparty=inputs["counterparty"], + _from_unsigned=True, + ) + except SigningKeyError: + still_unsigned += 1 + continue + except (RefundReconciliationError, RefundReconciliationContendedError): + # Signed concurrently by another replica, or contended: the + # next pass reads it again. + logger.info( + "refund_reconciliation_unsigned_skipped", + extra={"record_id": record.record_id}, + exc_info=True, + ) + still_unsigned += 1 + continue + signed += 1 + return signed, still_unsigned + @staticmethod def _decode_response(record: IdempotencyRecordModel) -> dict[str, Any]: try: diff --git a/gateway/docs/failure-semantics.md b/gateway/docs/failure-semantics.md index 4b94f9221..990d9cea6 100644 --- a/gateway/docs/failure-semantics.md +++ b/gateway/docs/failure-semantics.md @@ -368,6 +368,44 @@ ack was lost is recognized rather than duplicated `resolved` claim without the matching ledger row fails closed on every read and replay (`test_forged_resolved_reconciliation_without_refund_fails_closed`). +If the receipt cannot be signed at that moment (the signing key became +unusable after the call was admitted, for example it was disabled), the work +item is still recorded, without a receipt: the caller gets the same 500 / +`-32603` answer with `refund_reconciliation.status` `pending`, `receipt_id` +`null` and `receipt_status` `unsigned`, and a replay of the same key never +runs the tool again; it is refused or given the stored answer, and it is +always refused while the signing key that signed the call's permit is +`disabled`. The stored record keeps the receipt +inputs server side. The periodic cleanup on every replica runs +`RefundReconciliationService.sign_unsigned_pending`: a replica whose key can +sign writes the `failed_unrefunded` receipt and turns the item into an +ordinary pending work item, which the operator list and retry then see; a +replica that cannot sign leaves it for the next pass. Each pass visits every +unsigned item once, oldest first, and moves past an item it refuses, so an +item that can never be signed does not keep newer ones waiting. Until it is signed the +item does not appear in the operator list +(`tests/test_refund_reconciliation_unsigned.py`). The unsigned item then +owns that debt: the dispatch reconciler skips an upstream attempt whose +record carries it, as it skips one with a signed `failed_unrefunded` +receipt, so no reconcile that picks up the attempt after the item is +recorded refunds that charge. A refund still owed then is left to the +operator retry, unless a reconcile that picked up the attempt before then +makes it first, and the money is refunded at most once. A retry of the +pending item that finds the signing key that signed the call's permit +`disabled` refuses, also in the case described next: it refunds nothing, +releases no reservation and leaves the item pending. Unless such an +earlier reconcile settles the charge and replaces the item, that item has +no automatic resolution and needs an operator. If a +refund for the charge is already in the ledger and its permit reservation is +still held (the live path refunded, then failed to record the refund on the +dispatch attempt), the signer signs as usual and logs +`refund_reconciliation_unsigned_refund_unacknowledged`; the operator retry +then finds that refund, refunds nothing more, and releases the reservation +once. If the reservation was already released as well, the signer refuses and +logs `refund_reconciliation_unsigned_already_refunded`; that item has no +automatic resolution and needs an operator +(`tests/test_mcp_upstream_governed.py`). + ## What this deliberately does not claim 1. **Post-dispatch ambiguity is never resolved automatically.** No retry, no diff --git a/gateway/tests/test_mcp_upstream_governed.py b/gateway/tests/test_mcp_upstream_governed.py index 6f471bdce..00596fd6e 100644 --- a/gateway/tests/test_mcp_upstream_governed.py +++ b/gateway/tests/test_mcp_upstream_governed.py @@ -26,6 +26,7 @@ McpDispatchAttemptModel, PermitModel, ReceiptModel, + SigningKeyModel, WalletModel, ) from app.main import app @@ -40,6 +41,7 @@ DispatchPrepareCommitUncertainError, DispatchPrepareRolledBackError, McpDispatchAttemptService, + get_mcp_dispatch_attempt_service, ) from app.services.mcp_dispatch_reconciliation import ( McpDispatchReconciliationService, @@ -49,7 +51,8 @@ from app.services.quotes import get_quote_service from app.services.receipts import ReceiptService, get_receipt_service from app.services.service_registry import get_service_registry -from app.services.signing_keys import sha256_hex +from app.services.refund_reconciliation import get_refund_reconciliation_service +from app.services.signing_keys import get_signing_key_service, sha256_hex from app.core.config import Settings from app.services.upstream_mcp import ( DiscoveredUpstreamTool, @@ -3329,3 +3332,326 @@ def test_register_upstream_read_only_is_operator_declared(read_only): assert registry.get_local(tool_name)["read_only"] is read_only finally: registry.unregister_local(tool_name) + + +async def _set_signing_key_status(key_id: str, status: str) -> None: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + +async def _wallet_state(wallet_id: str) -> tuple[Decimal, int]: + async with get_session_factory()() as session: + wallet = await session.get(WalletModel, wallet_id) + assert wallet is not None + refunds = int( + await session.scalar( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.action == "refund", + ) + ) + or 0 + ) + return Decimal(str(wallet.balance)), refunds + + +async def _backdate_attempt(attempt_id: str) -> None: + async with get_session_factory()() as session: + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + assert attempt is not None + attempt.updated_at = utc_now() - timedelta(minutes=10) + session.add(attempt) + await session.commit() + + +async def _upstream_refund_failure_with_key_lost( + client: AsyncClient, + *, + suffix: str, + prior_success: bool, + lost_ack: bool = False, +) -> 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. + + The refund-failed path then records the pending refund without a receipt + (issue #280). Faults are injected at class or module level only: the + refund store fails, and the signing key row is disabled. With + ``lost_ack`` the refund itself lands and only its checkpoint on the + dispatch attempt (``mark_debit_refunded``) fails, so the live path takes + the refund-failed branch with the money already back. + """ + provisioned = await provision_agent_wallet(client) + wallet_id = provisioned["agent_wallet_id"] + 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"], + ) + 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" + 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, + } + + +@pytest.mark.anyio +@pytest.mark.parametrize("prior_success", [False, True]) +async def test_dispatch_reconciler_leaves_an_unsigned_pending_refund_to_its_owner( + client: AsyncClient, clean_database: None, prior_success: bool +) -> None: + """One owner for the debt: the unsigned item, not the dispatch reconciler. + + Before the fix the reconciler compensated the returned_error attempt (it + has no receipt yet), refunding the charge, and the unsigned signer then + wrote a failed_unrefunded receipt for money already returned; the operator + retry either failed forever (budget conflict) or, with an earlier paid + call on the same permit, released that call's budget too, so the permit + under-counted. Now the reconciler skips the attempt like it skips a signed + failed_unrefunded receipt, and the refund is recorded as one ledger entry, through + the operator retry. + """ + case = await _upstream_refund_failure_with_key_lost( + client, suffix=f"owner-{prior_success}", prior_success=prior_success + ) + try: + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + # The reconciler did not touch the money it does not own. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"] - Decimal("2"), + case["refunds_before"], + ) + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (1, 0) + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + async with get_session_factory()() as session: + receipt = ( + await session.execute( + select(ReceiptModel).where( + ReceiptModel.dispatch_attempt_id == case["attempt_id"] + ) + ) + ).scalar_one() + assert receipt.outcome == "failed_unrefunded" + + item, already = await service.retry(receipt.receipt_id) + assert item.status == "resolved" and already is False + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + permit = await get_permit_service().get_permit(case["permit_id"]) + 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 +async def test_unsigned_item_is_never_signed_after_a_refund_landed_elsewhere( + client: AsyncClient, clean_database: None +) -> None: + """Defense in depth for a refund that already landed by another path. + + Stages the state the reconciler produced before it learned to skip these + items (its own compensation step, called directly): the charge is + 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( + client, suffix="landed-elsewhere", prior_success=False + ) + try: + reconciler = get_mcp_dispatch_reconciliation_service() + attempt = await get_mcp_dispatch_attempt_service().get_context( + case["attempt_id"] + ) + assert attempt is not None + await reconciler._compensate_returned_error(attempt.attempt) + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + await _set_signing_key_status(case["key_id"], "active") + + assert await get_refund_reconciliation_service().sign_unsigned_pending() == ( + 0, + 1, + ) + async with get_session_factory()() as session: + receipts = int( + await session.scalar( + select(func.count()) + .select_from(ReceiptModel) + .where(ReceiptModel.dispatch_attempt_id == case["attempt_id"]) + ) + or 0 + ) + assert receipts == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +@pytest.mark.parametrize("prior_success", [False, True]) +async def test_unsigned_item_whose_refund_landed_unacknowledged_is_signed_and_released_once( + client: AsyncClient, clean_database: None, prior_success: bool +) -> None: + """The lost acknowledgement case: refund landed, reservation still held. + + The live path refunds the charge, then fails to checkpoint the refund on + the dispatch attempt, so it records a pending refund (unsigned, because + the key is lost too). Nothing else releases that reservation: the + dispatch sweep skips an attempt whose refund was never checkpointed while + its debit stands. The signer must therefore not refuse this item just + 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( + client, + suffix=f"lost-ack-{prior_success}", + prior_success=prior_success, + lost_ack=True, + ) + try: + # The money is already back, and the reservation is still held. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + held = Decimal("4") if prior_success else Decimal("2") + assert permit.spent_credits == held + + # The dispatch sweep does not release it. + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + permit = await get_permit_service().get_permit(case["permit_id"]) + assert permit is not None + assert permit.spent_credits == held + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (1, 0) + async with get_session_factory()() as session: + receipt = ( + await session.execute( + select(ReceiptModel).where( + ReceiptModel.dispatch_attempt_id == case["attempt_id"] + ) + ) + ).scalar_one() + assert receipt.outcome == "failed_unrefunded" + + item, already = await service.retry(receipt.receipt_id) + assert item.status == "resolved" and already is False + # No second refund, and the reservation is released once. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + 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) + + # Neither a second retry nor a later sweep releases it again. + _item, already = await service.retry(receipt.receipt_id) + assert already is True + await _backdate_attempt(case["attempt_id"]) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + 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"]) diff --git a/gateway/tests/test_refund_reconciliation_unsigned.py b/gateway/tests/test_refund_reconciliation_unsigned.py new file mode 100644 index 000000000..f7a8083b3 --- /dev/null +++ b/gateway/tests/test_refund_reconciliation_unsigned.py @@ -0,0 +1,798 @@ +"""A pending refund is recorded even when its receipt cannot be signed yet. + +The refund-failed path runs after the tool ran and the wallet was charged. Its +``failed_unrefunded`` receipt and the operator work item used to be written in +one transaction that needed a usable signing key. If the key became unusable +after the call was admitted (disabled, or retired once a retired key refuses +to sign), ``create_pending`` raised a ``SigningKeyError`` that nothing +classified: the caller got ``internal_error`` and neither the receipt nor the +work item was written, so the debt was recorded nowhere (issue #280). + +``create_pending`` now records the work item without a receipt in that case, +with an ``unsigned_receipt`` marker holding the receipt inputs, and +``sign_unsigned_pending`` signs the receipt from a replica whose key can sign. +These tests pin both halves and that the item then flows through the normal +operator path. +""" + +from __future__ import annotations + +import base64 +from collections.abc import Iterator +from contextlib import contextmanager +from decimal import Decimal +import json +from typing import Any +from unittest.mock import patch + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, +) +from httpx import ASGITransport, AsyncClient +from sqlalchemy import event, func, select + +from app.db.database import get_engine, get_session_factory +from app.db.models import ( + IdempotencyRecordModel, + LedgerEntryModel, + ReceiptModel, + SigningKeyModel, +) +from app.main import app +from app.routers import mcp as mcp_router +from app.routers.mcp import INTERNAL_ERROR_MESSAGE +from app.schemas.billing import ServiceCategory +from app.services.mcp_dispatch_attempts import get_mcp_dispatch_attempt_service +from app.services.refund_reconciliation import ( + UNSIGNED_RECEIPT_KEY, + RefundReconciliationService, + get_refund_reconciliation_service, +) +from app.services.service_registry import get_service_registry +from app.services.signing_keys import get_signing_key_service +from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet + +TOOL_COST = 2.0 +TOOL_NAME = "refund-unsigned-tool" + + +@pytest.fixture +async def client() -> AsyncClient: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as value: + yield value + + +async def _set_key_status(key_id: str, status: str) -> None: + async with get_session_factory()() as session: + row = await session.get(SigningKeyModel, key_id) + assert row is not None + row.status = status + session.add(row) + await session.commit() + + +@pytest.fixture +def key_lost_mid_call_tool(): + """A tool that, while it runs, loses this replica its signing key. + + It stands in for an operator disabling (or, once retired keys refuse, + retiring) the key after the call was admitted and charged. Then the tool + fails, so the call goes down the refund path with no usable key. + """ + state: dict[str, Any] = {"runs": 0, "key_id": None, "lose_key": True} + + async def run() -> dict[str, Any]: + state["runs"] += 1 + if state["lose_key"]: + await _set_key_status(state["key_id"], "disabled") + raise RuntimeError("tool exploded") + + get_service_registry().register_local( + service_id=TOOL_NAME, + name="Refund unsigned tool", + description="Pending refund without a signable receipt test tool", + category=ServiceCategory.AGENT_COMMS, + func=run, + credits_per_unit=TOOL_COST, + unit_name="call", + ) + try: + yield state + finally: + get_service_registry().unregister_local(TOOL_NAME) + + +async def _failing_refund(self, **_kwargs): # noqa: ANN001 + raise RuntimeError("refund down") + + +async def _record_for(key: str) -> IdempotencyRecordModel: + async with get_session_factory()() as session: + record = ( + await session.execute( + select(IdempotencyRecordModel).where( + IdempotencyRecordModel.idempotency_key == key + ) + ) + ).scalar_one() + return record + + +async def _count(model: Any) -> int: + async with get_session_factory()() as session: + return int(await session.scalar(select(func.count()).select_from(model)) or 0) + + +async def _run_call_that_loses_its_key( + client: AsyncClient, state: dict[str, Any], *, key: str +) -> dict[str, Any]: + ctx = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=TOOL_NAME, + max_credits=10, + idem_key=f"{key}-permit", + ) + signing_key = await get_signing_key_service().ensure_active_key() + state["key_id"] = signing_key.key_id + body = { + "jsonrpc": "2.0", + "id": f"call-{key}", + "method": "tools/call", + "params": { + "name": TOOL_NAME, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "permit_id": permit["permit_id"], + "idempotency_key": key, + }, + }, + } + with patch("app.services.agent_money.AgentMoney.refund_charge", _failing_refund): + resp = await client.post( + "/mcp/messages", json=body, headers=ctx["agent_headers"] + ) + return {"ctx": ctx, "permit": permit, "body": body, "resp": resp} + + +@pytest.mark.anyio +async def test_a_refund_whose_receipt_cannot_be_signed_is_still_recorded( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + receipts_before = await _count(ReceiptModel) + case = await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-1" + ) + resp = case["resp"] + + assert key_lost_mid_call_tool["runs"] == 1 + assert resp.status_code == 200, resp.text + error = resp.json()["error"] + # Not the unclassified answer: the reason and the debt are on the wire. + assert error["message"] != INTERNAL_ERROR_MESSAGE, error + reconciliation = error["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending", reconciliation + assert reconciliation["receipt_id"] is None, reconciliation + assert reconciliation["receipt_status"] == "unsigned", reconciliation + assert Decimal(reconciliation["credits"]) == Decimal("2") + # Internal receipt inputs never reach the caller. + assert UNSIGNED_RECEIPT_KEY not in json.dumps(resp.json()) + + # The debt is durable: the record is completed with the work item and the + # marker, and no receipt was written. + assert await _count(ReceiptModel) == receipts_before + record = await _record_for("refund-unsigned-1") + assert record.response_reference is None + assert record.status_code == 500 + stored = json.loads(record.response_json or "{}") + assert stored["refund_reconciliation"]["status"] == "pending" + marker = stored[UNSIGNED_RECEIPT_KEY] + assert marker["signing_error"] == "signing_key_disabled" + assert marker["inputs"]["ledger_entry_id"] == record.ledger_entry_id + + # The same key replays the same pending answer and never runs the tool. + # (The key is usable again first: a disabled key also fails the permit's + # signature check, which runs before the replay is served.) + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + with patch("app.services.agent_money.AgentMoney.refund_charge", _failing_refund): + replay = await client.post( + "/mcp/messages", json=case["body"], headers=case["ctx"]["agent_headers"] + ) + assert key_lost_mid_call_tool["runs"] == 1 + replayed = replay.json()["error"]["data"]["refund_reconciliation"] + assert replayed["status"] == "pending" + assert replayed["receipt_id"] is None + + +@pytest.mark.anyio +async def test_a_replica_that_cannot_sign_leaves_the_item_unsigned( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-2" + ) + service = get_refund_reconciliation_service() + + signed, still_unsigned = await service.sign_unsigned_pending() + + assert (signed, still_unsigned) == (0, 1) + record = await _record_for("refund-unsigned-2") + assert record.response_reference is None + assert UNSIGNED_RECEIPT_KEY in json.loads(record.response_json or "{}") + + +@pytest.mark.anyio +async def test_a_replica_that_can_sign_completes_the_item_and_it_can_be_refunded( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + case = await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-3" + ) + wallet_id = case["ctx"]["agent_wallet_id"] + service = get_refund_reconciliation_service() + # The key is usable again (for example the replica was redeployed). + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + signed, still_unsigned = await service.sign_unsigned_pending() + assert (signed, still_unsigned) == (1, 0) + + record = await _record_for("refund-unsigned-3") + assert record.response_reference is not None + stored = json.loads(record.response_json or "{}") + assert UNSIGNED_RECEIPT_KEY not in stored + assert stored["receipt"]["outcome"] == "failed_unrefunded" + assert stored["refund_reconciliation"]["receipt_id"] == record.response_reference + + async with get_session_factory()() as session: + receipt = await session.get(ReceiptModel, record.response_reference) + assert receipt is not None + assert receipt.outcome == "failed_unrefunded" + assert receipt.ledger_entry_id == record.ledger_entry_id + assert receipt.idempotency_record_id == record.record_id + assert receipt.credits_charged == Decimal("2") + + # A second pass finds nothing left to sign. + assert await service.sign_unsigned_pending() == (0, 0) + + # The signed item is now an ordinary pending work item for the operator. + items, _total = await service.list_items(status="pending", wallet_id=wallet_id) + assert [item.receipt_id for item in items] == [record.response_reference] + assert await get_receipt_service_verifies(record.response_reference) + + # And the operator retry refunds that charged row and no additional row. + item, already = await service.retry(record.response_reference) + assert item.status == "resolved" + assert already is False + async with get_session_factory()() as session: + refunds = int( + await session.scalar( + select(func.count()) + .select_from(LedgerEntryModel) + .where( + LedgerEntryModel.wallet_id == wallet_id, + LedgerEntryModel.action == "refund", + ) + ) + or 0 + ) + assert refunds == 1 + + +async def get_receipt_service_verifies(receipt_id: str) -> bool: + from app.services.receipts import get_receipt_service + + async with get_session_factory()() as session: + receipt = await session.get(ReceiptModel, receipt_id) + assert receipt is not None + return await get_receipt_service().verify_model(receipt, session=session) + + +@pytest.mark.anyio +async def test_a_tampered_stored_payload_is_never_signed( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """The signer refuses a payload that no longer hashes to the caller's response. + + The unsigned item keeps the response payload and, separately, its hash as + recorded when the call failed. If the stored payload changes afterwards (a + JSON round trip that alters a value, or an edit), signing it would put the + gateway's signature on a response the caller never got. The item stays + unsigned and the record is left exactly as it was. + """ + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-tampered" + ) + record = await _record_for("refund-unsigned-tampered") + stored = json.loads(record.response_json or "{}") + # The injected fault: change the stored payload, not the recorded hash. + stored[UNSIGNED_RECEIPT_KEY]["inputs"]["response_payload"] = { + "error": "not what the caller was told" + } + tampered_json = json.dumps(stored) + async with get_session_factory()() as session: + row = await session.get(IdempotencyRecordModel, record.record_id) + assert row is not None + row.response_json = tampered_json + session.add(row) + await session.commit() + receipts_before = await _count(ReceiptModel) + # A key that can sign, so the hash check is the only thing that refuses. + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + ( + signed, + still_unsigned, + ) = await get_refund_reconciliation_service().sign_unsigned_pending() + + assert (signed, still_unsigned) == (0, 1) + assert await _count(ReceiptModel) == receipts_before + after = await _record_for("refund-unsigned-tampered") + assert after.response_reference is None + assert after.response_json == tampered_json + assert after.status_code == record.status_code + + +@pytest.mark.anyio +async def test_a_receipt_signed_later_carries_the_fields_the_signed_path_writes( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """Signing later must not lose or change what the receipt says about the call. + + Two calls on the same wallet, permit and tool, both ending refund-failed. + The first keeps its key and gets its ``failed_unrefunded`` receipt on the + spot. The second loses its key, is recorded unsigned, and is signed by + ``sign_unsigned_pending``. Every receipt column that describes the call + is compared; only the columns that identify the individual call differ. + """ + state = key_lost_mid_call_tool + ctx = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=ctx["agent_wallet_id"], + key_id=ctx["key_id"], + tool_name=TOOL_NAME, + max_credits=10, + idem_key="refund-unsigned-fields-permit", + ) + state["key_id"] = (await get_signing_key_service().ensure_active_key()).key_id + + async def call(key: str) -> IdempotencyRecordModel: + body = { + "jsonrpc": "2.0", + "id": "call-fields", + "method": "tools/call", + "params": { + "name": TOOL_NAME, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "permit_id": permit["permit_id"], + "idempotency_key": key, + }, + }, + } + with patch( + "app.services.agent_money.AgentMoney.refund_charge", _failing_refund + ): + resp = await client.post( + "/mcp/messages", json=body, headers=ctx["agent_headers"] + ) + assert resp.json()["error"]["data"]["refund_reconciliation"]["status"] == ( + "pending" + ), resp.text + return await _record_for(key) + + state["lose_key"] = False + signed_record = await call("refund-unsigned-fields-signed") + assert signed_record.response_reference is not None + + state["lose_key"] = True + unsigned_record = await call("refund-unsigned-fields-later") + assert unsigned_record.response_reference is None + await _set_key_status(state["key_id"], "active") + assert await get_refund_reconciliation_service().sign_unsigned_pending() == (1, 0) + later_record = await _record_for("refund-unsigned-fields-later") + assert later_record.response_reference is not None + + async with get_session_factory()() as session: + on_the_spot = await session.get(ReceiptModel, signed_record.response_reference) + later = await session.get(ReceiptModel, later_record.response_reference) + assert on_the_spot is not None and later is not None + + # Columns that name the individual call, checked against that call. + per_call = { + "receipt_id", + "idempotency_record_id", + "ledger_entry_id", + "audit_event_id", + "request_hash", + "response_hash", + "created_at", + "signature", + } + same = set(ReceiptModel.model_fields) - per_call + assert { + "tool", + "key_id", + "counterparty", + "dispatch_attempt_id", + "approval_id", + "permit_id", + "wallet_id", + "outcome", + "reason_code", + "credits_authorized", + "credits_charged", + } <= same + differing = { + name: (getattr(on_the_spot, name), getattr(later, name)) + for name in sorted(same) + if getattr(on_the_spot, name) != getattr(later, name) + } + assert differing == {} + assert later.tool == TOOL_NAME + assert later.key_id == ctx["key_id"] + assert later.idempotency_record_id == later_record.record_id + assert later.ledger_entry_id == later_record.ledger_entry_id + assert later.request_hash == later_record.request_hash + # Known limitation: the key was + # lost before the pending audit event could be signed, so the later + # receipt links no audit event. The on-the-spot receipt links its own. + assert on_the_spot.audit_event_id is not None + assert later.audit_event_id is None + + +@pytest.mark.anyio +async def test_the_periodic_cleanup_runs_the_unsigned_signer( + clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """``sign_unsigned_pending`` only helps if the cleanup loop calls it. + + Runs the application lifespan with the loop's 300 second wait shortened to + nothing for one pass, and observes the signer being called. The signer is + replaced at class level so the pass itself is the thing under test. + """ + import asyncio + + import app.main as main_module + + called = asyncio.Event() + real_sleep = asyncio.sleep + long_waits = 0 + + async def one_pass_sleep(delay: float, result: Any = None) -> Any: + nonlocal long_waits + if delay >= 60: + long_waits += 1 + if long_waits > 1: + # Second wait of the loop: block until shutdown cancels it. + await asyncio.Event().wait() + return result + return await real_sleep(delay, result) + + async def observed(self: RefundReconciliationService, **_kwargs: Any): + called.set() + return (0, 0) + + async def no_upstream(settings: Any = None) -> None: + return None + + monkeypatch.setattr(main_module.asyncio, "sleep", one_pass_sleep) + monkeypatch.setattr(RefundReconciliationService, "sign_unsigned_pending", observed) + monkeypatch.setattr( + "app.services.upstream_mcp.register_configured_upstream_mcp", no_upstream + ) + + async with main_module.lifespan(main_module.app): + await asyncio.wait_for(called.wait(), timeout=10) + + +@pytest.mark.anyio +async def test_an_item_that_can_never_be_signed_does_not_block_newer_items( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """The scan moves past an item it refuses, within the same pass. + + The oldest unsigned item is made permanently unsignable (its stored + payload no longer matches its recorded hash). A newer item is signable. + With a page size of one, a scan that re-selected the oldest items on every + pass would never reach the newer one, which would then stay invisible to + the operator refund list for good. + """ + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-blocked-old" + ) + old = await _record_for("refund-unsigned-blocked-old") + stored = json.loads(old.response_json or "{}") + stored[UNSIGNED_RECEIPT_KEY]["inputs"]["response_payload"] = { + "error": "not what the caller was told" + } + async with get_session_factory()() as session: + row = await session.get(IdempotencyRecordModel, old.record_id) + assert row is not None + row.response_json = json.dumps(stored) + session.add(row) + await session.commit() + + # The first call disabled the key; the second call needs it to be admitted. + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + await _run_call_that_loses_its_key( + client, key_lost_mid_call_tool, key="refund-unsigned-blocked-new" + ) + new = await _record_for("refund-unsigned-blocked-new") + assert (old.created_at, old.record_id) < (new.created_at, new.record_id) + await _set_key_status(key_lost_mid_call_tool["key_id"], "active") + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=1) == (1, 1) + + assert (await _record_for("refund-unsigned-blocked-old")).response_reference is None + signed = await _record_for("refund-unsigned-blocked-new") + assert signed.response_reference is not None + assert UNSIGNED_RECEIPT_KEY not in json.loads(signed.response_json or "{}") + # The blocked item is still counted on every later pass, never signed. + assert await service.sign_unsigned_pending(limit=1) == (0, 1) + + +@contextmanager +def _statements_sent() -> Iterator[list[str]]: + """Collect the text of every statement the engine is sent while open.""" + engine = get_engine() + assert engine is not None + sent: list[str] = [] + + def note( + _conn: Any, + _cursor: Any, + statement: str, + _parameters: Any, + _context: Any, + _executemany: bool, + ) -> None: + sent.append(statement) + + event.listen(engine.sync_engine, "before_cursor_execute", note) + try: + yield sent + finally: + event.remove(engine.sync_engine, "before_cursor_execute", note) + + +@pytest.fixture +def strict_trust_mode(monkeypatch: pytest.MonkeyPatch) -> None: + """The shipped trust flags, which the suite's conftest relaxes. + + Under the relaxed flags the denial of a call without a permit is not + stored. A deployment in trust mode has a configured signing key, so one is + generated here, as ``strict_trust_mode`` in test_mcp_trust_mode does. The + signing service drops the key it had loaded and takes the configured id. + """ + raw_private_key = Ed25519PrivateKey.generate().private_bytes( + Encoding.Raw, PrivateFormat.Raw, NoEncryption() + ) + monkeypatch.setattr(mcp_router.settings, "TRUST_MODE_ENABLED", True) + monkeypatch.setattr(mcp_router.settings, "ALLOW_LEGACY_UNPERMITTED_MCP", False) + monkeypatch.setattr( + mcp_router.settings, + "TRUST_SIGNING_PRIVATE_KEY_B64", + base64.b64encode(raw_private_key).decode(), + ) + signing_keys = get_signing_key_service() + monkeypatch.setattr(signing_keys, "_private_key", None) + monkeypatch.setattr( + signing_keys, "_key_id", mcp_router.settings.TRUST_SIGNING_KEY_ID + ) + + +async def _record_of_a_call_to_an_unregistered_tool( + client: AsyncClient, ctx: dict[str, Any], *, tool_name: str, key: str +) -> IdempotencyRecordModel: + """Call a tool nobody registered and return the record of the denial. + + The call carries an idempotency key and no permit. It needs + ``strict_trust_mode``: under the suite's relaxed flags nothing is stored. + """ + resp = await client.post( + "/mcp/messages", + json={ + "jsonrpc": "2.0", + "id": f"call-{key}", + "method": "tools/call", + "params": { + "name": tool_name, + "arguments": {}, + "mcpContext": { + "wallet_id": ctx["agent_wallet_id"], + "idempotency_key": key, + }, + }, + }, + headers=ctx["agent_headers"], + ) + assert resp.json()["error"]["message"] == "Tool not found", resp.text + record = await _record_for(key) + # What the gateway stored: a completed denial that repeats the caller's + # tool name, with no charge and no receipt. + assert json.loads(record.response_json or "{}")["error"] == ( + f"Tool not found: {tool_name}" + ) + assert record.ledger_entry_id is None + assert record.response_reference is None + return record + + +@pytest.mark.anyio +async def test_a_denial_that_repeats_the_marker_name_is_not_an_unsigned_item( + client: AsyncClient, + clean_database: None, + strict_trust_mode: None, + key_lost_mid_call_tool, +) -> None: + """Only a charged record can be an unsigned pending refund. + + A call to a tool that is not registered, made with an idempotency key and + no permit, is completed with ``Tool not found: `` and is not charged. + The caller picks the name, so the stored text can contain the marker's + name in quotes, which is the text the signer's page looks for. Such a + record used to be on a page of every pass on every replica, to be read, + parsed and dropped, so one wallet key could grow the cost of every pass at + no charge. ``_`` is a LIKE wildcard, so a name with any other character in + its place was returned as well. + + Under the shipped trust flags, one denial of each kind is stored on either + side of a real unsigned item. The page holds the real item alone, the pass + signs it, and the denials are left as they were. + + Both denials are uncharged, so the charge test alone keeps them off the + page, and neither has a dispatch attempt for the reconciler to look at. No + record the gateway writes can tell the escaped match from the plain one, + or the reconciler's three tests from the single one it had, so the two + statements are checked as well: the page escapes its match, and the + reconciler leaves an attempt out only on the same three tests, each a + separate alternative. + """ + state = key_lost_mid_call_tool + caller = await provision_agent_wallet(client) + + # The name ends the stored JSON string, so that string's closing quote + # completes the marker's name in quotes. + exact = await _record_of_a_call_to_an_unregistered_tool( + client, + caller, + tool_name=f'x"{UNSIGNED_RECEIPT_KEY}', + key="refund-unsigned-denied-exact", + ) + assert f'"{UNSIGNED_RECEIPT_KEY}"' in (exact.response_json or "") + + await _run_call_that_loses_its_key( + client, state, key="refund-unsigned-among-denials" + ) + real = await _record_for("refund-unsigned-among-denials") + assert real.ledger_entry_id is not None + assert UNSIGNED_RECEIPT_KEY in json.loads(real.response_json or "{}") + # That call disabled the key; the rest of the test needs it usable again. + await _set_key_status(state["key_id"], "active") + + one_character_off = UNSIGNED_RECEIPT_KEY.replace("_", "X") + wildcard = await _record_of_a_call_to_an_unregistered_tool( + client, + caller, + tool_name=f'x"{one_character_off}', + key="refund-unsigned-denied-wildcard", + ) + assert f'"{one_character_off}"' in (wildcard.response_json or "") + assert f'"{UNSIGNED_RECEIPT_KEY}"' not in (wildcard.response_json or "") + + in_scan_order = [ + (record.created_at, record.record_id) for record in (exact, real, wildcard) + ] + assert in_scan_order == sorted(in_scan_order) + + with _statements_sent() as sent: + page = await RefundReconciliationService._unsigned_page(after=None, limit=50) + await get_mcp_dispatch_attempt_service().list_unfinalized_terminal_contexts( + idle_seconds=0 + ) + assert [record.record_id for record in page] == [real.record_id] + matching = [statement for statement in sent if " LIKE " in statement] + assert len(matching) == 2, sent + page_statement, reconciler_statement = matching + assert " NOT LIKE " not in page_statement + assert " ESCAPE " in page_statement + for alternative in ( + "response_json IS NULL OR ", + "response_reference IS NOT NULL OR ", + "ledger_entry_id IS NULL OR ", + ): + assert alternative in reconciler_statement, reconciler_statement + assert " NOT LIKE " in reconciler_statement + assert " ESCAPE " in reconciler_statement + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=1) == (1, 0) + signed = await _record_for("refund-unsigned-among-denials") + assert signed.response_reference is not None + for denial in (exact, wildcard): + unchanged = await _record_for(denial.idempotency_key) + assert unchanged.response_json == denial.response_json + assert unchanged.response_reference is None + assert await service.sign_unsigned_pending(limit=1) == (0, 0) + + +@pytest.mark.anyio +async def test_a_pass_reads_items_recorded_at_the_same_instant_once_each( + client: AsyncClient, clean_database: None, key_lost_mid_call_tool +) -> None: + """Paging stays exact when unsigned items share a ``created_at``. + + Each page after the first is bounded below by the last ``created_at`` the + scan has read, so the database can seek into the ``created_at`` index, and + a tie on that instant is broken on ``record_id``. A bound that left the + instant itself out would skip the items that share it. Five unsigned items + are recorded and the middle three are given the same ``created_at``. Pages + of one, two and fifty then read each item one time, in order, and one + pass signs them all. The bound changes no result, so the statements are + checked for it as well. + """ + state = key_lost_mid_call_tool + keys = [f"refund-unsigned-tied-{index}" for index in range(5)] + for key in keys: + await _run_call_that_loses_its_key(client, state, key=key) + # Each call disabled the key; the next call and the signing pass need it. + await _set_key_status(state["key_id"], "active") + + recorded = [await _record_for(key) for key in keys] + # The injected condition: three records written in the same instant. + tied_at = recorded[2].created_at + async with get_session_factory()() as session: + for record in (recorded[1], recorded[3]): + row = await session.get(IdempotencyRecordModel, record.record_id) + assert row is not None + row.created_at = tied_at + session.add(row) + await session.commit() + recorded = [await _record_for(key) for key in keys] + assert [record.created_at for record in recorded[1:4]] == [tied_at] * 3 + assert recorded[0].created_at < tied_at < recorded[4].created_at + expected = [ + record.record_id + for record in sorted( + recorded, key=lambda record: (record.created_at, record.record_id) + ) + ] + + async def read_every_page(limit: int) -> list[str]: + seen: list[str] = [] + after: tuple[Any, str] | None = None + while True: + page = await RefundReconciliationService._unsigned_page( + after=after, limit=limit + ) + if not page: + return seen + assert len(page) <= limit + seen.extend(record.record_id for record in page) + # A page that stops advancing fails here; it does not hang. + assert len(seen) <= len(expected), limit + after = (page[-1].created_at, page[-1].record_id) + + for limit in (2, 50): + assert await read_every_page(limit) == expected, limit + with _statements_sent() as sent: + assert await read_every_page(1) == expected + pages = [statement for statement in sent if " LIKE " in statement] + assert len(pages) == len(expected) + 1, sent + assert "created_at >= " not in pages[0] + assert all("created_at >= " in statement for statement in pages[1:]), pages + + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending(limit=2) == (5, 0) + assert await service.sign_unsigned_pending(limit=2) == (0, 0)