diff --git a/gateway/app/services/refund_reconciliation.py b/gateway/app/services/refund_reconciliation.py index 404e8c6c2..d49e90fa1 100644 --- a/gateway/app/services/refund_reconciliation.py +++ b/gateway/app/services/refund_reconciliation.py @@ -454,8 +454,68 @@ def retired_under_the_attempt(exc: BaseException) -> bool: response_hash=sha256_hex(effective_payload), signing_error=str(exc), ) + if reconciliation is None: + # Nothing is owed any more (see _record_unsigned_pending), so + # no work item is stored. The signing error stands as it did + # before unsigned items existed: the record stays open and the + # dispatch reconciler writes the failed_refunded receipt from + # a replica whose key can sign. + logger.warning( + "refund_reconciliation_unsigned_not_recorded_already_refunded", + extra={ + "ledger_entry_id": ledger_entry_id, + "dispatch_attempt_id": dispatch_attempt_id, + }, + ) + raise return None, reconciliation + @staticmethod + async def _refund_and_release_state( + session: AsyncSession, + inputs: dict[str, Any], + *, + lock_attempt: bool = False, + ) -> tuple[bool, bool]: + """``(refund landed, reservation released)`` for this charge. + + The reservation counts as released when the dispatch attempt says so. + Without a dispatch attempt nothing but the operator retry releases it. + ``lock_attempt`` reads the attempt under a row lock, so that a caller + about to write on the strength of the answer does not race the + checkpoint and release writes, which take the same row. + """ + ledger_entry_id = inputs["ledger_entry_id"] + 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, False + attempt_id = inputs.get("dispatch_attempt_id") + if not attempt_id: + return True, False + attempt = await session.get( + McpDispatchAttemptModel, attempt_id, with_for_update=lock_attempt + ) + return True, attempt is not None and attempt.budget_released_at is not None + @staticmethod async def _refund_landed_and_budget_released(inputs: dict[str, Any]) -> bool: """Whether this charge was refunded *and* its reservation released. @@ -469,49 +529,20 @@ async def _refund_landed_and_budget_released(inputs: dict[str, Any]) -> bool: 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 + state = RefundReconciliationService._refund_and_release_state + landed, released = await state(session, inputs) + if landed and not released and inputs.get("dispatch_attempt_id"): + logger.warning( + "refund_reconciliation_unsigned_refund_unacknowledged", + extra={ + "ledger_entry_id": inputs["ledger_entry_id"], + "dispatch_attempt_id": inputs["dispatch_attempt_id"], + }, + ) + return landed and released async def _record_unsigned_pending( self, @@ -520,7 +551,7 @@ async def _record_unsigned_pending( inputs: dict[str, Any], response_hash: str, signing_error: str, - ) -> dict[str, Any]: + ) -> dict[str, Any] | None: """Store the pending refund without a receipt, in one transaction. The work item names no receipt yet (``receipt_id`` ``None``) and the @@ -530,13 +561,30 @@ async def _record_unsigned_pending( 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). + + Returns ``None`` and stores nothing when the charge was already + refunded and its reservation released (issue #435). The dispatch + reconciler can get to the attempt between the failed live refund and + this write, through a retry of the same key or through its sweep, and + give both back while the record is still open. An item stored after + that would list a debt that is gone: no receipt could ever be signed + for it, and it would keep the reconciler from writing the + ``failed_refunded`` receipt. The check runs inside the write's + transaction, after the record lock and with the attempt locked, so + each restart repeats it and a release that already committed is + always seen. """ factory = get_session_factory() - async def attempt() -> dict[str, Any]: + async def attempt() -> dict[str, Any] | None: async with factory() as session: async with session.begin(): record = await validated_checkpoint(session, lock=True) + landed, released = await self._refund_and_release_state( + session, inputs, lock_attempt=True + ) + if landed and released: + return None reconciliation = build_pending_refund_reconciliation( receipt_id=None, wallet_id=inputs["wallet_id"], diff --git a/gateway/tests/test_unsigned_pending_refund_followups.py b/gateway/tests/test_unsigned_pending_refund_followups.py new file mode 100644 index 000000000..9ee4adf46 --- /dev/null +++ b/gateway/tests/test_unsigned_pending_refund_followups.py @@ -0,0 +1,625 @@ +"""Follow-ups to the unsigned pending refund (issue #435). + +An upstream call is charged, the upstream returns an error, and the live +refund fails. When the receipt of that failure cannot be signed, the pending +refund is stored without one (``create_pending``, issue #280). These tests +cover what the first round left open: + +* the dispatch reconciler can refund the charge and release the reservation + between the failed live refund and that write. Nothing may be stored then; +* the signing key can become unusable before the terminal audit event, so the + refund-failed path never reaches the write; +* a second key can sign the item while the key that signed the permit stays + disabled; +* the refund checkpoint can commit and the request still see an exception; +* which attempts the dispatch reconciler lists, by what it returns. + +Faults are injected at class or module level only. Every wallet, charge, +refund, receipt and record is written by the gateway. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from decimal import Decimal +import json +from typing import Any + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import select + +from app.db.database import get_session_factory +from app.db.models import ( + IdempotencyRecordModel, + McpDispatchAttemptModel, + 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.services.agent_money import AgentMoney +from app.services.mcp_dispatch_attempts import ( + McpDispatchAttemptService, + get_mcp_dispatch_attempt_service, +) +from app.services.mcp_dispatch_reconciliation import ( + get_mcp_dispatch_reconciliation_service, +) +from app.services.permits import get_permit_service +from app.services.refund_reconciliation import ( + UNSIGNED_RECEIPT_KEY, + RefundReconciliationError, + 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_mcp_upstream_governed import ( + FakeUpstreamExecutor, + _backdate_attempt, + _call_body, + _register_upstream, + _set_signing_key_status, + _wallet_state, +) +from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet + +Competitor = Callable[[str], Awaitable[None]] + + +@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 _retry_of_the_same_key(attempt_id: str) -> None: + """What a retry with the same idempotency key does to a terminal attempt. + + ``IdempotencyService`` hands the attempt to the dispatch reconciler and + goes on waiting when that fails, as it does here once the reconciler gets + to the receipt: this replica's key cannot sign. + """ + try: + await get_mcp_dispatch_reconciliation_service().reconcile_attempt(attempt_id) + except Exception: # noqa: BLE001 - the retry path absorbs it the same way + pass + + +async def _sweep_after_a_stall(attempt_id: str) -> None: + """The periodic sweep, reaching an attempt whose request stalled.""" + await _backdate_attempt(attempt_id) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + +async def _upstream_refund_failure( + client: AsyncClient, + *, + suffix: str, + refund_fault: str, + key_lost: str, + key_status: str = "disabled", + competitor: Competitor | None = None, +) -> dict[str, Any]: + """A real upstream call that errors and whose live refund fails once. + + ``refund_fault`` picks what fails in the live refund: + + * ``refund``: the refund itself, so the charge stands; + * ``checkpoint``: the refund lands and its checkpoint on the dispatch + attempt (``mark_debit_refunded``) does not commit; + * ``after_checkpoint``: the refund lands, the checkpoint commits, and the + request sees an exception all the same. + + Only the first call fails, so a competitor that runs later can refund. + + ``key_lost`` sets this replica's signing key row to ``key_status`` either + ``before_audit`` or ``after_audit``, relative to the terminal audit event + of the refund-failed path. ``competitor`` runs between that audit event + and ``create_pending``, with the dispatch attempt id. + """ + provisioned = await provision_agent_wallet(client) + wallet_id = provisioned["agent_wallet_id"] + tool_name = f"partner-upstream-followup-{suffix}" + executor = FakeUpstreamExecutor("returned_error") + _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-followup-{suffix}-permit", + ) + 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 + real_finalize = mcp_router._finalize_unrefunded_failure + real_refund = AgentMoney.refund_charge + real_checkpoint = McpDispatchAttemptService.mark_debit_refunded + failed: set[str] = set() + + async def audit_and_lose_key(**kwargs: Any) -> Any: + refund_failed = str(kwargs.get("error") or "").startswith("refund_failed") + if refund_failed and key_lost == "before_audit": + await _set_signing_key_status(signing_key.key_id, key_status) + event = await real_audit(**kwargs) + if refund_failed and key_lost == "after_audit": + await _set_signing_key_status(signing_key.key_id, key_status) + return event + + async def compete_then_finalize(**kwargs: Any) -> Any: + if competitor is not None: + await competitor(kwargs["dispatch_attempt_id"]) + return await real_finalize(**kwargs) + + async def refund_failing_once(self: AgentMoney, **kwargs: Any) -> Any: + if "refund" not in failed: + failed.add("refund") + raise RuntimeError("refund unavailable") + return await real_refund(self, **kwargs) + + async def checkpoint_failing_once( + self: McpDispatchAttemptService, **kwargs: Any + ) -> Any: + if "checkpoint" in failed: + return await real_checkpoint(self, **kwargs) + failed.add("checkpoint") + if refund_fault == "after_checkpoint": + await real_checkpoint(self, **kwargs) + raise RuntimeError("refund checkpoint unavailable") + + body = _call_body( + tool_name=tool_name, + wallet_id=wallet_id, + permit_id=permit["permit_id"], + idempotency_key=f"partner-upstream-followup-{suffix}-1", + ) + with pytest.MonkeyPatch.context() as patched: + patched.setattr(mcp_router, "_audit_mcp_invocation", audit_and_lose_key) + patched.setattr( + mcp_router, "_finalize_unrefunded_failure", compete_then_finalize + ) + if refund_fault == "refund": + patched.setattr(AgentMoney, "refund_charge", refund_failing_once) + else: + patched.setattr( + McpDispatchAttemptService, + "mark_debit_refunded", + checkpoint_failing_once, + ) + response = await client.post( + "/mcp/messages", json=body, headers=provisioned["agent_headers"] + ) + assert failed, "the injected refund fault never ran" + async with get_session_factory()() as session: + record = ( + await session.execute( + select(IdempotencyRecordModel).where( + IdempotencyRecordModel.idempotency_key + == body["params"]["mcpContext"]["idempotency_key"] + ) + ) + ).scalar_one() + attempt = ( + await session.execute( + select(McpDispatchAttemptModel).where( + McpDispatchAttemptModel.idempotency_record_id == record.record_id + ) + ) + ).scalar_one() + assert attempt.state == "returned_error" + return { + "wallet_id": wallet_id, + "headers": provisioned["agent_headers"], + "tool_name": tool_name, + "executor": executor, + "permit_id": permit["permit_id"], + "attempt_id": attempt.attempt_id, + "record_id": record.record_id, + "key_id": signing_key.key_id, + "balance_before": balance_before, + "refunds_before": refunds_before, + "body": body, + "error": response.json()["error"], + } + + +async def _record(record_id: str) -> IdempotencyRecordModel: + async with get_session_factory()() as session: + record = await session.get(IdempotencyRecordModel, record_id) + assert record is not None + return record + + +async def _attempt(attempt_id: str) -> McpDispatchAttemptModel: + async with get_session_factory()() as session: + attempt = await session.get(McpDispatchAttemptModel, attempt_id) + assert attempt is not None + return attempt + + +async def _receipts_of(attempt_id: str) -> list[ReceiptModel]: + async with get_session_factory()() as session: + return list( + ( + await session.execute( + select(ReceiptModel).where( + ReceiptModel.dispatch_attempt_id == attempt_id + ) + ) + ) + .scalars() + .all() + ) + + +async def _spent(permit_id: str) -> Decimal: + permit = await get_permit_service().get_permit(permit_id) + assert permit is not None + return Decimal(str(permit.spent_credits)) + + +async def _sweep(attempt_id: str) -> None: + await _backdate_attempt(attempt_id) + await get_mcp_dispatch_reconciliation_service().reconcile(idle_seconds=300) + + +@pytest.mark.anyio +@pytest.mark.parametrize("refund_fault", ["refund", "checkpoint"]) +@pytest.mark.parametrize( + "competitor", + [_retry_of_the_same_key, _sweep_after_a_stall], + ids=["same_key_retry", "sweep"], +) +async def test_no_unsigned_pending_refund_is_stored_for_a_charge_already_refunded( + client: AsyncClient, + clean_database: None, + refund_fault: str, + competitor: Competitor, +) -> None: + """The record matches the ledger when the reconciler gets there first. + + The live refund fails, the terminal audit event is written, and the key is + disabled. Before ``create_pending`` runs, the dispatch reconciler handles + the attempt, through a retry of the same key or through its sweep: it + refunds the charge and releases the reservation, and cannot write the + receipt. ``create_pending`` then cannot sign either. It used to store + "refund pending, receipt unsigned" for that charge: an item that no pass + would ever sign, that the reconciler skipped and that no operator list + showed, while a replay kept answering that a refund was pending. + + Now nothing is stored. The call fails as it did before unsigned items + existed, the record stays open, and the reconciler writes the + ``failed_refunded`` receipt once a key can sign. + """ + case = await _upstream_refund_failure( + client, + suffix=f"refunded-{refund_fault}-{competitor.__name__.strip('_')}", + refund_fault=refund_fault, + key_lost="after_audit", + competitor=competitor, + ) + try: + # The competitor gave back the money and the reservation, once. + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == 0 + attempt = await _attempt(case["attempt_id"]) + assert attempt.debit_refunded_at is not None + assert attempt.budget_released_at is not None + + # No work item for a debt that is gone, and no pending answer: the + # caller gets the unclassified error a signing failure gave before. + assert case["error"]["code"] == -32603 + assert case["error"]["message"] == INTERNAL_ERROR_MESSAGE + record = await _record(case["record_id"]) + assert record.response_json is None + assert record.response_reference is None + assert "refund_reconciliation" not in json.dumps(case["error"]) + assert await _receipts_of(case["attempt_id"]) == [] + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (0, 0) + items, _total = await service.list_items(status="pending") + assert items == [] + + await _sweep(case["attempt_id"]) + (receipt,) = await _receipts_of(case["attempt_id"]) + assert receipt.outcome == "failed_refunded" + record = await _record(case["record_id"]) + assert record.response_reference == receipt.receipt_id + + replay = await client.post( + "/mcp/messages", json=case["body"], headers=case["headers"] + ) + replayed = replay.json()["error"]["data"] + assert replayed["receipt"]["receipt_id"] == receipt.receipt_id + assert replayed["receipt"]["outcome"] == "failed_refunded" + assert "refund_reconciliation" not in replayed + assert case["executor"].dispatch_count == 1 + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_a_reservation_still_held_keeps_the_unsigned_pending_refund( + client: AsyncClient, clean_database: None +) -> None: + """The guard needs the refund *and* the release, not the refund alone. + + Here the refund lands and its checkpoint commits, and the request sees an + exception all the same. No test made the checkpoint commit before: the + lost acknowledgement tests replace it with a function that only raises. + The money is back and the reservation is still held, so the item is owed + an operator retry and is stored. Signed, that retry refunds nothing more + and releases the reservation once. + + The dispatch sweep is not run between the call and the retry: what it does + to a checkpointed refund whose reservation is held is issue #434. + """ + case = await _upstream_refund_failure( + client, + suffix="after-checkpoint", + refund_fault="after_checkpoint", + key_lost="after_audit", + ) + try: + reconciliation = case["error"]["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending" + assert reconciliation["receipt_status"] == "unsigned" + stored = json.loads((await _record(case["record_id"])).response_json or "{}") + assert UNSIGNED_RECEIPT_KEY in stored + attempt = await _attempt(case["attempt_id"]) + assert attempt.debit_refunded_at is not None + assert attempt.budget_released_at is None + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == Decimal("2") + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (1, 0) + (receipt,) = await _receipts_of(case["attempt_id"]) + 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, + ) + assert await _spent(case["permit_id"]) == 0 + _item, already = await service.retry(receipt.receipt_id) + assert already is True + assert await _spent(case["permit_id"]) == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_a_second_key_signs_while_the_permit_key_stays_disabled( + client: AsyncClient, clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """Current behavior of the open question in issue #435, part 2. + + Every earlier test set the first key back to ``active`` before it signed + or refunded an unsigned item. Here it stays ``disabled`` and the replica + comes back with a second key, which signs the item. The operator retry + then refuses with ``refund_reconciliation_permit_invalid``, because the + permit was signed by the disabled key, and the charge stays unrefunded for + as long as that key row stays ``disabled``. Once the row is ``active`` + again, one retry refunds the charge once. + + Whether the retry should depend on that key's status is undecided. This + test records what the gateway does today. It does not settle the question. + """ + case = await _upstream_refund_failure( + client, suffix="second-key", refund_fault="refund", key_lost="after_audit" + ) + try: + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (0, 1) + + # The replica restarts with new key material. The signing service + # generates it and registers it under its own key id. Both fields are + # put back afterwards, so later tests sign with the first key again. + signing_keys = get_signing_key_service() + monkeypatch.setattr(signing_keys, "_key_id", signing_keys._key_id) + monkeypatch.setattr(signing_keys, "_private_key", None) + second_key = await signing_keys.ensure_active_key() + assert second_key.key_id != case["key_id"] + + assert await service.sign_unsigned_pending() == (1, 0) + (receipt,) = await _receipts_of(case["attempt_id"]) + assert receipt.outcome == "failed_unrefunded" + assert receipt.signature_key_id == second_key.key_id + async with get_session_factory()() as session: + first_key = await session.get(SigningKeyModel, case["key_id"]) + assert first_key is not None and first_key.status == "disabled" + + with pytest.raises(RefundReconciliationError) as refused: + await service.retry(receipt.receipt_id) + assert refused.value.reason == "refund_reconciliation_permit_invalid" + assert refused.value.status_code == 409 + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"] - Decimal("2"), + case["refunds_before"], + ) + assert await _spent(case["permit_id"]) == Decimal("2") + + await _set_signing_key_status(case["key_id"], "active") + item, already = await service.retry(receipt.receipt_id) + assert item.status == "resolved" and already is False + _item, already = await service.retry(receipt.receipt_id) + assert already is True + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_a_key_disabled_before_the_terminal_audit_leaves_it_to_the_reconciler( + client: AsyncClient, clean_database: None +) -> None: + """The key is disabled before the audit write, not right after it. + + The audit event cannot be signed, so the refund-failed path stops there: + the call fails with no receipt and no work item, and the record stays + open. The dispatch reconciler owns the attempt. Its first pass refunds the + charge and releases the reservation, and cannot write the evidence. Once + the key can sign, a pass writes one ``failed_refunded`` receipt and + completes the record. + """ + case = await _upstream_refund_failure( + client, + suffix="before-audit-disabled", + refund_fault="refund", + key_lost="before_audit", + ) + try: + assert "refund_reconciliation" not in json.dumps(case["error"]) + record = await _record(case["record_id"]) + assert record.response_json is None + assert await _receipts_of(case["attempt_id"]) == [] + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"] - Decimal("2"), + case["refunds_before"], + ) + assert await _spent(case["permit_id"]) == Decimal("2") + + await _sweep(case["attempt_id"]) + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == 0 + assert await _receipts_of(case["attempt_id"]) == [] + assert (await _record(case["record_id"])).response_json is None + + await _set_signing_key_status(case["key_id"], "active") + service = get_refund_reconciliation_service() + assert await service.sign_unsigned_pending() == (0, 0) + await _sweep(case["attempt_id"]) + (receipt,) = await _receipts_of(case["attempt_id"]) + assert receipt.outcome == "failed_refunded" + record = await _record(case["record_id"]) + assert record.response_reference == receipt.receipt_id + + await _sweep(case["attempt_id"]) + assert len(await _receipts_of(case["attempt_id"])) == 1 + assert await _wallet_state(case["wallet_id"]) == ( + case["balance_before"], + case["refunds_before"] + 1, + ) + assert await _spent(case["permit_id"]) == 0 + assert case["executor"].dispatch_count == 1 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_a_key_retired_before_the_terminal_audit_still_signs_the_pending_refund( + client: AsyncClient, clean_database: None +) -> None: + """A ``retired`` key row is not a lost key at this head. + + The signing service sets a ``retired`` row of its own key back to + ``active`` when it next signs, so the audit event and the + ``failed_unrefunded`` receipt are signed as usual and the charge waits + for an operator retry. + + This follows the signing service. Where a retired key refuses to sign, the + call ends as in the ``disabled`` test above. + """ + case = await _upstream_refund_failure( + client, + suffix="before-audit-retired", + refund_fault="refund", + key_lost="before_audit", + key_status="retired", + ) + try: + reconciliation = case["error"]["data"]["refund_reconciliation"] + assert reconciliation["status"] == "pending" + assert "receipt_status" not in reconciliation + (receipt,) = await _receipts_of(case["attempt_id"]) + assert receipt.outcome == "failed_unrefunded" + assert reconciliation["receipt_id"] == receipt.receipt_id + async with get_session_factory()() as session: + key = await session.get(SigningKeyModel, case["key_id"]) + assert key is not None and key.status == "active" + + service = get_refund_reconciliation_service() + 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, + ) + assert await _spent(case["permit_id"]) == 0 + finally: + get_service_registry().unregister_local(case["tool_name"]) + + +@pytest.mark.anyio +async def test_the_reconciler_lists_an_open_attempt_and_not_an_unsigned_item( + client: AsyncClient, clean_database: None +) -> None: + """Which terminal attempts the dispatch reconciler takes, by its result. + + Two attempts have no receipt. The first has an open record, with no + stored response at all: the key was disabled before the terminal audit + event. The second has an unsigned pending refund. The reconciler must + list the first, or nothing ever refunds it, and must leave the second to + the unsigned signer and the operator retry. + + The earlier test of this condition read the statement text, which a + reordering of the same logic breaks. This one reads the rows. + """ + open_case = await _upstream_refund_failure( + client, suffix="listed-open", refund_fault="refund", key_lost="before_audit" + ) + await _set_signing_key_status(open_case["key_id"], "active") + unsigned_case = await _upstream_refund_failure( + client, + suffix="listed-unsigned", + refund_fault="refund", + key_lost="after_audit", + ) + try: + assert (await _record(open_case["record_id"])).response_json is None + unsigned = json.loads( + (await _record(unsigned_case["record_id"])).response_json or "{}" + ) + assert UNSIGNED_RECEIPT_KEY in unsigned + + listed = ( + await get_mcp_dispatch_attempt_service().list_unfinalized_terminal_contexts( + idle_seconds=0 + ) + ) + + assert [context.attempt.attempt_id for context in listed] == [ + open_case["attempt_id"] + ] + finally: + get_service_registry().unregister_local(open_case["tool_name"]) + get_service_registry().unregister_local(unsigned_case["tool_name"])