Files
CyberGril/tests/test_rework_hel908.py
T
xiaomoandmultica-agent b8ec832f35 HEL-908: terminal chat.cancelled + no-revive gate for text interrupt; reasoning/content separation at the adapter seam
Bug 1 (recorded call1): server-side cancel ended the voice SSE without a
terminal frame BEFORE the first delta (worker.log:108 SDK retry 13ms after
the text POST); the adapter raised a connection error, livekit-agents 1.8.8
silently retried the same turn_id, the retry re-acquired the gate, cancelled
the user's text turn and re-spoke a full ~32s reply. The HEL-907 claim that
the _retry_on_chunk_sent guard never worked is corrected: the guard only
applies after output (output_sent), verified against the installed SDK
source. Fix: explicit chat.cancelled terminal frame; a cancelled turn_id is
refused re-activation (never touches the newer active turn); the worker ends
cancelled turns on the SDK's own 499 path (no retry) and stops the cached
playout via SpeechHandle.interrupt(); a server_cancelled latch short-circuits
any re-entry with zero network. Failed-turn retries, completed-turn replay
and receipt validation are unchanged (dedicated tests).

Bug 2 (recorded row id=12): the endpoint streams implicit-open reasoning
plus a stray </think> inline in content into subtitles and TTS. Fix:
ReasoningSeparator at the OpenAI-compat adapter seam (cross-chunk safe,
reasoning_content field side-channel on LLMDelta.reasoning, never persisted)
plus a turn-level split before persist/final/receipt. Recorded stream
replays clean at every chunk size; normal zh/en content preserved
byte-for-byte; documented residual: implicit-open reasoning whose closer
lies beyond the 128-char hold streams partially (persistence stays clean).

Offline verification: .venv311 full suite 445 passed / 5 skipped (2
pre-existing test_r3 failures fail identically at 5625de6); real-SDK harness
(livekit-agents 1.8.8, agent venv) 5/5; reasoning separation 37/37; ruff
clean. Zero real requests, zero deployment, no dependency changes.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-28 21:27:08 +08:00

367 lines
15 KiB
Python

"""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 ``</think>``
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</think>\n\n"
"大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码,"
"连肉都没有,怕硌着您的金箍棒。"
)
RECORDED_VISIBLE = (
"大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码,"
"连肉都没有,怕硌着您的金箍棒。"
)
RECORDED_CHUNKS = [RECORDED_RAW[:60], RECORDED_RAW[60:104],
RECORDED_RAW[104:112], RECORDED_RAW[112:]]
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 (the seam where the reasoning separation
lives, exercised end to end)."""
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")
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 </think> 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
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(["<think>只想不说到结尾"])]
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_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