Files
CyberGril/tests/test_voice_rework_hel879.py
T
zonggongandmultica-agent 7c73d392b9 HEL-879 rework materials: hatchling cache correction with the offline mem0ai wheel actually built from the fixed source (sha256 698284b6..., zero downloads/installs, no 3.10 mixing, recorded in release-artifacts.json), hel895 release doc §0 now separates the historical HEL-895/896 candidate from the current hel-879-assembly candidate and §4/§5 carry the v3 snapshot semantics, budget §6.2.4 amended - a sealed library is never reopened by raising total_requests (contradiction removed), runbook §3.3/3.5/3.6/4.4/4.5 corrected (bounded cleanup ledger replaces the unproven rooms-die-naturally claim; assistant_interim kind; real-but-default-off proactive seam; single-owner dual launcher), one comment-only correction in web/src/voice/session.ts removing the unproven server-auto-cleanup claim (no logic/style change; CSS and JS bundle hashes byte-stable), CG-011 + her incremental subtitles now have a real minimal backend seam (voice/seam.py + worker/llm_chat_api wiring, proactive default off) with the precise frontend interface and acceptance list in docs/rework/hel879/voice-seam-interfaces.md, real-SDK check extended to 10 items (worker callback path on real SpeechHandle/SpeechCreatedEvent; interim seam through real LLMStream) and re-run on .12 ALL PASS, handoff-HEL-879.json appended with the rework scope; regression at this head: pytest 341/341, ruff clean except 1 pre-existing error identical at 7f0a739, web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 88/88 / build passes (CSS index-BpZaybfD.css unchanged), voice chain 8/8, budget split 10/10, release offline R1-R7, http pagination 7/7, real-service browser 9/9 with zero non-loopback outbound, pinned-SDK 16/16+12/12+6/6+7/7+12/12, requirements checks 4/4 (origin/main and c121c42, each with/without handoff)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-27 04:27:04 +08:00

553 lines
22 KiB
Python

