[Core][Frontend] Unified Full-duplex Framework (#7413)

Signed-off-by: chickeyton <ngton2014@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
chickeytonandClaude Opus 5 authored and GitHub committed 2026-09-16 15:35:36 +08:00
1 parent 9005d78903
commit 99ff4f3070
182 files changed
+26951 -34743

No files matched your search

@@ -0,0 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""One engine-resident duplex session, and everything that runs it.
``DuplexEngineSession`` (``engine_session``) is the state -- the input,
response, playback and conversation ledgers, the lease and the identity fence.
``DuplexSessionRunner`` (``runner``) owns one of those on the orchestrator loop
and is the only writer of it; ``DuplexSessionManager`` (``manager``) owns the
runners and the admission slots.
The rest of the package is what the runner was split into, and each module
names the thing it owns rather than a layer:
* ``context`` -- the state a runner and its components share, and the only
services a component may ask the runner for.
* ``emitter`` -- everything the session sends: the Realtime projection, the
epoch filter, the domain effects a terminal event applies.
* ``model_channel`` -- the model side: submitting an append, projecting the
stage output that comes back, continuing a turn with silence.
* ``control`` -- server VAD and the events that reconfigure the session.
* ``append_task`` -- one append in flight, and the rollback its failure owes.
* ``helpers`` -- the small pure reads and payload builders over a session.
* ``overlap_policy`` / ``commit_policy`` / ``playback_ledger`` -- the decisions
a session makes about speech that arrives while the model is speaking, what a
commit should do, and what the client has actually played.
* ``lease`` -- the idle/activity lease that decides when a session expires.
Imports here are the package's public surface; a module of this package is fair
game for anything inside it, but code outside ``engine.duplex`` should reach for
these three names.
"""
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
__all__ = ["DuplexEngineSession", "DuplexSessionManager", "DuplexSessionRunner"]
@@ -0,0 +1,195 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""One append in flight, and what its failure owes the session.
An append is not a call: it is a task queued behind the previous append, which
may be cancelled, may find the session closed before it starts, and on any of
those paths has to give back what it reserved --- the PCM bytes it took from the
input budget, the committed audio it was going to consume, and the response it
precreated.
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.
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass
from vllm.logger import init_logger
from vllm_omni.engine.duplex.config import DuplexSessionState, DuplexTurnEventType
from vllm_omni.engine.duplex.plugin import PcmAppendReservation
from vllm_omni.engine.duplex.session import helpers
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
from vllm_omni.engine.duplex.session.emitter import SessionEmitter
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
logger = init_logger(__name__)
@dataclass(slots=True)
class AppendAttempt:
"""One queued append to the model, with the rollback each failure path owes."""
ctx: DuplexSessionContext
out: SessionEmitter
model: ModelChannel
#: Marks the session closing before the close coroutine gets to run.
fail_session: Callable[[str], None]
payload: dict[str, object]
epoch: int
request_id: str
final: bool
pcm_reservation: PcmAppendReservation | None
operation_id: str | None
#: Committed audio this append consumes; released once it is safely submitted.
retained_committed_payload: dict[str, object] | None
#: Response reserved before submission, to be failed if submission does not happen.
precreated_response_id: str | None
#: Last chance to call the append off, checked once the predecessor is done.
before_append: Callable[[], bool] | None
# ------------------------------------------------------------------ #
# Compensation #
# ------------------------------------------------------------------ #
def discard_retained_audio(self) -> None:
"""Release the committed audio this append was going to consume.
Only if it is still the session's: a later commit may have replaced it,
and that one belongs to the append that will carry it.
"""
model_state = self.ctx.model_state
if self.retained_committed_payload is not None and (
model_state.committed_audio_payload is self.retained_committed_payload
):
self.ctx.session.release_input_bytes(model_state.clear_committed_audio())
def abandon(self) -> None:
"""Give back everything this append reserved but never used."""
if self.pcm_reservation is not None:
self.pcm_reservation.rollback()
self.discard_retained_audio()
def release_on_failure(self, done: asyncio.Task[bool]) -> None:
"""Done-callback: a cancelled or failed append must not hold the audio."""
if done.cancelled():
self.discard_retained_audio()
return
try:
append_ok = done.result()
except Exception:
append_ok = False
if not append_ok:
self.discard_retained_audio()
def clear_pending_silence(self, done: asyncio.Task[bool]) -> None:
"""Done-callback of a silence continuation: it is no longer pending."""
model_state = self.ctx.model_state
if model_state.pending_silence_task is done:
model_state.pending_silence_task = None
model_state.pending_silence_owner_id = None
# ------------------------------------------------------------------ #
# Running #
# ------------------------------------------------------------------ #
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."""
if predecessor is not None:
try:
predecessor_ok = await predecessor
except asyncio.CancelledError:
current = asyncio.current_task()
if current is not None and current.cancelling():
raise
predecessor_ok = False
except Exception:
predecessor_ok = False
if not predecessor_ok:
self.abandon()
return False
run = self.ctx.run
if run.closing or run.runtime_closed or self.ctx.session.state != DuplexSessionState.OPEN:
self.abandon()
return False
if self.before_append is not None and not self.before_append():
self.abandon()
# 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()
return False
return await self._submit()
async def _submit(self) -> bool:
session = self.ctx.session
model_state = self.ctx.model_state
try:
append_ok, emitted_response = await self.model.append_runtime_input(
self.payload,
operation_id=(
self.pcm_reservation.operation_id if self.pcm_reservation is not None else self.operation_id
),
final=self.final,
expected_epoch=self.epoch,
)
if append_ok:
model_state.context_locked = True
if self.pcm_reservation is not None:
self.pcm_reservation.commit()
session.release_input_bytes(self.pcm_reservation.byte_count)
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
if not emitted_response and session.epoch == self.epoch:
if session.active_request_id == helpers.stage0_request_id(session, self.epoch):
session.clear_request(self.request_id)
if self.final:
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()
logger.exception("Native duplex append task failed: %s", exc)
self.model.send_runtime_error("runtime_append_task_failed", exc)
if session.state != DuplexSessionState.CLOSED:
self.fail_session("runtime_append_task_failed")
return False
def _precreated_response_still_active(self) -> bool:
return (
self.precreated_response_id is not None
and self.ctx.session.active_response_id == self.precreated_response_id
)
def _fail_precreated_response(self) -> None:
session = self.ctx.session
session.end_response(commit_text=False)
self.out.emit(
{
"type": "response.done",
"session_id": session.session_id,
"response_id": self.precreated_response_id,
"epoch": session.epoch,
"committed": False,
"status": "failed",
"status_details": {"type": "failed", "reason": "runtime_append_failed"},
"playback": session.playback.as_dict(),
}
)
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
class CommitAction(str, Enum):
"""How one native audio commit participates in response scheduling."""
START_AUTO_RESPONSE = "start_auto_response"
DEFER_ACTIVE_RESPONSE = "defer_active_response"
COMMIT_ONLY = "commit_only"
@dataclass(frozen=True, slots=True)
class CommitSnapshot:
auto_responds: bool
speech_since_commit: bool
active_response_id: str | None
overlap_speech_ms: int
response_in_progress: bool
playback_active: bool
def decide_commit_action(snapshot: CommitSnapshot) -> CommitAction:
"""Choose response scheduling from an immutable session snapshot."""
if snapshot.auto_responds:
if snapshot.speech_since_commit:
return CommitAction.START_AUTO_RESPONSE
return CommitAction.COMMIT_ONLY
if snapshot.response_in_progress and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
if snapshot.playback_active and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
return CommitAction.COMMIT_ONLY
__all__ = ["CommitAction", "CommitSnapshot", "decide_commit_action"]
+161
View File
@@ -0,0 +1,161 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Shared state for :class:`DuplexSessionRunner` and its components.
The runner is a state machine that several components read and write. Splitting
it into modules only helps if the shared part stops being implicit: a component
holding a back-reference to the runner is a mixin with extra steps, and one
holding its own copy of a flag diverges from the others.
So the mutable part is named. ``DuplexRunState`` is the small set of flags that
more than one component touches -- ``grep "\\.run\\."`` finds every mutation --
and ``DuplexSessionContext`` is the read-mostly collaborator bundle everything
is constructed with. Anything a component needs from the runner that is neither
of those is infrastructure, and goes through :class:`RunnerServices`.
"""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Protocol, TypeVar
if TYPE_CHECKING:
from vllm.outputs import RequestOutput
from vllm_omni.engine.duplex.contracts import (
DuplexOutputContext,
DuplexOutputDecision,
DuplexStagePort,
)
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, DuplexModelSessionState
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
from vllm_omni.metrics.stats import StageRequestStats
_OffloadT = TypeVar("_OffloadT")
@dataclass(slots=True)
class DuplexRunState:
"""Mutable per-run flags shared by the runner and its components.
Every field here is written by one component and read by another; that is
the criterion for being in this object rather than private to a component.
"""
#: An irreversible close has begun: commands and control ops are refused.
closing: bool = False
#: ``session.closed`` / ``session.expired`` already left the runner.
closed_emitted: bool = False
#: The terminal event is deferred to the manager, which emits it after the
#: stage cleanup so it also means "the admission slot is free again".
closed_deferred: bool = False
close_reason: str | None = None
#: The model runtime reported a close; further data-plane work is pointless.
runtime_closed: bool = False
#: Request id of the resumable data-plane stream currently bound to the session.
stream_request_id: str | None = None
class RunnerServices(Protocol):
"""The only things a component may ask the runner for.
Deliberately two methods. A component that needs more than task scheduling
from the runner is reaching for orchestration that belongs in the runner.
"""
def spawn(self, coro: Awaitable[None], *, name: str) -> None:
"""Run ``coro`` as a tracked background task on the session's loop."""
...
async def offload(self, fn: Callable[..., _OffloadT], *args: object, **kwargs: object) -> _OffloadT:
"""Run a blocking call off the orchestrator loop."""
...
@dataclass(slots=True)
class DuplexSessionContext:
"""Collaborators one session's components are built with.
Read-mostly: the session and the model state are mutated through their own
APIs, not by rebinding these fields. The mutable flags live in ``run``.
"""
session: DuplexEngineSession
model_state: DuplexModelSessionState
plugin: DuplexModelPlugin
stage_port: DuplexStagePort
manager: DuplexSessionManager
tasks: DuplexSessionTasks
run: DuplexRunState
services: RunnerServices
# --------------------------------------------------------------------------- #
# Task bookkeeping #
# --------------------------------------------------------------------------- #
@dataclass(frozen=True, slots=True)
class DuplexAppendTaskMeta:
epoch: int
final: bool
response_bound: bool
@dataclass
class DuplexSessionTasks:
"""Tracked task handles of one session (append tail, active response, pending silence)."""
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
def track_append_task(
self,
task: asyncio.Task[bool],
*,
epoch: int,
final: bool,
response_bound: bool,
) -> None:
self.append_tasks[task] = DuplexAppendTaskMeta(epoch, final, response_bound)
task.add_done_callback(self.append_tasks.pop)
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:
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
for task in tasks:
task.cancel()
try:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=timeout_s)
except TimeoutError:
pass
if cancelled_tail is not None and self.append_tail is cancelled_tail:
self.append_tail = None
return True
# --------------------------------------------------------------------------- #
# Stage output (the mailbox item the orchestrator hands the runner) #
# --------------------------------------------------------------------------- #
@dataclass(frozen=True, slots=True)
class StageOutput:
"""One stage result, queued for the session that owns the request."""
stage_id: int
output: RequestOutput
metrics: StageRequestStats | None
request_id: str
context: DuplexOutputContext
decision: DuplexOutputDecision | None
+328
View File
@@ -0,0 +1,328 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Control of one duplex session: server VAD, and the events that reconfigure it.
Server turn detection and ``session.update`` are the same concern seen from two
sides. The detector is per-session mutable state, and ``session.update`` is the
event that replaces it mid-flight -- along with the session config, the runtime
config and the sampling policy, each of which has to be validated against a
candidate before the live session adopts it. The rest of ``turn.signal``
(conversation items, local turn markers) travels the same path and is small, so
it lives here rather than in a module of its own.
The one thing this does not own is ordering against the data plane: a
``session.update`` must not overtake an append still in flight, so the runner
supplies ``wait_for_append_tail``.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from copy import deepcopy
from vllm.logger import init_logger
from vllm_omni.engine.duplex.config import DuplexConfigError, realtime_item_to_history_message
from vllm_omni.engine.duplex.plugin import DuplexRuntimeConfigError
from vllm_omni.engine.duplex.session import helpers
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
from vllm_omni.engine.duplex.session.emitter import SessionEmitter
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
from vllm_omni.engine.duplex.turn_detection import (
PendingTurnDetectionUpdate,
ServerTurnDetector,
ServerVADUnavailableError,
SileroVADBackendProvider,
TurnDetectionConfig,
TurnDetectionResult,
apply_turn_detection_result,
)
logger = init_logger(__name__)
class SessionControl:
"""Server VAD and the control events that reconfigure one session."""
def __init__(
self,
ctx: DuplexSessionContext,
out: SessionEmitter,
model: ModelChannel,
*,
wait_for_append_tail: Callable[[], Awaitable[bool]],
) -> None:
self._ctx = ctx
self._out = out
self._model = model
self._wait_for_append_tail = wait_for_append_tail
self._config: TurnDetectionConfig | None = None
self._detector: ServerTurnDetector | None = None
def init_turn_detection(self) -> None:
turn_detection = self._ctx.session.config.extra_body.get("realtime_turn_detection")
if not isinstance(turn_detection, dict) or turn_detection.get("type") != "server_vad":
self._config = None
self._detector = None
return
try:
config = TurnDetectionConfig.from_realtime(turn_detection)
self._config = config
self._detector = config.build_detector(self._vad_backend_provider())
except Exception as exc:
logger.warning("Duplex session %s: turn detection disabled: %s", self._ctx.session.session_id, exc)
self._config = None
self._detector = None
def _vad_backend_provider(self) -> SileroVADBackendProvider | None:
"""The engine-wide Silero backend, so one model serves every session.
Held by the manager rather than built here: the ONNX backend is shared,
and ``duplex_session.server_vad_model_path`` is a deploy-level setting.
"""
return getattr(self._ctx.manager, "vad_backend_provider", None)
def reset_vad(self) -> None:
"""Drop the detector's speech state (a barge-in or a clear starts a new turn)."""
if self._detector is not None:
self._detector.reset()
async def run_turn_detection(self, event: dict[str, object]) -> TurnDetectionResult | None:
detector = self._detector
if detector is None:
return None
audio = event.get("audio")
if not isinstance(audio, str) or not audio:
return None
fmt = event.get("format") if isinstance(event.get("format"), str) else "pcm_f32le"
sample_rate_hz = event.get("sample_rate_hz")
try:
result = await self._ctx.services.offload(
detector.process,
audio,
fmt=fmt,
sample_rate_hz=sample_rate_hz if isinstance(sample_rate_hz, int) else None,
audio_end_ms=event.get("audio_end_ms") if isinstance(event.get("audio_end_ms"), int) else None,
)
except ServerVADUnavailableError as exc:
self._out.emit_error("server_vad_unavailable", str(exc))
self._detector = None
return None
except ValueError as exc:
self._out.emit_error("bad_audio", str(exc))
return None
apply_turn_detection_result(event, result)
return result
# ------------------------------------------------------------------ #
# Control events #
# ------------------------------------------------------------------ #
async def on_turn_signal(self, event: dict[str, object]) -> None:
session = self._ctx.session
turn_event = event.get("event")
realtime_event_id = event.get("realtime_event_id")
if not isinstance(turn_event, str):
self._out.emit_error("bad_event", "turn.signal requires event")
return
if turn_event == "barge_in" and not session.capabilities.supports_barge_in:
self._out.emit_events([helpers.barge_in_unsupported_error()])
return
if turn_event == "session.update":
payload = event.get("payload")
if not isinstance(payload, dict):
self._out.emit_error(
"bad_event", "session.update requires a session payload", event_id=realtime_event_id
)
return
await self.on_session_update(
payload,
realtime_event_id=realtime_event_id if isinstance(realtime_event_id, str) else None,
)
return
if turn_event == "conversation.item.create":
await self._on_conversation_item_create(event)
return
if turn_event == "conversation.item.delete":
payload = event.get("payload")
item_id = payload.get("item_id") if isinstance(payload, dict) else None
deleted = session.delete_history_item(item_id) if isinstance(item_id, str) else False
self._out.emit(
{
"type": "conversation.item.deleted",
"session_id": session.session_id,
"item_id": item_id,
"deleted": deleted,
}
)
return
if turn_event == "conversation.item.truncate":
payload = event.get("payload")
item_id = payload.get("item_id") if isinstance(payload, dict) else None
audio_end_ms = payload.get("audio_end_ms") if isinstance(payload, dict) else None
truncated = (
session.truncate_history_item(
item_id,
audio_end_ms=int(audio_end_ms) if isinstance(audio_end_ms, int | float) else 0,
hard=True,
)
if isinstance(item_id, str)
else False
)
self._out.emit(
{
"type": "conversation.item.truncated",
"session_id": session.session_id,
"item_id": item_id,
"content_index": (payload.get("content_index", 0) if isinstance(payload, dict) else 0),
"audio_end_ms": audio_end_ms,
"truncated": truncated,
}
)
return
self._out.emit_events([session.signal_turn(turn_event, event)])
async def on_session_update(self, payload: dict[str, object], *, realtime_event_id: str | None) -> None:
session = self._ctx.session
model_state = self._ctx.model_state
pending_turn_detection: PendingTurnDetectionUpdate | None = None
def reject_update() -> None:
if pending_turn_detection is not None:
pending_turn_detection.reject()
try:
pending_turn_detection = PendingTurnDetectionUpdate.prepare(
payload, backend_provider=self._vad_backend_provider()
)
except Exception as exc:
self._out.emit_error("unsupported_turn_detection", str(exc), event_id=realtime_event_id)
return
if not await self._wait_for_append_tail():
self._out.emit_error(
"session_update_aborted",
"session.update was not applied because the preceding append failed",
event_id=realtime_event_id,
)
reject_update()
return
try:
self._ctx.plugin.validate_client_extra_body(payload.get("extra_body"))
except DuplexRuntimeConfigError as exc:
self._out.emit_error(exc.code, str(exc), event_id=realtime_event_id)
reject_update()
return
candidate_config = deepcopy(session.config)
audio_started = session.playback.generated_ms > 0 or session.playback.sent_ms > 0
try:
candidate_config.apply_realtime_update(
payload,
session_id=session.session_id,
audio_started=audio_started,
)
except DuplexConfigError as exc:
self._out.emit_error(exc.code, str(exc) or "session.update was rejected", event_id=realtime_event_id)
reject_update()
return
if candidate_config.instructions != session.config.instructions and model_state.context_locked:
self._out.emit_error(
"instructions_update_unsupported",
"session.update cannot change instructions after the native duplex context is initialized",
event_id=realtime_event_id,
)
reject_update()
return
requests_audio = any(str(modality).lower() == "audio" for modality in candidate_config.modalities)
if (
requests_audio
and "ref_audio_data" not in session.runtime_config
and getattr(self._ctx.plugin, "requires_ref_audio", False)
):
self._out.emit_error(
"ref_audio_required", "Native duplex audio output requires ref_audio", event_id=realtime_event_id
)
reject_update()
return
try:
candidate_runtime_config = self._ctx.plugin.runtime_config_for_update(
candidate_config,
dict(session.runtime_config),
)
# Validate the sampling policy for the candidate before adopting it.
self._ctx.plugin.configure_sampling_params(
runtime_config=dict(candidate_runtime_config),
defaults=tuple(self._ctx.stage_port.sampling_defaults()),
)
except (DuplexRuntimeConfigError, DuplexConfigError) as exc:
self._out.emit_error(exc.code, str(exc), event_id=realtime_event_id)
reject_update()
return
except Exception as exc:
self._out.emit_error("runtime_signal_failed", str(exc), event_id=realtime_event_id)
reject_update()
return
session.replace_config(candidate_config)
session.replace_runtime_config(candidate_runtime_config)
try:
session.touch_lease(DuplexLeaseActivity.SIGNAL)
except Exception:
pass
if pending_turn_detection is not None:
self._config, self._detector = pending_turn_detection.commit(self._detector)
projector = self._out.require_projector()
projector.apply_session_defaults(payload)
self._out.emit({"type": "session.updated", "session": session.as_public_dict()})
async def _on_conversation_item_create(self, event: dict[str, object]) -> None:
session = self._ctx.session
payload = event.get("payload")
item = payload.get("item") if isinstance(payload, dict) else None
item_type = item.get("type") if isinstance(item, dict) else None
if item_type == "function_call_output" and isinstance(item, dict):
if not await self._wait_for_append_tail():
return
try:
candidate_runtime_config = self._ctx.plugin.runtime_config_for_function_output(
session.config,
dict(session.runtime_config),
item,
)
except DuplexRuntimeConfigError as exc:
self._out.emit_error(exc.code, str(exc))
return
if candidate_runtime_config is not None:
session.replace_runtime_config(candidate_runtime_config)
self._out.emit(
{
"type": "conversation.item.created",
"session_id": session.session_id,
"item": item,
"created": True,
}
)
self._ctx.services.spawn(
self._model.maybe_continue_response(
expected_epoch=session.epoch,
expected_model_turn_id=session.turn_id,
),
name="duplex-continue",
)
return
message = realtime_item_to_history_message(item)
item_id = item.get("id") if isinstance(item, dict) else None
if message is not None:
session.append_history_message(message)
session.register_history_item(item_id if isinstance(item_id, str) else None, message)
if message.get("role") == "user":
# A later response.create may answer this without any audio.
session.notify_new_user_item()
self._out.emit(
{
"type": "conversation.item.created",
"session_id": session.session_id,
"item": item,
"created": message is not None,
}
)
+249
View File
@@ -0,0 +1,249 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Everything one duplex session sends to its client.
Emission is the hub of the session runner: near enough every path through the
runner ends in an event, which is why this is a collaborator rather than a
module of functions. It owns three things the rest of the runner should not
have to think about --- the Realtime projection state, the epoch filter that
drops output from a superseded turn, and the domain transitions an outbound
terminal event applies to the session before it is projected.
The one thing it cannot own is what happens *after* a terminal promotes
deferred overlap audio: that re-enters the mailbox of the runner, so the
runner injects it as ``promote_deferred_overlap``.
"""
from __future__ import annotations
from collections.abc import Callable
from vllm_omni.engine.duplex.config import DuplexSessionState
from vllm_omni.engine.duplex.events import (
DOMAIN_TERMINAL_EVENTS,
MODEL_OUTPUT_EVENTS,
DuplexEvent,
error_event,
)
from vllm_omni.engine.duplex.realtime_events import (
RealtimeProjectionState,
discard_pending_input_audio,
project_internal_event,
)
from vllm_omni.engine.duplex.session import overlap_policy
from vllm_omni.engine.duplex.session.context import DuplexSessionContext
class SessionEmitter:
"""Outbound events for one session."""
def __init__(
self,
ctx: DuplexSessionContext,
*,
promote_deferred_overlap: Callable[[dict[str, object], bool], None],
) -> None:
self._ctx = ctx
self._promote_deferred_overlap = promote_deferred_overlap
self._projector: RealtimeProjectionState | None = ctx.session.projector
# ------------------------------------------------------------------ #
# Projection state #
# ------------------------------------------------------------------ #
@property
def projector(self) -> RealtimeProjectionState | None:
"""The Realtime projection state, or ``None`` before anything needs it."""
return self._projector
@projector.setter
def projector(self, value: RealtimeProjectionState | None) -> None:
self._projector = value
self._ctx.session.projector = value
def require_projector(self) -> RealtimeProjectionState:
"""The projection state, created on first use.
A session torn down before ``start()`` never builds one, so the lazy
path here is reachable rather than defensive.
"""
projector = self._projector
if projector is None:
session = self._ctx.session
projector = RealtimeProjectionState(
session_id=session.session_id,
model=session.config.model,
initial_session_update=True,
)
self.projector = projector
return projector
# ------------------------------------------------------------------ #
# Sending #
# ------------------------------------------------------------------ #
def emit_events(self, events: list[DuplexEvent]) -> None:
for event in events:
self._ctx.manager.emit(self._ctx.session, event)
def emit_error(
self,
code: str,
message: str,
*,
event_id: object | None = None,
retryable: bool | None = None,
) -> None:
"""Send one typed ``error`` event (``event_id`` is the client event it answers)."""
extra = {} if retryable is None else {"retryable": retryable}
self.emit_events([error_event(code, message, event_id=event_id, extra=extra)])
def emit(self, payload: dict[str, object]) -> None:
"""Apply the domain effects of an internal event, then project it to typed events and send them.
Only events with domain effects (response / cancel / close terminals) or
Realtime projection state (response items, content parts) still travel as
internal dictionaries; stateless events are constructed typed at the
emit site.
"""
accepted, deferred_overlap_payload = self._apply_outbound_session_event(payload)
if not accepted:
return
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
self._ctx.model_state.deferred_precreate_response = False
self._promote_deferred_overlap(deferred_overlap_payload, precreate_response)
# ------------------------------------------------------------------ #
# Filtering and domain effects #
# ------------------------------------------------------------------ #
def auto_responds(self) -> bool:
"""Whether the session answers committed input without a ``response.create``."""
extra = getattr(self._ctx.session.config, "extra_body", None)
if not isinstance(extra, dict):
return False
return extra.get("auto_response") is True or extra.get("full_duplex") is True
def is_stale_model_output(self, payload: dict[str, object]) -> bool:
"""Whether ``payload`` belongs to a turn the session has already moved past."""
session = self._ctx.session
event_type = payload.get("type")
if event_type in DOMAIN_TERMINAL_EVENTS:
return False
if event_type not in MODEL_OUTPUT_EVENTS:
return False
if self._ctx.run.closing and event_type != "response.listen":
return True
if session.state == DuplexSessionState.CLOSED and event_type != "response.listen":
return True
epoch = payload.get("epoch")
return isinstance(epoch, int) and epoch != session.epoch
def _apply_outbound_session_event(self, payload: dict[str, object]) -> tuple[bool, dict[str, object] | None]:
"""Apply domain transitions before an event is projected (moved from serving)."""
session = self._ctx.session
model_state = self._ctx.model_state
payload_type = payload.get("type")
is_terminal = payload_type in DOMAIN_TERMINAL_EVENTS
if is_terminal:
payload_epoch = payload.get("epoch")
if isinstance(payload_epoch, int) and payload_epoch != session.epoch:
return False, None
if payload_type in {"response.done", "response.listen"} and (
self._ctx.run.closing or session.state == DuplexSessionState.CLOSED
):
return False, None
elif self.is_stale_model_output(payload):
return False, None
if payload_type == "session.closed":
self._ctx.run.close_reason = self._ctx.run.close_reason or str(payload.get("reason") or "closed")
session.mark_closing()
if not is_terminal:
return True, None
terminal_status = payload.get("status")
terminal_status_details = payload.get("status_details")
if terminal_status is None and isinstance(terminal_status_details, dict):
terminal_status = terminal_status_details.get("type")
response_terminal = payload_type == "response.done" or (
payload_type == "response.listen" and session.active_response_id is not None
)
can_promote_overlap = response_terminal and terminal_status not in {"cancelled", "failed"}
deferred_overlap_payload: dict[str, object] | None = None
continuous_input_crosses_terminal = (
can_promote_overlap
and self.auto_responds()
and model_state.input_since_commit
and not model_state.deferred_response_create
)
if continuous_input_crosses_terminal:
session.reset_overlap_speech()
return True, None
realtime_input_still_open = (
can_promote_overlap and model_state.input_since_commit and not model_state.deferred_response_create
)
if realtime_input_still_open:
session.reset_overlap_speech()
return True, None
if can_promote_overlap and session.overlap_speech_ms > 0:
has_deferred_overlap = (
model_state.audio_buffer.has_pending() or model_state.committed_audio_payload is not None
)
should_promote_overlap = (
session.state == DuplexSessionState.OPEN
and has_deferred_overlap
and session.overlap_speech_ms > session.config.overlap_short_ack_ms
)
if should_promote_overlap:
flushed_reserved_bytes = model_state.audio_buffer.pending_byte_count
deferred_overlap_payload = model_state.audio_buffer.flush(
chunk_period_ms=session.capabilities.chunk_period_ms or 1000
)
if model_state.committed_audio_payload is not None:
if deferred_overlap_payload is not None:
deferred_overlap_payload = overlap_policy.merge_audio_payloads(
model_state.committed_audio_payload,
deferred_overlap_payload,
)
else:
deferred_overlap_payload = model_state.committed_audio_payload
if self.auto_responds() and deferred_overlap_payload is not None:
deferred_overlap_payload = dict(deferred_overlap_payload)
deferred_overlap_payload["force_listen"] = False
if deferred_overlap_payload is not None:
model_state.retain_committed_audio(
deferred_overlap_payload,
operation_id=model_state.committed_audio_operation_id,
reserved_bytes=flushed_reserved_bytes,
)
model_state.input_since_commit = deferred_overlap_payload is not None
# Realtime path: defer the promoted response to the next terminal.
model_state.deferred_response_create = True
model_state.deferred_precreate_response = False
deferred_overlap_payload = None
else:
had_pending_overlap_audio = model_state.audio_buffer.has_pending()
model_state.audio_buffer.clear()
model_state.input_since_commit = False
model_state.speech_since_commit = False
if had_pending_overlap_audio and self._projector is not None:
self.emit_events(discard_pending_input_audio(self._projector, session.overlap_speech_ms))
if payload_type in {"audio.cancelled", "input.cancelled", "session.closed"}:
session.release_input_bytes(model_state.clear_committed_audio())
session.reset_overlap_speech()
if (
can_promote_overlap
and model_state.deferred_response_create
and model_state.committed_audio_payload is not None
):
deferred_overlap_payload = model_state.committed_audio_payload
model_state.deferred_response_create = False
model_state.input_since_commit = False
model_state.speech_since_commit = False
return True, deferred_overlap_payload
File diff suppressed because it is too large. Load diff
+195
View File
@@ -0,0 +1,195 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Small reads and payload builders over one duplex session.
None of these hold state or decide anything: they answer a question about the
session, or shape one of the wire payloads its events carry. They were methods
on the runner only because that is where the session reference lived, which
made every component that needed one a reason to reach back into the runner.
Functions, not a component, because there is nothing here to own.
"""
from __future__ import annotations
import binascii
from typing import TYPE_CHECKING
import pybase64 as base64
from vllm_omni.engine.duplex.config import DuplexPlaybackCommitPolicy
from vllm_omni.engine.duplex.contracts import DuplexFence, duplex_resource_request_id
from vllm_omni.engine.duplex.events import ErrorEvent, OverlapDecision, error_event
if TYPE_CHECKING:
from collections.abc import Mapping
from vllm_omni.engine.duplex.session.context import DuplexSessionTasks
from vllm_omni.engine.duplex.session.engine_session import DuplexCommittedInput, DuplexEngineSession
# --------------------------------------------------------------------------- #
# Questions about the session #
# --------------------------------------------------------------------------- #
def stage0_request_id(session: DuplexEngineSession, epoch: int) -> str:
return duplex_resource_request_id(DuplexFence(session.session_id, epoch=epoch), "stage0")
def response_in_progress(session: DuplexEngineSession, tasks: DuplexSessionTasks) -> bool:
"""Whether the model still owns the turn.
Broader than ``active_response_id``: audio already sent but not yet played
back, and an append still in flight, both mean the turn is not free.
"""
if session.active_response_id is not None:
return True
if assistant_playback_active(session):
return True
active_task = tasks.active_response_task
if active_task is not None and not active_task.done():
return True
return tasks.has_response_bound_append_tasks()
def assistant_playback_active(session: DuplexEngineSession) -> bool:
"""Whether the client is still playing audio the session has sent."""
return (
session.config.playback_commit_policy == DuplexPlaybackCommitPolicy.ACK_ONLY.value
and session.playback.sent_ms > session.playback.committed_ms
)
def audio_payload_size_bytes(payload: Mapping[str, object]) -> int:
audio = payload.get("audio") or payload.get("data")
if not isinstance(audio, str):
return 0
try:
return len(base64.b64decode(audio, validate=True))
except (ValueError, binascii.Error):
return 0
# --------------------------------------------------------------------------- #
# Turn transitions #
# --------------------------------------------------------------------------- #
def advance_barge_in_epoch(session: DuplexEngineSession) -> tuple[int, dict[str, int]]:
"""Start a new epoch for a barge-in, returning it with the playback it cut off."""
old_playback = session.playback.as_dict()
new_epoch = session.barge_in()
session.clear_playback_cursor()
return new_epoch, old_playback
def commit_played_response_history(
session: DuplexEngineSession,
response_id: str | None,
committed_ms: int,
) -> None:
"""Truncate an interrupted response in history to what the client actually heard."""
if not response_id or committed_ms < 0:
return
session.truncate_history_item(
f"item_{response_id}",
audio_end_ms=committed_ms,
playback=session.playback_for_response(response_id),
)
def commit_audio_input(
session: DuplexEngineSession,
*,
realtime_item_id: object | None = None,
transcript: object | None = None,
turn_id: int | None = None,
) -> DuplexCommittedInput:
clean_transcript = transcript.strip() if isinstance(transcript, str) else None
committed = session.commit_audio_input(
transcript=clean_transcript or None,
turn_id=turn_id,
)
if isinstance(realtime_item_id, str) and realtime_item_id:
session.register_history_item(realtime_item_id, committed.message)
return committed
# --------------------------------------------------------------------------- #
# Payloads #
# --------------------------------------------------------------------------- #
def barge_in_unsupported_error() -> ErrorEvent:
return error_event("barge_in_unsupported", "Barge-in is not supported by this duplex model")
def overlap_decision_event(session: DuplexEngineSession, decision: dict[str, object]) -> OverlapDecision:
details: dict[str, object] = {
"type": "overlap.decision",
"session_id": session.session_id,
"epoch": session.epoch,
"policy": session.config.overlap_policy,
**decision,
}
action = decision.get("action")
reason = decision.get("reason")
return OverlapDecision(
policy=session.config.overlap_policy,
action=action if isinstance(action, str) else None,
reason=reason if isinstance(reason, str) else None,
details=details,
)
def input_committed_payload(
session: DuplexEngineSession,
committed: DuplexCommittedInput,
*,
realtime_item_id: object | None = None,
) -> dict[str, object]:
payload: dict[str, object] = {
"type": "input.committed",
"session_id": session.session_id,
"turn_id": committed.turn_id,
"epoch": committed.epoch,
"history_len": len(session.history),
"message": committed.message,
}
if isinstance(realtime_item_id, str) and realtime_item_id:
payload["realtime_item_id"] = realtime_item_id
return payload
def audio_committed_payload(
session: DuplexEngineSession,
*,
committed: DuplexCommittedInput | None = None,
realtime_item_id: object | None = None,
transcript: object | None = None,
) -> dict[str, object]:
message = committed.message if committed is not None else None
if not isinstance(message, dict):
input_audio_part: dict[str, object] = {
"type": "audio_url",
"audio_url": {"url": "native-duplex:input-audio"},
}
if isinstance(transcript, str) and transcript:
input_audio_part["transcript"] = transcript
message = {"role": "user", "content": [input_audio_part]}
payload: dict[str, object] = {
"type": "input.committed",
"session_id": session.session_id,
"turn_id": committed.turn_id if committed is not None else session.turn_id,
"epoch": committed.epoch if committed is not None else session.epoch,
"history_len": len(session.history),
"native_audio": True,
"message": message,
}
if isinstance(transcript, str) and transcript:
payload["transcript"] = transcript
if isinstance(realtime_item_id, str) and realtime_item_id:
payload["realtime_item_id"] = realtime_item_id
return payload
+116
View File
@@ -0,0 +1,116 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Generic engine lease primitives shared by optional session runtimes."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
class DuplexLeaseActivity(str, Enum):
APPEND = "append"
SIGNAL = "signal"
PLAYBACK_ACK = "playback_ack"
HEARTBEAT = "heartbeat"
ATTACH = "attach"
DETACH = "detach"
RESUME = "resume"
MODEL_OUTPUT = "model_output"
@dataclass(frozen=True)
class DuplexLeaseConfig:
idle_ttl_s: float | None = 300.0
disconnect_grace_s: float = 30.0
def __post_init__(self) -> None:
if self.idle_ttl_s is not None and self.idle_ttl_s <= 0:
raise ValueError("idle_ttl_s must be positive or null")
if self.disconnect_grace_s <= 0:
raise ValueError("disconnect_grace_s must be positive")
@dataclass
class DuplexLeaseState:
config: DuplexLeaseConfig
generation: int
last_activity: float
detached_at: float | None = None
active_operations: set[str] = field(default_factory=set)
terminal_reason: str | None = None
@property
def expires_at(self) -> float | None:
if self.config.idle_ttl_s is None:
return None
return self.last_activity + self.config.idle_ttl_s
def _require_open(self) -> None:
if self.terminal_reason is not None:
raise RuntimeError(f"duplex lease is terminal: {self.terminal_reason}")
def touch(self, now: float, activity: DuplexLeaseActivity) -> None:
self._require_open()
if not isinstance(activity, DuplexLeaseActivity):
raise TypeError("lease activity must be DuplexLeaseActivity")
self.last_activity = now
def detach(self, now: float) -> None:
self.touch(now, DuplexLeaseActivity.DETACH)
self.detached_at = now
def resume(self, now: float, *, expected_generation: int) -> int:
self._require_open()
if expected_generation != self.generation:
raise ValueError(f"duplex lease generation mismatch: expected {self.generation}, got {expected_generation}")
self.generation += 1
self.detached_at = None
self.last_activity = now
return self.generation
def begin_operation(self, now: float, operation_id: str) -> None:
self._require_open()
if not operation_id:
raise ValueError("duplex lease operation_id must not be empty")
if operation_id in self.active_operations:
raise ValueError(f"duplex lease operation already active: {operation_id}")
self.active_operations.add(operation_id)
self.last_activity = now
def end_operation(self, now: float, operation_id: str) -> None:
self._require_open()
if operation_id not in self.active_operations:
raise KeyError(f"duplex lease operation is not active: {operation_id}")
self.active_operations.remove(operation_id)
self.last_activity = now
def disconnect_grace_expired(self, now: float) -> bool:
return (
self.terminal_reason is None
and self.detached_at is not None
and now >= self.detached_at + self.config.disconnect_grace_s
)
def idle_expired(self, now: float) -> bool:
expires_at = self.expires_at
return (
self.terminal_reason is None and not self.active_operations and expires_at is not None and now >= expires_at
)
def mark_terminal(self, reason: str) -> bool:
if self.terminal_reason is not None:
return False
self.terminal_reason = reason
self.generation += 1
self.detached_at = None
self.active_operations.clear()
return True
__all__ = [
"DuplexLeaseActivity",
"DuplexLeaseConfig",
"DuplexLeaseState",
]
+872
View File
@@ -0,0 +1,872 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Engine-side owner of duplex sessions: admission, lease reaping, command dispatch.
``DuplexOrchestrator`` hosts exactly one manager. The whole session
(``DuplexEngineSession``) lives here, owned by one ``DuplexSessionRunner`` per
session on the orchestrator loop; nothing outside the engine holds session
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``.
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import time
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
from vllm.logger import init_logger
from vllm_omni.engine.duplex.commands import AppendAudio, Commit, DuplexCommand
from vllm_omni.engine.duplex.contracts import (
DuplexFence,
DuplexStagePort,
DuplexStageRequestContext,
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.messages import (
CloseDuplexSessionMessage,
DuplexControlResultMessage,
DuplexSessionCommandMessage,
DuplexSessionError,
DuplexSessionEventMessage,
OpenDuplexSessionMessage,
ResumeDuplexSessionMessage,
TouchDuplexSessionMessage,
)
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, DuplexRuntimeConfigError, validate_duplex_plugin_sampling
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession, DuplexFenceMismatchError
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity, DuplexLeaseConfig, DuplexLeaseState
from vllm_omni.engine.duplex.turn_detection import SileroVADBackendProvider
if TYPE_CHECKING:
import janus
from vllm.config import ModelConfig
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
from vllm_omni.engine.messages import EngineQueueMessage
logger = init_logger(__name__)
@dataclass(frozen=True)
class _PendingRequestCleanup:
session_id: str
lease_generation: int
request_ids: tuple[str, ...]
abort: bool
@dataclass(frozen=True)
class _PendingSessionCleanup:
"""A close/expiry whose stage cleanup has not succeeded yet (retried by the reaper)."""
kind: str
session_id: str
lease_generation: int
reason: str
submitted_request_ids: tuple[str, ...]
reserved_request_ids: tuple[str, ...]
class DuplexSessionManager:
_CONTROL_TYPES = (
OpenDuplexSessionMessage,
CloseDuplexSessionMessage,
ResumeDuplexSessionMessage,
TouchDuplexSessionMessage,
)
_MESSAGE_TYPES = (*_CONTROL_TYPES, DuplexSessionCommandMessage)
def __init__(
self,
*,
plugin: DuplexModelPlugin,
stage_port: DuplexStagePort,
output_sink: janus.AsyncQueue[EngineQueueMessage],
result_sink: janus.AsyncQueue[EngineQueueMessage],
runtime_config: DuplexSessionRuntimeConfig,
model_config: ModelConfig | None,
clock: Callable[[], float] | None = None,
executor: concurrent.futures.ThreadPoolExecutor | None = None,
) -> None:
validate_duplex_plugin_sampling(plugin, sampling_defaults=tuple(stage_port.sampling_defaults()))
self.plugin = plugin
self.stage_port = stage_port
self.model_config = model_config
self.runtime_config = runtime_config
self._output_sink = output_sink
self._result_sink = result_sink
self._clock = clock or time.monotonic
self.executor = executor or concurrent.futures.ThreadPoolExecutor(
max_workers=4,
thread_name_prefix="duplex-session",
)
self._owns_executor = executor is None
self._lease_config = DuplexLeaseConfig(
idle_ttl_s=runtime_config.idle_ttl_s,
disconnect_grace_s=runtime_config.disconnect_grace_s,
)
#: One Silero backend for the whole engine: the ONNX graph is stateless
#: per call, so every session's detector can share it. Resolved lazily,
#: on the first session that actually turns server VAD on.
self.vad_backend_provider = SileroVADBackendProvider(
model_path=getattr(runtime_config, "server_vad_model_path", None)
)
self.runners: dict[str, DuplexSessionRunner] = {}
#: Sessions whose close/expiry began but whose stage cleanup has not finalized;
#: they keep their admission slot until finalized.
self._closing: dict[str, _PendingSessionCleanup] = {}
#: Session ids whose ``open`` passed the capacity check and is still awaiting the plugin.
self._admitting: set[str] = set()
#: Opens whose caller gave up (control RPC timeout / cancellation) before
#: admission finished. The open completes anyway -- it is already past
#: the capacity check -- so it must tear itself down on arrival instead
#: of holding a slot and a stage resource until idle expiry.
self._abandoned_opens: set[str] = set()
self._request_index: dict[str, str] = {}
self._session_control_tails: dict[str, asyncio.Task[None]] = {}
self._dispatched_control_tasks: set[asyncio.Task[None]] = set()
self._pending_request_cleanups: dict[tuple[str, int], _PendingRequestCleanup] = {}
self._request_cleanup_tasks: dict[tuple[str, int], asyncio.Task[None]] = {}
self._request_cleanups_in_progress: set[tuple[str, int]] = set()
#: Sessions retained for cleanup retry after their runner is gone.
self._session_snapshots: dict[str, DuplexEngineSession] = {}
# ------------------------------------------------------------------ #
# Views #
# ------------------------------------------------------------------ #
def active_count(self) -> int:
return len(self.runners)
def get(self, session_id: str) -> DuplexEngineSession | None:
runner = self.runners.get(session_id)
return runner.session if runner is not None else None
def sessions(self) -> dict[str, DuplexEngineSession]:
return {session_id: runner.session for session_id, runner in self.runners.items()}
def runner_for_request_id(self, request_id: str) -> DuplexSessionRunner | None:
session_id = self._request_index.get(request_id)
if session_id is None:
for candidate_id in self.runners:
if duplex_resource_request_belongs_to_session(request_id, candidate_id):
session_id = candidate_id
break
if session_id is None:
return None
return self.runners.get(session_id)
def register_request(self, request_id: str, session_id: str) -> None:
self._request_index[request_id] = session_id
def unregister_request(self, request_id: str) -> None:
self._request_index.pop(request_id, None)
def _unregister_session_requests(self, session_id: str) -> None:
for request_id in [rid for rid, sid in self._request_index.items() if sid == session_id]:
self._request_index.pop(request_id, None)
# ------------------------------------------------------------------ #
# Message routing #
# ------------------------------------------------------------------ #
def accepts(self, message: object) -> bool:
return isinstance(message, self._MESSAGE_TYPES)
def dispatch(self, message: object) -> None:
"""Route one engine request-queue message without blocking the request handler."""
if isinstance(message, DuplexSessionCommandMessage):
self._dispatch_command(message)
return
if not isinstance(message, self._CONTROL_TYPES):
raise TypeError(f"Unsupported duplex control message: {type(message).__name__}")
session_id = message.session_id
async def handle_message() -> None:
await self.handle(message)
self._run_control(session_id, f"duplex-control-{session_id}-{message.control_id}", handle_message)
def _run_control(
self,
session_id: str,
name: str,
operation: Callable[[], Awaitable[None]],
) -> asyncio.Task[None]:
"""Run one control operation after the session's previous one (per-session order)."""
predecessor = self._session_control_tails.get(session_id)
async def run_ordered() -> None:
if predecessor is not None:
try:
await predecessor
except BaseException:
pass
await operation()
task = asyncio.create_task(run_ordered(), name=name)
self._session_control_tails[session_id] = task
self._track_task(task)
def discard(completed: asyncio.Task[None]) -> None:
if self._session_control_tails.get(session_id) is completed:
self._session_control_tails.pop(session_id, None)
task.add_done_callback(discard)
return task
def _track_task(self, task: asyncio.Task[None]) -> None:
"""Keep a background task alive until it finishes and log an escaped exception."""
self._dispatched_control_tasks.add(task)
def done(completed: asyncio.Task[None]) -> None:
self._dispatched_control_tasks.discard(completed)
if not completed.cancelled() and completed.exception() is not None:
logger.error("duplex control task %s failed: %r", completed.get_name(), completed.exception())
task.add_done_callback(done)
async def handle(self, message: object) -> None:
if isinstance(message, OpenDuplexSessionMessage):
await self.open(message)
elif isinstance(message, CloseDuplexSessionMessage):
await self.close(message)
elif isinstance(message, ResumeDuplexSessionMessage):
await self.resume(message)
elif isinstance(message, TouchDuplexSessionMessage):
await self.touch(message)
elif isinstance(message, DuplexSessionCommandMessage):
self._dispatch_command(message)
else:
raise TypeError(f"Unsupported duplex control message: {type(message).__name__}")
def _dispatch_command(self, message: DuplexSessionCommandMessage) -> None:
"""Admit one command: identity check, backpressure, then the runner's ordered mailbox.
Backpressure contract shared with the runner: a ``Commit`` that passes
admission holds one pending-turn reservation and an ``AppendAudio``
holds its wire-size byte reservation until the runner dequeues the
command (the runner then re-reserves the decoded size around its PCM
reservation), so the mailbox never holds more bytes than the session
limit even while the worker is busy.
"""
runner = self.runners.get(message.session_id)
command = message.command
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,
),
)
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
),
)
return
if isinstance(command, AppendAudio):
limit = int(self.runtime_config.max_pending_input_bytes_per_session)
if not session.reserve_input_bytes(len(command.audio), limit=limit):
self.emit(
session,
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,
),
)
return
runner.submit(command)
@staticmethod
def _error_event(code: str, message: str, *, command: DuplexCommand | None = None) -> ErrorEvent:
return error_event(code, message, event_id=command.event_id if command is not None else None)
# ------------------------------------------------------------------ #
# 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_raw(
self,
session_id: str,
event: DuplexEvent,
*,
epoch: int | None = None,
) -> None:
event = replace(event, session_id=session_id, epoch=epoch)
message = DuplexSessionEventMessage(session_id=session_id, event=event)
put_nowait = getattr(self._output_sink, "put_nowait", None)
if callable(put_nowait):
put_nowait(message)
else: # pragma: no cover - sink without put_nowait
asyncio.ensure_future(self._output_sink.put(message))
async def _put_result(
self,
message: (
OpenDuplexSessionMessage
| CloseDuplexSessionMessage
| ResumeDuplexSessionMessage
| TouchDuplexSessionMessage
),
*,
operation: str,
ok: bool,
session: DuplexEngineSession | None = None,
error: BaseException | None = None,
) -> None:
error_code, error_message, error_retryable = (
self._control_error(error) if error is not None else (None, None, False)
)
result = DuplexControlResultMessage(
control_id=message.control_id,
operation=operation,
session_id=message.session_id,
ok=ok,
lease_generation=session.lease_generation if session is not None else None,
capabilities=session.capabilities if session is not None and ok else None,
public_session=session.as_public_dict() if session is not None and ok else None,
error_code=error_code,
error_message=error_message,
error_retryable=error_retryable,
)
await self._result_sink.put(result)
@staticmethod
def _control_error(error: BaseException) -> tuple[str, str, bool]:
"""Map an exception to ``(code, message, retryable)`` for a control result."""
message = str(error)
retryable = False
if isinstance(error, DuplexSessionError):
code = error.code
retryable = error.retryable
elif isinstance(error, DuplexRuntimeConfigError):
code = error.code
elif isinstance(error, DuplexFenceMismatchError):
code = "stale_fence"
elif isinstance(error, KeyError):
code = "not_found"
elif isinstance(error, TypeError | ValueError):
code = "invalid_argument"
elif isinstance(error, TimeoutError):
code = "timeout"
retryable = True
else:
code = "failed_precondition"
return code, message, retryable
# ------------------------------------------------------------------ #
# Sampling / stage request helpers shared with the runner #
# ------------------------------------------------------------------ #
def sampling_params_for(self, session: DuplexEngineSession) -> tuple[object, ...]:
defaults = tuple(self.stage_port.sampling_defaults())
configured = self.plugin.configure_sampling_params(
runtime_config=dict(session.runtime_config),
defaults=defaults,
)
if not isinstance(configured, tuple):
raise TypeError("duplex plugin must return sampling parameters as a tuple")
if len(configured) != len(defaults):
raise ValueError("duplex plugin must return one sampling parameter per stage")
return configured
@staticmethod
def stage_request_id(fence: DuplexFence, *, stage_id: int) -> str:
return duplex_resource_request_id(fence, f"stage{stage_id}")
def ensure_stage_request(
self,
session: DuplexEngineSession,
*,
stage_id: int,
fence: DuplexFence | None = None,
) -> DuplexStageRequestContext | None:
"""Reserve the session's stage request id and register it with the stage port."""
if stage_id >= self.stage_port.stage_count:
return None
effective_fence = fence or session.fence
request_id = self.stage_request_id(effective_fence, stage_id=stage_id)
session.reserve_stage_request(stage_id, request_id, fence=effective_fence)
context = DuplexStageRequestContext(
request_id=request_id,
session_id=session.session_id,
fence=effective_fence,
stage_id=stage_id,
final_stage_id=self.stage_port.stage_count - 1,
config_generation=session.config_generation,
sampling_params=self.sampling_params_for(session),
session_config=session.config.as_dict(),
runtime_config=session.runtime_config,
)
self.stage_port.ensure_request(context)
self.register_request(request_id, session.session_id)
return context
# ------------------------------------------------------------------ #
# Control operations #
# ------------------------------------------------------------------ #
def _admission_count(self) -> int:
return len(set(self.runners) | set(self._closing) | self._admitting)
async def open(self, message: OpenDuplexSessionMessage) -> None:
from vllm_omni.engine.duplex.session.runner import DuplexSessionRunner
session_id = message.session_id
session: DuplexEngineSession | None = None
runner: DuplexSessionRunner | None = None
# Only the open that put the id in ``_admitting`` may take it out again:
# a duplicate open must not release the slot the first one is holding.
holds_admission_slot = False
try:
if session_id in self.runners or session_id in self._closing or session_id in self._admitting:
raise DuplexSessionError(f"Duplex session already exists: {session_id}", code="session_exists")
max_sessions = int(self.runtime_config.max_sessions)
if self._admission_count() >= max_sessions:
raise DuplexSessionError(
f"duplex_session_capacity_exhausted: limit={max_sessions}",
code="resource_exhausted",
retryable=True,
)
# Hold the slot across the plugin await: opens of different
# sessions run concurrently and must not all pass the check above.
self._admitting.add(session_id)
holds_admission_slot = True
config = message.session_config
self.plugin.validate_client_extra_body(config.extra_body)
try:
runtime_config = await self.plugin.prepare_runtime_config(config, model_config=self.model_config)
except DuplexRuntimeConfigError:
raise
except ValueError as exc:
raise DuplexRuntimeConfigError(str(exc)) from exc
capabilities = self.plugin.capabilities(max_sessions=max_sessions)
session = DuplexEngineSession(
session_id=session_id,
config=config,
capabilities=capabilities,
lease=DuplexLeaseState(config=self._lease_config, generation=0, last_activity=self._clock()),
_clock=self._clock,
_runtime_config=dict(runtime_config),
)
# Validates the plugin's sampling policy for this runtime config before admission.
self.sampling_params_for(session)
session.model_state = self.plugin.create_session_state()
runner = DuplexSessionRunner(
session=session,
plugin=self.plugin,
stage_port=self.stage_port,
manager=self,
model_config=self.model_config,
)
self.runners[session_id] = runner
# Reserve the Stage0 request resource atomically with admission.
self.ensure_stage_request(session, stage_id=0)
runner.start()
await self._put_result(message, operation="open", ok=True, session=session)
if session_id in self._abandoned_opens:
# The caller timed out while we were admitting; hand the slot
# and the stage resource straight back.
self._abandoned_opens.discard(session_id)
await self._close_runner(runner, kind="close", reason="open_abandoned")
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._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)
def _require_runner(self, session_id: str) -> DuplexSessionRunner:
runner = self.runners.get(session_id)
if runner is None:
raise DuplexSessionError(f"Unknown duplex session: {session_id}", code="unknown_session")
if runner.closing:
raise DuplexSessionError(f"Duplex session is closing: {session_id}", code="session_closed")
return runner
async def close(self, message: CloseDuplexSessionMessage) -> None:
session_id = message.session_id
runner = self.runners.get(session_id)
if runner is None:
if session_id in self._admitting:
# The open is still awaiting the plugin. It cannot be cancelled
# from here, so leave a note it checks before returning.
self._abandoned_opens.add(session_id)
# Already closing, or closed and forgotten: ids are never reused
# (D16), so a repeated close is idempotent rather than an error.
await self._put_result(message, operation="close", ok=True)
return
session = runner.session
try:
await self._close_runner(runner, kind="close", reason=message.reason)
except Exception as exc:
# The session is closed either way; only the stage cleanup is
# outstanding and the reaper retries it while the slot stays held.
logger.warning("close_duplex_session: stage cleanup for %s remains pending: %s", session_id, exc)
await self._put_result(message, operation="close", ok=True, session=session)
def close_from_runner(self, runner: DuplexSessionRunner, reason: str) -> None:
"""Finish a close the runner started from its command stream (``session.close``).
Runs on the orchestrator loop as a tracked task (the runner's worker
cannot await its own teardown): stage requests are aborted, the
admission slot is released and ``session.closed`` is emitted last.
"""
session_id = runner.session.session_id
if self.runners.get(session_id) is not runner:
return
async def close_runner() -> None:
if self.runners.get(session_id) is runner:
await self._close_runner(runner, kind="close", reason=reason)
# Chained on the session's control tail so a control RPC issued after
# the wire close observes the closed session, never a half-torn one.
self._run_control(session_id, f"duplex-close-{session_id}", close_runner)
async def _close_runner(self, runner: DuplexSessionRunner, *, kind: str, reason: str) -> None:
"""Begin an irreversible close, tear down the runner, then release stage resources.
The session keeps its admission slot (``_closing``) until stage cleanup
succeeded; a failed cleanup is retried by the reaper. For an explicit
close the ``session.closed`` event is emitted only after the cleanup
attempt, so a client that sees it can open a replacement session at
once (the runner used to emit it before the stage requests were
aborted, which let a prompt reopen hit ``resource_exhausted``).
"""
session = runner.session
submitted = tuple(session.resource_request_ids(submitted=True))
reserved = tuple(session.resource_request_ids(submitted=False))
session.begin_close(reason=reason)
pending = _PendingSessionCleanup(
kind=kind,
session_id=session.session_id,
lease_generation=session.lease_generation,
reason=reason,
submitted_request_ids=submitted,
reserved_request_ids=reserved,
)
self._closing[session.session_id] = pending
if self.runners.get(session.session_id) is runner:
self.runners.pop(session.session_id, None)
emit_after_cleanup = kind in {"close", "expired"} and not runner.closed_emitted
try:
if kind == "expired":
await runner.expire(reason, emit_expired=not emit_after_cleanup)
else:
await runner.close(reason, emit_closed=not emit_after_cleanup)
except Exception:
logger.exception("duplex runner %s failed for session %s", kind, session.session_id)
session.close()
try:
await self._finalize_pending_cleanup(pending, session)
finally:
# ``emit_after_cleanup`` was decided before the teardown awaits; a
# runtime close racing them may have emitted the terminal already.
if emit_after_cleanup and not runner.closed_emitted:
runner.mark_closed_emitted()
terminal: DuplexEvent = (
SessionExpired(reason=reason) if kind == "expired" else SessionClosed(reason=reason)
)
self.emit(session, terminal)
async def _finalize_pending_cleanup(
self,
pending: _PendingSessionCleanup,
session: DuplexEngineSession | None,
) -> None:
if pending.submitted_request_ids:
await self.stage_port.cleanup(list(pending.submitted_request_ids), abort=True)
if pending.reserved_request_ids:
await self.stage_port.cleanup(list(pending.reserved_request_ids))
if session is not None:
session.release_all_requests()
self._unregister_session_requests(pending.session_id)
if self._closing.get(pending.session_id) is pending:
self._closing.pop(pending.session_id, None)
self._session_snapshots.pop(pending.session_id, None)
async def resume(self, message: ResumeDuplexSessionMessage) -> None:
session: DuplexEngineSession | None = None
try:
runner = self._require_runner(message.session_id)
session = runner.session
try:
session.resume_lease(expected_lease_generation=message.expected_lease_generation)
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)
except Exception as exc:
logger.exception("resume_duplex_session failed: %s", exc)
await self._put_result(message, operation="resume", ok=False, session=session, error=exc)
async def touch(self, message: TouchDuplexSessionMessage) -> None:
session: DuplexEngineSession | None = None
try:
runner = self._require_runner(message.session_id)
session = runner.session
activity = DuplexLeaseActivity(message.activity)
if activity is DuplexLeaseActivity.DETACH:
session.detach_lease()
else:
session.touch_lease(activity)
await self._put_result(message, operation="touch", ok=True, session=session)
except DuplexSessionError as exc:
# A lease touch racing the session's own close is routine: the
# caller learns the session is gone from the result, not a fault.
logger.debug("touch_duplex_session skipped: %s", exc)
await self._put_result(message, operation="touch", ok=False, session=session, error=exc)
except Exception as exc:
logger.exception("touch_duplex_session failed: %s", exc)
await self._put_result(message, operation="touch", ok=False, session=session, error=exc)
# ------------------------------------------------------------------ #
# Lease expiry / reaper #
# ------------------------------------------------------------------ #
async def reaper_loop(self, shutdown_event: asyncio.Event) -> None:
interval = float(self.runtime_config.reaper_interval_s)
while not shutdown_event.is_set():
try:
await asyncio.wait_for(shutdown_event.wait(), timeout=interval)
except TimeoutError:
try:
await self.reap_expired()
except Exception:
logger.exception("[DuplexSessionManager] expiry cleanup failed; retrying on next tick")
async def reap_expired(self, now: float | None = None) -> int:
completed = 0
effective_now = self._clock() if now is None else now
# Retry request cleanups recorded by the orchestrator error paths.
for key, request_cleanup in list(self._pending_request_cleanups.items()):
if key in self._request_cleanups_in_progress:
continue
try:
await self._complete_request_cleanup(key, request_cleanup)
except Exception as exc:
logger.warning(
"duplex request cleanup remains pending for session %s: %s",
request_cleanup.session_id,
exc,
)
continue
completed += 1
# Retry closes/expiries whose stage cleanup failed.
for session_id, session_cleanup in list(self._closing.items()):
if session_id in self.runners:
continue
if session_cleanup.kind == "request_cleanup" and any(
key[0] == session_id for key in self._pending_request_cleanups
):
# The stage cleanup is owned by the request-cleanup path (orchestrator
# or the retry above); ``finalize_closed_sessions`` releases the slot.
continue
try:
await self._finalize_pending_cleanup(session_cleanup, self._session_snapshots.get(session_id))
except Exception as exc:
logger.warning(
"duplex %s cleanup remains pending for session %s: %s",
session_cleanup.kind,
session_id,
exc,
)
continue
completed += 1
# Expire leases.
for session_id, runner in list(self.runners.items()):
lease = runner.session.lease
if lease.disconnect_grace_expired(effective_now):
reason = "disconnect_grace_expired"
elif lease.idle_expired(effective_now):
reason = "idle_ttl_expired"
else:
continue
self._session_snapshots[session_id] = runner.session
try:
await self._close_runner(runner, kind="expired", reason=reason)
except Exception as exc:
logger.warning("duplex expiry cleanup remains pending for session %s: %s", session_id, exc)
continue
completed += 1
return completed
# ------------------------------------------------------------------ #
# Request-triggered cleanup (orchestrator error paths) #
# ------------------------------------------------------------------ #
def close_sessions_for_request_ids(
self,
request_ids: list[str],
*,
abort: bool = False,
cleanup_in_progress: bool = False,
) -> dict[str, list[str]]:
request_id_set = set(request_ids)
closed: dict[str, list[str]] = {}
for session_id, runner in list(self.runners.items()):
session = runner.session
stale = session.resource_request_ids()
if request_id_set.isdisjoint(stale):
continue
if not session.begin_close(reason="request_cleanup"):
continue
closed[session_id] = stale
key = (session_id, session.lease_generation)
existing = self._pending_request_cleanups.get(key)
merged = tuple(dict.fromkeys([*(existing.request_ids if existing is not None else ()), *stale]))
self._pending_request_cleanups[key] = _PendingRequestCleanup(
session_id=session_id,
lease_generation=session.lease_generation,
request_ids=merged,
abort=abort or (existing.abort if existing is not None else False),
)
if cleanup_in_progress:
self._request_cleanups_in_progress.add(key)
# Tear the runner down in the background; the orchestrator owns the stage cleanup.
self._session_snapshots[session_id] = session
self._closing[session_id] = _PendingSessionCleanup(
kind="request_cleanup",
session_id=session_id,
lease_generation=session.lease_generation,
reason="request_cleanup",
submitted_request_ids=(),
reserved_request_ids=(),
)
self.runners.pop(session_id, None)
task = asyncio.create_task(runner.expire("request_cleanup"), name=f"duplex-request-cleanup-{session_id}")
self._track_task(task)
return closed
def defer_request_cleanups(self, session_ids: Iterable[str]) -> None:
session_id_set = set(session_ids)
active_keys = {key for key in self._request_cleanups_in_progress if key[0] in session_id_set}
self._request_cleanups_in_progress.difference_update(active_keys)
def finalize_closed_sessions(self, session_ids: Iterable[str]) -> None:
session_id_set = set(session_ids)
for key in list(self._pending_request_cleanups):
if key[0] not in session_id_set:
continue
self._pending_request_cleanups.pop(key, None)
self._request_cleanups_in_progress.discard(key)
for session_id in session_id_set:
session = self._session_snapshots.pop(session_id, None)
if session is not None and session.lease.terminal_reason is not None:
session.release_all_requests()
session.close()
self._closing.pop(session_id, None)
self._unregister_session_requests(session_id)
async def _complete_request_cleanup(
self,
key: tuple[str, int],
pending: _PendingRequestCleanup,
) -> None:
task = self._request_cleanup_tasks.get(key)
if task is not None and task.done():
self._request_cleanup_tasks.pop(key, None)
task = None
if task is None:
task = asyncio.create_task(
self._run_request_cleanup(key, pending),
name=f"duplex-request-cleanup-{pending.session_id}",
)
self._request_cleanup_tasks[key] = task
def discard(completed: asyncio.Task[None]) -> None:
if self._request_cleanup_tasks.get(key) is completed:
self._request_cleanup_tasks.pop(key, None)
task.add_done_callback(discard)
await asyncio.shield(task)
async def _run_request_cleanup(self, key: tuple[str, int], pending: _PendingRequestCleanup) -> None:
await self.stage_port.cleanup(list(pending.request_ids), abort=pending.abort)
if self._pending_request_cleanups.get(key) is pending:
self._pending_request_cleanups.pop(key, None)
self._request_cleanups_in_progress.discard(key)
self.finalize_closed_sessions([pending.session_id])
# ------------------------------------------------------------------ #
# Shutdown #
# ------------------------------------------------------------------ #
async def shutdown(self) -> None:
runners = list(self.runners.values())
self.runners.clear()
for runner in runners:
try:
await runner.shutdown()
except Exception:
logger.exception("duplex runner shutdown failed for %s", runner.session.session_id)
tasks = tuple(self._dispatched_control_tasks | set(self._request_cleanup_tasks.values()))
for task in tasks:
task.cancel()
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
self._session_control_tails.clear()
self._closing.clear()
self._session_snapshots.clear()
self._request_index.clear()
if self._owns_executor:
self.executor.shutdown(wait=False, cancel_futures=True)
__all__ = ["DuplexSessionManager"]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,388 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""How one duplex session reacts to input that arrives while it is speaking.
Short acknowledgement, barge-in, or keep listening: the rules read the session
config and the incoming append, and nothing else. Extracted from
``DuplexSessionRunner`` because they were a decision function wearing a
method's clothes -- the only runner state they ever touched was ``session`` --
and because reaching them previously meant driving a whole append through the
runner.
"""
from __future__ import annotations
import binascii
from collections.abc import Mapping
import numpy as np
import pybase64 as base64
from vllm_omni.engine.duplex.config import DuplexOverlapPolicy
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
def decide(
session: DuplexEngineSession,
event: dict[str, object],
payload: dict[str, object],
*,
auto_responds: bool,
) -> dict[str, object]:
duration_ms = input_audio_duration_ms(event, payload)
is_speech = input_looks_like_speech(session, event, payload)
if not session.capabilities.supports_barge_in and event_requests_barge_in(event):
return defer_unsupported_barge_in(session, duration_ms=duration_ms, is_speech=is_speech)
explicit = event.get("overlap_action") or event.get("overlap")
if isinstance(explicit, str):
normalized = explicit.strip().lower()
if normalized in {"barge_in", "interrupt", "cancel"}:
return {
"action": "barge_in",
"reason": "client_overlap_action",
"duration_ms": duration_ms,
"buffer_audio": True,
}
if normalized in {"listen", "continue", "continue_output", "ack"}:
session.reset_overlap_speech()
return {
"action": "listen",
"reason": "client_overlap_action",
"duration_ms": duration_ms,
"buffer_audio": (
normalized == "listen" and is_speech and duration_ms > session.config.overlap_short_ack_ms
),
"defer_runtime_append": True,
}
if normalized in {"drop", "ignore", "silence"}:
session.reset_overlap_speech()
return {
"action": "drop",
"reason": "client_overlap_action",
"duration_ms": duration_ms,
"buffer_audio": False,
}
if bool(event.get("force_barge_in", False)):
return {
"action": "barge_in",
"reason": "client_force_barge_in",
"duration_ms": duration_ms,
"buffer_audio": True,
}
if auto_responds:
if is_speech:
session.accumulate_overlap_speech(duration_ms)
speech_started = vad_speech_started(event, payload)
if (
session.capabilities.supports_barge_in
and is_speech
and session.config.overlap_policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value
and speech_started is not False
):
return {
"action": "barge_in",
"reason": ("server_vad_speech_started" if speech_started is True else "barge_in_on_speech"),
"cancel_reason": "turn_detected" if speech_started is True else "barge_in",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
}
return {
"action": "listen",
"reason": "auto_response_continuous",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": False,
"force_listen": event.get("force_listen") is True or payload.get("force_listen") is True,
"preserve_realtime_input": True,
}
if bool(event.get("force_listen", False)):
session.reset_overlap_speech()
return {
"action": "listen",
"reason": "client_force_listen",
"duration_ms": duration_ms,
"buffer_audio": is_speech,
"defer_runtime_append": True,
}
policy = session.config.overlap_policy
if not is_speech:
if session.overlap_speech_ms <= 0:
session.reset_overlap_speech()
return {
"action": "drop",
"reason": "silence_or_noise",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": False,
}
if is_short_ack_transcript_hint(event, payload):
session.reset_overlap_speech()
return {
"action": "listen",
"reason": "short_ack_transcript",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": False,
"defer_runtime_append": True,
}
if policy == DuplexOverlapPolicy.LISTEN_ONLY.value:
session.accumulate_overlap_speech(duration_ms)
return {
"action": "listen",
"reason": "policy_listen_only",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": True,
}
if policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value and not session.capabilities.supports_barge_in:
return defer_unsupported_barge_in(session, duration_ms=duration_ms, is_speech=True)
session.accumulate_overlap_speech(duration_ms)
if policy == DuplexOverlapPolicy.BARGE_IN_ON_SPEECH.value:
speech_started = vad_speech_started(event, payload)
if speech_started is False:
return {
"action": "listen",
"reason": "server_vad_utterance_active",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": False,
"force_listen": True,
"preserve_realtime_input": True,
}
return {
"action": "barge_in",
"reason": ("server_vad_speech_started" if speech_started is True else "policy_barge_in_on_speech"),
"cancel_reason": "turn_detected" if speech_started is True else "barge_in",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
}
if (
duration_ms <= session.config.overlap_short_ack_ms
and session.overlap_speech_ms <= session.config.overlap_short_ack_ms
):
return {
"action": "listen",
"reason": "short_ack",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": True,
}
if session.overlap_speech_ms >= session.config.overlap_barge_in_ms:
if not session.capabilities.supports_barge_in:
return {
"action": "listen",
"reason": "barge_in_unsupported",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": True,
}
return {
"action": "barge_in",
"reason": "long_overlap_speech",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
}
return {
"action": "listen",
"reason": "accumulating_overlap_speech",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": True,
"defer_runtime_append": True,
}
def vad_speech_started(event: Mapping[str, object], payload: Mapping[str, object]) -> bool | None:
for source in (event, payload):
vad = source.get("vad")
if isinstance(vad, Mapping) and isinstance(vad.get("speech_started"), bool):
return bool(vad["speech_started"])
return None
def event_requests_barge_in(event: Mapping[str, object]) -> bool:
if event.get("force_barge_in") is True:
return True
explicit = event.get("overlap_action") or event.get("overlap")
return isinstance(explicit, str) and explicit.strip().lower() in {"barge_in", "interrupt", "cancel"}
def defer_unsupported_barge_in(
session: DuplexEngineSession,
*,
duration_ms: int,
is_speech: bool,
) -> dict[str, object]:
if is_speech:
session.accumulate_overlap_speech(duration_ms)
return {
"action": "listen",
"reason": "barge_in_unsupported",
"duration_ms": duration_ms,
"overlap_speech_ms": session.overlap_speech_ms,
"buffer_audio": is_speech,
"defer_runtime_append": True,
}
def is_short_ack_transcript_hint(event: dict[str, object], payload: dict[str, object]) -> bool:
raw_text = event.get("transcript") or event.get("text") or payload.get("transcript") or payload.get("text")
if not isinstance(raw_text, str):
return False
normalized = raw_text.strip().lower()
if not normalized:
return False
compact = "".join(ch for ch in normalized if ch.isalnum() or "一" <= ch <= "鿿")
if compact in {
"嗯",
"嗯嗯",
"对",
"对的",
"好",
"好的",
"继续",
"继续说",
"可以",
"是的",
"yes",
"yeah",
"yep",
"ok",
"okay",
"continue",
"goon",
"right",
}:
return True
return normalized in {"go on", "keep going", "please continue"}
def input_audio_duration_ms(event: dict[str, object], payload: dict[str, object]) -> int:
for key in ("duration_ms", "audio_duration_ms"):
value = event.get(key)
if isinstance(value, int | float):
return max(0, int(value))
fmt = payload.get("format")
sample_rate_hz = payload.get("sample_rate_hz")
audio = payload.get("audio")
if fmt == "pcm_f32le" and isinstance(sample_rate_hz, int) and sample_rate_hz > 0 and isinstance(audio, str):
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError):
return 0
return int((len(raw) // 4) * 1000 / sample_rate_hz)
return 0
def merge_audio_payloads(first: dict[str, object], second: dict[str, object]) -> dict[str, object]:
if first.get("format") != "pcm_f32le" or second.get("format") != "pcm_f32le":
return second
first_rate = first.get("sample_rate_hz")
second_rate = second.get("sample_rate_hz")
if not isinstance(first_rate, int) or not isinstance(second_rate, int) or first_rate != second_rate:
return second
first_audio = first.get("audio")
second_audio = second.get("audio")
if not isinstance(first_audio, str) or not isinstance(second_audio, str):
return second
try:
first_raw = base64.b64decode(first_audio, validate=True)
second_raw = base64.b64decode(second_audio, validate=True)
except (binascii.Error, ValueError):
return second
merged = dict(second)
merged["audio"] = base64.b64encode(first_raw + second_raw).decode("ascii")
merged["sample_rate_hz"] = first_rate
merged_frames = [
frame
for source in (first.get("video_frames"), second.get("video_frames"))
if isinstance(source, list)
for frame in source
if isinstance(frame, str) and frame
]
if merged_frames:
merged["video_frames"] = merged_frames
else:
merged.pop("video_frames", None)
merged["force_listen"] = bool(first.get("force_listen", False)) or bool(second.get("force_listen", False))
merged.pop("force_speak", None)
merged["is_speech"] = bool(first.get("is_speech", False)) or bool(second.get("is_speech", False))
return merged
def should_force_listen_for_short_commit(
session: DuplexEngineSession, event: dict[str, object], payload: dict[str, object]
) -> bool:
if event.get("force_listen") is True or payload.get("force_listen") is True:
return True
if event.get("force_barge_in") is True:
return False
if event.get("response_create") is not True:
return False
duration_ms = input_audio_duration_ms(event, payload)
return 0 < duration_ms <= session.config.overlap_short_ack_ms
def should_force_listen_for_auto_response_overlap(
event: dict[str, object], payload: dict[str, object], *, auto_responds: bool
) -> bool:
if not auto_responds:
return False
if event.get("force_barge_in") is True:
return False
return event.get("force_listen") is True or payload.get("force_listen") is True
def input_looks_like_speech(session: DuplexEngineSession, event: dict[str, object], payload: dict[str, object]) -> bool:
for key in ("is_speech", "speech"):
value = event.get(key)
if isinstance(value, bool):
return value
vad = event.get("vad")
if isinstance(vad, dict):
value = vad.get("is_speech")
if isinstance(value, bool):
return value
probability = vad.get("speech_probability", vad.get("probability"))
if isinstance(probability, int | float):
return float(probability) >= 0.5
probability = event.get("speech_probability")
if isinstance(probability, int | float):
return float(probability) >= 0.5
fmt = payload.get("format")
audio = payload.get("audio")
if fmt in {"pcm_f32le", "pcm16"} and isinstance(audio, str):
try:
raw = base64.b64decode(audio, validate=True)
except (binascii.Error, ValueError):
return True
if fmt == "pcm_f32le":
if len(raw) < 4 or len(raw) % 4 != 0:
return True
samples = np.frombuffer(raw, dtype=np.float32)
else:
if len(raw) < 2 or len(raw) % 2 != 0:
return True
samples = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
if samples.size == 0:
return False
rms = float(np.sqrt(np.mean(np.square(samples.astype(np.float32)))))
return rms >= session.config.overlap_silence_rms
return True
@@ -0,0 +1,137 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Applying one ``playback.ack`` to a duplex session.
The client reports how much of a response it has actually played; the session
uses that to commit or truncate the assistant item in conversation history, and
to release the response's playback state once it is fully played.
Extracted from ``DuplexSessionRunner`` because the only runner state it touched
was ``session``. It returns the events it produces rather than emitting them,
so the rules can be exercised without a runner.
"""
from __future__ import annotations
from vllm_omni.engine.duplex.events import DuplexEvent, PlaybackAcknowledged, error_event
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
from vllm_omni.engine.duplex.session.lease import DuplexLeaseActivity
def apply_playback_ack(session: DuplexEngineSession, event: dict[str, object]) -> list[DuplexEvent]:
"""Apply one ``playback.ack`` and return the events it produces."""
played_ms = event.get("played_ms", event.get("audio_ms", 0))
committed_ms = event.get("committed_ms")
if not isinstance(played_ms, int | float):
return [error_event("bad_event", "playback.ack requires played_ms")]
try:
session.touch_lease(DuplexLeaseActivity.PLAYBACK_ACK)
except Exception:
pass
committed_cursor = int(committed_ms) if isinstance(committed_ms, int | float) else int(played_ms)
item_id = event.get("item_id")
response_id = event.get("response_id")
response_id = response_id if isinstance(response_id, str) and response_id else None
if not isinstance(item_id, str) or not item_id:
item_id = f"item_{response_id}" if response_id is not None else None
elif response_id is None and item_id.startswith("item_"):
response_id = item_id.removeprefix("item_")
if response_id is None and item_id is None and len(session.pending_history_item_ids) == 1:
item_id = next(iter(session.pending_history_item_ids))
if item_id.startswith("item_"):
response_id = item_id.removeprefix("item_")
if response_id is None and item_id is None and session.active_response_id is not None:
response_id = session.active_response_id
item_id = f"item_{response_id}"
if response_id is not None:
expected_item_id = f"item_{response_id}"
if item_id is None:
item_id = expected_item_id
elif item_id != expected_item_id:
return [error_event("playback_item_mismatch", "playback.ack item_id must match item_<response_id>.")]
if not session.has_assistant_response_item(response_id, item_id):
return [
error_event("playback_item_not_found", f"No assistant response item is registered for {response_id}.")
]
if session.playback_ack_is_too_late(response_id, item_id):
return [
error_event("playback_ack_too_late", "playback.ack arrived after a later user input was committed.")
]
session.reserve_history_item(item_id)
elif item_id is not None:
return [error_event("playback_item_not_found", "playback.ack requires a response-owned assistant item.")]
hard_truncate = event.get("truncate") is True
if hard_truncate:
playback = session.acknowledge_playback(int(played_ms), committed_cursor, response_id=response_id)
playback = session.truncate_playback_commit(committed_cursor, response_id=response_id)
else:
playback = session.acknowledge_playback(int(played_ms), committed_cursor, response_id=response_id)
committed_history = False
if isinstance(item_id, str) and item_id:
expected_item_id = f"item_{response_id}" if response_id is not None else None
if (
expected_item_id == item_id
and item_id not in session.history_item_ids
and item_id not in session.pending_history_item_ids
):
session.register_history_item(item_id, None)
committed_history = session.truncate_history_item(
item_id,
audio_end_ms=committed_cursor,
playback=playback,
hard=hard_truncate,
)
elif session.pending_history_item_ids:
pending_ids = list(session.pending_history_item_ids)
if len(pending_ids) == 1:
item_id = pending_ids[0]
committed_history = session.truncate_history_item(
item_id,
audio_end_ms=committed_cursor,
playback=playback,
hard=hard_truncate,
)
elif session.active_response_id is not None:
item_id = f"item_{session.active_response_id}"
committed_history = session.truncate_history_item(
item_id,
audio_end_ms=committed_cursor,
playback=playback,
hard=hard_truncate,
)
elif session.last_assistant_full_message is not None:
if item_id is None and session.history_item_ids:
assistant_item_ids = [
known_item_id
for known_item_id, message in session.history_item_ids.items()
if message.get("role") == "assistant"
]
if len(assistant_item_ids) == 1:
item_id = assistant_item_ids[0]
if isinstance(item_id, str) and item_id:
committed_history = session.truncate_history_item(
item_id,
audio_end_ms=committed_cursor,
playback=playback,
hard=hard_truncate,
)
events: list[DuplexEvent] = [
PlaybackAcknowledged(
details={
"type": "playback.acknowledged",
"session_id": session.session_id,
"epoch": session.epoch,
"item_id": item_id,
"played_ms": int(played_ms),
"committed_ms": committed_cursor,
"truncate": event.get("truncate") is True,
"playback": playback.as_dict(),
"history_committed": committed_history,
}
)
]
if committed_history and committed_cursor >= max(playback.sent_ms, playback.generated_ms):
session.release_response_playback(response_id)
session.release_response_history_snapshot(response_id)
return events
File diff suppressed because it is too large. Load diff