Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 90 additions & 42 deletions gateway/app/services/refund_reconciliation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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"],
Expand Down
Loading
Loading