HEL-911: fix AgentHandoff/shutdown seams, attribute & fix the 3.66s pre-generation wait

- worker _on_item: filter conversation_item_added by the real 1.8.8 item
  discriminator (ChatMessage | AgentHandoff | _TypeDiscriminator); only
  assistant str-part body feeds the echo filter (HEL-910 AttributeError)
- bind_interrupt_channel unload: async (JobContext shutdown callbacks are
  awaited), idempotent, disconnect-safe; interrupt/receipt/budget paths
  untouched (HEL-910 TypeError await None)
- TURN_HANDLING: explicit turn_detection=None — 1.8.8 silently installs an
  English EOU TurnDetector whose unlikely verdicts on Chinese finals push
  endpointing to max_delay=6.0 (measured 3.667/3.654s HEL-910 call2; offline
  A/B on the real SDK: baseline 3.704s vs fixed 0.004s). Endpointing
  0.8/6.0 kept verbatim; no VAD/buffer_turn/semantic change
- scripts/gen_hel911_wait_repro.py: offline reproduction harness (real
  AgentSession + real silero VAD + HEL-910 wav and measured timings)
- tests: +3 real-SDK checks (11/11 on .12 agent venv; prior 8 regressions
  kept, unload call sites await the new protocol)
- hel910_call1.mjs reliability: segmented probe/recorder dumps to disk,
  timing-A trigger requires the server-committed voice turn row (not a
  we-sent-it proxy); node --check only, no real run
- window-record.md §9: appended factual corrections (companion 9 not 18,
  turn_start +6.099 not +4.10, assistant_final is the playout/receipt gate,
  post-window ListRooms token failure is not empty-room evidence); original
  record untouched