"""HEL-879 rework regressions for the 总管's independent-review edges.
Four confirmed offline defects, each reproduced first and fixed:
1. dual uvicorn listeners both running the app lifespan (epoch 1→2, state
replaced, store closed under live listeners);
2. end_session popping the registry before the remote delete (lost retry
target; expiry pruning dropping rooms with zero DELETE attempts);
3. TurnLedger binding streams to handles by timestamp (a handle without a
generation steals the next turn's stream/receipt);
4. release-snapshot verify accepting self-contradictory success markers and
same-basename DBs overwriting each other (covered by the tool selftest).
Zero network beyond 127.0.0.1; fake LiveKit/TTS transports throughout.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import socket
import ssl
import subprocess
import sys
import time
from pathlib import Path
from types import SimpleNamespace
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 test_r2 import R2LLM # noqa: E402
from cybergril.api.app import create_app # noqa: E402
from cybergril.life.runtime import LifeConfig # noqa: E402
from cybergril.memory.store import Store # noqa: E402
from cybergril.think.router import build_router # noqa: E402
from cybergril.think.scenes import Tier # noqa: E402
from cybergril.voice import livekit_wire # noqa: E402
from cybergril.voice.receipt import TurnLedger # noqa: E402
from cybergril.voice.seam import ( # noqa: E402
AssistantInterimPublisher,
pick_proactive,
)
from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402
# ---------------------------------------------------------------- TurnLedger
def _stream(turn_id: str) -> SimpleNamespace:
return SimpleNamespace(turn_id=turn_id, receipt={"message_id": hash(turn_id) % 1000})
def test_ledger_binds_each_handle_to_its_own_stream():
ledger = TurnLedger()
h1, h2 = object(), object()
s1, s2 = _stream("old"), _stream("new")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.1)
ledger.note_handle(h2, 2.0)
ledger.note_stream(s2, 2.1)
# A late cleanup of H2 must leave H1's own stream to H1 (old code: None).
assert ledger.stream_for(h2) is s2
assert ledger.stream_for(h1) is s1
def test_ledger_handle_without_generation_consumes_nothing():
ledger = TurnLedger()
no_generation, real = object(), object()
s2 = _stream("new")
ledger.note_handle(no_generation, 10.0)
ledger.note_handle(real, 11.0) # retires the older, generation-less handle
ledger.note_stream(s2, 11.1)
assert ledger.stream_for(no_generation) is None
assert ledger.stream_for(real) is s2
def test_ledger_interrupted_handle_discards_only_its_own_binding():
ledger = TurnLedger()
h1, h2 = object(), object()
s1, s2 = _stream("one"), _stream("two")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.0)
ledger.note_handle(h2, 2.0)
ledger.note_stream(s2, 2.0)
ledger.discard(h1) # worker fail-closed path (interrupted/failed playout)
assert ledger.stream_for(h1) is None
assert ledger.stream_for(h2) is s2
def test_ledger_stream_without_pending_handle_stays_unclaimed():
ledger = TurnLedger()
stray = _stream("proactive")
ledger.note_stream(stray, 1.0) # no user turn awaited a generation
handle = object()
ledger.note_handle(handle, 2.0)
later = _stream("answer")
ledger.note_stream(later, 2.5)
assert ledger.stream_for(handle) is later
# --------------------------------------------------- session ownership ledger
def _proto_field1(data: bytes) -> str:
"""Decode varint-prefixed field 1 (room) from a livekit proto body."""
if not data or (data[0] >> 3) != 1 or (data[0] & 7) != 2:
return ""
length = 0
index = 1
shift = 0
while True:
byte = data[index]
length |= (byte & 0x7F) << shift
index += 1
if not byte & 0x80:
break
shift += 7
return data[index:index + length].decode()
class StandinLiveKit:
"""Fake Twirp transport: configurable delete failures per call."""
def __init__(self) -> None:
self.deleted: list[str] = []
self.delete_errors: list[Exception | int] = []
self._transport = httpx.MockTransport(self._handle)
def _handle(self, request: httpx.Request) -> httpx.Response:
path = request.url.path
if path.endswith("/CreateDispatch"):
return httpx.Response(200, json={"id": "AD_1", "room": "r"})
if path.endswith("/DeleteRoom"):
if self.delete_errors:
error = self.delete_errors.pop(0)
if isinstance(error, int):
return httpx.Response(error, text="room service error")
raise error
self.deleted.append(_proto_field1(request.content))
return httpx.Response(200, content=b"")
return httpx.Response(404, text="unknown")
@property
def transport(self) -> httpx.MockTransport:
return self._transport
def _service(standin: StandinLiveKit, *, clock=None, backoff=0.0, **kwargs) -> VoiceSessionService:
config = VoiceConfig(
livekit_url="ws://voice.test:7880",
livekit_internal="http://livekit.test",
api_key="devkey",
api_secret="test-secret-not-real",
tts_health_url="http://tts.test/health",
session_ttl_seconds=kwargs.pop("session_ttl_seconds", 5.0),
)
return VoiceSessionService(
config=config,
http=httpx.AsyncClient(transport=standin.transport),
clock=clock or time.time,
cleanup_backoff_seconds=backoff,
**kwargs,
)
async def _open(service: VoiceSessionService) -> str:
return (await service.open_session(epoch=1)).session_id
@pytest.mark.asyncio
async def test_delete_failure_keeps_room_owned_until_retry_lands():
standin = StandinLiveKit()
standin.delete_errors = [RuntimeError("standin delete failed")]
service = _service(standin)
try:
session = await service.open_session(epoch=1)
with pytest.raises(RuntimeError):
await service.end_session(session.session_id)
# The room is retained for retry (old code: registry already popped,
# second call answered None and never deleted the room again).
debt = service.cleanup_debt(session.session_id)
assert debt is not None and debt.session.room == session.room
assert standin.deleted == []
ended = await service.end_session(session.session_id)
assert ended.room == session.room
assert standin.deleted == [session.room]
assert service.cleanup_debt(session.session_id) is None
assert await service.end_session(session.session_id) is None
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_expired_session_room_is_actually_deleted():
standin = StandinLiveKit()
now = [1000.0]
service = _service(standin, clock=lambda: now[0])
try:
session = await service.open_session(epoch=1)
now[0] += service.config.session_ttl_seconds + 1
# Old code: _prune dropped the registration silently — zero DELETEs.
ended = await service.end_session(session.session_id)
assert ended is not None and ended.room == session.room
assert standin.deleted == [session.room]
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_delete_already_gone_is_idempotent_success():
standin = StandinLiveKit()
standin.delete_errors = [404] # room vanished server-side first
service = _service(standin)
try:
session = await service.open_session(epoch=1)
ended = await service.end_session(session.session_id)
assert ended is not None
assert service.cleanup_debt(session.session_id) is None
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_background_cleanup_settles_expiry_debt():
standin = StandinLiveKit()
standin.delete_errors = [RuntimeError("flap"), RuntimeError("flap")]
now = [1000.0]
service = _service(standin, clock=lambda: now[0])
try:
session = await service.open_session(epoch=1)
now[0] += service.config.session_ttl_seconds + 1
with pytest.raises(RuntimeError):
await service.end_session(session.session_id)
now[0] += 1
for _ in range(50):
if standin.deleted:
break
await asyncio.sleep(0.02)
assert standin.deleted == [session.room]
for _ in range(50):
if service.cleanup_debt(session.session_id) is None:
break
await asyncio.sleep(0.02)
assert service.cleanup_debt(session.session_id) is None
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_cleanup_is_bounded_then_recorded_abandoned(tmp_path):
standin = StandinLiveKit()
standin.delete_errors = [503] * 50 # never succeeds
now = [1000.0]
service = _service(standin, clock=lambda: now[0],
state_path=tmp_path / "voice-sessions.json",
cleanup_max_attempts=3)
try:
session = await service.open_session(epoch=1)
now[0] += service.config.session_ttl_seconds + 1
with pytest.raises(livekit_wire.RoomDeleteError):
await service.end_session(session.session_id)
for _ in range(200):
debt = service.cleanup_debt(session.session_id)
if debt is not None and debt.abandoned:
break
await asyncio.sleep(0.02)
debt = service.cleanup_debt(session.session_id)
assert debt is not None and debt.abandoned == "attempts-exhausted"
# Bounded: after abandonment no further delete attempts happen.
attempts = len(standin.delete_errors)
await asyncio.sleep(0.2)
assert len(standin.delete_errors) == attempts
recorded = json.loads((tmp_path / "voice-sessions.json").read_text())
assert recorded["debts"][0]["abandoned"] == "attempts-exhausted"
finally:
await service.aclose()
@pytest.mark.asyncio
async def test_restart_compensation_deletes_previous_process_rooms(tmp_path):
standin = StandinLiveKit()
standin.delete_errors = [RuntimeError("down")] * 2 # end attempt + shutdown sweep
state = tmp_path / "voice-sessions.json"
now = [1000.0]
# big backoff: the background sweeper must not race this scenario
first = _service(standin, clock=lambda: now[0], state_path=state, backoff=3600.0)
session = await first.open_session(epoch=1)
with pytest.raises(RuntimeError):
await first.end_session(session.session_id)
await first.aclose()
assert standin.deleted == [] # LiveKit was down for process 1's whole life
persisted = json.loads(state.read_text())
assert any(d["session"]["room"] == session.room for d in persisted["debts"])
# "Restart": a new process of the same instance reads the same ledger and
# compensates only the rooms recorded there.
second = _service(standin, clock=lambda: now[0], state_path=state)
try:
await second.recover()
for _ in range(100):
if standin.deleted:
break
await asyncio.sleep(0.02)
assert standin.deleted == [session.room]
for _ in range(100):
settled = json.loads(state.read_text())
if settled["debts"] == [] and settled["sessions"] == []:
break
await asyncio.sleep(0.02)
settled = json.loads(state.read_text())
assert settled["debts"] == [] and settled["sessions"] == []
finally:
await second.aclose()
@pytest.mark.asyncio
async def test_active_room_surives_restart_until_ttl_then_compensated(tmp_path):
standin = StandinLiveKit()
state = tmp_path / "voice-sessions.json"
now = [1000.0]
first = _service(standin, clock=lambda: now[0], state_path=state,
session_ttl_seconds=0.5)
session = await first.open_session(epoch=1) # never ended by the user
await first.aclose() # graceful shutdown must not hang up a live call
assert standin.deleted == []
persisted = json.loads(state.read_text())
assert any(s["room"] == session.room for s in persisted["sessions"])
# Restart immediately: the call may still be alive on the SFU, so the
# compensation waits for the session's own TTL — then deletes, bounded.
second = _service(standin, clock=lambda: now[0], state_path=state,
session_ttl_seconds=0.5)
try:
await second.recover()
await asyncio.sleep(0.15)
assert standin.deleted == [] # still within TTL: untouched
now[0] += 1.0
for _ in range(100):
if standin.deleted:
break
await asyncio.sleep(0.05)
assert standin.deleted == [session.room]
finally:
await second.aclose()
# ------------------------------------------------------ router-level semantics
def _voice_app(standin: StandinLiveKit, tts_ok=True):
provider = R2LLM()
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
def handler(request: httpx.Request) -> httpx.Response:
if request.url.host == "tts.test":
return httpx.Response(200 if tts_ok else 503)
return standin._handle(request)
service = _service(standin, backoff=3600.0) # keep the sweep out of the race
service.http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
app = create_app(db_path=":memory:", router=router,
life_config=LifeConfig(enabled=False), semantic_mode="stub",
voice_service=service)
return app, service
def test_router_delete_failure_is_503_and_keeps_room_owned():
from fastapi.testclient import TestClient
standin = StandinLiveKit()
# interactive attempt + the background sweep's immediate first retry;
# the sweep then backs off (3600 s), leaving the debt visibly owned
standin.delete_errors = [RuntimeError("livekit down"), RuntimeError("livekit down")]
app, service = _voice_app(standin)
with TestClient(app) as client:
client.post("/api/companion", json={
"name": "语音重试", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"})
opened = client.post("/api/voice/session")
assert opened.status_code == 201
session_id = opened.json()["session_id"]
failed = client.delete(f"/api/voice/session/{session_id}")
assert failed.status_code == 503 # NOT 404: the room is still owned
assert service.cleanup_debt(session_id) is not None
retried = client.delete(f"/api/voice/session/{session_id}")
assert retried.status_code == 200 and retried.json()["ended"] is True
assert standin.deleted == [opened.json()["room"]]
again = client.delete(f"/api/voice/session/{session_id}")
assert again.status_code == 404
# ------------------------------------------------- CG-011 seam (HEL-879)
def test_assistant_interim_publisher_accumulates_and_resets():
published: list[dict] = []
publisher = AssistantInterimPublisher(published.append)
assert publisher.feed("") is None
assert publisher.feed("她在") is not None
publisher.feed("打字中")
assert published[-1] == {"kind": "assistant_interim", "role": "assistant",
"text": "她在打字中"}
publisher.reset()
publisher.feed("新的一轮")
assert published[-1]["text"] == "新的一轮", "no inheritance across turns"
def test_proactive_selection_is_archived_newest_bounded():
messages = [
{"id": 1, "role": "user", "status": "sent", "proactive": False, "text": "hi"},
{"id": 2, "role": "companion", "status": "sent", "proactive": True, "text": "旧主动"},
{"id": 3, "role": "companion", "status": "sent", "proactive": True, "text": "新主动"},
{"id": 4, "role": "companion", "status": "queued", "proactive": True, "text": "未落库"},
{"id": 5, "role": "companion", "status": "sent", "proactive": True, "text": " "},
{"id": 6, "role": "companion", "status": "sent", "proactive": False, "text": "普通回复"},
]
picked = pick_proactive(messages, already_spoken=set(), limit=1)
assert [m["id"] for m in picked] == [3], "newest eligible proactive row only"
again = pick_proactive(messages, already_spoken={3}, limit=1)
assert [m["id"] for m in again] == [2]
assert pick_proactive(messages, already_spoken={2, 3}, limit=1) == []
@pytest.mark.asyncio
async def test_pending_proactive_reads_unified_messages_page():
from cybergril.voice.chat_api_client import ChatApiClient
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/api/messages"
assert request.url.params["limit"] == "20"
return httpx.Response(200, json={"messages": [
{"id": 9, "role": "companion", "status": "sent",
"proactive": True, "text": "落库的主动留言"}], "epoch": 1})
client = ChatApiClient("http://api.test", transport=httpx.MockTransport(handler))
try:
rows = await client.recent_messages()
picked = pick_proactive(rows, already_spoken=set(), limit=1)
assert picked[0]["id"] == 9
finally:
await client.aclose()
# ---------------------------------------------------- dual-listener lifecycle
def _free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
@pytest.fixture
def self_signed_cert(tmp_path):
cert = tmp_path / "cert.pem"
key = tmp_path / "key.pem"
subprocess.run(
["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", str(key), "-out", str(cert), "-days", "1",
"-subj", "/CN=127.0.0.1",
"-addext", "subjectAltName=IP:127.0.0.1"],
check=True, capture_output=True)
return str(cert), str(key)
@pytest.mark.asyncio
async def test_dual_listeners_share_one_lifecycle_and_close_in_order(
tmp_path, self_signed_cert, monkeypatch):
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "deploy" / "voice"))
import serve_dual_8360_8361 as launcher
cert, key = self_signed_cert
events: list[str] = []
store_inits: list[int] = []
real_store_init = Store.__init__
real_store_close = Store.close
def counting_init(self, *args, **kwargs):
store_inits.append(id(self))
real_store_init(self, *args, **kwargs)
def recording_close(self):
events.append("store_close")
real_store_close(self)
monkeypatch.setattr(Store, "__init__", counting_init)
monkeypatch.setattr(Store, "close", recording_close)
import uvicorn
real_shutdown = uvicorn.Server.shutdown
async def recording_shutdown(self, sockets=None):
events.append(f"listener_shutdown:{self.config.port}")
await real_shutdown(self, sockets=sockets)
monkeypatch.setattr(uvicorn.Server, "shutdown", recording_shutdown)
provider = R2LLM()
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
app = create_app(db_path=tmp_path / "dual.db", router=router,
life_config=LifeConfig(enabled=False), semantic_mode="off")
http_port, https_port = _free_port(), _free_port()
serve_task = asyncio.get_running_loop().create_task(
launcher.serve(http_port, https_port, cert, key, app=app))
client = httpx.AsyncClient(timeout=5.0, verify=False)
try:
epochs = []
for _ in range(100):
try:
for port, scheme in ((http_port, "http"), (https_port, "https")):
response = await client.get(f"{scheme}://127.0.0.1:{port}/api/health")
if response.status_code == 200:
epochs.append(response.json()["epoch"])
if len(epochs) >= 2:
break
except (httpx.ConnectError, httpx.ConnectTimeout, ssl.SSLError):
await asyncio.sleep(0.05)
assert len(epochs) >= 2, "both listeners must come up"
# ONE lifecycle for both listeners: a second entry would be epoch 2.
assert epochs[0] == epochs[1]
assert len(set(store_inits)) == 1, "the app must be initialized exactly once"
finally:
serve_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await serve_task
await client.aclose()
# Exit boundary: both listeners fully shut down BEFORE the store closes,
# and the store closes exactly once (never closed under live listeners).
shutdowns = [e for e in events if e.startswith("listener_shutdown")]
assert len(shutdowns) == 2, events
assert events.index("store_close") > max(events.index(e) for e in shutdowns)
assert events.count("store_close") == 1
assert len(set(store_inits)) == 1
def test_second_lifespan_entry_fails_loudly(tmp_path):
from fastapi.testclient import TestClient
provider = R2LLM()
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
app = create_app(db_path=tmp_path / "guard.db", router=router,
life_config=LifeConfig(enabled=False), semantic_mode="off")
async def _double_enter():
async with app.router.lifespan_context(app):
pass
with TestClient(app) as client:
epoch_before = client.get("/api/health").json()["epoch"]
# A second entry (the old dual-uvicorn defect: epoch 1→2, Store/life/
# chat_lock silently replaced) must now fail closed.
with pytest.raises(RuntimeError, match="entered twice"):
asyncio.run(_double_enter())
assert client.get("/api/health").json()["epoch"] == epoch_before