"""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 def interrupt(self): self.interrupts += 1 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 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 # ── 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), ] 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()))