HEL-879 rework: fix the four manager-review edges - (1) dual-port launcher owns the app lifecycle exactly once: uvicorn listeners run with lifespan=off, either listener ending stops the other BEFORE the shared store closes, cancellation cleans up listeners first, and create_app's lifespan gains a fail-closed double-entry guard (the old shape silently re-initialized Store/epoch/life/chat_lock on the second entry); (2) room ownership survives delete failures: end_session keeps the session in a bounded persisted cleanup ledger until the remote delete lands (retry/idempotent, LiveKit 404 = already gone = settled), expiry moves rooms into that ledger instead of silently dropping them (the manager measured zero DELETE attempts on expired ends), graceful shutdown does not hang up live calls, restart compensates only this instance's own recorded rooms bounded by attempts/TTL+grace with abandonment recorded, and the router answers 503 (not 404) while a room is still owned so the browser keeps its owed DELETE; (3) TurnLedger binds each speech handle to its own generation stream explicitly (oldest pending handle gets the stream the SDK starts; a newer speech retires an older generation-less handle) - a handle without a generation can no longer steal the next turn's stream/receipt, the worker discards interrupted/failed bindings fail-closed before consuming; (4) release snapshot v3: verify requires three-way count equality (manifest source = manifest snapshot = restored actual; rows_match is an extra constraint, never an OR bypass), the rollback drill actually restores by source path into a persistent isolated tree and opens the restored DBs there, same-basename DBs get collision-free archive names, duplicate sources are refused; new regression file tests/test_voice_rework_hel879.py 14/14 reproducing every edge first, full pytest 338/338

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 04:10:23 +08:00
co-authored by multica-agent
parent 7f0a739213
commit 78a5cfd8d7
11 changed files with 1194 additions and 172 deletions
+268 -15
View File
@@ -5,14 +5,25 @@ silero VAD) exactly as HEL-876 audited it: this module only creates a room
dispatch for the dedicated ``cybergril-voice-agent`` worker and mints a
short-lived join token server-side, so no LiveKit key ever reaches the browser.
Everything here is process-local and stateless apart from the small session
registry: chat state, persona, memory and locks stay in the single API process
that mounts this router (HTTP and the HTTPS voice entry share it).
Everything here is process-local apart from the small session registry and its
persisted cleanup ledger (HEL-879): chat state, persona, memory and locks stay
in the single API process that mounts this router (HTTP and the HTTPS voice
entry share it).
Room ownership stays until the delete really lands (HEL-879 总管复核第 2 项):
a failed remote delete keeps the session in a bounded cleanup ledger — retried
on the next end call and by a bounded background sweep — and the ledger is
persisted beside the instance database so a restarted process compensates its
OWN rooms (never another instance's, never the generic worker). Retries are
idempotent (404 = already gone = settled). Every debt is bounded by attempts
and age, then recorded as abandoned instead of retried forever.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import secrets
import string
@@ -29,6 +40,10 @@ DEFAULT_AGENT_NAME = "cybergril-voice-agent"
DEFAULT_TOKEN_TTL = 300.0
DEFAULT_SESSION_TTL = 2 * 3600.0
TTS_HEALTH_CACHE_SECONDS = 30.0
CLEANUP_MAX_ATTEMPTS = 8
CLEANUP_BACKOFF_SECONDS = 0.5
CLEANUP_GRACE_SECONDS = 24 * 3600.0
STATE_VERSION = 1
@dataclass
@@ -103,6 +118,50 @@ class VoiceSession:
epoch: int
dispatch_id: str = ""
def as_state(self) -> dict:
return {
"session_id": self.session_id, "room": self.room, "identity": self.identity,
"created_at": self.created_at, "expires_at": self.expires_at,
"epoch": self.epoch, "dispatch_id": self.dispatch_id,
}
@classmethod
def from_state(cls, data: dict) -> "VoiceSession":
return cls(
session_id=str(data["session_id"]), room=str(data["room"]),
identity=str(data.get("identity", "")), created_at=float(data.get("created_at", 0)),
expires_at=float(data.get("expires_at", 0)), epoch=int(data.get("epoch", 0)),
dispatch_id=str(data.get("dispatch_id", "")),
)
@dataclass
class _CleanupDebt:
"""One room this instance still owns: its remote delete has not landed."""
session: VoiceSession
attempts: int = 0
first_debt_at: float = 0.0
last_error: str = ""
abandoned: str = ""
eligible_at: float = 0.0 # background retries wait until this clock time
def as_state(self) -> dict:
return {"session": self.session.as_state(), "attempts": self.attempts,
"first_debt_at": self.first_debt_at, "last_error": self.last_error,
"abandoned": self.abandoned, "eligible_at": self.eligible_at}
@classmethod
def from_state(cls, data: dict) -> "_CleanupDebt":
return cls(
session=VoiceSession.from_state(data.get("session", {})),
attempts=int(data.get("attempts", 0)),
first_debt_at=float(data.get("first_debt_at", 0)),
last_error=str(data.get("last_error", "")),
abandoned=str(data.get("abandoned", "")),
eligible_at=float(data.get("eligible_at", 0)),
)
@dataclass
class _Health:
@@ -116,11 +175,73 @@ class VoiceSessionService:
http: httpx.AsyncClient = field(default_factory=httpx.AsyncClient)
clock: object = time.time
tts_health_cache_seconds: float = TTS_HEALTH_CACHE_SECONDS
state_path: Path | str | None = None
cleanup_max_attempts: int = CLEANUP_MAX_ATTEMPTS
cleanup_backoff_seconds: float = CLEANUP_BACKOFF_SECONDS
cleanup_grace_seconds: float = CLEANUP_GRACE_SECONDS
def __post_init__(self) -> None:
self._sessions: dict[str, VoiceSession] = {}
self._debts: dict[str, _CleanupDebt] = {}
self._tts_health = _Health(checked=-1e9, ok=False)
self._tts_lock = asyncio.Lock()
self._cleaner: asyncio.Task | None = None
self._load_state()
# -- persisted cleanup ledger (own rooms only) ---------------------------
def _load_state(self) -> None:
"""Restart compensation: rooms recorded by a previous process of THIS
instance become cleanup debts (bounded by the persisted attempt counts
and age); they are the only rooms ever touched."""
if not self.state_path:
return
try:
data = json.loads(Path(self.state_path).read_text(encoding="utf-8"))
except (OSError, ValueError):
return
if data.get("version") != STATE_VERSION:
return
now = self.clock()
for entry in data.get("debts", []):
try:
debt = _CleanupDebt.from_state(entry)
except (KeyError, TypeError, ValueError):
continue
if debt.session.session_id not in self._debts:
self._debts[debt.session.session_id] = debt
for entry in data.get("sessions", []):
try:
session = VoiceSession.from_state(entry)
except (KeyError, TypeError, ValueError):
continue
# A room that was live when the process went down: the call may
# legitimately survive an API restart (the room lives on the SFU),
# so background compensation waits for the session's own TTL —
# bounded, never leaked, and never a longer-lived claim.
if session.session_id not in self._debts and session.session_id not in self._sessions:
self._debts[session.session_id] = _CleanupDebt(
session=session, first_debt_at=now,
eligible_at=max(now, session.expires_at))
self._prune()
def _persist_state(self) -> None:
if not self.state_path:
return
payload = {
"version": STATE_VERSION,
"sessions": [s.as_state() for s in self._sessions.values()],
"debts": [d.as_state() for d in self._debts.values()],
}
path = Path(self.state_path)
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(path)
except OSError:
# Best effort: losing the ledger never breaks a request, it only
# costs the restart compensation for still-owned rooms.
pass
# -- honest readiness ---------------------------------------------------
async def tts_available(self) -> bool:
@@ -141,12 +262,94 @@ class VoiceSessionService:
# -- lifecycle ----------------------------------------------------------
def _prune(self) -> None:
"""Expired registrations move into the cleanup ledger — never silently
dropped: their room stays owned until its bounded delete lands."""
now = self.clock()
for session_id in [k for k, v in self._sessions.items() if v.expires_at < now]:
del self._sessions[session_id]
expired = [k for k, v in self._sessions.items() if v.expires_at < now]
for session_id in expired:
session = self._sessions.pop(session_id)
if session_id not in self._debts:
self._debts[session_id] = _CleanupDebt(session=session, first_debt_at=now)
if expired:
self._persist_state()
def _abandon_reason(self, debt: _CleanupDebt) -> str:
if debt.abandoned:
return debt.abandoned
if debt.attempts >= self.cleanup_max_attempts:
return "attempts-exhausted"
if self.clock() - debt.session.expires_at > self.cleanup_grace_seconds:
return "aged-out"
return ""
def _retryable_debts(self) -> list[str]:
now = self.clock()
return [sid for sid, debt in self._debts.items()
if not self._abandon_reason(debt) and now >= debt.eligible_at]
async def _delete_room_once(self, session: VoiceSession) -> None:
"""One remote delete attempt; 2xx/404 settle, anything else raises."""
await livekit_wire.delete_room(
self.http,
internal_url=self.config.livekit_internal,
api_key=self.config.api_key,
api_secret=self.config.api_secret,
room=session.room,
timeout=self.config.dispatch_timeout_seconds,
)
async def _cleanup_loop(self) -> None:
try:
while True:
pending = self._retryable_debts()
if not pending:
waiting = [d for d in self._debts.values()
if not self._abandon_reason(d)]
if not waiting:
break
# Deferred debts (restart compensation waiting out a live
# session's TTL): re-check when the earliest becomes
# eligible, capped so the loop stays cheap and bounded.
now = self.clock()
delay = min(max(d.eligible_at - now for d in waiting), 60.0)
await asyncio.sleep(max(delay, 0.05) if delay > 0 else 0.05)
continue
for session_id in pending:
debt = self._debts.get(session_id)
if debt is None or self._abandon_reason(debt):
continue
try:
await self._delete_room_once(debt.session)
self._debts.pop(session_id, None)
except Exception as exc: # bounded retry, never a crash loop
debt.attempts += 1
debt.last_error = f"{type(exc).__name__}: {exc}"[:200]
reason = self._abandon_reason(debt)
if reason:
debt.abandoned = reason
self._persist_state()
if not debt.abandoned and session_id in self._debts:
await asyncio.sleep(self.cleanup_backoff_seconds)
finally:
self._cleaner = None
def _kick_cleanup(self) -> None:
if self._cleaner is not None and not self._cleaner.done():
return
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
self._cleaner = loop.create_task(self._cleanup_loop())
async def recover(self) -> None:
"""App-start hook: compensate rooms left over by a previous process of
this instance (bounded by the persisted ledger)."""
self._kick_cleanup()
async def open_session(self, *, epoch: int) -> VoiceSession:
self._prune()
self._kick_cleanup()
alphabet = string.ascii_lowercase + string.digits
room = "cg-voice-" + "".join(secrets.choice(alphabet) for _ in range(10))
identity = "user-" + "".join(secrets.choice(string.ascii_lowercase) for _ in range(8))
@@ -170,6 +373,7 @@ class VoiceSessionService:
dispatch_id=dispatch.dispatch_id,
)
self._sessions[session.session_id] = session
self._persist_state()
return session
def token_for(self, session: VoiceSession) -> str:
@@ -187,23 +391,72 @@ class VoiceSessionService:
)
async def end_session(self, session_id: str) -> VoiceSession | None:
"""End a session by actually deleting its room (HEL-879).
The registration is only removed AFTER the remote delete settles:
a failed delete keeps the session in the bounded cleanup ledger, so a
retry (this method again, the background sweep, or the next process
via the persisted ledger) still targets the same room — it can never
degrade into a 404 that silently drops the room. Unknown ids (never
seen here, or fully settled and forgotten) still return None → 404.
"""
self._prune()
session = self._sessions.pop(session_id, None)
session = self._sessions.get(session_id)
if session is None:
return None
await livekit_wire.delete_room(
self.http,
internal_url=self.config.livekit_internal,
api_key=self.config.api_key,
api_secret=self.config.api_secret,
room=session.room,
timeout=self.config.dispatch_timeout_seconds,
)
debt = self._debts.get(session_id)
if debt is None or debt.abandoned:
return None
session = debt.session
try:
await self._delete_room_once(session)
except Exception as exc:
debt = self._debts.get(session_id)
if debt is None:
debt = _CleanupDebt(session=session, first_debt_at=self.clock())
self._debts[session_id] = debt
debt.attempts += 1
debt.last_error = f"{type(exc).__name__}: {exc}"[:200]
reason = self._abandon_reason(debt)
if reason:
debt.abandoned = reason
self._persist_state()
self._kick_cleanup()
raise
self._sessions.pop(session_id, None)
self._debts.pop(session_id, None)
self._persist_state()
return session
def get(self, session_id: str) -> VoiceSession | None:
self._prune()
return self._sessions.get(session_id)
def cleanup_debt(self, session_id: str) -> _CleanupDebt | None:
"""Test/diagnostics view of the owned-but-not-deleted ledger."""
return self._debts.get(session_id)
async def aclose(self) -> None:
if self._cleaner is not None:
self._cleaner.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._cleaner
self._cleaner = None
# Graceful shutdown: rooms still active here become debts, then one
# final bounded sweep runs before the transport closes; whatever
# remains stays in the persisted ledger for the next process.
self._prune()
for session_id in self._retryable_debts():
debt = self._debts.get(session_id)
if debt is None or self._abandon_reason(debt):
continue
try:
await self._delete_room_once(debt.session)
self._debts.pop(session_id, None)
except Exception as exc:
debt.attempts += 1
debt.last_error = f"{type(exc).__name__}: {exc}"[:200]
reason = self._abandon_reason(debt)
if reason:
debt.abandoned = reason
self._persist_state()
await self.http.aclose()