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>
This commit is contained in:
+4
-1
@@ -314,7 +314,10 @@ async def test_disconnect_closes_real_openai_http_stream(tmp_path):
|
||||
async def completion():
|
||||
async def chunks():
|
||||
try:
|
||||
yield 'data: {"choices":[{"delta":{"content":"部分"}}]}\n\n'
|
||||
# ends with a sentence terminator so the HEL-908 reasoning
|
||||
# separator flushes it immediately (this test is about upstream
|
||||
# closure on disconnect, not about hold semantics)
|
||||
yield 'data: {"choices":[{"delta":{"content":"部分。"}}]}\n\n'
|
||||
await asyncio.sleep(30)
|
||||
finally:
|
||||
closed.set()
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"""HEL-908 reasoning separation tests: the adapter seam between raw model
|
||||
output and user-visible content, against the REAL ReasoningSeparator and the
|
||||
REAL OpenAICompatLLM adapter (fake SSE transports, zero network).
|
||||
|
||||
The recorded evidence (HEL-907 window, companion.db row id=12 and
|
||||
tts-window-tail.log) is replayed verbatim: the dialogue endpoint streamed
|
||||
"Considering the limited time by the user, ... now.\\n</think>\\n\\n大圣,…"
|
||||
into ``content`` — implicit-open reasoning (no ``<think>``, the chat template
|
||||
pre-fills it) that reached subtitles AND TTS.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
from cybergril.providers.llm.openai_compat import OpenAICompatLLM
|
||||
from cybergril.providers.llm.reasoning import (
|
||||
HOLD_LIMIT,
|
||||
ReasoningSeparator,
|
||||
split_reasoning,
|
||||
)
|
||||
|
||||
# companion.db row id=12 (call3, turn 3a67b253) — verbatim recorded stream.
|
||||
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_REASONING = (
|
||||
"Considering the limited time by the user, I have to give the solution "
|
||||
"based on the thinking directly now.\n</think>"
|
||||
)
|
||||
RECORDED_VISIBLE = (
|
||||
"大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码,"
|
||||
"连肉都没有,怕硌着您的金箍棒。"
|
||||
)
|
||||
|
||||
|
||||
def run_stream(text: str, chunk_size: int) -> tuple[str, str]:
|
||||
separator = ReasoningSeparator()
|
||||
visible_parts: list[str] = []
|
||||
for i in range(0, len(text), chunk_size):
|
||||
v, _ = separator.feed(text[i : i + chunk_size])
|
||||
visible_parts.append(v)
|
||||
v, _ = separator.finish()
|
||||
visible_parts.append(v)
|
||||
return "".join(visible_parts), separator.reasoning
|
||||
|
||||
|
||||
# ── streaming separator ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunk", [1, 2, 3, 5, 7, 13, 1000])
|
||||
def test_recorded_stream_leaks_nothing_at_any_chunk_size(chunk):
|
||||
visible, reasoning = run_stream(RECORDED_RAW, chunk)
|
||||
assert visible == RECORDED_VISIBLE
|
||||
assert reasoning == RECORDED_REASONING
|
||||
|
||||
|
||||
@pytest.mark.parametrize("split_at", range(1, len("<think>隐藏</think>可见")))
|
||||
def test_explicit_tags_split_across_chunks(split_at):
|
||||
text = "<think>隐藏</think>可见"
|
||||
head, tail = text[:split_at], text[split_at:]
|
||||
separator = ReasoningSeparator()
|
||||
v1, _ = separator.feed(head)
|
||||
v2, _ = separator.feed(tail)
|
||||
v3, _ = separator.finish()
|
||||
assert v1 + v2 + v3 == "可见"
|
||||
|
||||
|
||||
def test_explicit_think_block_anywhere_in_stream():
|
||||
visible, _ = run_stream("先说。<think>中途思考</think>后说。", 3)
|
||||
assert visible == "先说。后说。"
|
||||
|
||||
|
||||
def test_unclosed_think_yields_no_visible_text():
|
||||
separator = ReasoningSeparator()
|
||||
visible, _ = separator.feed("<think>只想不说到结尾")
|
||||
tail_visible, _ = separator.finish()
|
||||
assert visible + tail_visible == ""
|
||||
|
||||
|
||||
def test_safe_no_think_chinese_streams_immediately():
|
||||
separator = ReasoningSeparator()
|
||||
visible, _ = separator.feed("哈哈,那走吧。")
|
||||
assert visible == "哈哈,那走吧。"
|
||||
|
||||
|
||||
def test_normal_chinese_body_preserved_byte_for_byte():
|
||||
text = "今天水母网我背,你负责举着泡泡喊“出发”。\n\n抓完水母我们就坐在海滩上。"
|
||||
visible, reasoning = run_stream(text, 4)
|
||||
assert visible == text
|
||||
assert reasoning == ""
|
||||
|
||||
|
||||
def test_normal_english_body_preserved_byte_for_byte():
|
||||
text = (
|
||||
"Sure, listening to you. A reply that happens to be English is normal "
|
||||
"user-facing content and must survive the separator untouched, "
|
||||
"including newlines\nand punctuation."
|
||||
)
|
||||
visible, reasoning = run_stream(text, 5)
|
||||
assert visible == text
|
||||
assert reasoning == ""
|
||||
|
||||
|
||||
def test_untagged_short_stream_flushes_at_finish():
|
||||
separator = ReasoningSeparator()
|
||||
v, _ = separator.feed("嗯") # below HOLD_LIMIT, no sentence end: held
|
||||
assert v == ""
|
||||
v, _ = separator.finish()
|
||||
assert v == "嗯"
|
||||
|
||||
|
||||
def test_residual_beyond_hold_limit_is_cleaned_at_turn_level():
|
||||
"""Documented residual: implicit-open reasoning whose closer lies beyond
|
||||
HOLD_LIMIT streams partially visible; the turn-level split still returns
|
||||
the clean reply for persistence and the receipt."""
|
||||
long_reasoning = "r" * (HOLD_LIMIT + 50) + "</think>"
|
||||
text = long_reasoning + "干净的回答。"
|
||||
streamed_visible, _ = run_stream(text, 64)
|
||||
assert streamed_visible != "干净的回答。" # partial streaming leak (known)
|
||||
final_visible, dropped = split_reasoning(text)
|
||||
assert final_visible == "干净的回答。"
|
||||
assert long_reasoning in dropped
|
||||
|
||||
|
||||
# ── turn-level final split ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_split_recorded_row_is_clean():
|
||||
visible, reasoning = split_reasoning(RECORDED_RAW)
|
||||
assert visible == RECORDED_VISIBLE
|
||||
assert reasoning == RECORDED_REASONING
|
||||
|
||||
|
||||
def test_split_explicit_blocks_and_unclosed():
|
||||
assert split_reasoning("<think>a</think>答") == ("答", "<think>a</think>")
|
||||
assert split_reasoning("<think>a") == ("", "<think>a")
|
||||
assert split_reasoning("正常回答") == ("正常回答", "")
|
||||
visible, reasoning = split_reasoning("<think>a</think>一<think>b</think>二")
|
||||
assert visible == "一二"
|
||||
assert reasoning == "<think>a</think><think>b</think>"
|
||||
|
||||
|
||||
# ── REAL OpenAICompatLLM adapter with fake upstream SSE ─────────────────────
|
||||
|
||||
|
||||
def sse_response(deltas: list[dict]) -> httpx.Response:
|
||||
lines = []
|
||||
for d in deltas:
|
||||
lines.append("data: " + json.dumps({"choices": [{"delta": d}]}, ensure_ascii=False))
|
||||
lines.append("data: [DONE]")
|
||||
return httpx.Response(
|
||||
200, headers={"content-type": "text/event-stream"},
|
||||
content=("\n\n".join(lines) + "\n\n").encode(),
|
||||
)
|
||||
|
||||
|
||||
async def collect_provider(provider: OpenAICompatLLM) -> tuple[str, str]:
|
||||
text = reasoning = ""
|
||||
async for delta in provider.stream([type("M", (), {"role": "user", "content": "你好"})()]):
|
||||
text += delta.text
|
||||
reasoning += delta.reasoning
|
||||
return text, reasoning
|
||||
|
||||
|
||||
async def test_adapter_separates_reasoning_field_from_content():
|
||||
seen: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen.append(request)
|
||||
return sse_response(
|
||||
[
|
||||
{"reasoning_content": "先在心里盘算一下"},
|
||||
{"content": ""},
|
||||
{"content": RECORDED_VISIBLE[:4]},
|
||||
{"content": RECORDED_VISIBLE[4:]},
|
||||
]
|
||||
)
|
||||
|
||||
provider = OpenAICompatLLM(base_url="http://isolated/v1", model="m")
|
||||
provider._client = httpx.AsyncClient(
|
||||
base_url="http://isolated/v1", transport=httpx.MockTransport(handler)
|
||||
)
|
||||
try:
|
||||
text, reasoning = await collect_provider(provider)
|
||||
assert text == RECORDED_VISIBLE
|
||||
assert reasoning == "先在心里盘算一下"
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
async def test_adapter_filters_recorded_inline_leak():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
# recorded id=12 shape: reasoning text + stray closer, no opening tag;
|
||||
# chunks split the closing tag across SSE frames
|
||||
return sse_response(
|
||||
[
|
||||
{"content": RECORDED_RAW[:60]},
|
||||
{"content": RECORDED_RAW[60:104]},
|
||||
{"content": RECORDED_RAW[104:112]},
|
||||
{"content": RECORDED_RAW[112:]},
|
||||
]
|
||||
)
|
||||
|
||||
provider = OpenAICompatLLM(base_url="http://isolated/v1", model="m")
|
||||
provider._client = httpx.AsyncClient(
|
||||
base_url="http://isolated/v1", transport=httpx.MockTransport(handler)
|
||||
)
|
||||
try:
|
||||
text, reasoning = await collect_provider(provider)
|
||||
assert text == RECORDED_VISIBLE, "reasoning must never reach delta.text"
|
||||
assert "Considering" in reasoning and "</think>" in reasoning
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
async def test_adapter_preserves_english_content_and_flags():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return sse_response(
|
||||
[
|
||||
{"content": "Plain English reply, kept fully. "},
|
||||
{"reasoning_content": "internal note"},
|
||||
{"content": "Second sentence."},
|
||||
]
|
||||
)
|
||||
|
||||
provider = OpenAICompatLLM(base_url="http://isolated/v1", model="m")
|
||||
provider._client = httpx.AsyncClient(
|
||||
base_url="http://isolated/v1", transport=httpx.MockTransport(handler)
|
||||
)
|
||||
try:
|
||||
text, reasoning = await collect_provider(provider)
|
||||
assert text == "Plain English reply, kept fully. Second sentence."
|
||||
assert reasoning == "internal note"
|
||||
finally:
|
||||
await provider.aclose()
|
||||
@@ -0,0 +1,366 @@
|
||||
"""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
|
||||
@@ -0,0 +1,246 @@
|
||||
"""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()))
|
||||
@@ -139,13 +139,18 @@ async def test_broken_stream_raises_connection_error():
|
||||
|
||||
|
||||
async def test_voice_turn_cancels_active_text_turn_same_gate(api):
|
||||
"""Voice and text contend through the server's one same-turn gate."""
|
||||
"""Voice and text contend through the server's one same-turn gate.
|
||||
|
||||
HEL-908: the cancelled side now ends with an explicit chat.cancelled
|
||||
terminal frame — a clean end, not a connection error the caller might
|
||||
mistake for a transient failure and retry (the HEL-907 defect family)."""
|
||||
app, provider, _ = api
|
||||
|
||||
outcome: dict = {}
|
||||
|
||||
async def slow_text() -> None:
|
||||
text_client = ChatApiClient("http://asgi", transport=httpx.ASGITransport(app=app))
|
||||
with pytest.raises((ChatApiConnectionError, Exception)):
|
||||
await text_client.send_turn("文字说一半")
|
||||
outcome["turn"] = await text_client.send_turn("文字说一半")
|
||||
|
||||
provider.mode = "slow"
|
||||
task = asyncio.create_task(slow_text())
|
||||
@@ -155,8 +160,10 @@ async def test_voice_turn_cancels_active_text_turn_same_gate(api):
|
||||
turn = await voice_client.send_turn("语音插进来")
|
||||
assert turn.completed
|
||||
provider.mode = "" # (already reset above; kept for clarity on early exits)
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await asyncio.wait_for(task, timeout=10)
|
||||
superseded = outcome["turn"]
|
||||
assert superseded.cancelled and not superseded.completed, \
|
||||
"the cancelled side ends on the explicit chat.cancelled terminal frame"
|
||||
|
||||
rows = app.state.store.query(
|
||||
"SELECT role, text, status, turn_id FROM chat_message ORDER BY id"
|
||||
|
||||
Reference in New Issue
Block a user