"""HEL-908 rework tests: text-interrupt turn semantics through the REAL app. Replays the recorded HEL-907 window defects offline (fake scripted LLM provider, real FastAPI app + real ChatApiClient protocol client, zero network beyond 127.0.0.1): 1. call1 third-turn defect: her voice turn was cancelled by the user's text POST BEFORE its first delta; the SSE then ended without a terminal frame, the worker's adapter raised a connection error, livekit-agents silently RETRIED the same turn_id, and that retry cancelled the text turn and re-spoke a full ~32s reply (worker.log line 108, api.log POST #5, chat_message ids 5/6/8). 2. call3 think leak: the model's implicit-open reasoning + stray ```` streamed into chat.delta and TTS (companion.db row id=12). """ from __future__ import annotations import asyncio import hashlib import sys from pathlib import Path from uuid import uuid4 import httpx import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from conftest import engineering_budget # noqa: E402 from test_r2 import R2LLM # noqa: E402 from cybergril.api.app import create_app # noqa: E402 from cybergril.contracts import LLMDelta # noqa: E402 from cybergril.life.runtime import LifeConfig # noqa: E402 from cybergril.think.router import build_router # noqa: E402 from cybergril.think.scenes import Tier # noqa: E402 from cybergril.voice.chat_api_client import ChatApiClient # noqa: E402 CREATE = {"name": "返修", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"} # companion.db row id=12 (call3), verbatim: implicit-open reasoning + stray # closer with NO opening tag, then her actual reply. RECORDED_RAW = ( "Considering the limited time by the user, I have to give the solution " "based on the thinking directly now.\n\n\n" "大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码," "连肉都没有,怕硌着您的金箍棒。" ) RECORDED_VISIBLE = ( "大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码," "连肉都没有,怕硌着您的金箍棒。" ) RECORDED_CHUNKS = [RECORDED_RAW[:60], RECORDED_RAW[60:104], RECORDED_RAW[104:112], RECORDED_RAW[112:]] # HEL-909 review reproductions A1/A2 — the shapes the old streaming hold # leaked into persistence and the receipt on real token arrival. A1_RAW = "private reasoning " * 20 + "回答。" A2_RAW = "我先想一下。内部思考回答。" A1_CHUNKS = [A1_RAW[i:i + 13] for i in range(0, len(A1_RAW), 13)] A2_CHUNKS = [A2_RAW[i:i + 5] for i in range(0, len(A2_RAW), 5)] class ScriptedLLM(R2LLM): """R2 controlled provider with HEL-908 scripted dialogue behaviour.""" def __init__(self): super().__init__() self.script: list[str] = [] self.hang_mode = "" # "" | "before" | "after" self.hang_release = asyncio.Event() # unset: a hang parks until released self.reply = "文字轮正常拿到了回复。" async def stream(self, messages, **kwargs): if "只返回JSON,不要Markdown" in messages[0].content: async for delta in super().stream(messages, **kwargs): yield delta return self.calls.append(messages) if self.hang_mode == "before": await self.hang_release.wait() if self.mode == "error": raise OSError("scripted upstream fault") for piece in self.script: yield LLMDelta(text=piece) if not self.script: yield LLMDelta(text=self.reply) if self.hang_mode == "after": await self.hang_release.wait() yield LLMDelta(done=True) @pytest.fixture def rework(tmp_path): provider = ScriptedLLM() router = build_router( providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget(), ) app = create_app(db_path=tmp_path / "hel908.db", router=router, life_config=LifeConfig(enabled=True, poll_seconds=3600), semantic_mode="stub") from fastapi.testclient import TestClient with TestClient(app) as client: client.post("/api/companion", json=CREATE) epoch = client.get("/api/health").json()["epoch"] yield app, provider, epoch provider.mode = "" def sse_chunks(raw_pieces: list[str]) -> bytes: """SSE lines for a raw content stream (mirrors the endpoint's wire shape).""" import json as _json lines = [ "data: " + _json.dumps({"choices": [{"delta": {"content": piece}}]}, ensure_ascii=False) for piece in raw_pieces ] lines.append("data: [DONE]") return ("\n\n".join(lines) + "\n\n").encode() @pytest.fixture def adapter_app(tmp_path): """The REAL OpenAICompatLLM behind the real app, fed by a scripted OpenAI-compatible SSE gateway — in buffer_turn mode, exactly what config/models.yaml configures for the product's tiers (the endpoint streams implicit-open reasoning, so the whole turn is gated before any content is emitted).""" from cybergril.providers.llm.openai_compat import OpenAICompatLLM state = {"answers": [sse_chunks(RECORDED_CHUNKS)]} async def handler(request: httpx.Request) -> httpx.Response: if request.url.path.endswith("/models"): return httpx.Response(200, json={"data": [{"id": "recorded"}]}) answer = state["answers"][0] return httpx.Response( 200, headers={"content-type": "text/event-stream"}, content=answer ) provider = OpenAICompatLLM(base_url="http://recorded/v1", model="recorded", reasoning="buffer_turn") provider._client = httpx.AsyncClient( base_url="http://recorded/v1", transport=httpx.MockTransport(handler) ) router = build_router( providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget(), ) app = create_app(db_path=tmp_path / "hel908-adapter.db", router=router, life_config=LifeConfig(enabled=True, poll_seconds=3600), semantic_mode="stub") from fastapi.testclient import TestClient with TestClient(app) as client: client.post("/api/companion", json=CREATE) epoch = client.get("/api/health").json()["epoch"] yield app, state, epoch def api_client(app) -> ChatApiClient: return ChatApiClient("http://asgi", transport=httpx.ASGITransport(app=app)) @pytest.fixture def live_rework(tmp_path): """Real-socket variant (uvicorn on 127.0.0.1, ephemeral port) for the cases that need genuine incremental SSE delivery — httpx.ASGITransport does not stream response bodies chunk-by-chunk mid-response. Same pattern as test_voice_chat_adapter's live_server: its own app instance on the same file-backed database (one lifespan owner per app).""" import socket import threading import time as _time import uvicorn provider = ScriptedLLM() router = build_router( providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget(), ) served = create_app(db_path=tmp_path / "hel908-live.db", router=router, life_config=LifeConfig(enabled=True, poll_seconds=3600), semantic_mode="stub") from fastapi.testclient import TestClient with TestClient(served) as client: client.post("/api/companion", json=CREATE) epoch = client.get("/api/health").json()["epoch"] probe = socket.socket() probe.bind(("127.0.0.1", 0)) port = probe.getsockname()[1] probe.close() server = uvicorn.Server(uvicorn.Config(served, host="127.0.0.1", port=port, log_level="error")) thread = threading.Thread(target=server.run, daemon=True) thread.start() for _ in range(100): try: httpx.get(f"http://127.0.0.1:{port}/api/health", timeout=1) break except Exception: _time.sleep(0.1) yield f"http://127.0.0.1:{port}", served, provider, epoch server.should_exit = True thread.join(timeout=5) def rows(app): return app.state.store.query( "SELECT id,role,text,status,turn_id FROM chat_message ORDER BY id" ) async def test_text_interrupt_pre_first_delta_no_retry_no_revive(rework): """The recorded call1 path: cancel arrives before the first delta. The cancelled voice stream must end on an explicit chat.cancelled terminal; a late retry of the same turn_id must be refused without re-acquiring the gate (so it can never cancel the text turn), and no regeneration may run.""" app, provider, epoch = rework provider.hang_mode = "before" # voice turn parks before its first token voice_tid = str(uuid4()) deltas: list[str] = [] voice = asyncio.create_task( api_client(app).send_turn("你是不是早就想睡我了呀", turn_id=voice_tid, epoch=epoch, on_delta=deltas.append) ) await asyncio.sleep(0.5) # voice turn is the active one, pre-first-delta provider.hang_mode = "" text = await api_client(app).send_turn("(文字通道)我改用打字了", epoch=epoch) assert text.completed and text.text == provider.reply, \ "the newer text turn keeps the gate and gets its reply" cancelled_voice = await voice assert cancelled_voice.cancelled and not cancelled_voice.completed assert deltas == [], "recorded case: no chunk was ever sent before cancel" calls_after_window = len(provider.calls) retry = await api_client(app).send_turn("你是不是早就想睡我了呀", turn_id=voice_tid, epoch=epoch) assert retry.cancelled and not retry.completed, \ "a cancelled turn_id is terminal — the refusal answers chat.cancelled" assert len(provider.calls) == calls_after_window, \ "the refused retry must not regenerate (no re-spoken 32s reply)" assert len(provider.calls) == 2 # exactly: voice attempt + text turn table = rows(app) voice_rows = [r for r in table if r["turn_id"] == voice_tid] assert voice_rows and voice_rows[0]["status"] == "cancelled" assert not [r for r in table if r["role"] == "companion" and r["turn_id"] == voice_tid], \ "the superseded voice turn never becomes her archived reply" text_rows = [r for r in table if r["text"] == "(文字通道)我改用打字了"] assert text_rows and text_rows[0]["status"] == "sent" assert any(r["role"] == "companion" and r["status"] == "sent" for r in table), "the text turn's reply is archived" async def test_text_interrupt_after_deltas_cancels_cleanly(live_rework): """Cancel AFTER the voice turn already streamed: the caller keeps the deltas it saw, then receives the terminal cancel frame. Real socket: the delta must arrive DURING the parked stream (ASGITransport buffers).""" url, app, provider, epoch = live_rework provider.script = ["哈哈,那走吧。"] provider.hang_mode = "after" got_delta = asyncio.Event() deltas: list[str] = [] voice_tid = str(uuid4()) live_client = ChatApiClient(url) voice = asyncio.create_task( live_client.send_turn("语音说到一半", turn_id=voice_tid, epoch=epoch, on_delta=lambda d: (deltas.append(d), got_delta.set())) ) await asyncio.wait_for(got_delta.wait(), timeout=10) provider.hang_mode = "" text = await live_client.send_turn("文字打断", epoch=epoch) assert text.completed cancelled_voice = await voice assert cancelled_voice.cancelled assert "".join(deltas) == "哈哈,那走吧。" assert not [r for r in rows(app) if r["role"] == "companion" and r["turn_id"] == voice_tid] await live_client.aclose() async def test_think_leak_replay_clean_deltas_archive_and_receipt(adapter_app): """The recorded id=12 stream through the real adapter and the whole app: chat.delta, the archived row and the receipt all bind the clean visible reply only.""" app, _, epoch = adapter_app deltas: list[str] = [] turn = await api_client(app).send_turn("老孙来也", epoch=epoch, on_delta=deltas.append) assert turn.completed assert turn.text == RECORDED_VISIBLE assert "".join(deltas) == RECORDED_VISIBLE, \ "reasoning and must never stream to subtitles/TTS" assert not any("Considering" in d or "think" in d for d in deltas) archived = [r for r in rows(app) if r["role"] == "companion"] assert archived and archived[0]["text"] == RECORDED_VISIBLE assert turn.receipt and turn.receipt["text_hash"] == \ hashlib.sha256(RECORDED_VISIBLE.encode()).hexdigest() assert await api_client(app).acknowledge(turn.receipt) is True @pytest.mark.parametrize("raw,pieces,label", [ (A1_RAW, A1_CHUNKS, "review-A1-long-implicit"), (A2_RAW, A2_CHUNKS, "review-A2-chinese-sentence"), ]) async def test_review_shapes_never_reach_stream_archive_or_receipt( adapter_app, raw, pieces, label): """HEL-909 A1/A2 verbatim, small chunks (real token arrival): through the real OpenAICompatLLM -> real app -> persistence and receipt. These exact shapes leaked wholesale in the previous delivery; the buffer_turn gate keeps them out of chat.delta, the archive and the receipt.""" app, state, epoch = adapter_app state["answers"] = [sse_chunks(pieces)] deltas: list[str] = [] turn = await api_client(app).send_turn(label, epoch=epoch, on_delta=deltas.append) assert turn.completed assert turn.text == "回答。", "the archived reply is the clean visible text" assert "".join(deltas) == "回答。", "chat.delta (subtitles/TTS) stays clean" assert "private reasoning" not in turn.text and "内部思考" not in turn.text archived = [r for r in rows(app) if r["role"] == "companion"] assert archived and archived[0]["text"] == "回答。" assert turn.receipt and turn.receipt["text_hash"] == \ hashlib.sha256("回答。".encode()).hexdigest() assert await api_client(app).acknowledge(turn.receipt) is True async def test_unclosed_think_fails_closed(adapter_app): """A reply that never leaves its think phase has no visible content: the turn fails honestly instead of archiving reasoning as her words.""" app, state, epoch = adapter_app state["answers"] = [sse_chunks(["只想不说到结尾"])] turn = await api_client(app).send_turn("这次只有思考", epoch=epoch) assert not turn.completed and not turn.cancelled assert turn.error_phi and "没接上话" in turn.error_phi assert not [r for r in rows(app) if r["role"] == "companion"] failed = [r for r in rows(app) if r["text"] == "这次只有思考"] assert failed and failed[0]["status"] == "failed" async def test_completed_replay_and_failed_retry_still_work(rework): """The refusal branch must not disturb replay idempotence or the existing retry-after-failure resilience (only 'cancelled' is terminal).""" app, provider, epoch = rework tid = str(uuid4()) first = await api_client(app).send_turn("正常一轮", turn_id=tid, epoch=epoch) assert first.completed replay = await api_client(app).send_turn("正常一轮", turn_id=tid, epoch=epoch) assert replay.completed and replay.text == first.text calls = len(provider.calls) provider.mode = "error" failed_tid = str(uuid4()) failed = await api_client(app).send_turn("会失败的一轮", turn_id=failed_tid, epoch=epoch) assert not failed.completed and failed.error_phi provider.mode = "" retried = await api_client(app).send_turn("会失败的一轮", turn_id=failed_tid, epoch=epoch) assert retried.completed, "failed turns stay retryable (only cancelled is final)" assert len(provider.calls) == calls + 2 async def test_text_after_clean_voice_final_is_a_normal_turn(rework): """R2 app-integration record (evidence C sequence): the voice turn already finished clean — the server has no active turn left to cancel, so only the worker's cg.interrupt channel can stop leftover playout (proved on the real SDK in test_sdk_livekit_hel908). At the app seam the text turn simply proceeds: nothing cancelled, no phantom rows.""" app, provider, epoch = rework voice = await api_client(app).send_turn("语音已经说完", epoch=epoch) assert voice.completed text = await api_client(app).send_turn("文字随后到达", epoch=epoch) assert text.completed and text.text == provider.reply table = rows(app) assert not [r for r in table if r["status"] == "cancelled"], \ "after a clean final there is nothing to cancel at the app seam" assert len([r for r in table if r["role"] == "companion" and r["status"] == "sent"]) == 2 async def test_client_treats_cancelled_frame_as_terminal(rework): """Unit-level protocol check: chat.cancelled ends the turn client-side without raising (a raise is what made livekit retry it as a network failure).""" import json as _json def handler(request: httpx.Request) -> httpx.Response: if request.url.path == "/api/health": return httpx.Response(200, json={"epoch": 1}) turn_id = _json.loads(request.read())["turn_id"] frame = _json.dumps( {"t": "chat.cancelled", "epoch": 1, "turn_id": turn_id} ).encode() return httpx.Response( 200, headers={"content-type": "text/event-stream"}, content=b"data: " + frame + b"\n\n", ) client = ChatApiClient("http://x", transport=httpx.MockTransport(handler)) turn = await client.send_turn("只收一帧") assert turn.cancelled and not turn.completed and not turn.error_phi