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:
co-authored by
multica-agent
parent
7f0a739213
commit
78a5cfd8d7
@@ -302,13 +302,23 @@ async def test_receipt_sender_confirms_once_and_reports_server_refusal():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def live_server(api):
|
||||
def live_server(api, tmp_path):
|
||||
app, provider, _ = api
|
||||
# HEL-879: an app's lifespan has exactly one owner — the api fixture's
|
||||
# TestClient still holds its lifespan, so the live server gets its OWN app
|
||||
# instance on the same file-backed database (companion row included) and
|
||||
# the same provider; the old fixture entered one app's lifespan twice
|
||||
# concurrently, the exact defect the app now refuses loudly.
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)},
|
||||
budget=engineering_budget())
|
||||
served = create_app(db_path=tmp_path / "adapter.db", router=router,
|
||||
life_config=LifeConfig(enabled=True, poll_seconds=3600),
|
||||
semantic_mode="stub")
|
||||
probe = socket.socket()
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
port = probe.getsockname()[1]
|
||||
probe.close() # free the port for uvicorn to bind
|
||||
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")
|
||||
config = uvicorn.Config(served, host="127.0.0.1", port=port, log_level="error")
|
||||
server = uvicorn.Server(config)
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
@@ -318,7 +328,7 @@ def live_server(api):
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(0.1)
|
||||
yield f"http://127.0.0.1:{port}", app, provider
|
||||
yield f"http://127.0.0.1:{port}", served, provider
|
||||
server.should_exit = True
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
"""HEL-879 rework regressions for the 总管's independent-review edges.
|
||||
|
||||
Four confirmed offline defects, each reproduced first and fixed:
|
||||
1. dual uvicorn listeners both running the app lifespan (epoch 1→2, state
|
||||
replaced, store closed under live listeners);
|
||||
2. end_session popping the registry before the remote delete (lost retry
|
||||
target; expiry pruning dropping rooms with zero DELETE attempts);
|
||||
3. TurnLedger binding streams to handles by timestamp (a handle without a
|
||||
generation steals the next turn's stream/receipt);
|
||||
4. release-snapshot verify accepting self-contradictory success markers and
|
||||
same-basename DBs overwriting each other (covered by the tool selftest).
|
||||
|
||||
Zero network beyond 127.0.0.1; fake LiveKit/TTS transports throughout.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
|
||||
from test_r2 import R2LLM # noqa: E402
|
||||
|
||||
from cybergril.api.app import create_app # noqa: E402
|
||||
from cybergril.life.runtime import LifeConfig # noqa: E402
|
||||
from cybergril.memory.store import Store # noqa: E402
|
||||
from cybergril.think.router import build_router # noqa: E402
|
||||
from cybergril.think.scenes import Tier # noqa: E402
|
||||
from cybergril.voice import livekit_wire # noqa: E402
|
||||
from cybergril.voice.receipt import TurnLedger # noqa: E402
|
||||
from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- TurnLedger
|
||||
|
||||
def _stream(turn_id: str) -> SimpleNamespace:
|
||||
return SimpleNamespace(turn_id=turn_id, receipt={"message_id": hash(turn_id) % 1000})
|
||||
|
||||
|
||||
def test_ledger_binds_each_handle_to_its_own_stream():
|
||||
ledger = TurnLedger()
|
||||
h1, h2 = object(), object()
|
||||
s1, s2 = _stream("old"), _stream("new")
|
||||
ledger.note_handle(h1, 1.0)
|
||||
ledger.note_stream(s1, 1.1)
|
||||
ledger.note_handle(h2, 2.0)
|
||||
ledger.note_stream(s2, 2.1)
|
||||
# A late cleanup of H2 must leave H1's own stream to H1 (old code: None).
|
||||
assert ledger.stream_for(h2) is s2
|
||||
assert ledger.stream_for(h1) is s1
|
||||
|
||||
|
||||
def test_ledger_handle_without_generation_consumes_nothing():
|
||||
ledger = TurnLedger()
|
||||
no_generation, real = object(), object()
|
||||
s2 = _stream("new")
|
||||
ledger.note_handle(no_generation, 10.0)
|
||||
ledger.note_handle(real, 11.0) # retires the older, generation-less handle
|
||||
ledger.note_stream(s2, 11.1)
|
||||
assert ledger.stream_for(no_generation) is None
|
||||
assert ledger.stream_for(real) is s2
|
||||
|
||||
|
||||
def test_ledger_interrupted_handle_discards_only_its_own_binding():
|
||||
ledger = TurnLedger()
|
||||
h1, h2 = object(), object()
|
||||
s1, s2 = _stream("one"), _stream("two")
|
||||
ledger.note_handle(h1, 1.0)
|
||||
ledger.note_stream(s1, 1.0)
|
||||
ledger.note_handle(h2, 2.0)
|
||||
ledger.note_stream(s2, 2.0)
|
||||
ledger.discard(h1) # worker fail-closed path (interrupted/failed playout)
|
||||
assert ledger.stream_for(h1) is None
|
||||
assert ledger.stream_for(h2) is s2
|
||||
|
||||
|
||||
def test_ledger_stream_without_pending_handle_stays_unclaimed():
|
||||
ledger = TurnLedger()
|
||||
stray = _stream("proactive")
|
||||
ledger.note_stream(stray, 1.0) # no user turn awaited a generation
|
||||
handle = object()
|
||||
ledger.note_handle(handle, 2.0)
|
||||
later = _stream("answer")
|
||||
ledger.note_stream(later, 2.5)
|
||||
assert ledger.stream_for(handle) is later
|
||||
|
||||
|
||||
# --------------------------------------------------- session ownership ledger
|
||||
|
||||
def _proto_field1(data: bytes) -> str:
|
||||
"""Decode varint-prefixed field 1 (room) from a livekit proto body."""
|
||||
if not data or (data[0] >> 3) != 1 or (data[0] & 7) != 2:
|
||||
return ""
|
||||
length, index, shift, value = 0, 1, 0, 0
|
||||
while True:
|
||||
byte = data[index]
|
||||
length |= (byte & 0x7F) << shift
|
||||
index += 1
|
||||
if not byte & 0x80:
|
||||
break
|
||||
shift += 7
|
||||
return data[index:index + length].decode()
|
||||
|
||||
|
||||
class StandinLiveKit:
|
||||
"""Fake Twirp transport: configurable delete failures per call."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.deleted: list[str] = []
|
||||
self.delete_errors: list[Exception | int] = []
|
||||
self._transport = httpx.MockTransport(self._handle)
|
||||
|
||||
def _handle(self, request: httpx.Request) -> httpx.Response:
|
||||
path = request.url.path
|
||||
if path.endswith("/CreateDispatch"):
|
||||
return httpx.Response(200, json={"id": "AD_1", "room": "r"})
|
||||
if path.endswith("/DeleteRoom"):
|
||||
if self.delete_errors:
|
||||
error = self.delete_errors.pop(0)
|
||||
if isinstance(error, int):
|
||||
return httpx.Response(error, text="room service error")
|
||||
raise error
|
||||
self.deleted.append(_proto_field1(request.content))
|
||||
return httpx.Response(200, content=b"")
|
||||
return httpx.Response(404, text="unknown")
|
||||
|
||||
@property
|
||||
def transport(self) -> httpx.MockTransport:
|
||||
return self._transport
|
||||
|
||||
|
||||
def _service(standin: StandinLiveKit, *, clock=None, backoff=0.0, **kwargs) -> VoiceSessionService:
|
||||
config = VoiceConfig(
|
||||
livekit_url="ws://voice.test:7880",
|
||||
livekit_internal="http://livekit.test",
|
||||
api_key="devkey",
|
||||
api_secret="test-secret-not-real",
|
||||
tts_health_url="http://tts.test/health",
|
||||
session_ttl_seconds=kwargs.pop("session_ttl_seconds", 5.0),
|
||||
)
|
||||
return VoiceSessionService(
|
||||
config=config,
|
||||
http=httpx.AsyncClient(transport=standin.transport),
|
||||
clock=clock or time.time,
|
||||
cleanup_backoff_seconds=backoff,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
async def _open(service: VoiceSessionService) -> str:
|
||||
return (await service.open_session(epoch=1)).session_id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_failure_keeps_room_owned_until_retry_lands():
|
||||
standin = StandinLiveKit()
|
||||
standin.delete_errors = [RuntimeError("standin delete failed")]
|
||||
service = _service(standin)
|
||||
try:
|
||||
session = await service.open_session(epoch=1)
|
||||
with pytest.raises(RuntimeError):
|
||||
await service.end_session(session.session_id)
|
||||
# The room is retained for retry (old code: registry already popped,
|
||||
# second call answered None and never deleted the room again).
|
||||
debt = service.cleanup_debt(session.session_id)
|
||||
assert debt is not None and debt.session.room == session.room
|
||||
assert standin.deleted == []
|
||||
ended = await service.end_session(session.session_id)
|
||||
assert ended.room == session.room
|
||||
assert standin.deleted == [session.room]
|
||||
assert service.cleanup_debt(session.session_id) is None
|
||||
assert await service.end_session(session.session_id) is None
|
||||
finally:
|
||||
await service.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expired_session_room_is_actually_deleted():
|
||||
standin = StandinLiveKit()
|
||||
now = [1000.0]
|
||||
service = _service(standin, clock=lambda: now[0])
|
||||
try:
|
||||
session = await service.open_session(epoch=1)
|
||||
now[0] += service.config.session_ttl_seconds + 1
|
||||
# Old code: _prune dropped the registration silently — zero DELETEs.
|
||||
ended = await service.end_session(session.session_id)
|
||||
assert ended is not None and ended.room == session.room
|
||||
assert standin.deleted == [session.room]
|
||||
finally:
|
||||
await service.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_already_gone_is_idempotent_success():
|
||||
standin = StandinLiveKit()
|
||||
standin.delete_errors = [404] # room vanished server-side first
|
||||
service = _service(standin)
|
||||
try:
|
||||
session = await service.open_session(epoch=1)
|
||||
ended = await service.end_session(session.session_id)
|
||||
assert ended is not None
|
||||
assert service.cleanup_debt(session.session_id) is None
|
||||
finally:
|
||||
await service.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_background_cleanup_settles_expiry_debt():
|
||||
standin = StandinLiveKit()
|
||||
standin.delete_errors = [RuntimeError("flap"), RuntimeError("flap")]
|
||||
now = [1000.0]
|
||||
service = _service(standin, clock=lambda: now[0])
|
||||
try:
|
||||
session = await service.open_session(epoch=1)
|
||||
now[0] += service.config.session_ttl_seconds + 1
|
||||
with pytest.raises(RuntimeError):
|
||||
await service.end_session(session.session_id)
|
||||
now[0] += 1
|
||||
for _ in range(50):
|
||||
if standin.deleted:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
assert standin.deleted == [session.room]
|
||||
for _ in range(50):
|
||||
if service.cleanup_debt(session.session_id) is None:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
assert service.cleanup_debt(session.session_id) is None
|
||||
finally:
|
||||
await service.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cleanup_is_bounded_then_recorded_abandoned(tmp_path):
|
||||
standin = StandinLiveKit()
|
||||
standin.delete_errors = [503] * 50 # never succeeds
|
||||
now = [1000.0]
|
||||
service = _service(standin, clock=lambda: now[0],
|
||||
state_path=tmp_path / "voice-sessions.json",
|
||||
cleanup_max_attempts=3)
|
||||
try:
|
||||
session = await service.open_session(epoch=1)
|
||||
now[0] += service.config.session_ttl_seconds + 1
|
||||
with pytest.raises(Exception):
|
||||
await service.end_session(session.session_id)
|
||||
for _ in range(200):
|
||||
debt = service.cleanup_debt(session.session_id)
|
||||
if debt is not None and debt.abandoned:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
debt = service.cleanup_debt(session.session_id)
|
||||
assert debt is not None and debt.abandoned == "attempts-exhausted"
|
||||
# Bounded: after abandonment no further delete attempts happen.
|
||||
attempts = len(standin.delete_errors)
|
||||
await asyncio.sleep(0.2)
|
||||
assert len(standin.delete_errors) == attempts
|
||||
recorded = json.loads((tmp_path / "voice-sessions.json").read_text())
|
||||
assert recorded["debts"][0]["abandoned"] == "attempts-exhausted"
|
||||
finally:
|
||||
await service.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restart_compensation_deletes_previous_process_rooms(tmp_path):
|
||||
standin = StandinLiveKit()
|
||||
standin.delete_errors = [RuntimeError("down")] * 2 # end attempt + shutdown sweep
|
||||
state = tmp_path / "voice-sessions.json"
|
||||
now = [1000.0]
|
||||
# big backoff: the background sweeper must not race this scenario
|
||||
first = _service(standin, clock=lambda: now[0], state_path=state, backoff=3600.0)
|
||||
session = await first.open_session(epoch=1)
|
||||
with pytest.raises(RuntimeError):
|
||||
await first.end_session(session.session_id)
|
||||
await first.aclose()
|
||||
assert standin.deleted == [] # LiveKit was down for process 1's whole life
|
||||
persisted = json.loads(state.read_text())
|
||||
assert any(d["session"]["room"] == session.room for d in persisted["debts"])
|
||||
# "Restart": a new process of the same instance reads the same ledger and
|
||||
# compensates only the rooms recorded there.
|
||||
second = _service(standin, clock=lambda: now[0], state_path=state)
|
||||
try:
|
||||
await second.recover()
|
||||
for _ in range(100):
|
||||
if standin.deleted:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
assert standin.deleted == [session.room]
|
||||
for _ in range(100):
|
||||
settled = json.loads(state.read_text())
|
||||
if settled["debts"] == [] and settled["sessions"] == []:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
settled = json.loads(state.read_text())
|
||||
assert settled["debts"] == [] and settled["sessions"] == []
|
||||
finally:
|
||||
await second.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_active_room_surives_restart_until_ttl_then_compensated(tmp_path):
|
||||
standin = StandinLiveKit()
|
||||
state = tmp_path / "voice-sessions.json"
|
||||
now = [1000.0]
|
||||
first = _service(standin, clock=lambda: now[0], state_path=state,
|
||||
session_ttl_seconds=0.5)
|
||||
session = await first.open_session(epoch=1) # never ended by the user
|
||||
await first.aclose() # graceful shutdown must not hang up a live call
|
||||
assert standin.deleted == []
|
||||
persisted = json.loads(state.read_text())
|
||||
assert any(s["room"] == session.room for s in persisted["sessions"])
|
||||
# Restart immediately: the call may still be alive on the SFU, so the
|
||||
# compensation waits for the session's own TTL — then deletes, bounded.
|
||||
second = _service(standin, clock=lambda: now[0], state_path=state,
|
||||
session_ttl_seconds=0.5)
|
||||
try:
|
||||
await second.recover()
|
||||
await asyncio.sleep(0.15)
|
||||
assert standin.deleted == [] # still within TTL: untouched
|
||||
now[0] += 1.0
|
||||
for _ in range(100):
|
||||
if standin.deleted:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
assert standin.deleted == [session.room]
|
||||
finally:
|
||||
await second.aclose()
|
||||
|
||||
|
||||
# ------------------------------------------------------ router-level semantics
|
||||
|
||||
def _voice_app(standin: StandinLiveKit, tts_ok=True):
|
||||
provider = R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.host == "tts.test":
|
||||
return httpx.Response(200 if tts_ok else 503)
|
||||
return standin._handle(request)
|
||||
|
||||
service = _service(standin, backoff=3600.0) # keep the sweep out of the race
|
||||
service.http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
app = create_app(db_path=":memory:", router=router,
|
||||
life_config=LifeConfig(enabled=False), semantic_mode="stub",
|
||||
voice_service=service)
|
||||
return app, service
|
||||
|
||||
|
||||
def test_router_delete_failure_is_503_and_keeps_room_owned():
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
standin = StandinLiveKit()
|
||||
# interactive attempt + the background sweep's immediate first retry;
|
||||
# the sweep then backs off (3600 s), leaving the debt visibly owned
|
||||
standin.delete_errors = [RuntimeError("livekit down"), RuntimeError("livekit down")]
|
||||
app, service = _voice_app(standin)
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/companion", json={
|
||||
"name": "语音重试", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"})
|
||||
opened = client.post("/api/voice/session")
|
||||
assert opened.status_code == 201
|
||||
session_id = opened.json()["session_id"]
|
||||
failed = client.delete(f"/api/voice/session/{session_id}")
|
||||
assert failed.status_code == 503 # NOT 404: the room is still owned
|
||||
assert service.cleanup_debt(session_id) is not None
|
||||
retried = client.delete(f"/api/voice/session/{session_id}")
|
||||
assert retried.status_code == 200 and retried.json()["ended"] is True
|
||||
assert standin.deleted == [opened.json()["room"]]
|
||||
again = client.delete(f"/api/voice/session/{session_id}")
|
||||
assert again.status_code == 404
|
||||
|
||||
|
||||
# ---------------------------------------------------- dual-listener lifecycle
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def self_signed_cert(tmp_path):
|
||||
cert = tmp_path / "cert.pem"
|
||||
key = tmp_path / "key.pem"
|
||||
subprocess.run(
|
||||
["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
|
||||
"-keyout", str(key), "-out", str(cert), "-days", "1",
|
||||
"-subj", "/CN=127.0.0.1",
|
||||
"-addext", "subjectAltName=IP:127.0.0.1"],
|
||||
check=True, capture_output=True)
|
||||
return str(cert), str(key)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dual_listeners_share_one_lifecycle_and_close_in_order(
|
||||
tmp_path, self_signed_cert, monkeypatch):
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "deploy" / "voice"))
|
||||
import serve_dual_8360_8361 as launcher
|
||||
|
||||
cert, key = self_signed_cert
|
||||
events: list[str] = []
|
||||
store_inits: list[int] = []
|
||||
real_store_init = Store.__init__
|
||||
real_store_close = Store.close
|
||||
|
||||
def counting_init(self, *args, **kwargs):
|
||||
store_inits.append(id(self))
|
||||
real_store_init(self, *args, **kwargs)
|
||||
|
||||
def recording_close(self):
|
||||
events.append("store_close")
|
||||
real_store_close(self)
|
||||
|
||||
monkeypatch.setattr(Store, "__init__", counting_init)
|
||||
monkeypatch.setattr(Store, "close", recording_close)
|
||||
|
||||
import uvicorn
|
||||
real_shutdown = uvicorn.Server.shutdown
|
||||
|
||||
async def recording_shutdown(self, sockets=None):
|
||||
events.append(f"listener_shutdown:{self.config.port}")
|
||||
await real_shutdown(self, sockets=sockets)
|
||||
|
||||
monkeypatch.setattr(uvicorn.Server, "shutdown", recording_shutdown)
|
||||
|
||||
provider = R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
app = create_app(db_path=tmp_path / "dual.db", router=router,
|
||||
life_config=LifeConfig(enabled=False), semantic_mode="off")
|
||||
http_port, https_port = _free_port(), _free_port()
|
||||
serve_task = asyncio.get_running_loop().create_task(
|
||||
launcher.serve(http_port, https_port, cert, key, app=app))
|
||||
|
||||
client = httpx.AsyncClient(timeout=5.0, verify=False)
|
||||
try:
|
||||
epochs = []
|
||||
for _ in range(100):
|
||||
try:
|
||||
for port, scheme in ((http_port, "http"), (https_port, "https")):
|
||||
response = await client.get(f"{scheme}://127.0.0.1:{port}/api/health")
|
||||
if response.status_code == 200:
|
||||
epochs.append(response.json()["epoch"])
|
||||
if len(epochs) >= 2:
|
||||
break
|
||||
except (httpx.ConnectError, httpx.ConnectTimeout, ssl.SSLError):
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(epochs) >= 2, "both listeners must come up"
|
||||
# ONE lifecycle for both listeners: a second entry would be epoch 2.
|
||||
assert epochs[0] == epochs[1]
|
||||
assert len(set(store_inits)) == 1, "the app must be initialized exactly once"
|
||||
finally:
|
||||
serve_task.cancel()
|
||||
try:
|
||||
await serve_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
await client.aclose()
|
||||
|
||||
# Exit boundary: both listeners fully shut down BEFORE the store closes,
|
||||
# and the store closes exactly once (never closed under live listeners).
|
||||
shutdowns = [e for e in events if e.startswith("listener_shutdown")]
|
||||
assert len(shutdowns) == 2, events
|
||||
assert events.index("store_close") > max(events.index(e) for e in shutdowns)
|
||||
assert events.count("store_close") == 1
|
||||
assert len(set(store_inits)) == 1
|
||||
|
||||
|
||||
def test_second_lifespan_entry_fails_loudly(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
provider = R2LLM()
|
||||
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
|
||||
app = create_app(db_path=tmp_path / "guard.db", router=router,
|
||||
life_config=LifeConfig(enabled=False), semantic_mode="off")
|
||||
|
||||
async def _double_enter():
|
||||
async with app.router.lifespan_context(app):
|
||||
pass
|
||||
|
||||
with TestClient(app) as client:
|
||||
epoch_before = client.get("/api/health").json()["epoch"]
|
||||
# A second entry (the old dual-uvicorn defect: epoch 1→2, Store/life/
|
||||
# chat_lock silently replaced) must now fail closed.
|
||||
with pytest.raises(RuntimeError, match="entered twice"):
|
||||
asyncio.run(_double_enter())
|
||||
assert client.get("/api/health").json()["epoch"] == epoch_before
|
||||
Reference in New Issue
Block a user