"""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\\n\\n大圣,…"
into ``content`` — implicit-open reasoning (no ````, 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\n\n"
"大圣,您这定身法没点准啊,我可不是什么妖精妖怪,我是一行代码,"
"连肉都没有,怕硌着您的金箍棒。"
)
RECORDED_REASONING = (
"Considering the limited time by the user, I have to give the solution "
"based on the thinking directly now.\n"
)
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("隐藏可见")))
def test_explicit_tags_split_across_chunks(split_at):
text = "隐藏可见"
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("先说。中途思考后说。", 3)
assert visible == "先说。后说。"
def test_unclosed_think_yields_no_visible_text():
separator = ReasoningSeparator()
visible, _ = separator.feed("只想不说到结尾")
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) + ""
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("a答") == ("答", "a")
assert split_reasoning("a") == ("", "a")
assert split_reasoning("正常回答") == ("正常回答", "")
visible, reasoning = split_reasoning("a一b二")
assert visible == "一二"
assert reasoning == "ab"
# ── 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 "" 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()