[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
@@ -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