"""HEL-908 SDK-path harness: the cancelled-turn fix through the REAL livekit-agents 1.8.8 LLMStream machinery. These checks drive the installed SDK's own retry/cancel code (``LLMStream ._main_task``, verified read-only on .12) against fake SSE transports — no room, no LLM/ASR/TTS call, zero network beyond the in-process transport. They need ``livekit.agents`` importable, i.e. the agent venv on .12 (`/opt/voice-agent/agent/venv`, which has no pytest). Two ways to run: pytest tests/test_sdk_livekit_hel908.py /opt/voice-agent/agent/venv/bin/python \\ tests/test_sdk_livekit_hel908.py --standalone The HEL-907 defect under test: worker.log line-108's retry ("chat stream ended without final or error ... retrying in 0.1s") fired 13ms after the user's text POST — the cancelled stream ended WITHOUT a terminal frame BEFORE any chunk was sent, so ``output_sent`` was False, the ``_retry_on_chunk_sent`` guard was inapplicable, and the SDK silently re-ran ``_run``: the retried POST cancelled the user's text turn and re-spoke a full ~32s reply (api.log POST #5, chat_message ids 5/6/8). """ from __future__ import annotations import asyncio import sys from pathlib import Path import httpx try: import pytest except ImportError: # the agent venv has no pytest; standalone mode only pytest = None # type: ignore[assignment] sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) try: # the SDK only exists in the agent venv / worker environments import livekit.agents.llm as lk_llm from livekit.agents import APIConnectionError, APIStatusError from livekit.agents.types import APIConnectOptions HAVE_SDK = True SKIP_REASON = "" except Exception as exc: # pragma: no cover - environment-dependent HAVE_SDK = False SKIP_REASON = f"livekit-agents not importable in this env: {exc}" if pytest is not None: pytestmark = pytest.mark.skipif(not HAVE_SDK, reason=SKIP_REASON or "sdk present") class _Raises: """Minimal pytest.raises stand-in so the standalone runner (agent venv, no pytest installed) executes the very same assertions.""" def __init__(self, exc_type): self.exc_type = exc_type self.value = None def __enter__(self): return self def __exit__(self, exc_type, exc, tb): assert exc_type is not None and issubclass(exc_type, self.exc_type), ( f"expected {self.exc_type.__name__}, got {exc_type.__name__ if exc_type else exc_type}" ) self.value = exc return True def raises(exc_type): return pytest.raises(exc_type) if pytest is not None else _Raises(exc_type) if HAVE_SDK: FAST = APIConnectOptions(timeout=10, retry_interval=0.05, max_retry=2) def sse(frames: list[str]) -> bytes: return "".join(f"data: {frame}\n\n" for frame in frames).encode() def chat_ctx(): ctx = lk_llm.ChatContext() ctx.add_message(role="user", content="你好呀") return ctx class Backend: """Scripted /api/chat backend: one canned answer per POST (Exception instances are raised), counting every POST it serves.""" def __init__(self, answers: list): self.answers = answers self.chat_posts = 0 def transport(self) -> httpx.MockTransport: backend = self async def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/api/health": return httpx.Response(200, json={"epoch": 1}) backend.chat_posts += 1 answer = backend.answers[(backend.chat_posts - 1) % len(backend.answers)] if isinstance(answer, Exception): raise answer return httpx.Response( 200, headers={"content-type": "text/event-stream"}, content=answer ) return httpx.MockTransport(handler) def make_llm(answers: list): from cybergril.voice.chat_api_client import ChatApiClient from cybergril.voice.llm_chat_api import CyberGrillLLM backend = Backend(answers) return CyberGrillLLM( "http://x", client=ChatApiClient("http://x", transport=backend.transport()) ), backend class InterruptSpy: """Stands in for the SDK SpeechHandle: records interrupt() calls only.""" def __init__(self) -> None: self.interrupts = 0 self.forced: list[bool] = [] def interrupt(self, *, force: bool = False): self.interrupts += 1 self.forced.append(force) return self CANCELLED = sse(['{"t":"chat.cancelled","epoch":1,"turn_id":null}']) TWO_DELTAS_THEN_CANCELLED = sse([ '{"t":"chat.delta","epoch":1,"turn_id":null,"delta":"哈哈,"}', '{"t":"chat.delta","epoch":1,"turn_id":null,"delta":"那走吧。"}', '{"t":"chat.cancelled","epoch":1,"turn_id":null}', ]) COMPLETED = sse([ '{"t":"chat.delta","epoch":1,"turn_id":null,"delta":"完整"}', '{"t":"chat.delta","epoch":1,"turn_id":null,"delta":"回复。"}', '{"t":"chat.final","epoch":1,"turn_id":null,"utterance":{"text":"完整回复。"},' '"receipt":{"message_id":9,"turn_id":null,"epoch":1,"token":"' + "k" * 48 + '","text_hash":"' + "h" * 64 + '"}}', ]) async def _collect(stream): chunks: list[str] = [] try: async for chunk in stream: if chunk.delta and chunk.delta.content: chunks.append(chunk.delta.content) finally: await stream.aclose() return chunks async def test_pre_first_delta_cancel_never_retries(): """The recorded call1 path: cancel before any chunk. The 499 end means the SDK's retry loop never re-runs _run — exactly one POST.""" llm, backend = make_llm([CANCELLED]) stream = llm.chat(chat_ctx=chat_ctx(), conn_options=FAST) chunks = await _collect(stream) assert chunks == [] assert stream.server_cancelled and not stream.completed assert backend.chat_posts == 1, "a cancelled turn must never be retried" async def test_mid_stream_cancel_interrupts_handle_and_never_retries(): llm, backend = make_llm([TWO_DELTAS_THEN_CANCELLED]) stream = llm.chat(chat_ctx=chat_ctx(), conn_options=FAST) spy = InterruptSpy() stream.speech_handle = spy chunks = await _collect(stream) assert chunks == ["哈哈,", "那走吧。"], "chunks already sent stay visible" assert stream.server_cancelled assert spy.interrupts == 1, \ "server-side cancel must stop the cached playout via SpeechHandle.interrupt" assert spy.forced == [True], \ "programmatic user interrupt goes through with force (HEL-909 R2)" assert backend.chat_posts == 1 async def test_reentry_after_cancel_short_circuits_without_network(): llm, backend = make_llm([CANCELLED]) stream = llm.chat(chat_ctx=chat_ctx(), conn_options=FAST) await _collect(stream) assert backend.chat_posts == 1 with raises(APIStatusError) as excinfo: await stream._run() assert excinfo.value.status_code == 499 assert backend.chat_posts == 1, \ "a cancelled turn_id never re-acquires the gate, not even in-process" async def test_real_connection_errors_still_retry_not_globally_disabled(): llm, backend = make_llm([httpx.ConnectError("network is genuinely down")]) stream = llm.chat(chat_ctx=chat_ctx(), conn_options=FAST) with raises(APIConnectionError): await _collect(stream) assert backend.chat_posts == FAST.max_retry + 1, \ "transient network failures keep the SDK's own bounded retry" async def test_completed_turn_still_streams_with_receipt(): llm, backend = make_llm([COMPLETED]) stream = llm.chat(chat_ctx=chat_ctx(), conn_options=FAST) chunks = await _collect(stream) assert chunks == ["完整", "回复。"] assert stream.completed and stream.receipt and stream.text == "完整回复。" assert backend.chat_posts == 1 # ── R2 (HEL-909): the cg.interrupt data channel for "LLM final, TTS playing" ─ class HandleSessionBridge: """Stands exactly where AgentSession.interrupt stands in production. The SDK's AgentActivity.interrupt (verified read-only on .12, agent_activity.py:1932-1934) forwards force to the LIVE SpeechHandle's own interrupt(); everything below this delegate is real SDK machinery — the real handle, the real pending playout wait, the real interrupt semantics (no Spy counting masquerading as a stopped buffer).""" def __init__(self, handle) -> None: self.handle = handle self.calls: list[bool] = [] def interrupt(self, *, force: bool = False): self.calls.append(force) return self.handle.interrupt(force=force) def _data_packet(topic: str, payload: bytes, sender: str = "user-1"): """Structured stand-in for rtc's DataPacket (offline: no room server). sender: 'user-1' remote user page | 'self' the agent | 'server'.""" from types import SimpleNamespace participant = None if sender != "server": participant = SimpleNamespace(is_local=sender == "self", identity=sender) return SimpleNamespace(topic=topic, data=payload, participant=participant) def _quiet_await(handle) -> None: """Clean the interrupt-timeout timer a real interrupt arms (5s) so the loop can close without pending-callback noise.""" timer = getattr(handle, "_interrupt_timeout_handle", None) if timer is not None: timer.cancel() async def test_interrupt_message_stops_pending_playout_after_final(): """Reviewer evidence-C shape: the old voice turn already ended CLEAN (chat.final, no cancel — nothing ever touched its handle; the server has no active turn left to cancel), while a real playout wait is still hanging. The page's cg.interrupt data message must stop it through the SDK's own interrupt, with force.""" from livekit import rtc from livekit.agents.voice import SpeechHandle from cybergril.voice.worker import bind_interrupt_channel # allow_interruptions=False: proves the force semantics on a real handle handle = SpeechHandle.create(allow_interruptions=False) bridge = HandleSessionBridge(handle) room = rtc.Room() unload = bind_interrupt_channel(room, bridge) playout = asyncio.Future() # the playout work the TTS pipeline would owe waiter = asyncio.create_task(handle.wait_if_not_interrupted([playout])) await asyncio.sleep(0.05) assert not waiter.done(), "the playout wait is genuinely pending" room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.wait_for(waiter, timeout=5) # real interrupt releases the pending playout wait await asyncio.sleep(0.05) assert handle.interrupted assert bridge.calls == [True], "programmatic user interrupt goes with force" # real force semantics on this SDK: non-force on a no-interruptions # speech raises (HEL-909 evidence B2); force does not. fresh = SpeechHandle.create(allow_interruptions=False) with raises(RuntimeError): fresh.interrupt() fresh.interrupt(force=True) _quiet_await(fresh) _quiet_await(handle) await unload() async def test_interrupt_channel_validation_and_unload(): """Topic/sender/payload validation, and the shutdown callback removal.""" from livekit import rtc from livekit.agents.voice import SpeechHandle from cybergril.voice.worker import bind_interrupt_channel handle = SpeechHandle.create(allow_interruptions=True) bridge = HandleSessionBridge(handle) room = rtc.Room() unload = bind_interrupt_channel(room, bridge) for topic, payload, sender in [ ("cg.subtitle", b'{"v":1}', "user-1"), # wrong topic (our own bus) ("cg.interrupt", b'{"v":1}', "server"), # no participant ("cg.interrupt", b'{"v":1}', "self"), # the agent itself ("cg.interrupt", b"not json", "user-1"), # broken payload ("cg.interrupt", b'{"v":2}', "user-1"), # unknown version ("cg.interrupt", b'{"v":"1"}', "user-1"), # wrong type ]: room.emit("data_received", _data_packet(topic, payload, sender)) await asyncio.sleep(0.02) assert bridge.calls == [] and not handle.interrupted, \ "nothing but the user page's valid same-room message interrupts" room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.sleep(0.05) assert bridge.calls == [True] and handle.interrupted await unload() room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.sleep(0.05) assert bridge.calls == [True], "the unload callback removed the listener" _quiet_await(handle) async def test_interrupt_message_survives_session_not_running(): """session.interrupt raises RuntimeError before session.start; the channel logs loudly and keeps the room listener alive (no crash, no silent success).""" from livekit import rtc from cybergril.voice.worker import bind_interrupt_channel class NotRunning: def interrupt(self, *, force: bool = False): raise RuntimeError("AgentSession isn't running") room = rtc.Room() unload = bind_interrupt_channel(room, NotRunning()) room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.sleep(0.05) # logged, swallowed at the boundary, listener intact room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.sleep(0.05) await unload() # ── HEL-911: conversation_item_added item types + async shutdown seam ──────── def _echo_stt_state() -> "SimpleNamespace": from types import SimpleNamespace return SimpleNamespace(agent_recent_text="", agent_speaking=False) async def test_conversation_item_added_filters_non_message_items(): """The session-start AgentHandoff (real 1.8.8 ConversationItemAddedEvent payload: ChatMessage | AgentHandoff | _TypeDiscriminator, events.py:419) crashed the old handler with AttributeError (HEL-910 worker.log, both calls). Non-message items and user messages must not touch the echo filter state.""" from livekit.agents.llm.chat_context import AgentHandoff, ChatMessage from livekit.agents.voice import AgentSession from livekit.agents.voice.events import ConversationItemAddedEvent, _TypeDiscriminator from cybergril.voice.worker import bind_voice_session class _Noop: def __getattr__(self, name): # any other seam touch fails the test raise AssertionError(f"unexpected seam use: {name}") session = AgentSession() stt = _echo_stt_state() bind_voice_session(session, llm=_Noop(), ledger=_Noop(), interim=_Noop(), bus=_Noop(), stt=stt, receipts=_Noop()) # 1. real SDK AgentHandoff (the session-start item that crashed 1.8.8) session.emit("conversation_item_added", ConversationItemAddedEvent(item=AgentHandoff(new_agent_id="agent_1"))) assert stt.agent_recent_text == "" # 2. the SDK's own unknown-item discriminator shape session.emit("conversation_item_added", ConversationItemAddedEvent(item=_TypeDiscriminator())) assert stt.agent_recent_text == "" # 3. a real user ChatMessage must not feed the assistant echo filter session.emit("conversation_item_added", ConversationItemAddedEvent( item=ChatMessage(role="user", content=["用户说的话"]))) assert stt.agent_recent_text == "" # 4. real assistant ChatMessage with mixed content parts: only the str # parts are body text (ChatContent = str | ImageContent | AudioContent | # CacheBreakpoint, chat_context.py:459) from livekit.agents.llm.chat_context import CacheBreakpoint session.emit("conversation_item_added", ConversationItemAddedEvent( item=ChatMessage(role="assistant", content=["好,小十。", CacheBreakpoint()]))) assert stt.agent_recent_text == "好,小十。" async def test_shutdown_callback_protocol_real_jobcontext_wrapper(): """The unload seam must satisfy the REAL JobContext.add_shutdown_callback contract: the SDK wraps a no-arg callback into `await callback()` (job.py:633-643) and the job runner awaits every callback (ipc/job_proc_lazy_main.py:493). The old sync `def unload() -> None` raised TypeError: object NoneType can't be used in 'await' expression (HEL-910 worker.log). Here the REAL JobContext method does the wrapping and the runner's exact await pattern drives it — only the job plumbing around it is absent, so a broken seam reproduces the production error. """ import inspect from livekit import rtc from livekit.agents import JobContext from livekit.agents.voice import SpeechHandle from cybergril.voice.worker import bind_interrupt_channel handle = SpeechHandle.create(allow_interruptions=True) class _Bridge: def interrupt(self, *, force: bool = False): return handle.interrupt(force=force) room = rtc.Room() unload = bind_interrupt_channel(room, _Bridge()) assert inspect.iscoroutinefunction(unload), \ "add_shutdown_callback awaits its callbacks; unload must be async" # register through the REAL SDK method (it appends the wrapper it will await) ctx = object.__new__(JobContext) # real method, minimal instance: no job plumbing ctx._shutdown_callbacks = [] ctx.add_shutdown_callback(unload) wrapped = ctx._shutdown_callbacks[-1] # exactly what ipc/job_proc_lazy_main._traced_shutdown_callback does await wrapped("job shutdown") # must not raise (the old sync seam did) # the old seam reproduces the production TypeError through the same wrapper def sync_unload() -> None: return None ctx.add_shutdown_callback(sync_unload) broken = ctx._shutdown_callbacks[-1] try: await broken("job shutdown") raise AssertionError("sync unload should have failed the real await") except TypeError as exc: assert "await" in str(exc) # duplicate shutdown: the runner may only fire callbacks once per job, but # idempotency must not depend on that await unload() await unload() # subscription really unloaded: a valid interrupt message after unload is a no-op room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}')) await asyncio.sleep(0.05) assert not handle.interrupted, "listener must be gone after unload" _quiet_await(handle) async def test_turn_handling_disables_default_english_eou_detector(): """HEL-911: livekit-agents 1.8.8 silently installs an English EOU TurnDetector when turn_handling has no explicit turn_detection key (agent_session.py:576-579, `turn_handling.get("turn_detection", inference.TurnDetector())`). Its unlikely-eot verdicts on CHINESE transcripts push the endpointing delay to max_delay and cost the measured ~3.66s between ASR final and turn_start (HEL-910 call2: 3.667s/3.654s; offline A/B in scripts/gen_hel911_wait_repro.py: default 3.704s vs explicit None 0.004s). The worker's TURN_HANDLING must keep the detector off so the configured VAD endpointing alone decides the turn boundary.""" from livekit.agents import AgentSession from cybergril.voice.worker import TURN_HANDLING # the SDK default that bites: same options minus the explicit key with_default = {k: v for k, v in TURN_HANDLING.items() if k != "turn_detection"} default_session = AgentSession(turn_handling=with_default) assert default_session._turn_detection is not None, ( "precondition: 1.8.8 installs a default turn detector — if this fails " "the SDK changed; re-check the HEL-911 wait attribution" ) session = AgentSession(turn_handling=TURN_HANDLING) assert session._turn_detection is None, \ "the worker must not run the English EOU detector on Chinese turns" assert TURN_HANDLING["endpointing"] == {"min_delay": 0.8, "max_delay": 6.0}, \ "the measured endpointing parameters stay exactly as configured" # ── standalone runner (agent venv has no pytest) ───────────────────────────── async def _standalone() -> int: checks = [ ("pre_first_delta_cancel_never_retries", test_pre_first_delta_cancel_never_retries), ("mid_stream_cancel_interrupts_handle_and_never_retries", test_mid_stream_cancel_interrupts_handle_and_never_retries), ("reentry_after_cancel_short_circuits_without_network", test_reentry_after_cancel_short_circuits_without_network), ("real_connection_errors_still_retry_not_globally_disabled", test_real_connection_errors_still_retry_not_globally_disabled), ("completed_turn_still_streams_with_receipt", test_completed_turn_still_streams_with_receipt), ("interrupt_message_stops_pending_playout_after_final", test_interrupt_message_stops_pending_playout_after_final), ("interrupt_channel_validation_and_unload", test_interrupt_channel_validation_and_unload), ("interrupt_message_survives_session_not_running", test_interrupt_message_survives_session_not_running), ("conversation_item_added_filters_non_message_items", test_conversation_item_added_filters_non_message_items), ("shutdown_callback_protocol_real_jobcontext_wrapper", test_shutdown_callback_protocol_real_jobcontext_wrapper), ("turn_handling_disables_default_english_eou_detector", test_turn_handling_disables_default_english_eou_detector), ] failures = 0 for name, check in checks: try: await check() print(f"PASS {name}") except Exception as exc: # noqa: BLE001 - report and continue failures += 1 print(f"FAIL {name}: {type(exc).__name__}: {exc}") print(f"{len(checks) - failures}/{len(checks)} passed") return 1 if failures else 0 if __name__ == "__main__": if not HAVE_SDK: print(f"SKIP: {SKIP_REASON}") raise SystemExit(77) raise SystemExit(asyncio.run(_standalone()))