HEL-879 timing closure: the three contract-approval findings fixed as implementation-timing only (v2 envelope fields/event kinds untouched, web/src untouched, no re-audit of passed binding/backup/budget work) - (1) open_session re-kicks the cleanup owner AFTER registration+persist: a real dispatch await yields the loop and the pre-dispatch kick's cleaner already exited with nothing to watch (manager repro: 20ms real dispatch await, TTL 25ms, 120ms of silence -> DELETE=0, expired registration still present, cleaner=None; fixed: exactly one DELETE, registration settled, no dangling coroutine - the bounded auto-expiry/shared-cap mechanism itself is unchanged), new regressions reproduce first on the old code with a genuinely-yielding dispatch stand-in (asyncio.sleep, not the instantly-returning MockTransport) plus an earlier-deadline wake negative; (2) speak_proactive_row takes the handle the real sync AgentSession.say returns (iscoroutine only unwraps await-style stand-ins - the real SpeechHandle itself defines __await__, so awaiting it would wait out the whole playout), publishes proactive_start IMMEDIATELY, registers the handle's own end/cancel, then waits out that one row (sequential rows kept); .12 real-SDK probe: start visible while handle_done=false, end only after, cancel-only on interrupt, v2 fields identical; (3) _after_playout gates assistant_final on the completed+legal-same-turn-receipt conditions BEFORE anything is sent - incomplete streams, missing/partial receipts and stale epochs close with turn_cancel only (reason incomplete/no-receipt), never final-then-unack; the complete+receipt path keeps BOTH final and ack; phi/interrupt/failure/unattributed fail-closed unchanged; real-SDK check extended to 14/14 ALL PASS on .12 (proactive timing, proactive interrupt, no-receipt no-final negatives all driving the actual worker module's registered callbacks), before/after evidence in docs/rework/hel879/timing-fix/ and sdk-check-hel879-timing.log, reusable probe generator scripts/gen_hel879_timing_probe.py; regression at this head: pytest 352/352 x3 consecutive runs, ruff(src/tests/tools) clean, verify_hel877_voice_chain 8/8, requirements checks 4/4 (origin/main and c121c42, each with/without handoff-HEL-879.json, handoff appended with this round's scope); zero real LLM/embed/ASR/TTS, zero downloads, .12 touched read-only via SSH stdin only, not deployed, nothing merged, PR#11 and hel-870-assembly untouched, real caps stay 0

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 05:31:05 +08:00
co-authored by multica-agent
parent 3228b1e0d7
commit fc905fe6bd
12 changed files with 483 additions and 74 deletions
+98
View File
@@ -15,6 +15,15 @@ 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).
HEL-879 timing closure (contract-approval round): the real SDK's
AgentSession.say is a SYNC method returning an awaitable SpeechHandle (awaiting
it awaits the whole playout) — speak_proactive_row must publish
proactive_start DURING the playout with end/cancel on the handle's done
callback; and a clearly-attributed but incomplete/no-receipt stream must close
the subtitle turn with turn_cancel ONLY (contract v2: no complete same-turn
receipt means no assistant_final), while the complete+receipt path keeps
final AND the ack.
"""
from __future__ import annotations
@@ -372,6 +381,95 @@ asyncio.run(interim_seam())
ok.append("assistant_interim seam: real LLMStream deltas feed per-speech_id v2 "
"payloads (replace semantics); unattributed streams feed nothing")
# 11. HEL-879 timing closure: proactive_start DURING the playout on the real
# sync-say shape (a bare handle.__await__ would wait out the whole play).
async def proactive_timing_case():
events: list[dict] = []
h = SpeechHandle.create()
class SyncSay:
def say(self, *args, **kwargs): # real SDK shape: sync -> handle
asyncio.get_running_loop().call_later(.06, h._mark_done)
return h
task = asyncio.create_task(worker_mod.speak_proactive_row(
SyncSay(), seam_mod.SubtitleBus(events.append),
{"id": 7, "text": "offline sample"}))
await asyncio.sleep(.015)
assert h.done() is False
assert [e["kind"] for e in events] == ["proactive_start"], events
await task
await asyncio.sleep(.015)
assert [e["kind"] for e in events] == ["proactive_start", "proactive_end"]
start = events[0]
assert (start["v"], start["role"], start["message_id"], start["text"]) == \
(2, "assistant", 7, "offline sample")
assert start["speech_id"] == h.id
asyncio.run(proactive_timing_case())
ok.append("speak_proactive_row publishes proactive_start while the real "
"SpeechHandle is still playing (sync-say shape), end/cancel on the "
"handle's done callback")
# 11b. an interrupted proactive row closes with cancel, never end
async def proactive_interrupt_case():
events: list[dict] = []
h = SpeechHandle.create()
class SyncSay:
def say(self, *args, **kwargs):
return h
task = asyncio.create_task(worker_mod.speak_proactive_row(
SyncSay(), seam_mod.SubtitleBus(events.append),
{"id": 8, "text": "被打断的主动留言"}))
await asyncio.sleep(.005) # start emitted, done callback registered
h.interrupt()
h._mark_done()
await task
await asyncio.sleep(.02)
assert [e["kind"] for e in events] == ["proactive_start", "proactive_cancel"], events
assert events[-1]["reason"] == "interrupted"
asyncio.run(proactive_interrupt_case())
ok.append("interrupted proactive row emits proactive_cancel(reason=interrupted), "
"never proactive_end")
# 12. HEL-879 timing closure: a clearly-attributed but INCOMPLETE/no-receipt
# stream through the ACTUAL bind_voice_session callbacks must close the
# subtitle turn with turn_cancel ONLY — no assistant_final, no ack (v2).
async def no_receipt_incomplete_case():
events: list[dict] = []
session = AgentSession()
ledger = receipt_mod.TurnLedger()
bus = seam_mod.SubtitleBus(events.append)
interim = seam_mod.AssistantInterimPublisher(bus)
confirmed: list[str] = []
async def epoch():
return 1
class Receipts:
async def confirm(self, *args):
confirmed.append(args[0])
return True
llm = types.SimpleNamespace(client=types.SimpleNamespace(current_epoch=epoch))
worker_mod.bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=types.SimpleNamespace(),
receipts=Receipts())
h = SpeechHandle.create()
session.emit("speech_created", SpeechCreatedEvent(
user_initiated=True, source="generate_reply", speech_handle=h,
created_at=1.0))
stream = types.SimpleNamespace(
speech_id=h.id, error_phi=None, text="partial without receipt",
turn_id="incomplete", receipt=None, completed=False)
ledger.note_stream(stream, h)
interim.begin(h.id)
h._mark_done()
await asyncio.sleep(.06)
assert [e["kind"] for e in events] == ["turn_start", "turn_cancel"], events
assert events[-1]["reason"] == "incomplete"
assert confirmed == []
asyncio.run(no_receipt_incomplete_case())
ok.append("incomplete/no-receipt attributed stream: actual worker callbacks emit "
"turn_start -> turn_cancel only, no assistant_final, no ack")
print("HEL-877/879 real-SDK check on livekit-agents", end=" ")
import importlib.metadata as md
print(md.version("livekit-agents") + ":", "ALL PASS")
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Generate the HEL-879 timing-fix probe for the .12 agent venv (real SDK).
Reproduces the manager's two worker-side findings from the contract-approval
round (sdk-say / sdk-extra payloads), against WHATEVER sources are in the tree
when run — same script is used before AND after the fix:
1. speak_proactive_row on the REAL SDK shape: AgentSession.say is a SYNC
method returning an awaitable SpeechHandle (awaiting it awaits the whole
playout), so proactive_start must be published while the handle is still
playing (before done), with end/cancel on the handle's own done callback.
2. _after_playout through the ACTUAL bind_voice_session callbacks on a real
AgentSession: a clearly-attributed stream with text but completed=False
and receipt=None must NOT produce assistant_final — contract v2 says no
complete same-turn receipt means cancel, never final. The complete+receipt
path must still produce final AND the ack (checked in the same probe).
Embeds repo voice-module sources in a self-contained stdin script; no files
written on .12, no network, no service touched.
"""
from __future__ import annotations
import base64
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MODULES = ["chat_api_client", "receipt", "seam", "llm_chat_api",
"stt_funasr", "tts_cosyvoice", "worker"]
TEMPLATE = r'''
import asyncio, base64, json, sys, types
SOURCES = json.loads(base64.b64decode("__B64__"))
pkg = types.ModuleType("cybergril"); pkg.__path__ = []
voice = types.ModuleType("cybergril.voice"); voice.__path__ = []
sys.modules["cybergril"] = pkg
sys.modules["cybergril.voice"] = voice
for name, src in SOURCES.items():
mod = types.ModuleType(f"cybergril.voice.{name}")
mod.__package__ = "cybergril.voice"
sys.modules[f"cybergril.voice.{name}"] = mod
exec(compile(src, f"<cybergril.voice.{name}>", "exec"), mod.__dict__)
setattr(voice, name, mod)
from livekit.agents import AgentSession
from livekit.agents.voice.speech_handle import SpeechHandle
from livekit.agents.voice.events import SpeechCreatedEvent
w = voice.worker
out = {}
# --- 1. proactive say timing on the REAL SpeechHandle shape -------------------
async def proactive_case():
events = []
h = SpeechHandle.create()
class Say:
def say(self, *args, **kwargs): # real SDK: sync, returns SpeechHandle
asyncio.get_running_loop().call_later(.06, h._mark_done)
return h
task = asyncio.create_task(w.speak_proactive_row(
Say(), voice.seam.SubtitleBus(events.append), {"id": 7, "text": "offline sample"}))
await asyncio.sleep(.015)
out["proactive_before_playout_finishes"] = {
"handle_done": h.done(),
"events": [x["kind"] for x in events]}
await task
await asyncio.sleep(.015)
out["proactive_after_playout_finishes"] = [x["kind"] for x in events]
out["proactive_payload_fields"] = {k: events[0][k] for k in ("v", "kind", "role", "text", "speech_id", "message_id")}
asyncio.run(proactive_case())
# --- 2. actual-worker no-receipt/incomplete stream ---------------------------
async def no_receipt_case():
events = []
session = AgentSession()
ledger = voice.receipt.TurnLedger()
bus = voice.seam.SubtitleBus(events.append)
interim = voice.seam.AssistantInterimPublisher(bus)
async def epoch(): return 1
confirmed = []
class Receipts:
async def confirm(self, *args):
confirmed.append(args[0]); return True
llm = types.SimpleNamespace(client=types.SimpleNamespace(current_epoch=epoch))
w.bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=types.SimpleNamespace(), receipts=Receipts())
h = SpeechHandle.create()
session.emit("speech_created", SpeechCreatedEvent(
user_initiated=True, source="generate_reply", speech_handle=h, created_at=1.0))
stream = types.SimpleNamespace(
speech_id=h.id, error_phi=None, text="partial without receipt",
turn_id="incomplete", receipt=None, completed=False)
ledger.note_stream(stream, h)
interim.begin(h.id)
h._mark_done()
await asyncio.sleep(.06)
out["no_receipt_incomplete_actual_worker_events"] = [x["kind"] for x in events]
out["no_receipt_incomplete_confirmed"] = list(confirmed)
asyncio.run(no_receipt_case())
# --- 3. the complete+receipt path must keep final AND ack --------------------
async def complete_case():
events = []
session = AgentSession()
ledger = voice.receipt.TurnLedger()
bus = voice.seam.SubtitleBus(events.append)
interim = voice.seam.AssistantInterimPublisher(bus)
async def epoch(): return 1
confirmed = []
class Receipts:
async def confirm(self, *args):
confirmed.append(args[0]); return True
llm = types.SimpleNamespace(client=types.SimpleNamespace(current_epoch=epoch))
w.bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
bus=bus, stt=types.SimpleNamespace(), receipts=Receipts())
h = SpeechHandle.create()
session.emit("speech_created", SpeechCreatedEvent(
user_initiated=True, source="generate_reply", speech_handle=h, created_at=1.0))
receipt = {"message_id": 9, "turn_id": "ok-turn", "epoch": 1,
"token": "t" * 48, "text_hash": "z" * 64}
stream = types.SimpleNamespace(
speech_id=h.id, error_phi=None, text="her complete reply",
turn_id="ok-turn", receipt=receipt, completed=True)
ledger.note_stream(stream, h)
interim.begin(h.id)
h._mark_done()
await asyncio.sleep(.06)
out["complete_with_receipt_actual_worker_events"] = [x["kind"] for x in events]
out["complete_with_receipt_confirmed"] = list(confirmed)
asyncio.run(complete_case())
print(json.dumps(out, ensure_ascii=False))
'''
def main() -> int:
sources = {}
for name in MODULES:
path = ROOT / "src/cybergril/voice" / f"{name}.py"
sources[name] = path.read_text(encoding="utf-8")
payload = base64.b64encode(json.dumps(sources).encode()).decode()
script = TEMPLATE.replace("__B64__", payload)
out = ROOT / "scripts/_hel879_timing_probe_payload.py"
out.write_text(script, encoding="utf-8")
print(out)
return 0
if __name__ == "__main__":
sys.exit(main())