Files
CyberGril/tests/test_reasoning_separation_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

247 lines
9.0 KiB
Python

"""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()