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))