[Core][Frontend] Bound duplex output delivery and reject cancelled audio (#7644)
Signed-off-by: Nolen Liang <nliang@nvidia.com> Signed-off-by: bcsdhjew <nliang@nvidia.com>
This commit is contained in:
1 parent
3f20252151
commit
f781f7bb08
26 files changed
+1170
-147
No files matched your search
@@ -0,0 +1,242 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Bounded, single-consumer delivery across the engine and caller threads.
|
||||
|
||||
Only queued, unsequenced audio can be removed. The producer still rejects
|
||||
new stale model output; this buffer does not retain a growing response-id
|
||||
tombstone table. It tracks just the most recently dequeued event until the
|
||||
next ``get()`` so a consumer can recheck it immediately before delivery.
|
||||
|
||||
Limits cover queued events, with a separate small termination reserve and
|
||||
one final session-closure notification independent of that reserve. A
|
||||
consumer may additionally hold one dequeued event, at most one queue budget
|
||||
in size. Already journaled or delivered events are outside this buffer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from collections import deque
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
from vllm_omni.engine.duplex.events import AudioDelta, DuplexEvent, ErrorEvent, ResponseDone, SessionClosed
|
||||
|
||||
_MAX_TERMINAL_BYTES = 4096
|
||||
|
||||
|
||||
class DuplexOutputOverflowError(RuntimeError):
|
||||
"""One session exceeded its pending output budget; valid output was not dropped."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _PendingEvent:
|
||||
event: DuplexEvent
|
||||
size: int
|
||||
reserved: bool
|
||||
|
||||
|
||||
class DuplexOutputBuffer:
|
||||
"""Nonblocking producer, one async consumer, and response-scoped audio removal.
|
||||
|
||||
``get()`` releases tracking of its previous result. The consumer must
|
||||
finish delivering that result before requesting another. ``guard()``
|
||||
makes the final validity check and synchronous journal recording atomic
|
||||
with invalidation; never await while holding that guard.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
max_bytes: int,
|
||||
max_events: int,
|
||||
reserve_bytes: int = 64 * 1024,
|
||||
reserve_events: int = 8,
|
||||
) -> None:
|
||||
if min(max_bytes, max_events, reserve_bytes, reserve_events) <= 0:
|
||||
raise ValueError("output buffer limits must be positive")
|
||||
self._max_bytes = max_bytes
|
||||
self._max_events = max_events
|
||||
self._reserve_bytes = reserve_bytes
|
||||
self._reserve_events = reserve_events
|
||||
self._lock = threading.Lock()
|
||||
self._pending: deque[_PendingEvent] = deque()
|
||||
self._bytes = 0
|
||||
self._reserved_bytes = self._reserved_events = 0
|
||||
self._held: DuplexEvent | None = None
|
||||
self._waiter: tuple[asyncio.AbstractEventLoop, asyncio.Future[None]] | None = None
|
||||
self._closed = False
|
||||
self._terminal: SessionClosed | None = None
|
||||
|
||||
@property
|
||||
def pending_bytes(self) -> int:
|
||||
with self._lock:
|
||||
return self._bytes + self._reserved_bytes
|
||||
|
||||
@property
|
||||
def pending_events(self) -> int:
|
||||
with self._lock:
|
||||
return len(self._pending)
|
||||
|
||||
def put(self, event: DuplexEvent) -> bool:
|
||||
"""Append without blocking; overflow leaves the queue unchanged.
|
||||
|
||||
Return false for late output after closure. A session terminal closes
|
||||
through its own single slot, even when the ordinary reserve is full.
|
||||
Error and response terminals can use the finite reserve.
|
||||
They retain FIFO order and cannot overtake still-valid media. The
|
||||
caller must stop the affected session after ordinary overflow instead
|
||||
of repeatedly generating errors until the reserve also overflows.
|
||||
"""
|
||||
if isinstance(event, SessionClosed):
|
||||
self.close(event)
|
||||
return True
|
||||
payload = event.to_realtime()
|
||||
audio_size = 0
|
||||
if isinstance(event, AudioDelta):
|
||||
# The producer has already encoded this as base64 ASCII. Count it
|
||||
# directly without serializing the large string or decoding PCM.
|
||||
audio_size = len(event.delta)
|
||||
payload["delta"] = ""
|
||||
size = audio_size + len(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return False
|
||||
reserved = self._bytes + size > self._max_bytes or (
|
||||
len(self._pending) - self._reserved_events >= self._max_events
|
||||
)
|
||||
if reserved and (
|
||||
not isinstance(event, ErrorEvent | ResponseDone)
|
||||
or self._reserved_bytes + size > self._reserve_bytes
|
||||
or self._reserved_events >= self._reserve_events
|
||||
):
|
||||
raise DuplexOutputOverflowError("duplex session pending output limit exceeded")
|
||||
self._pending.append(_PendingEvent(event=event, size=size, reserved=reserved))
|
||||
if reserved:
|
||||
self._reserved_bytes += size
|
||||
self._reserved_events += 1
|
||||
else:
|
||||
self._bytes += size
|
||||
waiter = self._waiter
|
||||
self._waiter = None
|
||||
self._notify(waiter)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _matches(event: DuplexEvent, response_id: str, through_epoch: int) -> bool:
|
||||
return (
|
||||
isinstance(event, AudioDelta)
|
||||
and event.response_id == response_id
|
||||
and event.epoch is not None
|
||||
and event.epoch <= through_epoch
|
||||
)
|
||||
|
||||
def invalidate(self, response_id: str, through_epoch: int) -> None:
|
||||
"""Remove queued audio for one accepted cancellation.
|
||||
|
||||
Non-audio events and other responses retain their exact order. An
|
||||
already dequeued matching event becomes invalid too. The producer
|
||||
must not enqueue further stale events after this call.
|
||||
"""
|
||||
with self._lock:
|
||||
kept: deque[_PendingEvent] = deque()
|
||||
for pending in self._pending:
|
||||
if self._matches(pending.event, response_id, through_epoch):
|
||||
self._release(pending)
|
||||
else:
|
||||
kept.append(pending)
|
||||
self._pending = kept
|
||||
if self._held is not None and self._matches(self._held, response_id, through_epoch):
|
||||
self._held = None
|
||||
|
||||
def _is_valid(self, event: DuplexEvent) -> bool:
|
||||
return not isinstance(event, AudioDelta) or event is self._held
|
||||
|
||||
def is_valid(self, event: DuplexEvent) -> bool:
|
||||
"""Check the current dequeued event; use ``guard`` for an atomic handoff."""
|
||||
with self._lock:
|
||||
return self._is_valid(event)
|
||||
|
||||
@contextmanager
|
||||
def guard(self, event: DuplexEvent) -> Iterator[bool]:
|
||||
"""Hold validity stable during synchronous sequencing; never await here."""
|
||||
with self._lock:
|
||||
yield self._is_valid(event)
|
||||
|
||||
def _release(self, pending: _PendingEvent) -> None:
|
||||
if pending.reserved:
|
||||
self._reserved_bytes -= pending.size
|
||||
self._reserved_events -= 1
|
||||
else:
|
||||
self._bytes -= pending.size
|
||||
|
||||
async def get(self) -> DuplexEvent | None:
|
||||
"""Return the next event, or ``None`` once a closed buffer is drained."""
|
||||
loop = asyncio.get_running_loop()
|
||||
with self._lock:
|
||||
self._held = None
|
||||
while True:
|
||||
with self._lock:
|
||||
if self._pending:
|
||||
pending = self._pending.popleft()
|
||||
self._release(pending)
|
||||
self._held = pending.event
|
||||
return pending.event
|
||||
if self._closed:
|
||||
if self._terminal is not None:
|
||||
terminal = self._terminal
|
||||
self._terminal = None
|
||||
return terminal
|
||||
return None
|
||||
if self._waiter is not None:
|
||||
raise RuntimeError("duplex output buffer already has a waiting consumer")
|
||||
future: asyncio.Future[None] = loop.create_future()
|
||||
self._waiter = (loop, future)
|
||||
try:
|
||||
await future
|
||||
finally:
|
||||
with self._lock:
|
||||
if self._waiter is not None and self._waiter[1] is future:
|
||||
self._waiter = None
|
||||
|
||||
def close(self, event: SessionClosed | None = None) -> None:
|
||||
"""Finish once, preserving FIFO output before an optional final notification.
|
||||
|
||||
The single final slot cannot be consumed by errors or response endings.
|
||||
Oversized close details are replaced by a compact notification retaining
|
||||
the generated session/event identity and terminal type. Duplicate closure
|
||||
and late output are harmless, including after a local
|
||||
shutdown that already ended consumption without a session event.
|
||||
"""
|
||||
if event is not None:
|
||||
size = len(json.dumps(event.to_realtime(), ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
|
||||
if size > _MAX_TERMINAL_BYTES:
|
||||
event = replace(event, reason="close_details_exceed_output_limit", details={})
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._terminal = event
|
||||
waiter = self._waiter
|
||||
self._waiter = None
|
||||
self._notify(waiter)
|
||||
|
||||
@staticmethod
|
||||
def _notify(waiter: tuple[asyncio.AbstractEventLoop, asyncio.Future[None]] | None) -> None:
|
||||
if waiter is None:
|
||||
return
|
||||
loop, future = waiter
|
||||
|
||||
def wake() -> None:
|
||||
if not future.done():
|
||||
future.set_result(None)
|
||||
|
||||
try:
|
||||
loop.call_soon_threadsafe(wake)
|
||||
except RuntimeError:
|
||||
if not loop.is_closed():
|
||||
raise
|
||||
@@ -5,8 +5,9 @@
|
||||
|
||||
Sessions live inside the engine (``DuplexSessionRunner`` on the orchestrator
|
||||
loop). The API layer only opens/closes/resumes/touches sessions through
|
||||
correlated RPC and pushes ``DuplexCommand`` objects one-way; every session
|
||||
output travels back as a ``DuplexSessionEventMessage``.
|
||||
correlated RPC and pushes ``DuplexCommand`` objects one-way. Open binds a
|
||||
bounded in-process output buffer; closure notifications and errors without
|
||||
a live session travel back as ``DuplexSessionEventMessage``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +19,7 @@ from vllm_omni.engine.messages import EngineQueueMessage
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.commands import DuplexCommand
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.delivery import DuplexOutputBuffer
|
||||
from vllm_omni.engine.duplex.events import DuplexEvent
|
||||
|
||||
|
||||
@@ -44,6 +46,8 @@ class OpenDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
session_id: str
|
||||
#: Already normalized by ``DuplexOmni``; the queue is in-process, so the object crosses as is.
|
||||
session_config: DuplexSessionConfig
|
||||
#: In-process, bounded output shared with the single consumer; no media in the engine-wide queue.
|
||||
output_buffer: DuplexOutputBuffer
|
||||
|
||||
|
||||
class CloseDuplexSessionMessage(EngineQueueMessage, kw_only=True):
|
||||
|
||||
@@ -804,7 +804,9 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
"status": "in_progress",
|
||||
"content": [],
|
||||
}
|
||||
state.conversation_items[item_id] = item
|
||||
# Later deltas grow the state item. Keep creation events independent
|
||||
# so their queued payloads retain the size measured at admission.
|
||||
state.conversation_items[item_id] = {**item, "content": []}
|
||||
events = [
|
||||
_response_created_event(event),
|
||||
*_conversation_item_added_events(state, item),
|
||||
|
||||
@@ -17,13 +17,15 @@ runner injects it as ``promote_deferred_overlap``.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import replace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexSessionState
|
||||
from vllm_omni.engine.duplex.events import (
|
||||
DOMAIN_TERMINAL_EVENTS,
|
||||
MODEL_OUTPUT_EVENTS,
|
||||
DuplexEvent,
|
||||
ResponseDone,
|
||||
error_event,
|
||||
)
|
||||
from vllm_omni.engine.duplex.realtime_events import (
|
||||
@@ -84,8 +86,51 @@ class SessionEmitter:
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def emit_events(self, events: list[DuplexEvent]) -> None:
|
||||
for event in events:
|
||||
self._ctx.manager.emit(self._ctx.session, event)
|
||||
self._ctx.manager.emit(self._ctx.session, events)
|
||||
|
||||
def fail_output(self, message: str, *, response_id: str | None, terminal: ResponseDone | None) -> list[DuplexEvent]:
|
||||
"""Fail undelivered output, returning recovery events without sending them again."""
|
||||
session = self._ctx.session
|
||||
self._ctx.manager.invalidate_output(session.session_id, response_id, through_epoch=session.epoch)
|
||||
if session.active_response_id is not None:
|
||||
# Close still needs the request binding to abort the real engine work.
|
||||
session.end_response(commit_text=False, preserve_request=True)
|
||||
events: list[DuplexEvent] = [error_event("output_backpressure", message)]
|
||||
if response_id is None:
|
||||
return events
|
||||
# Normal completion can commit just before its projected ending is
|
||||
# delivered. An ending converted to failure must undo that commit.
|
||||
session.delete_history_item(f"item_{response_id}")
|
||||
payload = {
|
||||
"type": "response.done",
|
||||
"session_id": session.session_id,
|
||||
"response_id": response_id,
|
||||
"epoch": session.epoch,
|
||||
"committed": False,
|
||||
"status": "failed",
|
||||
"status_details": {"type": "failed", "reason": "output_backpressure"},
|
||||
"playback": session.playback.as_dict(),
|
||||
}
|
||||
if terminal is None:
|
||||
projected = project_internal_event(self.require_projector(), payload)
|
||||
terminal = next((event for event in projected if isinstance(event, ResponseDone)), None)
|
||||
else:
|
||||
response = dict(terminal.response)
|
||||
metadata = response.get("metadata")
|
||||
response.update(
|
||||
status="failed",
|
||||
status_details=payload["status_details"],
|
||||
metadata={**(metadata if isinstance(metadata, Mapping) else {}), **payload},
|
||||
)
|
||||
output = response.get("output")
|
||||
if isinstance(output, list):
|
||||
response["output"] = [
|
||||
{**item, "status": "failed"} if isinstance(item, Mapping) else item for item in output
|
||||
]
|
||||
terminal = replace(terminal, response=response)
|
||||
if terminal is not None:
|
||||
events.append(terminal)
|
||||
return events
|
||||
|
||||
def emit_error(
|
||||
self,
|
||||
@@ -110,6 +155,13 @@ class SessionEmitter:
|
||||
accepted, deferred_overlap_payload = self._apply_outbound_session_event(payload)
|
||||
if not accepted:
|
||||
return
|
||||
if payload.get("type") == "audio.cancelled":
|
||||
response_id = payload.get("response_id")
|
||||
cancelled_epoch = payload.get("cancelled_epoch")
|
||||
if isinstance(response_id, str) and isinstance(cancelled_epoch, int):
|
||||
self._ctx.manager.invalidate_output(
|
||||
self._ctx.session.session_id, response_id, through_epoch=cancelled_epoch
|
||||
)
|
||||
self.emit_events(project_internal_event(self.require_projector(), payload))
|
||||
if deferred_overlap_payload is not None and not self._ctx.run.closing:
|
||||
precreate_response = self._ctx.model_state.deferred_precreate_response
|
||||
|
||||
@@ -11,8 +11,9 @@ state.
|
||||
Control operations (open / close / resume / touch) arrive as correlated RPC
|
||||
messages and answer through ``result_sink``; session commands arrive one-way
|
||||
as ``DuplexSessionCommandMessage`` and are pushed onto the runner's ordered
|
||||
mailbox after backpressure admission; everything a session emits leaves
|
||||
through ``output_sink`` as ``DuplexSessionEventMessage``.
|
||||
mailbox after backpressure admission. Public output uses a bounded buffer
|
||||
shared with that session's consumer. The engine-wide ``output_sink`` only
|
||||
carries closure notifications and errors without a live session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,7 +35,16 @@ from vllm_omni.engine.duplex.contracts import (
|
||||
duplex_resource_request_belongs_to_session,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.events import DuplexEvent, ErrorEvent, SessionClosed, SessionExpired, error_event
|
||||
from vllm_omni.engine.duplex.delivery import DuplexOutputBuffer, DuplexOutputOverflowError
|
||||
from vllm_omni.engine.duplex.events import (
|
||||
DuplexEvent,
|
||||
ErrorEvent,
|
||||
OutputAudioCleared,
|
||||
ResponseDone,
|
||||
SessionClosed,
|
||||
SessionExpired,
|
||||
error_event,
|
||||
)
|
||||
from vllm_omni.engine.duplex.messages import (
|
||||
CloseDuplexSessionMessage,
|
||||
DuplexControlResultMessage,
|
||||
@@ -128,6 +138,8 @@ class DuplexSessionManager:
|
||||
model_path=getattr(runtime_config, "server_vad_model_path", None)
|
||||
)
|
||||
self.runners: dict[str, DuplexSessionRunner] = {}
|
||||
self._outputs: dict[str, DuplexOutputBuffer] = {}
|
||||
self._output_failed: set[str] = set()
|
||||
#: Sessions whose close/expiry began but whose stage cleanup has not finalized;
|
||||
#: they keep their admission slot until finalized.
|
||||
self._closing: dict[str, _PendingSessionCleanup] = {}
|
||||
@@ -270,20 +282,24 @@ class DuplexSessionManager:
|
||||
if runner is None:
|
||||
self._emit_raw(
|
||||
message.session_id,
|
||||
self._error_event(
|
||||
"unknown_session",
|
||||
f"Unknown or closed duplex session: {message.session_id}",
|
||||
command=command,
|
||||
),
|
||||
[
|
||||
self._error_event(
|
||||
"unknown_session",
|
||||
f"Unknown or closed duplex session: {message.session_id}",
|
||||
command=command,
|
||||
)
|
||||
],
|
||||
)
|
||||
return
|
||||
session = runner.session
|
||||
if runner.closing:
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"session_closed", f"Duplex session is closing: {session.session_id}", command=command
|
||||
),
|
||||
[
|
||||
self._error_event(
|
||||
"session_closed", f"Duplex session is closing: {session.session_id}", command=command
|
||||
)
|
||||
],
|
||||
)
|
||||
return
|
||||
if isinstance(command, AppendAudio):
|
||||
@@ -293,7 +309,7 @@ class DuplexSessionManager:
|
||||
if modality_error is not None:
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event("invalid_input_modality", modality_error, command=command),
|
||||
[self._error_event("invalid_input_modality", modality_error, command=command)],
|
||||
)
|
||||
return
|
||||
limit = int(self.runtime_config.max_pending_input_bytes_per_session)
|
||||
@@ -301,22 +317,26 @@ class DuplexSessionManager:
|
||||
if not session.reserve_input_bytes(pending_bytes, limit=limit):
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input bytes",
|
||||
command=command,
|
||||
),
|
||||
[
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input bytes",
|
||||
command=command,
|
||||
)
|
||||
],
|
||||
)
|
||||
return
|
||||
elif isinstance(command, Commit):
|
||||
if not session.reserve_pending_turn(limit=int(self.runtime_config.max_pending_turns_per_session)):
|
||||
self.emit(
|
||||
session,
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input turns",
|
||||
command=command,
|
||||
),
|
||||
[
|
||||
self._error_event(
|
||||
"input_backpressure",
|
||||
"Duplex session has too many pending input turns",
|
||||
command=command,
|
||||
)
|
||||
],
|
||||
)
|
||||
return
|
||||
runner.submit(command)
|
||||
@@ -329,18 +349,72 @@ class DuplexSessionManager:
|
||||
# Emission #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def emit(self, session: DuplexEngineSession, event: DuplexEvent) -> None:
|
||||
"""Bind the session identity to one typed event and push it to the engine output queue."""
|
||||
self._emit_raw(session.session_id, event, epoch=session.epoch)
|
||||
def emit(self, session: DuplexEngineSession, events: list[DuplexEvent]) -> None:
|
||||
"""Bind identity and deliver through the session's bounded output."""
|
||||
self._emit_raw(session.session_id, events, epoch=session.epoch)
|
||||
|
||||
def invalidate_output(self, session_id: str, response_id: str | None, *, through_epoch: int) -> None:
|
||||
output = self._outputs.get(session_id)
|
||||
if output is not None and response_id is not None:
|
||||
output.invalidate(response_id, through_epoch=through_epoch)
|
||||
|
||||
def _emit_raw(
|
||||
self,
|
||||
session_id: str,
|
||||
event: DuplexEvent,
|
||||
events: list[DuplexEvent],
|
||||
*,
|
||||
epoch: int | None = None,
|
||||
) -> None:
|
||||
ending_delivered = False
|
||||
for index, event in enumerate(events):
|
||||
try:
|
||||
self._deliver(session_id, event, epoch=epoch)
|
||||
except DuplexOutputOverflowError as exc:
|
||||
if session_id in self._output_failed:
|
||||
return
|
||||
self._output_failed.add(session_id)
|
||||
runner = self.runners.get(session_id)
|
||||
if runner is None:
|
||||
return
|
||||
# Projection has already marked this batch's ending as emitted.
|
||||
# Retain it instead of recursively projecting a second ending.
|
||||
terminal = next((item for item in events[index:] if isinstance(item, ResponseDone)), None)
|
||||
response_id = terminal.response_id if terminal is not None else event.response_id
|
||||
if response_id is None and not ending_delivered:
|
||||
response_id = runner.session.active_response_id
|
||||
for recovery in runner.fail_output(str(exc), response_id=response_id, terminal=terminal):
|
||||
try:
|
||||
self._deliver(session_id, recovery, epoch=epoch)
|
||||
except DuplexOutputOverflowError:
|
||||
# A full control reserve may omit an error/response ending;
|
||||
# session closure still has its independent terminal slot.
|
||||
pass
|
||||
return
|
||||
ending_delivered |= isinstance(event, ResponseDone)
|
||||
|
||||
def _deliver(self, session_id: str, event: DuplexEvent, *, epoch: int | None) -> None:
|
||||
event = replace(event, session_id=session_id, epoch=epoch)
|
||||
output = self._outputs.get(session_id)
|
||||
if output is not None and not isinstance(event, SessionClosed):
|
||||
if isinstance(event, OutputAudioCleared) and epoch is not None:
|
||||
self.invalidate_output(session_id, event.response_id, through_epoch=epoch)
|
||||
if session_id in self._output_failed:
|
||||
# The failure/close path has a finite reserve; stop adding ordinary output.
|
||||
if not isinstance(event, ErrorEvent) and not (
|
||||
isinstance(event, ResponseDone) and event.status in {"failed", "cancelled"}
|
||||
):
|
||||
return
|
||||
output.put(event)
|
||||
return
|
||||
if isinstance(event, SessionClosed):
|
||||
self._outputs.pop(session_id, None)
|
||||
self._output_failed.discard(session_id)
|
||||
elif not isinstance(event, ErrorEvent):
|
||||
# A closed/rolled-back session must not move late audio back into
|
||||
# the unbounded shared queue after its output buffer is removed.
|
||||
return
|
||||
# Only closure notifications and errors without a live session use the
|
||||
# engine-wide queue. Audio never accumulates there before the bounded buffer.
|
||||
message = DuplexSessionEventMessage(session_id=session_id, event=event)
|
||||
put_nowait = getattr(self._output_sink, "put_nowait", None)
|
||||
if callable(put_nowait):
|
||||
@@ -514,6 +588,7 @@ class DuplexSessionManager:
|
||||
model_config=self.model_config,
|
||||
)
|
||||
self.runners[session_id] = runner
|
||||
self._outputs[session_id] = message.output_buffer
|
||||
# Reserve the Stage0 request resource atomically with admission.
|
||||
self.ensure_stage_request(session, stage_id=0)
|
||||
runner.start()
|
||||
@@ -566,6 +641,7 @@ class DuplexSessionManager:
|
||||
owned_runner = runner is not None and self.runners.get(session_id) is runner
|
||||
if owned_runner:
|
||||
self.runners.pop(session_id, None)
|
||||
self._outputs.pop(session_id, None)
|
||||
pending: _PendingRequestCleanup | None = None
|
||||
key: tuple[str, int] | None = None
|
||||
if session is not None:
|
||||
@@ -686,7 +762,7 @@ class DuplexSessionManager:
|
||||
terminal: DuplexEvent = (
|
||||
SessionExpired(reason=reason) if kind == "expired" else SessionClosed(reason=reason)
|
||||
)
|
||||
self.emit(session, terminal)
|
||||
self.emit(session, [terminal])
|
||||
|
||||
async def _finalize_pending_cleanup(
|
||||
self,
|
||||
@@ -943,6 +1019,8 @@ class DuplexSessionManager:
|
||||
self._closing.clear()
|
||||
self._session_snapshots.clear()
|
||||
self._request_index.clear()
|
||||
self._outputs.clear()
|
||||
self._output_failed.clear()
|
||||
if self._owns_executor:
|
||||
self.executor.shutdown(wait=False, cancel_futures=True)
|
||||
|
||||
|
||||
@@ -577,6 +577,8 @@ class ModelChannel:
|
||||
close_reason, emitted_response = await self._send_model_output_events(
|
||||
drain_result, expected_epoch=expected_epoch
|
||||
)
|
||||
if self._ctx.run.closing:
|
||||
return
|
||||
if close_reason is not None:
|
||||
await self._close_from_runtime(close_reason)
|
||||
return
|
||||
@@ -607,7 +609,7 @@ class ModelChannel:
|
||||
expected_epoch: int | None = None,
|
||||
) -> tuple[str | None, bool]:
|
||||
session = self._ctx.session
|
||||
if expected_epoch is not None and session.epoch != expected_epoch:
|
||||
if self._ctx.run.closing or (expected_epoch is not None and session.epoch != expected_epoch):
|
||||
return None, False
|
||||
close_reason: str | None = None
|
||||
emitted_response = False
|
||||
@@ -624,7 +626,7 @@ class ModelChannel:
|
||||
)
|
||||
emitted_response = emitted_response or did_emit
|
||||
close_reason = close_reason or close_reason_for_result
|
||||
if expected_epoch is not None and session.epoch != expected_epoch:
|
||||
if self._ctx.run.closing or (expected_epoch is not None and session.epoch != expected_epoch):
|
||||
return None, emitted_response
|
||||
return close_reason, emitted_response
|
||||
|
||||
@@ -636,7 +638,7 @@ class ModelChannel:
|
||||
str(model_result.get("error_code")),
|
||||
str(model_result.get("error") or "Duplex native data-plane error"),
|
||||
)
|
||||
if response_id is None:
|
||||
if self._ctx.run.closing or response_id is None:
|
||||
return
|
||||
session.end_response(commit_text=False)
|
||||
self._out.emit(
|
||||
@@ -734,6 +736,8 @@ class ModelChannel:
|
||||
close_reason: str | None = None
|
||||
emitted_response = False
|
||||
self._end_active_response_before_future_model_turn(model_turn_id=model_turn_id)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
if (
|
||||
session.active_response_id is not None
|
||||
and model_turn_id is not None
|
||||
@@ -776,10 +780,14 @@ class ModelChannel:
|
||||
payload["response_id"] = response_id
|
||||
self._attach_runtime_metadata(payload, model_result)
|
||||
self._out.emit(payload)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
if model_result.get("abort_data_plane_request") is True and isinstance(data_plane_request_id, str):
|
||||
# stage_port.abort_requests expects a list of ids; a bare str is
|
||||
# iterated as characters and never matches the prewarmed binding.
|
||||
await self._abort_request([data_plane_request_id], notify=False)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
if response_id is not None:
|
||||
if not auto_response and self.response_continuations_remaining(response_id):
|
||||
self._ctx.services.spawn(
|
||||
@@ -822,7 +830,7 @@ class ModelChannel:
|
||||
data_plane = self._ctx.plugin.data_plane
|
||||
close_reason: str | None = None
|
||||
emitted_response = False
|
||||
if expected_epoch is not None and session.epoch != expected_epoch:
|
||||
if self._ctx.run.closing or (expected_epoch is not None and session.epoch != expected_epoch):
|
||||
return close_reason, emitted_response
|
||||
data_plane_request_id = model_result.get("data_plane_request_id")
|
||||
if isinstance(data_plane_request_id, str) and data_plane.is_terminal(data_plane_request_id):
|
||||
@@ -932,6 +940,8 @@ class ModelChannel:
|
||||
return close_reason, emitted_response
|
||||
if draining_response_id is None:
|
||||
self._end_active_response_before_future_model_turn(model_turn_id=model_turn_id)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
if (
|
||||
draining_response_id is None
|
||||
and session.active_response_id is not None
|
||||
@@ -955,6 +965,8 @@ class ModelChannel:
|
||||
if response_request_metrics:
|
||||
created_payload["response_request_metrics"] = response_request_metrics
|
||||
self._out.emit(created_payload)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
stage_metrics = model_result.get("stage_metrics")
|
||||
response_stage_metrics = session.accumulate_response_stage_metrics(
|
||||
stage_metrics if isinstance(stage_metrics, Mapping) else None
|
||||
@@ -976,6 +988,8 @@ class ModelChannel:
|
||||
response_request_metrics=response_request_metrics,
|
||||
)
|
||||
self._out.emit(speak_payload)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
target_id = draining_response_id if draining_response_id not in (None, session.active_response_id) else None
|
||||
previous_sent_ms = session.playback_for_response(target_id).sent_ms
|
||||
text_chars_before_append = len(session.assistant_transcript(target_id))
|
||||
@@ -1052,6 +1066,8 @@ class ModelChannel:
|
||||
response_request_metrics=response_request_metrics,
|
||||
)
|
||||
self._out.emit(payload)
|
||||
if self._ctx.run.closing:
|
||||
return close_reason, emitted_response
|
||||
if (
|
||||
not end_of_turn
|
||||
and model_result.get("stage_role") == "tts"
|
||||
@@ -1233,7 +1249,7 @@ class ModelChannel:
|
||||
response_id = session.active_response_id
|
||||
response_epoch = session.epoch
|
||||
response_turn_id = model_turn_id if model_turn_id is not None else session.active_response_turn_id
|
||||
if expected_epoch is not None and response_epoch != expected_epoch:
|
||||
if self._ctx.run.closing or (expected_epoch is not None and response_epoch != expected_epoch):
|
||||
return
|
||||
model_state.clear_continuation()
|
||||
payload: dict[str, object] = {
|
||||
@@ -1246,6 +1262,8 @@ class ModelChannel:
|
||||
if response_id is not None:
|
||||
payload["response_id"] = response_id
|
||||
self._out.emit(payload)
|
||||
if self._ctx.run.closing:
|
||||
return
|
||||
if response_id is None:
|
||||
if session.epoch == response_epoch and response_turn_id is not None:
|
||||
session.complete_model_turn(response_turn_id)
|
||||
@@ -1277,7 +1295,8 @@ class ModelChannel:
|
||||
) -> bool:
|
||||
session = self._ctx.session
|
||||
stale_common_owner = (
|
||||
session.state == DuplexSessionState.CLOSED
|
||||
self._ctx.run.closing
|
||||
or session.state == DuplexSessionState.CLOSED
|
||||
or session.active_request_id != request_id
|
||||
or (expected_epoch is not None and session.epoch != expected_epoch)
|
||||
)
|
||||
@@ -1372,6 +1391,6 @@ class ModelChannel:
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to schedule duplex native response continuation: %s", exc)
|
||||
scheduled = False
|
||||
if scheduled:
|
||||
if scheduled and not self._ctx.run.closing:
|
||||
model_state.continuation_owner_id = owner_id
|
||||
model_state.continuation_units = count + 1
|
||||
@@ -64,6 +64,7 @@ from vllm_omni.engine.duplex.contracts import (
|
||||
from vllm_omni.engine.duplex.events import (
|
||||
DuplexEvent,
|
||||
InputCleared,
|
||||
ResponseDone,
|
||||
SessionExpired,
|
||||
SessionHeartbeatAck,
|
||||
)
|
||||
@@ -347,6 +348,15 @@ class DuplexSessionRunner:
|
||||
"""Whether ``session.closed`` / ``session.expired`` already left this runner."""
|
||||
return self.run.closed_emitted
|
||||
|
||||
def fail_output(self, message: str, *, response_id: str | None, terminal: ResponseDone | None) -> list[DuplexEvent]:
|
||||
"""Experimental overflow policy: fail this response and close only its session."""
|
||||
if self.closing:
|
||||
return []
|
||||
events = self.out.fail_output(message, response_id=response_id, terminal=terminal)
|
||||
self._begin_close("output_backpressure")
|
||||
self.manager.close_from_runner(self, "output_backpressure")
|
||||
return events
|
||||
|
||||
def mark_closed_emitted(self) -> None:
|
||||
"""Claim the session's one terminal event for the caller.
|
||||
|
||||
@@ -1474,6 +1484,9 @@ class DuplexSessionRunner:
|
||||
if older_abort_ids:
|
||||
session.release_resources_for_request_ids(older_abort_ids)
|
||||
new_epoch, old_playback = helpers.advance_barge_in_epoch(session)
|
||||
self.manager.invalidate_output(session.session_id, old_response_id, through_epoch=old_epoch)
|
||||
for response_id, _, _ in draining_cancels:
|
||||
self.manager.invalidate_output(session.session_id, response_id, through_epoch=old_epoch)
|
||||
if old_request_id is not None:
|
||||
# Release projector/parser cursors so cancelled epochs do not
|
||||
# accumulate until the whole session closes.
|
||||
|
||||
Reference in new issue
Block a user