- docs/rework/hel911/summary.md + handoff-HEL-911.json; requirement checks
  pass vs origin/main and 407fc81

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
施工员2号
2026-10-29 21:25:25 +08:00
co-authored by multica-agent
parent 407fc8158c
commit 4a38106eef
7 changed files with 868 additions and 24 deletions
+155 -3
View File
@@ -291,7 +291,7 @@ async def test_interrupt_message_stops_pending_playout_after_final():
fresh.interrupt(force=True)
_quiet_await(fresh)
_quiet_await(handle)
unload()
await unload()
async def test_interrupt_channel_validation_and_unload():
@@ -323,7 +323,7 @@ async def test_interrupt_channel_validation_and_unload():
await asyncio.sleep(0.05)
assert bridge.calls == [True] and handle.interrupted
unload()
await unload()
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
assert bridge.calls == [True], "the unload callback removed the listener"
@@ -348,7 +348,153 @@ async def test_interrupt_message_survives_session_not_running():
await asyncio.sleep(0.05) # logged, swallowed at the boundary, listener intact
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
unload()
await unload()
# ── HEL-911: conversation_item_added item types + async shutdown seam ────────
def _echo_stt_state() -> "SimpleNamespace":
from types import SimpleNamespace
return SimpleNamespace(agent_recent_text="", agent_speaking=False)
async def test_conversation_item_added_filters_non_message_items():
"""The session-start AgentHandoff (real 1.8.8 ConversationItemAddedEvent
payload: ChatMessage | AgentHandoff | _TypeDiscriminator, events.py:419)
crashed the old handler with AttributeError (HEL-910 worker.log, both
calls). Non-message items and user messages must not touch the echo
filter state."""
from livekit.agents.llm.chat_context import AgentHandoff, ChatMessage
from livekit.agents.voice import AgentSession
from livekit.agents.voice.events import ConversationItemAddedEvent, _TypeDiscriminator
from cybergril.voice.worker import bind_voice_session
class _Noop:
def __getattr__(self, name): # any other seam touch fails the test
raise AssertionError(f"unexpected seam use: {name}")
session = AgentSession()
stt = _echo_stt_state()
bind_voice_session(session, llm=_Noop(), ledger=_Noop(), interim=_Noop(),
bus=_Noop(), stt=stt, receipts=_Noop())
# 1. real SDK AgentHandoff (the session-start item that crashed 1.8.8)
session.emit("conversation_item_added",
ConversationItemAddedEvent(item=AgentHandoff(new_agent_id="agent_1")))
assert stt.agent_recent_text == ""
# 2. the SDK's own unknown-item discriminator shape
session.emit("conversation_item_added",
ConversationItemAddedEvent(item=_TypeDiscriminator()))
assert stt.agent_recent_text == ""
# 3. a real user ChatMessage must not feed the assistant echo filter
session.emit("conversation_item_added", ConversationItemAddedEvent(
item=ChatMessage(role="user", content=["用户说的话"])))
assert stt.agent_recent_text == ""
# 4. real assistant ChatMessage with mixed content parts: only the str
# parts are body text (ChatContent = str | ImageContent | AudioContent |
# CacheBreakpoint, chat_context.py:459)
from livekit.agents.llm.chat_context import CacheBreakpoint
session.emit("conversation_item_added", ConversationItemAddedEvent(
item=ChatMessage(role="assistant", content=["好,小十。", CacheBreakpoint()])))
assert stt.agent_recent_text == "好,小十。"
async def test_shutdown_callback_protocol_real_jobcontext_wrapper():
"""The unload seam must satisfy the REAL JobContext.add_shutdown_callback
contract: the SDK wraps a no-arg callback into `await callback()`
(job.py:633-643) and the job runner awaits every callback
(ipc/job_proc_lazy_main.py:493). The old sync `def unload() -> None`
raised TypeError: object NoneType can't be used in 'await' expression
(HEL-910 worker.log). Here the REAL JobContext method does the wrapping
and the runner's exact await pattern drives it — only the job plumbing
around it is absent, so a broken seam reproduces the production error.
"""
import inspect
from livekit import rtc
from livekit.agents import JobContext
from livekit.agents.voice import SpeechHandle
from cybergril.voice.worker import bind_interrupt_channel
handle = SpeechHandle.create(allow_interruptions=True)
class _Bridge:
def interrupt(self, *, force: bool = False):
return handle.interrupt(force=force)
room = rtc.Room()
unload = bind_interrupt_channel(room, _Bridge())
assert inspect.iscoroutinefunction(unload), \
"add_shutdown_callback awaits its callbacks; unload must be async"
# register through the REAL SDK method (it appends the wrapper it will await)
ctx = object.__new__(JobContext) # real method, minimal instance: no job plumbing
ctx._shutdown_callbacks = []
ctx.add_shutdown_callback(unload)
wrapped = ctx._shutdown_callbacks[-1]
# exactly what ipc/job_proc_lazy_main._traced_shutdown_callback does
await wrapped("job shutdown") # must not raise (the old sync seam did)
# the old seam reproduces the production TypeError through the same wrapper
def sync_unload() -> None:
return None
ctx.add_shutdown_callback(sync_unload)
broken = ctx._shutdown_callbacks[-1]
try:
await broken("job shutdown")
raise AssertionError("sync unload should have failed the real await")
except TypeError as exc:
assert "await" in str(exc)
# duplicate shutdown: the runner may only fire callbacks once per job, but
# idempotency must not depend on that
await unload()
await unload()
# subscription really unloaded: a valid interrupt message after unload is a no-op
room.emit("data_received", _data_packet("cg.interrupt", b'{"v":1}'))
await asyncio.sleep(0.05)
assert not handle.interrupted, "listener must be gone after unload"
_quiet_await(handle)
async def test_turn_handling_disables_default_english_eou_detector():
"""HEL-911: livekit-agents 1.8.8 silently installs an English EOU
TurnDetector when turn_handling has no explicit turn_detection key
(agent_session.py:576-579, `turn_handling.get("turn_detection",
inference.TurnDetector())`). Its unlikely-eot verdicts on CHINESE
transcripts push the endpointing delay to max_delay and cost the measured
~3.66s between ASR final and turn_start (HEL-910 call2: 3.667s/3.654s;
offline A/B in scripts/gen_hel911_wait_repro.py: default 3.704s vs
explicit None 0.004s). The worker's TURN_HANDLING must keep the detector
off so the configured VAD endpointing alone decides the turn boundary."""
from livekit.agents import AgentSession
from cybergril.voice.worker import TURN_HANDLING
# the SDK default that bites: same options minus the explicit key
with_default = {k: v for k, v in TURN_HANDLING.items() if k != "turn_detection"}
default_session = AgentSession(turn_handling=with_default)
assert default_session._turn_detection is not None, (
"precondition: 1.8.8 installs a default turn detector — if this fails "
"the SDK changed; re-check the HEL-911 wait attribution"
)
session = AgentSession(turn_handling=TURN_HANDLING)
assert session._turn_detection is None, \
"the worker must not run the English EOU detector on Chinese turns"
assert TURN_HANDLING["endpointing"] == {"min_delay": 0.8, "max_delay": 6.0}, \
"the measured endpointing parameters stay exactly as configured"
# ── standalone runner (agent venv has no pytest) ─────────────────────────────
@@ -371,6 +517,12 @@ async def _standalone() -> int:
test_interrupt_channel_validation_and_unload),
("interrupt_message_survives_session_not_running",
test_interrupt_message_survives_session_not_running),
("conversation_item_added_filters_non_message_items",
test_conversation_item_added_filters_non_message_items),
("shutdown_callback_protocol_real_jobcontext_wrapper",
test_shutdown_callback_protocol_real_jobcontext_wrapper),
("turn_handling_disables_default_english_eou_detector",
test_turn_handling_disables_default_english_eou_detector),
]
failures = 0
for name, check in checks: