Files
CyberGril/src/cybergril/voice/session.py
T
施工员2号andmultica-agent 07dda2bfa2 HEL-904: backend rework — recoverable register-failure mapping, worker-state corruption docstring, call-window voice pin closes capture/worker race
- register(): local metadata write failure -> LocalRecordFailed -> 503 Chinese
  message with the cg- id (shared registration NOT rolled back, refresh list to
  recover, never re-register); register_asr journaled BEFORE local persist so
  failed registrations still count in the resource ledger
- write_worker_voice(): docstring now states the whole-file rewrite on
  unreadable/corrupt state (other keys preserved only when parseable)
- capture->worker race closed with a session-immutable-snapshot equivalent:
  _capture_voice holds the captured voice (no await gap); apply_selection
  defers its worker-state write while any call is live; open_session releases
  the hold on failure/cancel; VoiceSessionService.on_session_settled releases
  on explicit end, end-into-debt and TTL expiry; response voice == the voice
  the worker actually reads for that call, mid-call changes affect the next
  call only; overlapping-call residual documented honestly
- tests: hel902 fault-injection case 1 rewritten for the new contract
  (recovery + restart + 409 gate kept), 4 new deterministic Event-gated race
  tests (worker read delayed past dispatch, concurrent apply, failure/cancel
  cleanup, next-call voice), zero sleep-based assertions
- docs: contract §2.2/§2.5/§3 updated; r5 followup package tightened (head
  milestones d167ba9/b09a907/pending-review, register ASR vs call ASR split,
  call-ASR counting means + honest pending blocker, single-timebase frame
  silence measurement, D1 female_soft reference audio pinned by sha256,
  recycling checklist, shared-TTS snapshot/restore, git-revert is not
  recycling, caps count failures/retries/outbound-no-response)
- evidence: pytest 380/380 (376 baseline + 4), verify chain 12/12, ruff clean,
  requirement checks 4/4 (origin/main and b09a907, with/without handoff)

Co-authored-by: multica-agent <github@multica.ai>
2026-10-28 01:09:19 +08:00

