"""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) 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 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) unload() # ── 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), ] 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()))