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
+89 -65
View File
@@ -210,73 +210,90 @@ def create_app(
@asynccontextmanager
async def lifespan(app):
store = Store(db_path)
app.state.store = store
with store.conn:
store.execute(
"INSERT INTO api_meta(key,value) VALUES('epoch',1) ON CONFLICT(key) DO UPDATE SET value=value+1"
)
store.execute("UPDATE chat_message SET status='cancelled' WHERE status='pending'")
app.state.epoch = store.query_one("SELECT value FROM api_meta WHERE key='epoch'")["value"]
app.state.active = None
app.state.chat_lock = asyncio.Lock()
app.state.health_cache = (0, False)
app.state.health_lock = asyncio.Lock()
router.guard = PersistentBudget(store, router.guard)
app.state.sharing = Sharing(store, router, models)
app.state.persona = Persona(store, router, models, enabled=life_config.enabled)
app.state.public = PublicView(store)
app.state.mood = MoodRuntime(store, character)
app.state.dyad = DyadRuntime(store, character, router=router, models=models,
timezone=life_config.timezone)
app.state.semantic = build_semantic(store, mode=semantic_mode, config=semantic_config,
request_guard=router.guard)
# Original positional contract preserved; R4 collaborators attach after assembly.
app.state.life = LifeRuntime(store, router, models, life_config, app.state.sharing,
app.state.persona)
app.state.life.mood = app.state.mood
app.state.life.semantic = app.state.semantic
app.state.life.dyad = app.state.dyad
app.state.life.reach_out = ReachOut(store, router, models, app.state.persona,
app.state.mood, config=character.reach_out,
timezone=life_config.timezone)
# Preserve the original runtime factory contract. Assemble only after its
# clock is known, before any recovery or background work can run.
app.state.memories = Memories(store, router, models, timezone=life_config.timezone,
clock=lambda: app.state.life.clock())
app.state.life.memories = app.state.memories
app.state.memories.recover()
app.state.mood.recover()
if app.state.semantic:
app.state.semantic.recover()
if app.state.life.reach_out:
app.state.life.reach_out.recover()
life_task = asyncio.create_task(app.state.life.run())
# HEL-879 dual-entry guard: a second concurrent entry (e.g. two uvicorn
# servers both running the default lifespan against this app) must fail
# loudly, never silently re-initialize Store/epoch/life/chat_lock under
# live requests. Re-entry after a completed exit stays legitimate.
if getattr(app.state, "lifespan_active", False):
raise RuntimeError(
"application lifespan entered twice — the lifecycle has exactly "
"one owner (deploy/voice/serve_dual_8360_8361.py runs uvicorn "
"with lifespan='off' and owns it once)")
app.state.lifespan_active = True
try:
yield
finally:
app.state.life.stop.set()
if life_task:
life_task.cancel()
with suppress(asyncio.CancelledError):
await life_task
if app.state.active:
app.state.active["cancel"].set()
await app.state.active["finished"].wait()
store = Store(db_path)
app.state.store = store
with store.conn:
store.execute(
"INSERT INTO api_meta(key,value) VALUES('epoch',1) ON CONFLICT(key) DO UPDATE SET value=value+1"
)
store.execute("UPDATE chat_message SET status='cancelled' WHERE status='pending'")
app.state.epoch = store.query_one("SELECT value FROM api_meta WHERE key='epoch'")["value"]
app.state.active = None
app.state.chat_lock = asyncio.Lock()
app.state.health_cache = (0, False)
app.state.health_lock = asyncio.Lock()
router.guard = PersistentBudget(store, router.guard)
app.state.sharing = Sharing(store, router, models)
app.state.persona = Persona(store, router, models, enabled=life_config.enabled)
app.state.public = PublicView(store)
app.state.mood = MoodRuntime(store, character)
app.state.dyad = DyadRuntime(store, character, router=router, models=models,
timezone=life_config.timezone)
app.state.semantic = build_semantic(store, mode=semantic_mode, config=semantic_config,
request_guard=router.guard)
# Original positional contract preserved; R4 collaborators attach after assembly.
app.state.life = LifeRuntime(store, router, models, life_config, app.state.sharing,
app.state.persona)
app.state.life.mood = app.state.mood
app.state.life.semantic = app.state.semantic
app.state.life.dyad = app.state.dyad
app.state.life.reach_out = ReachOut(store, router, models, app.state.persona,
app.state.mood, config=character.reach_out,
timezone=life_config.timezone)
# Preserve the original runtime factory contract. Assemble only after its
# clock is known, before any recovery or background work can run.
app.state.memories = Memories(store, router, models, timezone=life_config.timezone,
clock=lambda: app.state.life.clock())
app.state.life.memories = app.state.memories
app.state.memories.recover()
app.state.mood.recover()
if app.state.semantic:
# HEL-889/894 shutdown ownership: aclose returns only after
# every live batch worker has actually exited (drain_timeout
# bounds the polite phase, never a licence to close under a
# worker). If this await is cancelled after the resource
# close began, the close still lands exactly once before the
# cancellation propagates (HEL-894) — the provider clients
# and the store below stay safe in either order.
await app.state.semantic.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
app.state.semantic.recover()
if app.state.life.reach_out:
app.state.life.reach_out.recover()
# HEL-879: bounded restart compensation for this instance's own
# voice rooms (persisted cleanup ledger; own rooms only).
if getattr(app.state, "voice_service", None):
await app.state.voice_service.aclose()
store.close()
await app.state.voice_service.recover()
life_task = asyncio.create_task(app.state.life.run())
try:
yield
finally:
app.state.life.stop.set()
if life_task:
life_task.cancel()
with suppress(asyncio.CancelledError):
await life_task
if app.state.active:
app.state.active["cancel"].set()
await app.state.active["finished"].wait()
if app.state.semantic:
# HEL-889/894 shutdown ownership: aclose returns only after
# every live batch worker has actually exited (drain_timeout
# bounds the polite phase, never a licence to close under a
# worker). If this await is cancelled after the resource
# close began, the close still lands exactly once before the
# cancellation propagates (HEL-894) — the provider clients
# and the store below stay safe in either order.
await app.state.semantic.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
if getattr(app.state, "voice_service", None):
await app.state.voice_service.aclose()
store.close()
finally:
app.state.lifespan_active = False
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None)
@@ -288,8 +305,15 @@ def create_app(
voice_config = load_voice_config()
except Exception:
voice_config = None
# Cleanup ledger beside the instance database: rooms this instance
# opened stay owned (persisted) until their bounded delete lands —
# a restarted process compensates its OWN rooms only (HEL-879).
voice_service = (
VoiceSessionService(voice_config) if voice_config is not None else None
VoiceSessionService(
voice_config,
state_path=None if str(db_path) == ":memory:" else Path(db_path).with_name(
Path(db_path).stem + "-voice-sessions.json"),
) if voice_config is not None else None
)
app.state.voice_service = voice_service
app.include_router(build_voice_router(voice_service))
+23 -2
View File
@@ -149,6 +149,21 @@ async def create_dispatch(
)
class RoomDeleteError(RuntimeError):
"""LiveKit refused a room delete with a status other than 2xx/404.
Raised (not returned) so callers cannot mistake a failed delete for a
settled one — the caller must keep the room owned for a bounded retry
(HEL-879). A 404 answer means the room is already gone and is reported
as success instead: the delete's goal (room no longer exists) holds.
"""
def __init__(self, status_code: int, room: str) -> None:
super().__init__(f"delete room {room!r} failed with HTTP {status_code}")
self.status_code = status_code
self.room = room
async def delete_room(
http: httpx.AsyncClient,
*,
@@ -162,6 +177,10 @@ async def delete_room(
Deleting the room disconnects every participant, ends the dispatched agent
job and releases the browser microphone server-side.
Returns True when the room is gone: 2xx, or 404 (already deleted — the
retry after a lost response stays idempotent). Any other status raises
RoomDeleteError so ownership is retained until the delete really lands.
"""
response = await http.post(
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{ROOM_SERVICE}/DeleteRoom",
@@ -172,8 +191,10 @@ async def delete_room(
},
timeout=timeout,
)
# LiveKit answers DeleteRoom with an empty protobuf body; treat 2xx as done.
return response.status_code // 100 == 2
# LiveKit answers DeleteRoom with an empty protobuf body; 404 = already gone.
if response.status_code // 100 == 2 or response.status_code == 404:
return True
raise RoomDeleteError(response.status_code, room)
def decode_token(token: str) -> tuple[dict[str, Any], bytes]:
+41 -22
View File
@@ -7,9 +7,13 @@ 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: AgentSession emits
speech_created before the LLM stream starts and runs one user-turn generation
at a time, so the first stream created at/after a handle belongs to it.
Speech-handle-to-stream binding lives in TurnLedger as an EXPLICIT
association, not a time-window guess (HEL-879 总管复核第 3 项): AgentSession
runs one user-turn generation at a time, so the LLM stream a generation starts
is bound to the oldest handle still awaiting its generation; a handle whose
generation never starts (cancelled/interrupted before the LLM call) is retired
the moment a newer speech appears — it can never consume a later turn's
stream, and a failed/interrupted handle only ever releases its own binding.
"""
from __future__ import annotations
@@ -48,31 +52,46 @@ class _HasHandle(Protocol):
class TurnLedger:
"""Binds livekit SpeechHandles to the ChatApiLLMStream of their generation."""
"""Binds livekit SpeechHandles to the ChatApiLLMStream of their generation.
The binding is exact, never inferred from ordering timestamps: a stream is
bound to the oldest handle that has not yet been retired (its generation is
the one the SDK is starting), and each stream is consumed exactly once by
exactly its own handle.
"""
def __init__(self) -> None:
self._handles: deque[tuple[float, Any]] = deque() # (created_at, handle)
self._streams: deque[tuple[float, Any]] = deque() # (created_at, stream)
self._pending: deque[Any] = deque() # handles awaiting their generation
self._bound: dict[int, Any] = {} # id(handle) -> its stream
self._retired: set[int] = set() # ended without a generation
def note_handle(self, handle: _HasHandle, created_at: float) -> None:
self._handles.append((created_at, handle))
def note_handle(self, handle: _HasHandle, created_at: float | None = None) -> None:
"""A new user speech started: every older handle still awaiting its
generation will never get one (the SDK moves on to the new turn), so it
is retired instead of staying eligible to steal the next stream."""
while self._pending:
self._retired.add(id(self._pending.popleft()))
self._pending.append(handle)
def note_stream(self, stream: Any, created_at: float) -> None:
self._streams.append((created_at, stream))
def note_stream(self, stream: Any, created_at: float | None = None) -> None:
"""The generation the SDK just started belongs to the oldest handle
still awaiting one. A stream with no pending handle (proactive speech
outside a user turn) is left unbound: no user turn may claim it."""
if self._pending:
handle = self._pending.popleft()
self._bound[id(handle)] = stream
def stream_for(self, handle: _HasHandle) -> Any | None:
"""First not-yet-consumed stream created at/after the handle."""
while self._handles and self._handles[0][1] is not handle:
self._handles.popleft() # older handles ended without a generation
if not self._handles:
return None
# (handle present below)
created = self._handles.popleft()[0]
while self._streams:
at, stream = self._streams.popleft()
if at >= created:
return stream
return None
"""This handle's own stream, exactly once; None when its generation
never started or it was retired/interrupted without one."""
return self._bound.pop(id(handle), None)
def discard(self, handle: _HasHandle) -> None:
"""Release a handle's binding without using it (fail-closed path for
interrupted/failed playout): the turn never acks, and the binding does
not leak into any later turn."""
self._bound.pop(id(handle), None)
self._retired.discard(id(handle))
class ReceiptSender:
+11 -1
View File
@@ -8,6 +8,10 @@ POST /api/voice/session open a room, dispatch the dedicated worker,
DELETE /api/voice/session/{id} end: delete the LiveKit room, which
disconnects browser and worker, ends the
agent job and releases the microphone.
A delete that cannot land keeps the room
in a bounded, persisted cleanup ledger
(503, retried); it never collapses into
a 404 while the room is still owned.
GET /api/voice/status honest switch state for the frontend
(configured / tts reachable / agent name).
@@ -70,7 +74,13 @@ def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
async def end_session(session_id: str) -> dict:
if service is None:
raise HTTPException(503, REFUSAL_NOT_CONFIGURED)
session = await service.end_session(session_id)
try:
session = await service.end_session(session_id)
except Exception:
# The remote delete did not land: the room stays owned in the
# bounded cleanup ledger and will be retried; the caller must NOT
# treat this as done (a 404 would erase the browser's owed DELETE).
raise HTTPException(503, "这次通话还没有完全挂断,会自动重试清理;请稍后再试。") from None
if session is None:
raise HTTPException(404, "这次通话已经不在了。")
return {"ended": True, "room": session.room}
+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()
+6 -1
View File
@@ -119,10 +119,15 @@ async def entrypoint(ctx: JobContext) -> None:
async def _after_playout(handle) -> None:
# SDK 真实播放完成(wait_for_playout 返回)之后才考虑回执。
await handle.wait_for_playout()
# HEL-879:先判定失败/打断并整单放弃(fail-closed)——被放弃的绑定
# 只属于这一轮,绝不会吞掉下一轮的回执归属。
failed = handle.exception() is not None
if handle.interrupted or failed:
ledger.discard(handle)
return
stream = ledger.stream_for(handle)
if stream is None:
return
failed = handle.exception() is not None
if stream.error_phi:
subtitle({"kind": "error", "role": "assistant", "text": stream.error_phi})
return