[Bugfix] Compensate cancelled duplex open, append and resume; fix serving README drift (#7636 Issues 1, 2, 3, 21) (#7785)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-09-24 19:23:08 -07:00
1 parent 551a03102f
commit 9e7e3a802c
19 files changed
+1697 -96

No files matched your search

+5
View File
@@ -65,6 +65,11 @@ class TouchDuplexSessionMessage(EngineQueueMessage, kw_only=True):
control_id: str
session_id: str
activity: str
#: For a detach: the lease generation the caller opened or resumed
#: against. The manager refuses to detach a newer lease, so a connection
#: giving up its own resume can never put the lease a later resume owns
#: into disconnect grace. ``None`` detaches whatever generation is current.
expected_lease_generation: int | None = None
class DuplexSessionCommandMessage(EngineQueueMessage, kw_only=True):
+59 -11
View File
@@ -13,6 +13,13 @@ That compensation is the reason this is an object. The five steps of an append
all need the same eleven values, so as closures over ``_start_append`` they read
as one function with five entry points and no way to test any of them. Named
fields make the captured state explicit and the compensation a method.
The precreated response has two other owners the compensation defers to. When
the runner cancels the append on purpose (``DuplexSessionTasks.cancel_append_tasks``,
for a ``response.cancel``, a barge-in or a close), the runner ends that response
itself right after, with the cancel status the client asked for. When the
session is already closing, the close ends it. Everywhere else, the append is
the last thing that knows the response will never be filled, and it fails it.
"""
from __future__ import annotations
@@ -53,6 +60,10 @@ class AppendAttempt:
retained_committed_payload: dict[str, object] | None
#: Response reserved before submission, to be failed if submission does not happen.
precreated_response_id: str | None
#: Whether ``_start_append`` bound the session's active request to this
#: append (a final or response-bound one), so an append that never happens
#: has to unbind it again.
owns_request: bool = False
#: Commits timing state once the runtime accepts the append (before any
#: returned output event can clear the continuation chain).
on_append_accepted: Callable[[float], None] | None = None
@@ -75,11 +86,31 @@ class AppendAttempt:
):
self.ctx.session.release_input_bytes(model_state.clear_committed_audio())
def abandon(self) -> None:
"""Give back everything this append reserved but never used."""
def abandon(self, *, reason: str = "runtime_append_failed", response_taken_over: bool = False) -> None:
"""Give back everything this append reserved but never used.
That includes the response it precreated: once the append is off,
nothing will ever fill it, and a client that saw ``response.created``
is owed a ``response.done``. It is left alone only when somebody else
ends it: the runner that cancelled this append on purpose
(``response_taken_over``) or the close already under way.
"""
if self.pcm_reservation is not None:
self.pcm_reservation.rollback()
self.discard_retained_audio()
if response_taken_over:
return
session = self.ctx.session
if self.ctx.run.closing or session.state != DuplexSessionState.OPEN:
# The close ends the active response and request itself, with the
# session's one terminal event after them.
return
if self.owns_request and session.epoch == self.epoch:
# Compare-before-clear: only if the session still points at this
# append's request, exactly as the submitted path does.
session.clear_request(self.request_id)
if self._precreated_response_still_active():
self._fail_precreated_response(reason)
def release_on_failure(self, done: asyncio.Task[bool]) -> None:
"""Done-callback: a cancelled or failed append must not hold the audio."""
@@ -105,7 +136,22 @@ class AppendAttempt:
# ------------------------------------------------------------------ #
async def run_in_wire_order(self, predecessor: asyncio.Task[bool] | None) -> bool:
"""Wait for the previous append, then submit this one if it still applies."""
"""Wait for the previous append, then submit this one if it still applies.
A cancellation is compensated here, wherever it lands (waiting for the
predecessor or mid-submit): the reservations go back, and the
precreated response is failed unless the runner cancelled the append
itself, in which case it ends the response with the status the
cancellation was for.
"""
try:
return await self._run(predecessor)
except asyncio.CancelledError:
taken_over = self.ctx.tasks.cancelled_by_runner(asyncio.current_task())
self.abandon(reason="append_cancelled", response_taken_over=taken_over)
raise
async def _run(self, predecessor: asyncio.Task[bool] | None) -> bool:
if predecessor is not None:
try:
predecessor_ok = await predecessor
@@ -127,7 +173,11 @@ class AppendAttempt:
# Called off, not failed: the chain behind it still runs.
return True
if self.pcm_reservation is not None and not self.pcm_reservation.active:
self.discard_retained_audio()
# The client cleared the input buffer while this append waited its
# turn: the audio is gone, so is the response it was going to
# answer, and that is the client's doing, not a runtime failure.
# The reservation rollback itself is already a no-op.
self.abandon(reason="input_cleared")
return False
return await self._submit()
@@ -152,8 +202,6 @@ class AppendAttempt:
self.discard_retained_audio()
else:
self.abandon()
if not append_ok and self._precreated_response_still_active():
self._fail_precreated_response()
if not append_ok and session.state == DuplexSessionState.CLOSED:
self.ctx.run.runtime_closed = True
return False
@@ -171,11 +219,11 @@ class AppendAttempt:
self.out.emit_events([session.signal_turn(DuplexTurnEventType.USER_STARTED.value)])
return append_ok
except asyncio.CancelledError:
if self.pcm_reservation is not None:
self.pcm_reservation.rollback()
raise
except Exception as exc:
self.abandon()
# Compensate while the session is still open, so the client gets
# the failed ``response.done`` before the error and the close.
self.abandon(reason="runtime_append_task_failed")
logger.exception("Native duplex append task failed: %s", exc)
self.model.send_runtime_error("runtime_append_task_failed", exc)
if session.state != DuplexSessionState.CLOSED:
@@ -188,7 +236,7 @@ class AppendAttempt:
and self.ctx.session.active_response_id == self.precreated_response_id
)
def _fail_precreated_response(self) -> None:
def _fail_precreated_response(self, reason: str) -> None:
session = self.ctx.session
session.end_response(commit_text=False)
self.out.emit(
@@ -199,7 +247,7 @@ class AppendAttempt:
"epoch": session.epoch,
"committed": False,
"status": "failed",
"status_details": {"type": "failed", "reason": "runtime_append_failed"},
"status_details": {"type": "failed", "reason": reason},
"playback": session.playback.as_dict(),
}
)
+21 -2
View File
@@ -20,7 +20,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Protocol, TypeVar
from typing import TYPE_CHECKING, Any, Protocol, TypeVar
if TYPE_CHECKING:
from vllm.outputs import RequestOutput
@@ -117,6 +117,10 @@ class DuplexSessionTasks:
append_tasks: dict[asyncio.Task[bool], DuplexAppendTaskMeta] = field(default_factory=dict)
append_tail: asyncio.Task[bool] | None = None
active_response_task: asyncio.Task[None] | None = None
#: Appends the runner cancelled on purpose (a cancel, barge-in or close).
#: The runner ends the response such an append precreated, so the append
#: leaves it alone on its way out instead of failing it.
runner_cancelled: set[asyncio.Task[bool]] = field(default_factory=set)
def track_append_task(
self,
@@ -127,16 +131,31 @@ class DuplexSessionTasks:
response_bound: bool,
) -> None:
self.append_tasks[task] = DuplexAppendTaskMeta(epoch, final, response_bound)
task.add_done_callback(self.append_tasks.pop)
task.add_done_callback(self._forget_append_task)
def _forget_append_task(self, task: asyncio.Task[bool]) -> None:
self.append_tasks.pop(task, None)
self.runner_cancelled.discard(task)
def cancelled_by_runner(self, task: asyncio.Task[Any] | None) -> bool:
"""Whether ``task`` is an append the runner cancelled through ``cancel_append_tasks``."""
return task is not None and task in self.runner_cancelled
def has_response_bound_append_tasks(self) -> bool:
return any(meta.response_bound for meta in self.append_tasks.values())
async def cancel_append_tasks(self, timeout_s: float = 0.25, *, response_bound_only: bool = False) -> bool:
"""Cancel the tracked appends; the caller owns their responses from here on.
Every caller ends the active response itself right after (with the
cancel status, or silently as part of a close), so the cancelled
appends are told not to fail the response they precreated.
"""
tasks = [task for task, meta in self.append_tasks.items() if not response_bound_only or meta.response_bound]
if not tasks:
return False
cancelled_tail = self.append_tail if self.append_tail in tasks else None
self.runner_cancelled.update(tasks)
for task in tasks:
task.cancel()
try:
@@ -280,9 +280,9 @@ class DuplexEngineSession:
self._validate_fence(self.fence)
self.lease.detach(self._clock())
def resume_lease(self, *, expected_lease_generation: int) -> int:
def resume_lease(self, *, expected_lease_generation: int, control_id: str | None = None) -> int:
self._validate_fence(self.fence)
return self.lease.resume(self._clock(), expected_generation=expected_lease_generation)
return self.lease.resume(self._clock(), expected_generation=expected_lease_generation, control_id=control_id)
def begin_lease_operation(self, fence: DuplexFence, operation_id: str) -> None:
self._validate_fence(fence)
+13 -1
View File
@@ -40,6 +40,12 @@ class DuplexLeaseState:
detached_at: float | None = None
active_operations: set[str] = field(default_factory=set)
terminal_reason: str | None = None
#: Control id of the resume that produced ``generation`` (``None`` for the
#: open). A resume replayed with the same id is answered with the current
#: generation instead of bumping it again: the caller lost the first
#: answer (its RPC waiter was cancelled or timed out) and is finding out
#: whether the resume landed.
resumed_by: str | None = None
@property
def expires_at(self) -> float | None:
@@ -61,11 +67,16 @@ class DuplexLeaseState:
self.touch(now, DuplexLeaseActivity.DETACH)
self.detached_at = now
def resume(self, now: float, *, expected_generation: int) -> int:
def resume(self, now: float, *, expected_generation: int, control_id: str | None = None) -> int:
self._require_open()
if control_id is not None and control_id == self.resumed_by:
# The same resume asking again: it already produced this
# generation, so answer without changing anything.
return self.generation
if expected_generation != self.generation:
raise ValueError(f"duplex lease generation mismatch: expected {self.generation}, got {expected_generation}")
self.generation += 1
self.resumed_by = control_id
self.detached_at = None
self.last_activity = now
return self.generation
@@ -104,6 +115,7 @@ class DuplexLeaseState:
return False
self.terminal_reason = reason
self.generation += 1
self.resumed_by = None
self.detached_at = None
self.active_operations.clear()
return True
+71 -15
View File
@@ -523,32 +523,74 @@ class DuplexSessionManager:
# and the stage resource straight back.
self._abandoned_opens.discard(session_id)
await self._close_runner(runner, kind="close", reason="open_abandoned")
except asyncio.CancelledError:
# A cancel (engine teardown, task cancellation) while awaiting the
# plugin or the result sink is not an ``Exception``: without this
# branch the runner stayed in ``runners`` with its Stage0
# reservation, and since admission counts runners, every cancelled
# open burned one slot for good. Nobody is answered: the caller's
# RPC waiter is being torn down with us or times out.
logger.info("open_duplex_session cancelled for %s; rolling the admission back", session_id)
await self._rollback_open(session_id, session=session, runner=runner)
raise
except Exception as exc:
error_code, _, _ = self._control_error(exc)
if error_code in {"resource_exhausted", "session_exists"}:
logger.info("open_duplex_session rejected: %s", exc)
else:
logger.exception("open_duplex_session failed: %s", exc)
if runner is not None and self.runners.get(session_id) is runner:
self.runners.pop(session_id, None)
try:
await runner.shutdown()
except Exception:
logger.exception("duplex open rollback: runner shutdown failed for %s", session_id)
if session is not None:
reserved = session.release_all_requests()
if reserved:
try:
await self.stage_port.cleanup(list(reserved))
except Exception:
logger.warning("duplex open rollback: request cleanup pending for %s", session_id)
self._unregister_session_requests(session_id)
await self._rollback_open(session_id, session=session, runner=runner)
await self._put_result(message, operation="open", ok=False, error=exc)
finally:
if holds_admission_slot:
self._admitting.discard(session_id)
self._abandoned_opens.discard(session_id)
async def _rollback_open(
self,
session_id: str,
*,
session: DuplexEngineSession | None,
runner: DuplexSessionRunner | None,
) -> None:
"""Undo whatever an open that will not complete already did.
The bookkeeping that decides admission (``runners`` and the session's
request reservations) is undone synchronously first, so a second
cancellation landing in the awaits below cannot leave the slot burned.
The Stage0 request ids are recorded as a pending request cleanup
before anything is awaited: if the runner shutdown or the cleanup
itself is cancelled or fails, the reaper retries the cleanup instead
of the orchestrator keeping the request state forever.
"""
owned_runner = runner is not None and self.runners.get(session_id) is runner
if owned_runner:
self.runners.pop(session_id, None)
pending: _PendingRequestCleanup | None = None
key: tuple[str, int] | None = None
if session is not None:
reserved = tuple(session.release_all_requests())
self._unregister_session_requests(session_id)
if reserved:
key = (session_id, session.lease_generation)
pending = _PendingRequestCleanup(
session_id=session_id,
lease_generation=session.lease_generation,
request_ids=reserved,
abort=False,
)
self._pending_request_cleanups[key] = pending
if owned_runner and runner is not None:
try:
await runner.shutdown()
except Exception:
logger.exception("duplex open rollback: runner shutdown failed for %s", session_id)
if pending is not None and key is not None:
try:
await self._complete_request_cleanup(key, pending)
except Exception:
logger.warning("duplex open rollback: request cleanup pending for %s; the reaper retries", session_id)
def _require_runner(self, session_id: str) -> DuplexSessionRunner:
runner = self.runners.get(session_id)
if runner is None:
@@ -668,7 +710,13 @@ class DuplexSessionManager:
runner = self._require_runner(message.session_id)
session = runner.session
try:
session.resume_lease(expected_lease_generation=message.expected_lease_generation)
# Keyed by the control id, so a caller that lost the answer
# (waiter cancelled or timed out) can replay the same resume
# to learn whether it landed instead of resuming twice.
session.resume_lease(
expected_lease_generation=message.expected_lease_generation,
control_id=message.control_id,
)
except ValueError as exc:
raise DuplexSessionError(str(exc), code="session_resume_conflict") from exc
await self._put_result(message, operation="resume", ok=True, session=session)
@@ -683,6 +731,14 @@ class DuplexSessionManager:
session = runner.session
activity = DuplexLeaseActivity(message.activity)
if activity is DuplexLeaseActivity.DETACH:
expected = message.expected_lease_generation
if expected is not None and expected != session.lease_generation:
# The caller is giving up a lease it no longer holds: a
# later resume owns the current one and must keep it.
raise DuplexSessionError(
f"duplex lease generation mismatch: expected {session.lease_generation}, got {expected}",
code="session_resume_conflict",
)
session.detach_lease()
else:
session.touch_lease(activity)
@@ -1107,6 +1107,7 @@ class DuplexSessionRunner:
operation_id=operation_id,
retained_committed_payload=retained_committed_payload,
precreated_response_id=session.active_response_id if precreate_response else None,
owns_request=final or precreate_response,
on_append_accepted=on_append_accepted,
before_append=before_append,
)
+15 -2
View File
@@ -214,9 +214,12 @@ class DuplexOmniEngine(AsyncOmniEngine):
session_id: str,
*,
expected_lease_generation: int,
control_id: str | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexControlResultMessage:
control_id = uuid.uuid4().hex
# A caller-supplied id makes the resume replayable: the engine answers
# a repeated id with the generation that resume produced.
control_id = control_id or uuid.uuid4().hex
return self._execute_control(
ResumeDuplexSessionMessage(
control_id=control_id,
@@ -234,6 +237,7 @@ class DuplexOmniEngine(AsyncOmniEngine):
session_id: str,
*,
expected_lease_generation: int,
control_id: str | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexControlResultMessage:
loop = asyncio.get_running_loop()
@@ -242,6 +246,7 @@ class DuplexOmniEngine(AsyncOmniEngine):
lambda: self._resume_session(
session_id,
expected_lease_generation=expected_lease_generation,
control_id=control_id,
timeout=timeout,
),
)
@@ -251,6 +256,7 @@ class DuplexOmniEngine(AsyncOmniEngine):
session_id: str,
*,
activity: str,
expected_lease_generation: int | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexControlResultMessage:
control_id = uuid.uuid4().hex
@@ -259,6 +265,7 @@ class DuplexOmniEngine(AsyncOmniEngine):
control_id=control_id,
session_id=session_id,
activity=activity,
expected_lease_generation=expected_lease_generation,
),
control_id=control_id,
operation="touch",
@@ -271,12 +278,18 @@ class DuplexOmniEngine(AsyncOmniEngine):
session_id: str,
*,
activity: str,
expected_lease_generation: int | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexControlResultMessage:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None,
lambda: self._touch_session(session_id, activity=activity, timeout=timeout),
lambda: self._touch_session(
session_id,
activity=activity,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
),
)
def _submit_command(self, session_id: str, command: DuplexCommand) -> None:
+168 -23
View File
@@ -36,11 +36,13 @@ from vllm_omni.engine.duplex.events import (
SessionResyncRequired,
)
from vllm_omni.engine.duplex.messages import DuplexSessionError
from vllm_omni.entrypoints.duplex.realtime_input import RealtimeEnvelope, parse_resume_request
from vllm_omni.entrypoints.duplex.realtime_input import RealtimeEnvelope, ResumeRequest, parse_resume_request
from vllm_omni.entrypoints.duplex.session_attachment import (
DuplexDetachedAttachment,
DuplexJournalGapError,
DuplexJournalOverflowError,
DuplexSessionAttachmentRegistry,
DuplexSessionResumeResult,
InvalidResumeTokenError,
ResumeToken,
)
@@ -67,6 +69,12 @@ _PUMP_DRAIN_TIMEOUT_S = 5.0
_UNJOURNALED_EVENTS = (SessionCreated,)
def _log_rollback_failure(done: asyncio.Task[None]) -> None:
"""A shielded resume rollback outlives its caller; its failure must still be seen."""
if not done.cancelled() and done.exception() is not None:
logger.error("duplex resume rollback %s failed: %r", done.get_name(), done.exception())
@dataclass
class _Attachment:
"""What one websocket connection knows about the session it is attached to."""
@@ -199,10 +207,14 @@ class OmniDuplexSessionHandler:
await send_json(envelope.error_payload("invalid_session_config", str(exc)))
return None
attachment_send, attachment_close = attachment_callbacks(websocket)
# The registry keeps the engine lease generation each attachment is
# serving, so every detach is fenced on the dropped connection's own
# lease (see ``release_attachment``).
created = await self._attachment_registry.create(
handle.session_id,
send=attachment_send,
close=attachment_close,
lease_generation=handle.lease_generation,
)
resume_supported = bool(handle.capabilities.supports_session_resume)
attachment = _Attachment(handle=handle, generation=created.attachment_generation)
@@ -258,14 +270,44 @@ class OmniDuplexSessionHandler:
except (KeyError, ValueError) as exc:
await send_json(envelope.error_payload("session_resume_conflict", str(exc)))
return None
# The claim tells the registry a resume is about to activate: a lease
# generation orphaned meanwhile (another resume abandoned mid-RPC) is
# parked for this activation instead of being handed to the socket it
# is about to replace. The claim ends whatever happens below, and an
# orphan nobody else will serve is then ours to put into grace.
await self._attachment_registry.begin_resume(session_id)
try:
return await self._resume_claimed(websocket, envelope, request, handle, send_json)
finally:
await self._end_resume_claim(session_id)
async def _resume_claimed(
self,
websocket: WebSocket,
envelope: RealtimeEnvelope,
request: ResumeRequest,
handle: DuplexSessionHandle,
send_json: SendJson,
) -> _Attachment | None:
session_id = request.session_id
try:
# If this task is cancelled while the RPC is in flight, DuplexOmni
# observes the outcome and settles a resume that landed through
# ``_settle_abandoned_resume``: the generation goes to the resume
# waiting to activate, else to whoever is attached, else the lease
# goes back into disconnect grace.
await self._omni.resume_session(
session_id,
expected_lease_generation=handle.lease_generation,
on_abandoned=lambda lease_generation: self._settle_abandoned_resume(session_id, lease_generation),
)
except DuplexSessionError as exc:
await send_json(envelope.error_payload("runtime_resume_failed", str(exc)))
return None
# The generation this resume produced, read before anything else can
# run: the handle is shared by every connection of the session, and a
# concurrent resume adopts its own, newer generation into it.
lease_generation = handle.lease_generation
attachment_send, attachment_close = attachment_callbacks(websocket)
@@ -277,6 +319,12 @@ class OmniDuplexSessionHandler:
resume_token=token.plaintext,
).to_realtime()
# From here on the engine lease is resumed (``detached_at`` cleared), so
# every exit that does not hand the attachment to the caller has to
# put the lease back into its disconnect grace, or the session sits
# attached to nothing until idle expiry. That includes cancellation of
# the handler task, which is not an ``Exception``.
resumed: DuplexSessionResumeResult | None = None
try:
resumed = await self._attachment_registry.resume(
session_id,
@@ -285,26 +333,27 @@ class OmniDuplexSessionHandler:
send=attachment_send,
close=attachment_close,
activation_payload_factory=activation_payload_factory,
lease_generation=lease_generation,
)
replaced = resumed.replaced_attachment
if replaced is not None:
with suppress(Exception):
await replaced.send(
SessionReplaced(session_id=session_id, attachment_generation=replaced.generation).to_realtime()
)
with suppress(Exception):
await replaced.close("session_replaced")
except asyncio.CancelledError:
await self._abandon_resume(
session_id,
attachment_generation=resumed.attachment_generation if resumed is not None else None,
lease_generation=lease_generation,
)
raise
except Exception as exc:
# The engine lease was already resumed above, so a failed activation
# would leave the session attached to nothing -- unless another
# connection won the race and is attached right now. Detaching then
# would start the disconnect grace for the *winner*, which ordinary
# heartbeats do not clear. Roll back only what this attempt owns.
if not await self._attachment_registry.has_attachment(session_id):
with suppress(DuplexSessionError):
await self._omni.detach_session(session_id)
await self._abandon_resume(session_id, attachment_generation=None, lease_generation=lease_generation)
await send_json(envelope.error_payload("session_resume_conflict", str(exc)))
return None
replaced = resumed.replaced_attachment
if replaced is not None:
with suppress(Exception):
await replaced.send(
SessionReplaced(session_id=session_id, attachment_generation=replaced.generation).to_realtime()
)
with suppress(Exception):
await replaced.close("session_replaced")
# A reconnect brings a fresh envelope carrying pcm16/16 kHz wire
# defaults. The negotiated input format is a wire default, not part of
# the public session object, so it has to be carried over explicitly:
@@ -315,6 +364,96 @@ class OmniDuplexSessionHandler:
self._start_pump(handle, None)
return _Attachment(handle=handle, generation=resumed.attachment_generation)
async def _abandon_resume(
self,
session_id: str,
*,
attachment_generation: int | None,
lease_generation: int,
) -> None:
"""Roll the engine lease of a resume this connection will never serve back into disconnect grace.
Only what this attempt owns is rolled back. ``attachment_generation``
is the attachment it activated, or ``None`` when activation did not
happen (or was rolled back by the registry): then the generation this
attempt's engine resume produced is settled like an abandoned resume
(``_settle_abandoned_resume``). The registry knows more than this
method does: a rolled-back activation may have been handed a newer
generation meanwhile, which the registry parks as the orphan, and the
claim ending in ``_resume`` gives it back if nobody else will serve
it. Every engine detach is fenced on the generation being given up, so
a newer lease a concurrent resume produced is never touched.
The rollback runs shielded: a second cancellation landing between the
registry detach and the engine detach would otherwise strand the
session exactly the way this method compensates for.
"""
rollback = asyncio.ensure_future(
self._roll_back_resume(
session_id,
attachment_generation=attachment_generation,
lease_generation=lease_generation,
)
)
rollback.add_done_callback(_log_rollback_failure)
await asyncio.shield(rollback)
async def _roll_back_resume(
self,
session_id: str,
*,
attachment_generation: int | None,
lease_generation: int,
) -> None:
if attachment_generation is None:
await self._settle_abandoned_resume(session_id, lease_generation)
return
released = await self._attachment_registry.release_attachment(
session_id, attachment_generation=attachment_generation
)
if released is not None:
await self._detach_lease(released)
async def _settle_abandoned_resume(self, session_id: str, lease_generation: int) -> None:
"""Settle the engine lease generation of a resume its connection never got to serve.
The engine already bumped the lease to ``lease_generation`` and
cleared its disconnect grace. The registry picks the owner: a resume
waiting to activate (it will serve the session), else the connection
attached right now (a takeover that never activated leaves the
previous socket serving, and its own disconnect must be able to
detach this lease), else nobody, and then the lease goes back into
disconnect grace here, fenced on the generation so a later resume is
never detached.
"""
orphan = await self._attachment_registry.settle_lease_generation(session_id, lease_generation)
if orphan is not None:
with suppress(DuplexSessionError):
await self._omni.detach_session(session_id, expected_lease_generation=orphan)
async def _end_resume_claim(self, session_id: str) -> None:
"""End this connection's resume claim; detach an orphaned lease nobody else will serve.
Runs from a ``finally``, so possibly during cancellation: the detach
is shielded like the other rollbacks.
"""
orphan = await self._attachment_registry.end_resume(session_id)
if orphan is None:
return
async def detach_orphan() -> None:
with suppress(DuplexSessionError):
await self._omni.detach_session(session_id, expected_lease_generation=orphan)
rollback = asyncio.ensure_future(detach_orphan())
rollback.add_done_callback(_log_rollback_failure)
await asyncio.shield(rollback)
async def _detach_lease(self, released: DuplexDetachedAttachment) -> None:
"""Engine-owned disconnect grace for the lease a dropped connection was serving."""
with suppress(DuplexSessionError):
await self._omni.detach_session(released.session_id, expected_lease_generation=released.lease_generation)
# ------------------------------------------------------------------ #
# Outbound pump (session-scoped, survives reconnects) #
# ------------------------------------------------------------------ #
@@ -420,9 +559,13 @@ class OmniDuplexSessionHandler:
if handle is None or handle.closed:
return
if handle.capabilities.supports_session_resume:
if await self._attachment_registry.detach(session_id, attachment_generation=None):
with suppress(DuplexSessionError):
await self._omni.detach_session(session_id)
# The lease generation comes with the dropped attachment, captured
# under the registry lock: the shared handle may already carry the
# generation of a resume that is waiting to activate behind this
# very send, and that lease is not ours to detach.
released = await self._attachment_registry.release_attachment(session_id, attachment_generation=None)
if released is not None:
await self._detach_lease(released)
return
with suppress(DuplexSessionError):
await handle.close(reason="disconnect")
@@ -532,10 +675,12 @@ class OmniDuplexSessionHandler:
if handle.closed:
return
if handle.capabilities.supports_session_resume:
if await self._attachment_registry.detach(handle.session_id, attachment_generation=attachment.generation):
released = await self._attachment_registry.release_attachment(
handle.session_id, attachment_generation=attachment.generation
)
if released is not None:
# Engine-owned disconnect grace: expiry arrives as session.expired.
with suppress(DuplexSessionError):
await self._omni.detach_session(handle.session_id)
await self._detach_lease(released)
# Otherwise a newer connection already took the session over; the
# replaced socket's disconnect must not touch it.
return
@@ -184,6 +184,15 @@ class DuplexSessionAttachmentCreated:
resume_token: ResumeToken = field(repr=False)
@dataclass(frozen=True)
class DuplexDetachedAttachment:
"""The transport a detach dropped, with the engine lease generation it was serving."""
session_id: str
attachment_generation: int
lease_generation: int
@dataclass(frozen=True)
class DuplexSessionResumeResult:
session_id: str
@@ -200,6 +209,21 @@ class _DuplexSessionAttachmentState:
journal: DuplexEventJournal
attachment: DuplexTransportAttachment | None
attachment_generation: int
#: The engine lease generation the attached connection is serving: the one
#: its open or resume produced, or one an abandoned resume handed to it.
#: Read together with the attachment under the lock, so a detach always
#: gives back the lease of the connection it drops, never a newer one.
lease_generation: int = 0
#: Resumes between ``begin_resume`` and ``end_resume``: their engine lease
#: resume is in flight or landed, and they have not activated yet. While
#: one is pending, the next activation is the connection that will serve,
#: so an orphaned generation waits for it instead of going to the socket
#: that is about to be replaced.
pending_resumes: int = 0
#: An engine lease generation nobody serves yet (its resume was abandoned,
#: or its provisional attachment was rolled back), waiting for the next
#: activation to absorb it. Generations only move forward.
orphaned_lease_generation: int | None = None
outbound_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
recovery_token_digest: bytes | None = field(default=None, repr=False)
@@ -231,6 +255,7 @@ class DuplexSessionAttachmentRegistry:
*,
send: Callable[[dict[str, object]], Awaitable[None]],
close: Callable[[str], Awaitable[None]],
lease_generation: int = 0,
) -> DuplexSessionAttachmentCreated:
async with self._lock:
if session_id in self._sessions:
@@ -251,6 +276,7 @@ class DuplexSessionAttachmentRegistry:
close=close,
),
attachment_generation=generation,
lease_generation=lease_generation,
)
return DuplexSessionAttachmentCreated(
session_id=session_id,
@@ -310,14 +336,91 @@ class DuplexSessionAttachmentRegistry:
session answers ``False`` so a second disconnect signal for the same
socket cannot restart the engine's disconnect grace window.
"""
return await self.release_attachment(session_id, attachment_generation=attachment_generation) is not None
async def release_attachment(
self, session_id: str, *, attachment_generation: int | None = None
) -> DuplexDetachedAttachment | None:
"""``detach`` that also hands back the lease generation the dropped connection was serving.
Captured under the same lock as the attachment: the shared session
handle may already carry a newer generation from a resume that has
not activated yet, and the engine detach that follows must be fenced
on the dropped connection's own lease, not on that one.
"""
async with self._lock:
state = self._sessions.get(session_id)
if state is None or state.attachment is None:
return False
return None
if attachment_generation is not None and state.attachment_generation != attachment_generation:
return False
return None
state.attachment = None
return True
return DuplexDetachedAttachment(
session_id=session_id,
attachment_generation=state.attachment_generation,
lease_generation=state.lease_generation,
)
async def begin_resume(self, session_id: str) -> None:
"""Claim that a resume of ``session_id`` is about to land and activate.
Held from before the engine lease resume until ``end_resume``. While
any claim is open, a lease generation that loses its owner is parked
for the next activation (see ``settle_lease_generation``) instead of
being handed to the currently attached connection, which that
activation is about to replace.
"""
async with self._lock:
self._require(session_id).pending_resumes += 1
async def end_resume(self, session_id: str) -> int | None:
"""Release a ``begin_resume`` claim, whether or not the resume activated.
Returns a lease generation the caller must detach itself: one that
was parked for an activation that never came, with nobody attached
to take it over. ``None`` when nothing is owed.
"""
async with self._lock:
state = self._sessions.get(session_id)
if state is None:
return None
state.pending_resumes = max(0, state.pending_resumes - 1)
return self._settle_orphan_locked(state)
async def settle_lease_generation(self, session_id: str, lease_generation: int) -> int | None:
"""Find an owner for the engine lease generation of a resume its connection never served.
The engine already bumped its lease to ``lease_generation``. The owner
is, in order: the resume waiting to activate (it will serve the session
and absorbs the generation when it activates); else the connection
attached right now (it keeps serving, and its own disconnect must be
able to detach this lease); else nobody, in which case the generation
is returned and the caller puts it back into disconnect grace.
Generations only move forward, so an older orphan never displaces a
newer one an owner already holds.
"""
async with self._lock:
state = self._sessions.get(session_id)
if state is None:
# The session is gone from the registry: the engine session
# closed with it, nothing is left to own.
return None
state.orphaned_lease_generation = max(state.orphaned_lease_generation or 0, lease_generation)
return self._settle_orphan_locked(state)
@staticmethod
def _settle_orphan_locked(state: _DuplexSessionAttachmentState) -> int | None:
orphan = state.orphaned_lease_generation
if orphan is None:
return None
if state.pending_resumes > 0:
# The next activation absorbs it (see ``resume``).
return None
state.orphaned_lease_generation = None
if state.attachment is not None:
state.lease_generation = max(state.lease_generation, orphan)
return None
return orphan
async def has_attachment(self, session_id: str) -> bool:
"""Whether some connection is attached right now, whoever it is.
@@ -362,6 +465,7 @@ class DuplexSessionAttachmentRegistry:
send: Callable[[dict[str, object]], Awaitable[None]],
close: Callable[[str], Awaitable[None]],
activation_payload_factory: Callable[[ResumeToken, int], Mapping[str, object]] | None = None,
lease_generation: int | None = None,
) -> DuplexSessionResumeResult:
async with self._lock:
state = self._require(session_id)
@@ -384,6 +488,15 @@ class DuplexSessionAttachmentRegistry:
send=send,
close=close,
)
# The activating connection serves the newest lease the engine
# holds: its own resume's generation, or a newer one whose
# resume was abandoned while this one was pending.
state.lease_generation = max(
state.lease_generation,
lease_generation if lease_generation is not None else 0,
state.orphaned_lease_generation or 0,
)
state.orphaned_lease_generation = None
if activation_payload_factory is not None:
try:
await send(dict(activation_payload_factory(rotated_token, attachment_generation)))
@@ -418,18 +531,26 @@ class DuplexSessionAttachmentRegistry:
*,
state: _DuplexSessionAttachmentState,
attachment_generation: int,
accepted_token_digest: bytes,
accepted_token_digest: bytes | None,
) -> None:
"""Undo a resume whose activation never reached the client.
Generation-checked: a later resume that already took over must keep its
attachment. Restoring ``recovery_token_digest`` is what lets the caller
retry with the token it presented, which ``resume`` had rotated past.
The lease the provisional attachment was serving loses its owner here.
That is not only its own resume's generation: a resume abandoned while
this one was activating may have handed it a newer one. It is parked as
the orphan, so the caller's settlement (which only knows its own
generation) and ``end_resume`` give back the newest lease, never a
stale one the engine would refuse.
"""
async with self._lock:
if self._sessions.get(session_id) is state and state.attachment_generation == attachment_generation:
state.attachment = None
state.recovery_token_digest = accepted_token_digest
state.orphaned_lease_generation = max(state.orphaned_lease_generation or 0, state.lease_generation)
async def close(self, session_id: str) -> DuplexTransportAttachment | None:
async with self._lock:
+152 -11
View File
@@ -26,7 +26,7 @@ Example::
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator, Mapping, Sequence
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
from contextlib import suppress
from typing import Any
from uuid import uuid4
@@ -286,8 +286,13 @@ class DuplexOmni(AsyncOmni):
return DuplexOmniEngine(duplex_audio_encoder=encode_audio, **engine_kwargs)
def __init__(self, model: str = "", *args: Any, **kwargs: Any) -> None:
super().__init__(*args, model=model, **kwargs)
super().__init__(model, *args, **kwargs)
self._handles: dict[str, DuplexSessionHandle] = {}
#: Rollbacks of resumes whose caller was cancelled mid-RPC (see ``resume_session``).
self._resume_compensations: set[asyncio.Task[None]] = set()
#: Initial and maximum delay between replays of an abandoned resume
#: whose answers keep timing out.
self._resume_replay_backoff_s: tuple[float, float] = (0.5, 5.0)
# ---- deployment facts ----
@@ -377,32 +382,166 @@ class DuplexOmni(AsyncOmni):
*,
expected_lease_generation: int,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
on_abandoned: Callable[[int], Awaitable[None]] | None = None,
) -> DuplexSessionHandle:
"""Engine lease resume (CAS on the lease generation); returns the existing handle."""
"""Engine lease resume (CAS on the lease generation); returns the existing handle.
The RPC runs to completion in an executor thread whatever happens to
this waiter, so a caller cancelled while it is in flight does not stop
the engine from applying the resume (lease generation bumped,
disconnect grace cleared) for a connection that will never serve it.
The outcome is then observed off the cancelled task. If the RPC times
out before answering, the outcome is unknown, so the same resume is
replayed under its control id: the engine answers a replay with the
generation the resume produced instead of resuming again. A resume
that landed is adopted into the handle (a later reconnect resumes
against the real generation) and settled through ``on_abandoned`` with
that generation; without a callback it is detached again, fenced on
the generation, so a resume that came after it is never touched.
``on_abandoned`` is for callers that own an attachment concept: they
decide whether the generation now belongs to a connection that is
still serving (a takeover that never activated leaves the previous
socket attached) or whether the lease goes back into disconnect grace.
"""
handle = self._require_handle(session_id)
result = await self.engine.resume_session_async(
session_id,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
control_id = uuid4().hex
rpc = asyncio.ensure_future(
self.engine.resume_session_async(
session_id,
expected_lease_generation=expected_lease_generation,
control_id=control_id,
timeout=timeout,
)
)
try:
result = await asyncio.shield(rpc)
except asyncio.CancelledError:
self._compensate_abandoned_resume(
handle,
rpc,
control_id=control_id,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
on_abandoned=on_abandoned,
)
raise
# The result carries the engine's current public session (state,
# epoch, turn ...), which a resumed client must see, not the open-time snapshot.
handle._adopt(result)
return handle
def _compensate_abandoned_resume(
self,
handle: DuplexSessionHandle,
rpc: asyncio.Future[DuplexControlResultMessage],
*,
control_id: str,
expected_lease_generation: int,
timeout: float | None,
on_abandoned: Callable[[int], Awaitable[None]] | None,
) -> None:
session_id = handle.session_id
async def observe() -> DuplexControlResultMessage | None:
# The first attempt is the RPC the caller abandoned. A timeout
# means its answer was dropped and the outcome is unknown: the
# engine may have applied the resume after the waiter gave up.
# Replaying under the same control id makes the engine answer with
# the generation that resume produced, whether it lands now or
# already did, and refuse if a newer resume won. A replay can time
# out too, so this keeps replaying, with backoff, until the engine
# answers one way or the other or the session is gone: giving up
# on a timeout would be exactly the lost-answer window again.
attempt: Awaitable[DuplexControlResultMessage] = rpc
delay, ceiling = self._resume_replay_backoff_s
while True:
try:
return await attempt
except DuplexSessionError as exc:
if exc.code != "timeout":
# Refused (conflict, unknown session, engine gone):
# the resume did not land, nothing to give back.
logger.debug("abandoned duplex resume of %s did not land: %s", session_id, exc)
return None
except Exception as exc:
logger.debug("abandoned duplex resume of %s did not land: %s", session_id, exc)
return None
if handle.closed:
return None
logger.warning(
"abandoned duplex resume of %s lost its answer to a timeout; replaying in %.1fs", session_id, delay
)
await asyncio.sleep(delay)
delay = min(delay * 2, ceiling)
attempt = self.engine.resume_session_async(
session_id,
expected_lease_generation=expected_lease_generation,
control_id=control_id,
timeout=timeout,
)
async def compensate() -> None:
result = await observe()
if result is None:
return
handle._adopt(result)
lease_generation = result.lease_generation
if lease_generation is None:
return
try:
if on_abandoned is not None:
await on_abandoned(lease_generation)
else:
await self.engine.touch_session_async(
session_id,
activity="detach",
expected_lease_generation=lease_generation,
timeout=timeout,
)
except Exception as exc:
logger.warning("abandoned duplex resume of %s could not be settled: %s", session_id, exc)
task = asyncio.create_task(compensate(), name=f"duplex-resume-compensation-{session_id}")
self._resume_compensations.add(task)
task.add_done_callback(self._resume_compensations.discard)
async def touch_session(
self,
session_id: str,
*,
activity: str = "heartbeat",
expected_lease_generation: int | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> None:
self._require_handle(session_id)
await self.engine.touch_session_async(session_id, activity=activity, timeout=timeout)
await self.engine.touch_session_async(
session_id,
activity=activity,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
)
async def detach_session(self, session_id: str, *, timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S) -> None:
"""Start the engine-owned disconnect grace; expiry arrives as ``session.expired``."""
await self.touch_session(session_id, activity="detach", timeout=timeout)
async def detach_session(
self,
session_id: str,
*,
expected_lease_generation: int | None = None,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> None:
"""Start the engine-owned disconnect grace; expiry arrives as ``session.expired``.
``expected_lease_generation`` names the lease the caller opened or
resumed against; the engine refuses to detach a newer one, so a
connection giving up its lease cannot start the grace for the lease a
later resume owns.
"""
await self.touch_session(
session_id,
activity="detach",
expected_lease_generation=expected_lease_generation,
timeout=timeout,
)
async def close_session(
self,
@@ -470,6 +609,8 @@ class DuplexOmni(AsyncOmni):
for handle in list(self._handles.values()):
handle._mark_closed("shutdown")
self._handles.clear()
for compensation in list(self._resume_compensations):
compensation.cancel()
super().shutdown(timeout)