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
+174 -62
View File
@@ -5,10 +5,16 @@ Embeds the repo voice-module sources in a self-contained stdin script (no files
written to .12, no network, no service touched) and runs it with
/opt/voice-agent/agent/venv/bin/python (livekit-agents 1.8.8, livekit 1.1.20).
HEL-879 additions: the check drives the WORKER'S ACTUAL callback path with real
SpeechHandle/SpeechCreatedEvent objects — the handle-without-generation and
late-cleanup interleavings from the manager's independent review — and verifies
the assistant_interim delta seam through the real LLMStream machinery.
HEL-879 remaining closure: the check LOADS THE ACTUAL WORKER MODULE
(cybergril.voice.worker, wiring included — no hand-copied callbacks) and drives
the callbacks IT registered on a real AgentSession with real
SpeechHandle/SpeechCreatedEvent objects. Attribution is proven two ways:
(a) source-level — the installed SDK's _create_speech_task sets the private
agents_speech_handle ContextVar around every speech task and speech_created is
emitted before the task starts; (b) runtime — generations started inside that
ContextVar bind exactly, including the manager's both-queued-then-delayed
interleaving, a say speech sandwiched between user turns, an unattributed
generation (fail-closed) and an interrupted turn (cancel, no receipt).
"""
from __future__ import annotations
@@ -17,10 +23,11 @@ import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MODULES = ["chat_api_client", "receipt", "seam", "llm_chat_api"]
MODULES = ["chat_api_client", "receipt", "seam", "llm_chat_api",
"stt_funasr", "tts_cosyvoice", "worker"]
TEMPLATE = r'''
import asyncio, base64, json, sys, types
import asyncio, base64, inspect, json, sys, types
SOURCES = json.loads(base64.b64decode("__B64__"))
@@ -179,86 +186,191 @@ async def cancel_case():
asyncio.run(cancel_case())
ok.append("barge-in task cancel closes the in-flight HTTP stream immediately")
# 9. HEL-879: the worker's ACTUAL callback path on real SpeechHandle objects —
# the manager's two interleavings (handle without generation consuming the
# next turn's stream; late cleanup) plus interrupt/failure discard order,
# driven exactly like worker.entrypoint wires them.
# 9. HEL-879 remaining closure: THE ACTUAL WORKER MODULE's registered callbacks
# on a real AgentSession — exact attribution from the SDK generation context.
from livekit.agents import AgentSession
from livekit.agents.voice import agent_activity
from livekit.agents.voice.speech_handle import SpeechHandle
from livekit.agents.voice.events import SpeechCreatedEvent
# 9a. source-level proof on the INSTALLED SDK: every speech task runs inside
# the private agents_speech_handle ContextVar, and speech_created is
# emitted BEFORE the pipeline task is created (so note_handle always
# happens-before its generation's llm.chat).
create_src = inspect.getsource(agent_activity.AgentActivity._create_speech_task)
assert "_SpeechHandleContextVar.set(speech_handle)" in create_src, create_src
gen_src = inspect.getsource(agent_activity.AgentActivity._generate_reply)
assert gen_src.index("speech_created") < gen_src.index("_pipeline_reply_task"), gen_src
say_src = inspect.getsource(agent_activity.AgentActivity.say)
assert say_src.index("speech_created") < say_src.index("_create_speech_task"), say_src
llm_call_src = inspect.getsource(
__import__("livekit.agents.voice.agent", fromlist=["Agent"]).Agent.default.llm_node)
assert "self.llm.chat(" in llm_call_src or "activity_llm.chat(" in llm_call_src
ok.append("installed-SDK source verified: speech tasks set agents_speech_handle around "
"the pipeline; speech_created precedes the task; llm_node calls llm.chat inside it")
worker_mod = sys.modules["cybergril.voice.worker"]
receipt_mod = sys.modules["cybergril.voice.receipt"]
seam_mod = sys.modules["cybergril.voice.seam"]
def receipt_echo_handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/api/health":
return httpx.Response(200, json={"epoch": 1})
if request.url.path == "/api/chat/received":
return httpx.Response(200, json={"accepted": True})
body = json.loads(request.content)
turn_id = body["turn_id"]
payload = (
'data: {"t":"chat.delta","epoch":1,"turn_id":null,"delta":"这句是"}\n\n'
'data: {"t":"chat.final","epoch":1,"turn_id":null,"utterance":{"text":"这句是她的完整回复。"},'
'"receipt":{"message_id":42,"turn_id":"' + turn_id + '","epoch":1,'
'"token":"' + "t" * 48 + '","text_hash":"' + "z" * 64 + '"}}\n\n'
).encode()
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=payload)
confirmed: list[str] = []
subtitle_payloads: list[dict] = []
class RecordingReceipts:
async def confirm(self, turn_id, receipt):
confirmed.append(turn_id)
return True
async def worker_callback_path():
session = AgentSession() # real SDK session object
ledger = receipt_mod.TurnLedger()
done_futures = []
bus = seam_mod.SubtitleBus(subtitle_payloads.append)
interim = seam_mod.AssistantInterimPublisher(bus)
stt = types.SimpleNamespace(agent_speaking=False, agent_recent_text="")
client = llm_mod.ChatApiClient("http://x",
transport=httpx.MockTransport(receipt_echo_handler))
llm = worker_mod.make_voice_llm("http://x", ledger=ledger, interim=interim,
client=client)
# the ACTUAL worker wiring registers every callback on the real session
worker_mod.bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=stt, receipts=RecordingReceipts())
def on_speech_created(ev): # same guard + wiring as worker._on_speech_created
if not ev.user_initiated:
return
ledger.note_handle(ev.speech_handle, ev.created_at)
ev.speech_handle.add_done_callback(
lambda handle=ev.speech_handle: asyncio.get_running_loop().create_task(
after_playout(handle)
)
)
def speech(hid_source):
handle = SpeechHandle.create()
session.emit("speech_created", SpeechCreatedEvent(
user_initiated=True, source=hid_source, speech_handle=handle,
created_at=1.0))
return handle
async def after_playout(handle): # same order as worker._after_playout
await handle.wait_for_playout()
failed = handle.exception() is not None
if handle.interrupted or failed:
ledger.discard(handle)
done_futures.append(("discarded", handle))
return
stream = ledger.stream_for(handle)
done_futures.append((stream, handle))
async def generation_for(handle):
# EXACTLY what _create_speech_task does (source-verified in 9a): the
# pipeline task runs with the SDK's own ContextVar set to its handle.
tk = agent_activity._SpeechHandleContextVar.set(handle)
try:
stream = llm.chat(chat_ctx=ctx)
async for _ in stream:
pass
return stream
finally:
agent_activity._SpeechHandleContextVar.reset(tk)
# H1: real handle, its turn is interrupted BEFORE any LLM stream starts.
h1 = SpeechHandle.create()
ev1 = SpeechCreatedEvent(user_initiated=True, source="generate_reply",
speech_handle=h1, created_at=1.0)
on_speech_created(ev1)
# H2: the next turn does start a generation (real handle + noted stream).
h2 = SpeechHandle.create()
ev2 = SpeechCreatedEvent(user_initiated=True, source="generate_reply",
speech_handle=h2, created_at=2.0)
on_speech_created(ev2)
s2 = types.SimpleNamespace(turn_id="new", receipt={"message_id": 2})
ledger.note_stream(s2, 2.1)
# Complete both handles through the SDK's own done-future machinery:
# H1 was interrupted (public interrupt()) before any generation started;
# H2 played out cleanly (done, no error).
h1.interrupt()
# the manager's exact interleaving: BOTH speech events queued first, the
# generations only start afterwards (delayed, in queue order).
h1 = speech("generate_reply")
h2 = speech("generate_reply")
s1, s2 = await asyncio.gather(generation_for(h1), generation_for(h2))
h1._mark_done()
h2._mark_done()
await asyncio.sleep(0.05) # let the scheduled done callbacks run
outcomes = {id(handle): (stream, handle) for stream, handle in done_futures}
assert outcomes[id(h1)][0] == "discarded", "interrupted handle must discard fail-closed"
assert outcomes[id(h2)][0] is s2, "the real turn must get its OWN stream"
# The manager's exact inputs, re-checked through stream_for directly:
assert ledger.stream_for(h1) is None
await asyncio.sleep(0.1) # let the scheduled done callbacks (_after_playout) run
assert ledger.stream_for(h1) is None and ledger.stream_for(h2) is None # consumed
assert s1.speech_handle is h1 and s2.speech_handle is h2, "exact attribution"
# both completed turns acked exactly once, each with its own turn_id
assert sorted(confirmed) == sorted([s1.turn_id, s2.turn_id]), confirmed
# v2 subtitle lifecycle per speech_id, seq monotonic, interleaved correctly
kinds = [(p["kind"], p.get("speech_id")) for p in subtitle_payloads]
assert kinds[0] == ("turn_start", h1.id)
for sid in (h1.id, h2.id):
seq = [p["kind"] for p in subtitle_payloads if p.get("speech_id") == sid]
assert seq == ["turn_start", "assistant_interim", "assistant_final", "turn_end"], seq
seqs = [p["seq"] for p in subtitle_payloads]
assert seqs == sorted(seqs) and len(set(seqs)) == len(seqs)
# no payload without a speech_id ever opened a turn
assert all(p.get("speech_id") for p in subtitle_payloads
if p["kind"] in ("turn_start", "assistant_interim")), subtitle_payloads
# a say speech sandwiched between user turns never takes a user stream
before = len(confirmed)
h_user = speech("generate_reply")
h_say = speech("say") # proactive/programmatic say: user_initiated but no LLM stream
stream_user = await generation_for(h_user)
h_say._mark_done() # say finishes without any generation
h_user._mark_done()
await asyncio.sleep(0.1)
assert stream_user.speech_handle is h_user
assert confirmed.count(stream_user.turn_id) == 1 and len(confirmed) == before + 1
say_events = [p for p in subtitle_payloads if p.get("speech_id") == h_say.id]
assert say_events == [], "say without an LLM stream opens/closes no subtitle turn"
# an UNATTRIBUTED generation (no speech task context) binds nobody
h_late = speech("generate_reply")
async def unattributed():
assert agent_activity._SpeechHandleContextVar.get(None) is None
return llm.chat(chat_ctx=ctx) # proactive background generation shape
stray = await unattributed()
await generation_for(h_late)
assert stray.speech_handle is None and stray.speech_id == ""
assert ledger.stream_for(h_late).speech_handle is h_late
assert stray in ledger.unattributed
assert not [p for p in subtitle_payloads if p["kind"] == "turn_start"
and not p.get("speech_id")], "unattributed generation must not open a subtitle turn"
# interrupted turn: cancel event, no final, no receipt
before = len(confirmed)
h3 = speech("generate_reply")
await generation_for(h3)
h3.interrupt()
h3._mark_done()
await asyncio.sleep(0.1)
assert len(confirmed) == before
ev3 = [p["kind"] for p in subtitle_payloads if p.get("speech_id") == h3.id]
assert ev3 == ["turn_start", "assistant_interim", "turn_cancel"], ev3
asyncio.run(worker_callback_path())
ok.append("worker callback path on real SpeechHandle/SpeechCreatedEvent: no-generation "
"handle discards, next turn keeps its own stream (explicit binding)")
ok.append("ACTUAL worker module loaded; its registered callbacks driven on a real "
"AgentSession: both-queued delayed generations bind exactly (manager "
"interleaving), say never steals a stream, unattributed fails closed, "
"interrupt cancels without final/receipt")
# 10. HEL-879: assistant_interim seam through the REAL LLMStream machinery.
# 10. HEL-879: assistant_interim seam through the REAL LLMStream machinery,
# per-speech_id accumulators (stream-passing delta callback).
interim_payloads = []
async def interim_seam():
publisher = seam_mod.AssistantInterimPublisher(interim_payloads.append)
from livekit.agents.voice import agent_activity
bus = seam_mod.SubtitleBus(interim_payloads.append)
publisher = seam_mod.AssistantInterimPublisher(bus)
adapter = llm_mod.CyberGrillLLM("http://x", client=llm_mod.ChatApiClient(
"http://x", transport=httpx.MockTransport(handler)),
on_assistant_delta=publisher.feed)
publisher.reset()
on_assistant_delta=lambda stream, delta: publisher.feed(stream.speech_id, delta))
publisher.begin("speech_seam")
# attribute the stream exactly like the SDK would (a speech task setting
# its own handle): the deltas then feed THIS turn's accumulator
fake_handle = types.SimpleNamespace(id="speech_seam")
tk = agent_activity._SpeechHandleContextVar.set(fake_handle)
stream = adapter.chat(chat_ctx=ctx)
async for _ in stream:
pass
assert [p["text"] for p in interim_payloads] == ["真实链路上", "真实链路上的一句完整回复。"]
assert all(p["kind"] == "assistant_interim" and p["role"] == "assistant"
for p in interim_payloads)
agent_activity._SpeechHandleContextVar.reset(tk)
assert stream.speech_handle is fake_handle and stream.speech_id == "speech_seam"
interims = [p for p in interim_payloads if p["kind"] == "assistant_interim"]
assert [p["text"] for p in interims] == ["真实链路上", "真实链路上的一句完整回复。"]
assert all(p["role"] == "assistant" and p["v"] == 2 and p["speech_id"] == "speech_seam"
for p in interims)
assert interim_payloads[0]["kind"] == "turn_start" # begin opened the turn
# a stream without attribution feeds no open turn (fail-closed, no leak)
stray = adapter.chat(chat_ctx=ctx) # no ctxvar set here
async for _ in stray:
pass
assert stray.speech_handle is None and stray.speech_id == ""
assert len(interim_payloads) == 3, interim_payloads # turn_start + 2 interims only
asyncio.run(interim_seam())
ok.append("assistant_interim seam: SSE deltas through real LLMStream feed her "
"incremental subtitle payloads (replace semantics, reset works)")
ok.append("assistant_interim seam: real LLMStream deltas feed per-speech_id v2 "
"payloads (replace semantics); unattributed streams feed nothing")
print("HEL-877/879 real-SDK check on livekit-agents", end=" ")
import importlib.metadata as md
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Generate the v2 subtitle contract sample recordings (HEL-879).
Drives the REAL seam implementation (seam.SubtitleBus / AssistantInterimPublisher
/ speak_proactive_row's event shape) offline — zero livekit imports, zero model
calls — and writes the JSONL sequences the visual author wires against:
docs/rework/hel879/subtitle-samples/normal-turn.jsonl
docs/rework/hel879/subtitle-samples/interrupt.jsonl
docs/rework/hel879/subtitle-samples/proactive.jsonl
Each line is exactly one cg.subtitle payload as it would be published on the
room topic (see docs/voice-subtitle-contract-v2.md).
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from cybergril.voice.seam import ( # noqa: E402
AssistantInterimPublisher,
SubtitleBus,
)
OUT = ROOT / "docs/rework/hel879/subtitle-samples"
def record(name: str, payloads: list[dict]) -> Path:
OUT.mkdir(parents=True, exist_ok=True)
path = OUT / name
path.write_text(
"".join(json.dumps(p, ensure_ascii=False) + "\n" for p in payloads),
encoding="utf-8")
return path
def normal_turn() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
interim = AssistantInterimPublisher(bus)
bus.emit("interim", role="user", text="你在听的")
bus.emit("user_final", role="user", text="你在听吗?")
interim.begin("speech_normal")
interim.feed("speech_normal", "在听呢,")
interim.feed("speech_normal", "在听呢,你刚才说到一半的那件事我还在想。")
interim.finish("speech_normal", turn_id="0e2f-demo-turn",
text="在听呢,你刚才说到一半的那件事我还在想。",
message_id=None)
return payloads
def interrupt_turn() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
interim = AssistantInterimPublisher(bus)
interim.begin("speech_cut")
interim.feed("speech_cut", "我正想跟你说,今天下午")
# barge-in: the turn dies without a final; the next user turn starts clean
interim.cancel("speech_cut", "interrupted")
bus.emit("interim", role="user", text="等一下")
bus.emit("user_final", role="user", text="等一下,先听我说。")
interim.begin("speech_next")
interim.feed("speech_next", "好,你先说。")
interim.finish("speech_next", turn_id="0e2f-demo-next", text="好,你先说。")
return payloads
def proactive() -> list[dict]:
payloads: list[dict] = []
bus = SubtitleBus(payloads.append)
# spoken to the end (same-source message_id 17)
bus.emit("proactive_start", role="assistant", speech_id="speech_pro1",
text="我看到一句很适合现在的话,先念给你听。", message_id=17)
bus.emit("proactive_end", role="assistant", speech_id="speech_pro1",
message_id=17)
# interrupted variant (message_id 18)
bus.emit("proactive_start", role="assistant", speech_id="speech_pro2",
text="还有一件事想告诉你——", message_id=18)
bus.emit("proactive_cancel", role="assistant", speech_id="speech_pro2",
message_id=18, reason="interrupted")
return payloads
def main() -> int:
for name, fn in (("normal-turn.jsonl", normal_turn),
("interrupt.jsonl", interrupt_turn),
("proactive.jsonl", proactive)):
path = record(name, fn())
seqs = [json.loads(line)["seq"] for line in
path.read_text(encoding="utf-8").splitlines()]
assert seqs == sorted(seqs) and len(set(seqs)) == len(seqs), (name, seqs)
print(f"{path} ({len(seqs)} payloads, seq 1..{seqs[-1]})")
return 0
if __name__ == "__main__":
sys.exit(main())