Files
CyberGril/src/cybergril/voice/receipt.py
T
zonggongandmultica-agent 3228b1e0d7 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>
2026-10-27 05:10:52 +08:00

121 lines
5.1 KiB
Python

"""Playback-completion-gated receive confirmation for voice turns (HEL-877).
A sharing receipt may only be confirmed after the SDK reports the assistant
speech truly finished playing out. None of these count as delivered, so none of
them may ack: interrupted (barge-in), failed playback/generation, turns that
ended in chat.error (the φ line is spoken verbatim but is not her archived
reply), missing receipt, or a receipt from an epoch the server has since left
(the server fail-closes those anyway — this is the client-side half).
Speech-handle-to-stream binding lives in TurnLedger as an EXACT association
taken from the SDK's own generation context (HEL-879 remaining closure):
``CyberGrillLLM.chat`` reads the ``agents_speech_handle`` ContextVar the SDK
sets around every speech pipeline task, so each ChatApiLLMStream is bound to
the very handle whose generation created it. No ordering assumption ("a newer
speech means the older one never starts", "oldest pending gets the stream")
is used anywhere. When attribution is missing — the var is absent, the handle
was never noted as a user-initiated turn, or the generation belongs to an
agent-initiated/proactive speech — the stream binds to NOBODY and the turn
cannot ack: fail-closed, and one turn's stream can never be consumed by
another turn's handle.
"""
from __future__ import annotations
from typing import Any, Protocol
from .chat_api_client import ChatApiClient
def should_ack(
*,
played_to_end: bool,
interrupted: bool,
failed: bool,
receipt: dict[str, Any] | None,
current_epoch: int | None = None,
) -> bool:
"""Pure decision: only a fully played-out, unerrored, receipted turn acks."""
if not played_to_end or interrupted or failed:
return False
if not receipt:
return False
for key in ("message_id", "turn_id", "epoch", "token", "text_hash"):
if not receipt.get(key):
return False
return current_epoch is None or receipt.get("epoch") == current_epoch
class _HasHandle(Protocol):
@property
def created_at(self) -> float: # SpeechCreatedEvent.created_at
...
def add_done_callback(self, callback) -> None: ...
class TurnLedger:
"""Binds livekit SpeechHandles to the ChatApiLLMStream of THEIR generation.
The binding is exact, never inferred from event order: ``note_stream``
carries the speech handle read from the SDK's generation context, so a
stream is bound if and only if that exact handle was noted as a
user-initiated turn. Handles without a generation (interrupted/cancelled
before the LLM call, ``say`` speeches without an LLM stream) simply never
bind; streams without a noted handle (proactive/agent-initiated replies)
bind to nobody. Each stream is consumed exactly once, by exactly its own
handle.
"""
def __init__(self) -> None:
self._noted: dict[int, Any] = {} # id(handle) -> handle (user turns)
self._bound: dict[int, Any] = {} # id(handle) -> its own stream
self.unattributed: list[Any] = [] # diagnostics: streams nobody may claim
def note_handle(self, handle: _HasHandle, created_at: float | None = None) -> None:
"""A user-initiated speech started. Registration only — a later speech
NEVER retires this one: whether its generation starts is the SDK's
decision, not an ordering inference."""
self._noted[id(handle)] = handle
def note_stream(self, stream: Any, handle: Any = None,
created_at: float | None = None) -> bool:
"""Bind a generation's stream to EXACTLY the handle whose pipeline
task created it (from the SDK speech context). Returns False and
binds nobody when the attribution is missing or the handle was never
noted — that turn cannot ack (fail-closed)."""
if handle is not None and id(handle) in self._noted:
self._bound[id(handle)] = stream
return True
self.unattributed.append(stream)
return False
def stream_for(self, handle: _HasHandle) -> Any | None:
"""This handle's own stream, exactly once; None when its generation
never started or it was interrupted/discarded without one."""
return self._bound.pop(id(handle), None)
def discard(self, handle: _HasHandle) -> None:
"""Release a handle's registration and binding without using it
(fail-closed path for interrupted/failed playout): the turn never
acks, and nothing of it leaks into any later turn."""
self._bound.pop(id(handle), None)
self._noted.pop(id(handle), None)
class ReceiptSender:
"""Posts accepted receipts to /api/chat/received exactly once per turn."""
def __init__(self, client: ChatApiClient) -> None:
self._client = client
self._acked: set[str] = set()
self.results: dict[str, bool] = {}
async def confirm(self, turn_id: str, receipt: dict[str, Any]) -> bool:
if turn_id in self._acked:
return self.results.get(turn_id, False)
accepted = await self._client.acknowledge(receipt)
self._acked.add(turn_id)
self.results[turn_id] = accepted
return accepted