Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
a573f96
fix(refunds): record a pending refund even when its receipt cannot be…
claude Nov 5, 2026
9943006
test(refunds): a tampered stored payload is never signed
claude Nov 5, 2026
1b7cc37
fix(refunds): give an unsigned pending refund a single owner
claude Nov 5, 2026
881028a
fix(refunds): sign an unsigned item whose refund landed but was never…
claude Nov 5, 2026
9baa043
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 18, 2026
eef58b5
test(refunds): pin the later-signed receipt's fields and the cleanup …
claude Nov 19, 2026
008ee3a
Merge remote-tracking branch 'origin/main' into claude/pending-refund…
claude Nov 19, 2026
9da448c
fix(refunds): scan every unsigned pending refund once per pass
claude Nov 19, 2026
dc47c68
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 24, 2026
a31694f
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
5d913c5
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
bdfd925
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 25, 2026
7ef97d7
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
18d785e
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
0c00379
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Nov 26, 2026
0c3790a
fix(refunds): only a charged record is an unsigned pending refund
claude Nov 27, 2026
893ac66
docs: say receipt ID and drop exactly-once claims
PetrefiedThunder Nov 27, 2026
707ba29
docs(refunds): do not promise the refund of an unsigned pending item
claude Nov 30, 2026
e0f675c
Merge branch 'main' into claude/pending-refund-unsigned
PetrefiedThunder Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions gateway/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
27 changes: 25 additions & 2 deletions gateway/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
26 changes: 25 additions & 1 deletion gateway/app/services/mcp_dispatch_attempts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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__)

Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading