HEL-879 remaining closure: auto-expiry cleanup ownership, exact SDK speech-turn attribution, and the versioned v2 subtitle contract for HEL-898

A. Room lifecycle (总管 review items A-1/A-2): the single cleanup owner now watches
   ACTIVE session deadlines as well as debts - a session nobody touches expires into
   the ledger and has its room really deleted with zero further requests (old code:
   _cleanup_loop only scanned debts, expired rooms were never deleted until some
   request ran _prune). Explicit end and the background sweep share ONE persisted
   attempt/age cap and abandoned state - _sessions no longer bypasses it (the
   manager measured 2 background attempts + 3 more interactive deletes = 5); an
   abandoned debt raises CleanupAbandoned -> 503 with room/attempts/reason instead
   of pretending done-404, success clears both _sessions and _debts, restart
   continues the same persisted cap, close/cancel leaves no dangling coroutine, and
   only this instance's own rooms are ever touched. New wake event makes a fresh
   debt retry immediately instead of waiting out a deadline sleep.

B. Queued speech turns bind EXACTLY (总管 interleaving note_handle(H1)->H2->
   note_stream(S1)->S2 gave H1=None, H2='turn-one'): CyberGrillLLM.chat now reads
   the SDK's own agents_speech_handle ContextVar (livekit-agents 1.8.8 sets it in
   _create_speech_task around every speech pipeline; source-verified on .12 and
   asserted at runtime) so each ChatApiLLMStream carries speech_handle/speech_id of
   the very handle whose generation created it. TurnLedger binds only on that exact
   attribution - a newer speech NEVER retires an older pending handle, say/proactive
   generations bind nobody, missing attribution fails closed (no ack, no subtitle
   turn), interrupt/failure discards only its own binding.

C. Versioned subtitle contract v2 for the visual author's wiring card (HEL-898):
   every cg.subtitle payload gains {v:2, seq} (session-monotonic), turn identity
   (speech_id, turn_id, same-source message_id for proactive rows) and explicit
   lifecycle events - turn_start/assistant_interim/assistant_final/turn_end/
   turn_cancel(reason) plus proactive_start/proactive_end/proactive_cancel that
   ride the say SpeechHandle instead of the receipt branch. Accumulators are
   isolated per speech_id (a late delta after cancel is dropped producer-side);
   seq + speech_id give the frontend two independent stale-rejection rules. Full
   executable contract: docs/voice-subtitle-contract-v2.md with recorded samples in
   docs/rework/hel879/subtitle-samples/ (scripts/gen_subtitle_samples_hel879.py).
   web/src untouched.

Verification: the .12 real-SDK check now LOADS THE ACTUAL WORKER MODULE and drives
the callbacks IT registered on a real AgentSession (no hand-copied functions) -
both-queued delayed generations bind exactly, a say sandwiched between user turns
steals nothing, unattributed generations fail closed, interrupted turns cancel
without final/receipt (11/11 ALL PASS, source-level proof of the ContextVar wiring
included; evidence docs/rework/hel879/sdk-check-hel879-remaining.log). The old r2
lifespan test flake is root-caused (clock freeze and block were two separate portal
calls; a 10ms life tick could slip between them and claim the frozen day unblocked)
and fixed atomically without raising timeouts or dropping assertions - 12/12 solo,
full suite 350/350 three times in a row on .venv311; ruff back to the single
pre-existing error; voice chain 8/8; release offline R1-R7 with zero failures;
requirement checks 4/4 (origin/main and c121c42, each with/without handoff).
Zero real LLM/embed/ASR/TTS calls, zero downloads/installs, nothing deployed or
merged, real caps stay 0.

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 05:10:52 +08:00
co-authored by multica-agent
parent b4dadd82b3
commit 3228b1e0d7
19 changed files with 1185 additions and 268 deletions
+20 -3
View File
@@ -632,10 +632,27 @@ def test_lifespan_cancels_owned_generation_and_joins_task(tmp_path):
c.post("/api/companion", json=CREATE)
runtime = app.state.life
clock = fixed_clock()
runtime.clock = lambda: clock[0]
async def block_next():
async def freeze_and_block_next():
# HEL-879 determinism fix: the clock freeze and the block must be
# ONE atomic step on this loop. They used to be two portal calls,
# and a 10ms life tick could slip between them — a frozen-clock
# tick then claimed the day UNBLOCKED, the run was marked done,
# and wait_started timed out forever (full-suite flake; single-run
# passed). Also wait for any in-flight real-day generation first:
# a tick that already claimed the real day may resume past this
# point, and its later provider calls must not trip the block.
loop = asyncio.get_running_loop()
deadline = loop.time() + 5
while app.state.store.query_one(
"SELECT 1 FROM life_run WHERE status='pending'"):
if loop.time() > deadline:
raise TimeoutError("real-day run never settled")
await asyncio.sleep(0.005)
runtime.clock = lambda: clock[0]
p.block, p.entered, p.release = True, asyncio.Event(), asyncio.Event()
c.portal.call(block_next)
c.portal.call(freeze_and_block_next)
async def wait_started():
await asyncio.wait_for(p.entered.wait(), 1)
c.portal.call(wait_started)
+7 -4
View File
@@ -267,12 +267,15 @@ def test_receipt_before_playout_not_possible_by_construction():
async def test_ledger_binds_handle_to_its_stream():
ledger = TurnLedger()
handle = type("H", (), {"created_at": 1.0})()
older = type("S", (), {"created_at": 0.5, "text": "old"})()
ledger.note_stream(older, 0.5)
stray = type("S", (), {"created_at": 0.5, "text": "old"})()
# A stream without exact attribution binds to nobody (fail-closed)...
assert ledger.note_stream(stray, None, 0.5) is False
assert ledger.unattributed == [stray]
ledger.note_handle(handle, 1.0)
stream = type("S", (), {"created_at": 1.2, "text": "new"})()
ledger.note_stream(stream, 1.2)
assert ledger.stream_for(handle) is stream, "first stream at/after the handle"
# ...and a noted handle claims ONLY the stream of its own generation.
assert ledger.note_stream(stream, handle, 1.2) is True
assert ledger.stream_for(handle) is stream, "exactly its own generation's stream"
assert ledger.stream_for(handle) is None, "binding consumed exactly once"
+282 -25
View File
@@ -53,52 +53,91 @@ 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():
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 = object(), object()
h1, h2 = _handle("speech_1"), _handle("speech_2")
s1, s2 = _stream("old"), _stream("new")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.1)
ledger.note_stream(s1, h1, 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).
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 = object(), object()
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) # retires the older, generation-less handle
ledger.note_stream(s2, 11.1)
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 = object(), object()
h1, h2 = _handle("speech_1"), _handle("speech_2")
s1, s2 = _stream("one"), _stream("two")
ledger.note_handle(h1, 1.0)
ledger.note_stream(s1, 1.0)
ledger.note_stream(s1, h1, 1.0)
ledger.note_handle(h2, 2.0)
ledger.note_stream(s2, 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_pending_handle_stays_unclaimed():
def test_ledger_stream_without_noted_handle_stays_unclaimed():
"""无确切归属即 fail-closed:未登记的 handle(主动/程序化生成)的流
不绑给任何用户轮,事后到达的 note_handle 也拿不到它。"""
ledger = TurnLedger()
stray = _stream("proactive")
ledger.note_stream(stray, 1.0) # no user turn awaited a generation
handle = object()
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")
ledger.note_stream(later, 2.5)
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
@@ -344,6 +383,140 @@ async def test_active_room_surives_restart_until_ttl_then_compensated(tmp_path):
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_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):
@@ -387,19 +560,103 @@ def test_router_delete_failure_is_503_and_keeps_room_owned():
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_accumulates_and_resets():
def test_assistant_interim_publisher_is_per_turn_and_fail_closed():
from cybergril.voice.seam import SubtitleBus
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"
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():