572 lines
25 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Voice session lifecycle for the unified API (HEL-877, approved R5 backend).
The endpoint reuses the .12 voice base (LiveKit SFU + FunASR + CosyVoice TTS +
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 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.
HEL-879 remaining closure: the cleanup owner also watches the ACTIVE session
deadlines — a session that nobody touches expires into the ledger and has its
room deleted without any further request — and explicit end shares the very
same persisted attempt cap and abandoned state with the background sweep (no
_sessions bypass). A debt that crossed its cap raises CleanupAbandoned instead
of answering a done-404: the room is still owned-but-unsettled and the caller
must keep treating the hang-up as not finished.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import os
import secrets
import string
import time
from dataclasses import dataclass, field
from pathlib import Path
import httpx
import yaml
from . import livekit_wire
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
class VoiceConfig:
livekit_url: str
livekit_internal: str
api_key: str
api_secret: str
agent_name: str = DEFAULT_AGENT_NAME
tts_health_url: str = "http://127.0.0.1:9880/health"
token_ttl_seconds: float = DEFAULT_TOKEN_TTL
session_ttl_seconds: float = DEFAULT_SESSION_TTL
dispatch_timeout_seconds: float = 5.0
# HEL-899 自定义音色(复用 .12 语音面板与 CosyVoice;缺省即本机默认值)
panel_url: str = "https://127.0.0.1:8090"
tts_url: str = "http://127.0.0.1:9880"
registry_file: str | None = None # 共享 voices.json 只读回看(ASR 参考文本补全)
worker_state_file: str = "/opt/voice-agent-cybergril/voice_state_cybergril.json"
def sanitized(self) -> dict:
return {
"livekit_url": self.livekit_url,
"agent_name": self.agent_name,
"tts_health_url": self.tts_health_url,
"token_ttl_seconds": self.token_ttl_seconds,
"session_ttl_seconds": self.session_ttl_seconds,
}
class VoiceNotConfigured(Exception):
"""Raised when no config file exists; the endpoint refuses honestly."""
class CleanupAbandoned(Exception):
"""The room is still owned but its bounded cleanup crossed the cap.
Raised by ``end_session`` when the persisted debt for the room is already
abandoned (attempts/age exhausted): no further remote delete is issued —
neither by the caller nor by the background sweep — and the state must be
reported as unsettled, never as a done-404. The debt (attempts, last
error, reason) stays persisted for the operator.
"""
def __init__(self, debt: _CleanupDebt) -> None:
self.debt = debt
super().__init__(
f"cleanup abandoned ({debt.abandoned}) after {debt.attempts} attempts: "
f"room {debt.session.room} is still owned and unsettled"
)
def load_voice_config(
path: Path | str | None = None,
) -> VoiceConfig | None:
"""Load config/voice.yaml; env overrides keep deployment keys out of the repo.
Returns None (not an exception) when nothing is configured: "voice not set
up on this instance" is an honest state, not an error.
"""
path = Path(path or os.environ.get("CYBERGRIL_VOICE_CONFIG", "config/voice.yaml"))
if not path.is_file():
return None
data = yaml.safe_load(path.read_text()) or {}
overrides = {
"livekit_url": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_URL"),
"livekit_internal": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_INTERNAL"),
"api_key": os.environ.get("CYBERGRIL_VOICE_API_KEY"),
"api_secret": os.environ.get("CYBERGRIL_VOICE_API_SECRET"),
"tts_health_url": os.environ.get("CYBERGRIL_VOICE_TTS_HEALTH_URL"),
"panel_url": os.environ.get("CYBERGRIL_VOICE_PANEL_URL"),
"tts_url": os.environ.get("CYBERGRIL_VOICE_TTS_URL"),
"registry_file": os.environ.get("CYBERGRIL_VOICE_REGISTRY_FILE"),
"worker_state_file": os.environ.get("CYBERGRIL_VOICE_WORKER_STATE"),
}
values = {**data, **{k: v for k, v in overrides.items() if v}}
required = ("livekit_url", "livekit_internal", "api_key", "api_secret")
missing = [k for k in required if not values.get(k)]
if missing:
raise VoiceNotConfigured(f"voice config missing fields: {', '.join(missing)}")
return VoiceConfig(
livekit_url=str(values["livekit_url"]),
livekit_internal=str(values["livekit_internal"]),
api_key=str(values["api_key"]),
api_secret=str(values["api_secret"]),
agent_name=str(values.get("agent_name") or DEFAULT_AGENT_NAME),
tts_health_url=str(values.get("tts_health_url") or "http://127.0.0.1:9880/health"),
token_ttl_seconds=float(values.get("token_ttl_seconds") or DEFAULT_TOKEN_TTL),
session_ttl_seconds=float(values.get("session_ttl_seconds") or DEFAULT_SESSION_TTL),
panel_url=str(values.get("panel_url") or "https://127.0.0.1:8090"),
tts_url=str(values.get("tts_url") or "http://127.0.0.1:9880"),
registry_file=(str(values["registry_file"]) if values.get("registry_file") else None),
worker_state_file=str(values.get("worker_state_file")
or "/opt/voice-agent-cybergril/voice_state_cybergril.json"),
)
@dataclass
class VoiceSession:
session_id: str
room: str
identity: str
created_at: float
expires_at: float
epoch: int
dispatch_id: str = ""
voice: str = "" # HEL-899: 本次通话捕获的有效音色(开启时定住,通话中改选不影响本通话)
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, "voice": self.voice,
}
@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", "")),
voice=str(data.get("voice", "")),
)
@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:
checked: float = 0.0
ok: bool = False
voices: list[str] | None = None # HEL-899: /health 顺带的热加载音色表(无则 None)
@dataclass
class VoiceSessionService:
config: VoiceConfig
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
# HEL-904: 可选回调 ``Callable[[VoiceSession], None]``。一个会话离开
# 活跃表(显式挂断、TTL 到期、或转入清理欠账)即「结算」:该通话
# worker 的入口读窗口关闭。router 用它释放自定义音色的通话持有
# (capture 与 worker 实读之间的竞态收口)。回调异常不结算失败拖垮
# 会话流程(持有多留一会儿只会让应用晚一拍写透,安全方向)。
on_session_settled: object = None
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._wake = asyncio.Event()
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:
"""Probe the CosyVoice TTS health endpoint, cached like /api/health's LLM probe."""
now = self.clock()
if now - self._tts_health.checked < self.tts_health_cache_seconds:
return self._tts_health.ok
async with self._tts_lock:
if self.clock() - self._tts_health.checked < self.tts_health_cache_seconds:
return self._tts_health.ok
try:
response = await self.http.get(self.config.tts_health_url, timeout=3.0)
ok = response.status_code // 100 == 2
voices: list[str] | None = None
if ok:
# CosyVoice /health = {"ok", "voices": [...]}(同请求内已热加载);
# 空体/异常体只当"探到了但没带名单",不推翻 ok 判定。
try:
listed = response.json().get("voices")
voices = sorted(str(v) for v in listed) if isinstance(listed, list) else None
except Exception:
voices = None
except Exception:
ok = False
voices = None
self._tts_health = _Health(checked=self.clock(), ok=ok, voices=voices)
return ok
def last_health_voices(self) -> list[str] | None:
"""最近一次健康探测拿到的音色表(None=本次探测没带回名单)."""
return self._tts_health.voices
# -- lifecycle ----------------------------------------------------------
def _settle(self, session: VoiceSession) -> None:
"""A session left the active registry (ended, expired, or moved into
the cleanup ledger): its worker's entry-read window is closed. The
optional HEL-904 hook releases the custom-voice hold for that call."""
hook = self.on_session_settled
if hook is None:
return
# 见字段注释:持有释放失败只会让应用写透晚一拍,不破坏会话流程
with contextlib.suppress(Exception):
hook(session)
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()
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)
self._settle(session) # TTL 到期:入口读窗口关闭(HEL-904)
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:
"""The single cleanup owner for THIS instance.
It watches two deadlines without needing any further request: every
debt's next retry eligibility and every ACTIVE session's expiry. When
there is nothing left to watch (no sessions, only settled/abandoned
debts) the loop exits; the next open/recover/end re-kicks it.
"""
try:
while True:
self._prune() # expired active sessions become retryable debts
pending = self._retryable_debts()
if not pending:
now = self.clock()
deadlines = [d.eligible_at for d in self._debts.values()
if not self._abandon_reason(d)]
deadlines += [s.expires_at for s in self._sessions.values()]
if not deadlines:
break
# Deferred debts (restart compensation waiting out a live
# session's TTL) and not-yet-expired sessions: sleep until
# the earliest deadline, bounded so the loop stays cheap —
# a newly created debt wakes it immediately (_wake).
delay = min(max(min(deadlines) - now, 0.05), 60.0)
self._wake.clear()
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._wake.wait(), timeout=delay)
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():
self._wake.set() # wake the sleeping watcher for the new debt
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, voice: str = "") -> 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))
dispatch = await livekit_wire.create_dispatch(
self.http,
internal_url=self.config.livekit_internal,
api_key=self.config.api_key,
api_secret=self.config.api_secret,
agent_name=self.config.agent_name,
room=room,
timeout=self.config.dispatch_timeout_seconds,
)
now = self.clock()
session = VoiceSession(
session_id=secrets.token_urlsafe(18),
room=room,
identity=identity,
created_at=now,
expires_at=now + self.config.session_ttl_seconds,
epoch=epoch,
dispatch_id=dispatch.dispatch_id,
voice=voice,
)
self._sessions[session.session_id] = session
self._persist_state()
# Re-kick AFTER the registration exists: a real dispatch await yields
# the loop, and the earlier kick's cleaner may have already found
# nothing to watch and exited — the new deadline needs an owner again
# (HEL-879 timing fix: the cleaner died mid-dispatch with zero deletes).
self._kick_cleanup()
return session
def token_for(self, session: VoiceSession) -> str:
return livekit_wire.mint_token(
self.config.api_key,
self.config.api_secret,
identity=session.identity,
name="用户",
room=session.room,
room_join=True,
can_publish=True,
can_subscribe=True,
ttl_seconds=self.config.token_ttl_seconds,
now=self.clock(),
)
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.
Explicit end and the background sweep share ONE persisted attempt
budget (HEL-879 remaining closure): both count into the same debt, so
a room whose cap the sweep exhausted is never re-deleted from here
either — it raises CleanupAbandoned (unsettled, honest) instead of
answering a done-404. Unknown ids never seen here return None → 404;
ids fully settled and forgotten also do.
"""
self._prune()
session = self._sessions.get(session_id)
debt = self._debts.get(session_id)
if session is None and debt is None:
return None
if debt is None:
debt = _CleanupDebt(session=session, first_debt_at=self.clock())
elif debt.abandoned:
# Cap already crossed (by this process or a previous one): no more
# remote deletes from any path; the room stays owned-unsettled.
raise CleanupAbandoned(debt)
else:
session = debt.session
try:
await self._delete_room_once(session)
except Exception as exc:
# From now on the room lives in the ledger alone: _sessions no
# longer bypasses the shared cap on a later end call.
self._sessions.pop(session_id, None)
self._settle(session) # 已挂断(删房在欠账里补):入口读窗口关闭
if session_id not in self._debts:
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._settle(session) # 删房落定:本通话结算(HEL-904 释放音色持有)
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()