881 lines
37 KiB
Python
881 lines
37 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 _handle(hid: str = "speech_x") -> SimpleNamespace:
|
||
return SimpleNamespace(id=hid, created_at=1.0)
|
||
|
||
|
||
def test_ledger_binds_each_handle_to_exactly_its_own_generation():
|
||
ledger = TurnLedger()
|
||
h1, h2 = _handle("speech_1"), _handle("speech_2")
|
||
s1, s2 = _stream("old"), _stream("new")
|
||
ledger.note_handle(h1, 1.0)
|
||
ledger.note_stream(s1, h1, 1.1)
|
||
ledger.note_handle(h2, 2.0)
|
||
ledger.note_stream(s2, h2, 2.1)
|
||
# Each handle consumes exactly the stream of ITS generation, in any order.
|
||
assert ledger.stream_for(h2) is s2
|
||
assert ledger.stream_for(h1) is s1
|
||
|
||
|
||
def test_ledger_manager_interleaving_no_cross_turn_steal():
|
||
"""总管独立复核的精确反例:两个 speech 事件先排队、生成后到。
|
||
|
||
note_handle(H1)→note_handle(H2)→note_stream(S1)→note_stream(S2) 旧代码
|
||
把 S1 错绑给 H2(H1=None, H2=turn-one)。绑定改为只认 SDK 生成上下文的
|
||
确切 handle:S1 只属于 H1,S2 只属于 H2;没有归属的流不绑任何轮。
|
||
"""
|
||
ledger = TurnLedger()
|
||
h1, h2 = _handle("speech_h1"), _handle("speech_h2")
|
||
s1, s2 = _stream("turn-one"), _stream("turn-two")
|
||
ledger.note_handle(h1, 1.0)
|
||
ledger.note_handle(h2, 2.0) # 旧代码在这里把 H1 退役掉
|
||
assert ledger.note_stream(s1, h1, 3.0) is True # S1 归 H1,绝不给 H2
|
||
assert ledger.note_stream(s2, h2, 4.0) is True
|
||
assert ledger.stream_for(h1) is s1
|
||
assert ledger.stream_for(h2) is s2
|
||
|
||
|
||
def test_ledger_newer_speech_never_retires_older_generation():
|
||
"""新 speech 出现不能证明旧 speech 不会再开始生成(总管复核 B)。"""
|
||
ledger = TurnLedger()
|
||
h1, h2 = _handle("speech_a"), _handle("speech_b")
|
||
s1 = _stream("old-turn")
|
||
ledger.note_handle(h1, 1.0)
|
||
ledger.note_handle(h2, 2.0)
|
||
# H2 出现之后 H1 的生成才真正开始:S1 在 H1 的生成上下文里创建。
|
||
assert ledger.note_stream(s1, h1, 3.0) is True
|
||
assert ledger.stream_for(h1) is s1
|
||
|
||
|
||
def test_ledger_handle_without_generation_consumes_nothing():
|
||
ledger = TurnLedger()
|
||
no_generation, real = _handle("speech_ng"), _handle("speech_real")
|
||
s2 = _stream("new")
|
||
ledger.note_handle(no_generation, 10.0)
|
||
ledger.note_handle(real, 11.0)
|
||
# real 的生成上下文只绑 real;no_generation 永远拿不到流(fail-closed)。
|
||
assert ledger.note_stream(s2, real, 11.1) is True
|
||
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 = _handle("speech_1"), _handle("speech_2")
|
||
s1, s2 = _stream("one"), _stream("two")
|
||
ledger.note_handle(h1, 1.0)
|
||
ledger.note_stream(s1, h1, 1.0)
|
||
ledger.note_handle(h2, 2.0)
|
||
ledger.note_stream(s2, h2, 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_noted_handle_stays_unclaimed():
|
||
"""无确切归属即 fail-closed:未登记的 handle(主动/程序化生成)的流
|
||
不绑给任何用户轮,事后到达的 note_handle 也拿不到它。"""
|
||
ledger = TurnLedger()
|
||
stray = _stream("proactive")
|
||
assert ledger.note_stream(stray, None, 1.0) is False # 无归属
|
||
assert ledger.note_stream(stray, object(), 1.0) is False # 未登记的 handle
|
||
handle = _handle("speech_late")
|
||
ledger.note_handle(handle, 2.0)
|
||
later = _stream("answer")
|
||
assert ledger.note_stream(later, handle, 2.5) is True
|
||
assert ledger.stream_for(handle) is later
|
||
assert ledger.unattributed == [stray, stray]
|
||
|
||
|
||
# --------------------------------------------------- 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()
|
||
|
||
|
||
# ------------------------------------- HEL-879 remaining closure: item A
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_expiry_deletes_room_with_no_further_request():
|
||
"""总管复核 A-1 精确复现:recover→open→不再来任何请求,过 TTL 后远端
|
||
删除必须由清理所有者自己完成(旧代码 0 次删除、登记仍在)。"""
|
||
standin = StandinLiveKit()
|
||
now = [100.0]
|
||
service = _service(standin, clock=lambda: now[0],
|
||
session_ttl_seconds=0.01, backoff=0.005)
|
||
try:
|
||
session = await service.open_session(epoch=1)
|
||
await service.recover()
|
||
await asyncio.sleep(0.025) # cleaner exits in the old code right here
|
||
now[0] += 1.0 # past TTL — with NO further request of any kind
|
||
for _ in range(100):
|
||
if standin.deleted:
|
||
break
|
||
await asyncio.sleep(0.02)
|
||
assert standin.deleted == [session.room]
|
||
assert session.session_id not in service._sessions
|
||
assert service.cleanup_debt(session.session_id) is None
|
||
# settled: the cleaner exits by itself, no dangling coroutine
|
||
for _ in range(100):
|
||
if service._cleaner is None or service._cleaner.done():
|
||
break
|
||
await asyncio.sleep(0.02)
|
||
assert service._cleaner is None or service._cleaner.done()
|
||
finally:
|
||
await service.aclose()
|
||
assert service._cleaner is None
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_cleaner_stays_alive_while_a_session_is_registered():
|
||
"""活跃登记存在期间清理所有者不得退出(A-1 的 cleaner_present 维度)。"""
|
||
standin = StandinLiveKit()
|
||
now = [100.0]
|
||
service = _service(standin, clock=lambda: now[0],
|
||
session_ttl_seconds=0.01, backoff=0.005)
|
||
try:
|
||
await service.recover()
|
||
await service.open_session(epoch=1)
|
||
await asyncio.sleep(0.1)
|
||
assert service._cleaner is not None and not service._cleaner.done()
|
||
finally:
|
||
await service.aclose()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_open_session_with_real_dispatch_yield_re_kicks_cleanup(monkeypatch):
|
||
"""总管契约核准轮第 1 项精确复现:建房 await 真正让出事件循环(真实 HTTP
|
||
一定如此),pre-dispatch kick 的清理所有者在等待期间已空转退出;注册成功
|
||
并持久化之后必须重新唤醒/重建清理所有者——过 TTL 且不再来任何请求也能
|
||
到期转债并真实删房。旧代码:DELETE=0、过期登记仍在、cleaner=None。"""
|
||
deletes: list[str] = []
|
||
dispatch_yielded = asyncio.Event()
|
||
|
||
async def slow_create(*args, **kwargs):
|
||
await asyncio.sleep(0.02) # real HTTP always gives the loop a chance
|
||
dispatch_yielded.set()
|
||
return SimpleNamespace(dispatch_id="AD_delayed")
|
||
|
||
async def slow_delete(*args, **kwargs):
|
||
deletes.append(kwargs["room"])
|
||
|
||
monkeypatch.setattr(livekit_wire, "create_dispatch", slow_create)
|
||
monkeypatch.setattr(livekit_wire, "delete_room", slow_delete)
|
||
service = _service(StandinLiveKit(), session_ttl_seconds=0.025)
|
||
try:
|
||
session = await service.open_session(epoch=1)
|
||
assert dispatch_yielded.is_set(), "dispatch await must really yield here"
|
||
# the registration's deadline has a live owner again right after open
|
||
assert service._cleaner is not None and not service._cleaner.done()
|
||
await asyncio.sleep(0.12) # past TTL with NO further request at all
|
||
assert deletes == [session.room] # exactly one delete, no duplicates
|
||
assert session.session_id not in service._sessions
|
||
assert service.cleanup_debt(session.session_id) is None
|
||
# settled: the cleaner exits by itself, no dangling coroutine
|
||
for _ in range(100):
|
||
if service._cleaner is None or service._cleaner.done():
|
||
break
|
||
await asyncio.sleep(0.02)
|
||
assert service._cleaner is None or service._cleaner.done()
|
||
finally:
|
||
await service.aclose()
|
||
assert service._cleaner is None
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_second_registration_wakes_a_sleeping_cleaner_for_earlier_deadline(
|
||
monkeypatch):
|
||
"""注册后的 kick 也唤醒仍在睡眠的清理所有者:更短 TTL 的新会话不必等
|
||
旧会话的截止时间才被观察(min(deadlines) 立即重算)。"""
|
||
deletes: list[str] = []
|
||
|
||
async def create(*args, **kwargs):
|
||
await asyncio.sleep(0.02)
|
||
return SimpleNamespace(dispatch_id="AD_2")
|
||
|
||
async def delete(*args, **kwargs):
|
||
deletes.append(kwargs["room"])
|
||
|
||
monkeypatch.setattr(livekit_wire, "create_dispatch", create)
|
||
monkeypatch.setattr(livekit_wire, "delete_room", delete)
|
||
service = _service(StandinLiveKit(), session_ttl_seconds=5.0, backoff=0.005)
|
||
try:
|
||
first = await service.open_session(epoch=1) # long TTL keeps cleaner sleeping
|
||
service.config.session_ttl_seconds = 0.025
|
||
second = await service.open_session(epoch=1) # short TTL + real dispatch await
|
||
for _ in range(100):
|
||
if deletes:
|
||
break
|
||
await asyncio.sleep(0.02)
|
||
assert deletes == [second.room]
|
||
assert first.session_id in service._sessions # the long-TTL call is untouched
|
||
finally:
|
||
await service.aclose()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_end_after_abandoned_cap_sends_no_further_deletes():
|
||
"""总管复核 A-2 精确复现:上限 2,后台到顶后再 3 次 end 不得再发删除
|
||
(旧代码共发 5 次,_sessions 旁路上限);也不得回 404 假装已完成。"""
|
||
standin = StandinLiveKit()
|
||
standin.delete_errors = [503] * 50 # never succeeds
|
||
now = [100.0]
|
||
service = _service(standin, clock=lambda: now[0], backoff=0.005,
|
||
cleanup_max_attempts=2)
|
||
try:
|
||
session = await service.open_session(epoch=1)
|
||
with pytest.raises(livekit_wire.RoomDeleteError):
|
||
await service.end_session(session.session_id) # attempt 1
|
||
for _ in range(100):
|
||
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"
|
||
total_errors = len(standin.delete_errors) + 2 # errors consumed = deletes sent
|
||
calls_at_abandon = total_errors - len(standin.delete_errors)
|
||
assert calls_at_abandon == 2
|
||
for _ in range(3):
|
||
from cybergril.voice.session import CleanupAbandoned
|
||
with pytest.raises(CleanupAbandoned):
|
||
await service.end_session(session.session_id)
|
||
# 3 more end requests: ZERO additional remote deletes (old code: +3).
|
||
assert total_errors - len(standin.delete_errors) == calls_at_abandon
|
||
# The failure state stays accurate and visible, never a done-404.
|
||
debt = service.cleanup_debt(session.session_id)
|
||
assert debt.abandoned == "attempts-exhausted" and debt.attempts == 2
|
||
finally:
|
||
await service.aclose()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_restart_continues_the_same_attempt_cap(tmp_path):
|
||
"""重启续同一上限:已到 2/2 的持久债,新进程不再发删除,end 也拒绝。"""
|
||
from cybergril.voice.session import CleanupAbandoned
|
||
|
||
standin = StandinLiveKit()
|
||
state = tmp_path / "voice-sessions.json"
|
||
state.write_text(json.dumps({
|
||
"version": 1,
|
||
"sessions": [],
|
||
"debts": [{"session": {"session_id": "sid-restart", "room": "cg-voice-restart",
|
||
"identity": "user-x", "created_at": 100.0,
|
||
"expires_at": 1100.0, "epoch": 1, "dispatch_id": "AD_9"},
|
||
"attempts": 2, "first_debt_at": 100.0, "last_error": "RuntimeError: x",
|
||
"abandoned": "attempts-exhausted", "eligible_at": 0.0}],
|
||
}), encoding="utf-8")
|
||
service = _service(standin, clock=lambda: 1000.0, state_path=state,
|
||
cleanup_max_attempts=2)
|
||
try:
|
||
await service.recover()
|
||
await asyncio.sleep(0.1)
|
||
assert standin.deleted == [], "abandoned debt is never re-deleted"
|
||
with pytest.raises(CleanupAbandoned):
|
||
await service.end_session("sid-restart")
|
||
assert standin.deleted == []
|
||
finally:
|
||
await service.aclose()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_success_clears_both_sessions_and_debts():
|
||
standin = StandinLiveKit()
|
||
standin.delete_errors = [503] # first delete fails, retry lands
|
||
service = _service(standin)
|
||
try:
|
||
session = await service.open_session(epoch=1)
|
||
with pytest.raises(livekit_wire.RoomDeleteError):
|
||
await service.end_session(session.session_id)
|
||
assert service.cleanup_debt(session.session_id) is not None
|
||
assert session.session_id not in service._sessions # debt is the owner now
|
||
ended = await service.end_session(session.session_id)
|
||
assert ended.room == session.room
|
||
assert service.cleanup_debt(session.session_id) is None
|
||
assert session.session_id not in service._sessions
|
||
assert await service.end_session(session.session_id) is None # honest 404
|
||
finally:
|
||
await service.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
|
||
|
||
|
||
def test_router_abandoned_cleanup_is_503_with_state_never_404():
|
||
"""到顶后的 end:503 + 准确状态(attempts/原因),绝不是 404 假完成。"""
|
||
from fastapi.testclient import TestClient
|
||
|
||
standin = StandinLiveKit()
|
||
standin.delete_errors = [503] * 50
|
||
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)
|
||
return standin._handle(request)
|
||
|
||
service = _service(standin, backoff=3600.0, cleanup_max_attempts=2)
|
||
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)
|
||
with TestClient(app) as client:
|
||
client.post("/api/companion", json={
|
||
"name": "语音到顶", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"})
|
||
opened = client.post("/api/voice/session")
|
||
session_id = opened.json()["session_id"]
|
||
assert client.delete(f"/api/voice/session/{session_id}").status_code == 503
|
||
# background sweep to the cap (backoff 3600 keeps it at exactly one
|
||
# more attempt here), then explicit end must refuse without deleting
|
||
for _ in range(100):
|
||
debt = service.cleanup_debt(session_id)
|
||
if debt is not None and debt.abandoned:
|
||
break
|
||
import asyncio as _a
|
||
client.portal.call(_a.sleep, 0.02)
|
||
debt = service.cleanup_debt(session_id)
|
||
assert debt is not None and debt.abandoned == "attempts-exhausted"
|
||
refused = client.delete(f"/api/voice/session/{session_id}")
|
||
assert refused.status_code == 503
|
||
detail = refused.json()["detail"]
|
||
assert detail["cleanup"]["abandoned"] == "attempts-exhausted"
|
||
assert detail["cleanup"]["attempts"] == 2
|
||
assert detail["cleanup"]["room"] == opened.json()["room"]
|
||
# still owned, still unsettled — never collapses into 404
|
||
assert service.cleanup_debt(session_id) is not None
|
||
|
||
|
||
# ------------------------------------------------- CG-011 seam (HEL-879)
|
||
|
||
def test_assistant_interim_publisher_is_per_turn_and_fail_closed():
|
||
from cybergril.voice.seam import SubtitleBus
|
||
|
||
published: list[dict] = []
|
||
bus = SubtitleBus(published.append)
|
||
publisher = AssistantInterimPublisher(bus)
|
||
publisher.begin("speech_1")
|
||
assert publisher.feed("speech_1", "") is None
|
||
assert publisher.feed("speech_1", "她在") is not None
|
||
publisher.feed("speech_1", "打字中")
|
||
interim = published[-1]
|
||
assert interim == {"v": 2, "seq": 3, "kind": "assistant_interim",
|
||
"role": "assistant", "speech_id": "speech_1",
|
||
"text": "她在打字中"}
|
||
# A delta after the turn closed (late/stale) is dropped, not accumulated.
|
||
publisher.finish("speech_1", turn_id="turn-1", text="她在打字中。")
|
||
assert publisher.feed("speech_1", "迟到") is None
|
||
# Another turn NEVER inherits the previous turn's text.
|
||
publisher.begin("speech_2")
|
||
publisher.feed("speech_2", "新的一轮")
|
||
assert published[-1]["text"] == "新的一轮"
|
||
assert published[-1]["speech_id"] == "speech_2"
|
||
# Cancel closes fail-closed: no final for this turn.
|
||
cancel = publisher.cancel("speech_2", "interrupted")
|
||
assert cancel["kind"] == "turn_cancel" and cancel["speech_id"] == "speech_2"
|
||
assert publisher.cancel("speech_2", "interrupted") is None # already closed
|
||
# Late interim from the cancelled turn cannot re-open it.
|
||
assert publisher.feed("speech_2", "残影") is None
|
||
kinds = [p["kind"] for p in published]
|
||
assert kinds == ["turn_start", "assistant_interim", "assistant_interim",
|
||
"assistant_final", "turn_end", "turn_start",
|
||
"assistant_interim", "turn_cancel"]
|
||
|
||
|
||
def test_subtitle_bus_seq_is_monotonic_and_enveloped():
|
||
from cybergril.voice.seam import SubtitleBus
|
||
|
||
published: list[dict] = []
|
||
bus = SubtitleBus(published.append)
|
||
a = bus.emit("interim", role="user", text="你在说什么")
|
||
b = bus.emit("user_final", role="user", text="你在说什么呀")
|
||
c = bus.emit("proactive_start", role="assistant", text="主动留言",
|
||
speech_id="speech_p", message_id=9)
|
||
assert [a["seq"], b["seq"], c["seq"]] == [1, 2, 3]
|
||
assert all(p["v"] == 2 for p in (a, b, c))
|
||
assert c["message_id"] == 9 and c["speech_id"] == "speech_p"
|
||
assert "turn_id" not in c and "reason" not in c
|
||
d = bus.emit("proactive_cancel", role="assistant", speech_id="speech_p",
|
||
message_id=9, reason="interrupted")
|
||
assert d["reason"] == "interrupted"
|
||
|
||
|
||
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
|