Skip to content
Merged
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
205 changes: 112 additions & 93 deletions gateway/app/services/permits.py
Original file line number Diff line number Diff line change
Expand Up @@ -1727,100 +1727,9 @@ async def _once() -> bool:
# Another caller claimed it first; its transaction owns
# the single decrement.
return False
# If this attempt holds a call slot, release it by decrementing
# the tool_call_counts_json counter. This happens in the same
# transaction as the budget release, so it's once-only.
permit_update_values: dict[str, Any] = {
"spent_credits": case(
(
cast(
ColumnElement[bool],
PermitModel.spent_credits
- attempt.credits_authorized
< Decimal("0"),
),
Decimal("0"),
),
else_=PermitModel.spent_credits
- attempt.credits_authorized,
),
"updated_at": now,
}

original_counts_json = None
if attempt.call_slot_reserved:
# Only release call slot if attempt never dispatched.
# A dispatched attempt consumed its slot even if it later
# errored and was refunded - the slot was used.
if attempt.dispatched_at is None:
# Pre-dispatch failure: release the call slot
permit = await session.get(PermitModel, attempt.permit_id)
if permit is not None:
original_counts_json = permit.tool_call_counts_json
current_counts = _loads_dict(
original_counts_json or "{}"
)
tool_name = attempt.public_tool_id
if tool_name in current_counts:
current_count = current_counts[tool_name]
if (
isinstance(current_count, int)
and current_count > 0
):
updated_counts = dict(current_counts)
updated_counts[tool_name] = current_count - 1
permit_update_values[
"tool_call_counts_json"
] = json.dumps(updated_counts)

# Atomic clamped decrement so a concurrent reservation on the
# same permit is not clobbered by a read-modify-write here.
# Add CAS on tool_call_counts_json when releasing a slot to
# prevent concurrent releases from clobbering each other.
where_conditions = [
cast(
ColumnElement[bool],
PermitModel.permit_id == attempt.permit_id,
)
]
if (
attempt.call_slot_reserved
and "tool_call_counts_json" in permit_update_values
):
# Add optimistic lock: only succeed if counts haven't changed
if original_counts_json is None:
where_conditions.append(
cast(
ColumnElement[bool],
cast(Any, PermitModel.tool_call_counts_json).is_(
None
),
)
)
else:
where_conditions.append(
cast(
ColumnElement[bool],
PermitModel.tool_call_counts_json
== original_counts_json,
)
)

released = await session.execute(
sa_update(PermitModel)
.where(*where_conditions)
.values(**permit_update_values)
.execution_options(synchronize_session=False)
await self.release_claimed_dispatch_reservation(
session, attempt, now=now
)
if (cast(Any, released).rowcount or 0) == 0:
# CAS failed - either permit doesn't exist or counts changed.
# Check if permit exists to distinguish the cases.
check_permit = await session.get(PermitModel, attempt.permit_id)
if check_permit is None:
raise PermitError("permit_not_found")
# Permit exists but CAS failed - counts changed concurrently.
# Raise a retryable error so _run_with_write_retry retries.
raise PermitWriteContendedError()
# budget_released_at was already set by the guarded claim
# above; refresh the identity-mapped instance so callers
# holding it observe the committed value.
Expand All @@ -1831,6 +1740,116 @@ async def _once() -> bool:

return await self._run_with_write_retry(_once)

async def release_claimed_dispatch_reservation(
self,
session: AsyncSession,
attempt: McpDispatchAttemptModel,
*,
now: datetime,
) -> None:
"""Give back one dispatch attempt's reservation inside ``session``.

The caller must already own the attempt's once-only claim: in this same
transaction it flipped ``budget_released_at`` from NULL. This is the
single place that decides what a release gives back, so every claimant
(``release_dispatch_budget_once`` and the operator refund retry) gives
back the same thing: ``credits_authorized`` from ``spent_credits``,
clamped at zero, and the per-tool call slot when the attempt reserved
one and never dispatched.

Raises ``PermitWriteContendedError`` when the call-slot compare and
swap misses; the caller's transaction must then roll back whole, claim
included.
"""
# If this attempt holds a call slot, release it by decrementing
# the tool_call_counts_json counter. This happens in the same
# transaction as the budget release, so it's once-only.
permit_update_values: dict[str, Any] = {
"spent_credits": case(
(
cast(
ColumnElement[bool],
PermitModel.spent_credits - attempt.credits_authorized
< Decimal("0"),
),
Decimal("0"),
),
else_=PermitModel.spent_credits - attempt.credits_authorized,
),
"updated_at": now,
}

original_counts_json = None
if attempt.call_slot_reserved:
# Only release call slot if attempt never dispatched.
# A dispatched attempt consumed its slot even if it later
# errored and was refunded - the slot was used.
if attempt.dispatched_at is None:
# Pre-dispatch failure: release the call slot. Read the
# counts fresh: the caller's session may already hold this
# permit from before its claim.
permit = await session.get(
PermitModel, attempt.permit_id, populate_existing=True
)
if permit is not None:
original_counts_json = permit.tool_call_counts_json
current_counts = _loads_dict(original_counts_json or "{}")
tool_name = attempt.public_tool_id
if tool_name in current_counts:
current_count = current_counts[tool_name]
if isinstance(current_count, int) and current_count > 0:
updated_counts = dict(current_counts)
updated_counts[tool_name] = current_count - 1
permit_update_values["tool_call_counts_json"] = json.dumps(
updated_counts
)

# Atomic clamped decrement so a concurrent reservation on the
# same permit is not clobbered by a read-modify-write here.
# Add CAS on tool_call_counts_json when releasing a slot to
# prevent concurrent releases from clobbering each other.
where_conditions = [
cast(
ColumnElement[bool],
PermitModel.permit_id == attempt.permit_id,
)
]
if (
attempt.call_slot_reserved
and "tool_call_counts_json" in permit_update_values
):
# Add optimistic lock: only succeed if counts haven't changed
if original_counts_json is None:
where_conditions.append(
cast(
ColumnElement[bool],
cast(Any, PermitModel.tool_call_counts_json).is_(None),
)
)
else:
where_conditions.append(
cast(
ColumnElement[bool],
PermitModel.tool_call_counts_json == original_counts_json,
)
)

released = await session.execute(
sa_update(PermitModel)
.where(*where_conditions)
.values(**permit_update_values)
.execution_options(synchronize_session=False)
)
if (cast(Any, released).rowcount or 0) == 0:
# CAS failed - either permit doesn't exist or counts changed.
# Check if permit exists to distinguish the cases.
check_permit = await session.get(PermitModel, attempt.permit_id)
if check_permit is None:
raise PermitError("permit_not_found")
# Permit exists but CAS failed - counts changed concurrently.
# Raise a retryable error so _run_with_write_retry retries.
raise PermitWriteContendedError()

async def _consumed_credits(self, session: Any, permit_id: str) -> Decimal:
"""Credits a permit's receipts prove it actually consumed.

Expand Down
Loading
Loading