fix(voice): correct input accounting and session termination

Separate detected speech limits from continuous microphone silence while preserving transport bounds and absolute commit fencing.

Handle verified OpenAI cancellation races and terminal items, preserve causal close outcomes, and share bounded cleanup ownership with safe diagnostics.

Add regression coverage and align the API contract and frontend handoff. Validation: 61 focused unit tests passed; staged diff whitespace checks passed. Live browser acceptance remains outstanding.
This commit is contained in:
amirhosein mazaheri
2026-10-10 17:41:11 +03:30
parent b06eaf59f4
commit a769196bfa
23 changed files with 1809 additions and 92 deletions
@@ -0,0 +1,87 @@
"""Durable close races on isolated PostgreSQL, with no paid provider."""
import asyncio
from types import SimpleNamespace
from uuid import UUID
import pytest
from sqlalchemy import text
from app.modules.voice import registry
from tests.integration.test_phase2_postgres import seeded_env, api, reserve, concurrent, session
from tests.unit.test_realtime_phase1 import until
@pytest.mark.parametrize("code", ["LIVE_PROVIDER_PROTOCOL_ERROR", "LIVE_CONTEXT_SYNC_FAILED", "DEPENDENCY_UNAVAILABLE",
"SEARCH_TIMEOUT", "SEARCH_SATURATED", "CONTEXT_REVOKED"])
def test_backend_failure_wins_following_close_without_rewriting_terminal(seeded_env, code):
async def scenario():
e = seeded_env
_, sid = reserve(e)
runtime = SimpleNamespace(failure=code, lock=asyncio.Lock(), fail=lambda _: None)
registry.register(sid, e.org, 1, e.user.auth_session_id, runtime)
try:
results = await asyncio.to_thread(concurrent,
lambda: e.lifecycle.close_live_session(e.user, sid),
lambda: e.lifecycle.finish_session(e.user, sid, code, failed=code != "CONTEXT_REVOKED"))
assert all(r["close_reason"] == code for r in results)
assert e.lifecycle.close_live_session(e.user, sid)["close_reason"] == code
with e.engine.connect() as conn:
row = conn.execute(text("SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id"),
{"id": sid}).one()
assert row == (("closed", code, None) if code == "CONTEXT_REVOKED" else ("failed", code, code))
finally:
registry.unregister(sid)
asyncio.run(scenario())
def test_genuine_close_and_late_failure_are_idempotent(seeded_env):
e = seeded_env
_, sid = reserve(e)
first = e.lifecycle.close_live_session(e.user, sid)
assert first["close_reason"] == "user_requested"
assert e.lifecycle.close_live_session(e.user, sid) == first
assert e.lifecycle.finish_session(e.user, sid, "LIVE_PROVIDER_PROTOCOL_ERROR", failed=True) == first
@pytest.mark.parametrize("api", ["gemini", "openai"], indirect=True)
@pytest.mark.parametrize("cleanup", ["timeout", "exception"])
def test_asgi_failure_then_browser_close_preserves_error_and_releases_guards(api, monkeypatch, caplog, cleanup):
from app.api.v1 import live
from app.modules.voice.settings import RuntimeSettings
from app.infrastructure.realtime import RealtimeAdapter
client, wire, _, e = api
headers, result, _ = session(client, e)
sid = UUID(result["session_id"])
real_settings = RuntimeSettings
monkeypatch.setattr(live, "RuntimeSettings", lambda: real_settings(_env_file=None, send_timeout_seconds=.5))
close_calls = []
async def close():
close_calls.append(1)
if cleanup == "timeout": await asyncio.Event().wait()
raise ConnectionError("SECRET_PROVIDER_CLOSE")
wire.close = close
with client.websocket_connect("ws://localhost:8000"+result["stream_path"],
headers={"Origin": "http://localhost:8000"}) as ws:
ack = {"setupComplete": {}} if e.voice_config.provider == "gemini" else {
"type": "session.updated", "session": RealtimeAdapter(wire).setup()["session"]}
client.portal.call(wire.inbound.put, ack)
assert ws.receive_json()["type"] == "session_ready"
client.portal.call(until, lambda: registry.ENTRIES[sid].runtime.ready)
# Fail runtime while the route and provider-close work are still live.
async def fail():
entry = registry.ENTRIES[sid]
async with entry.runtime.lock:
entry.runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
client.portal.call(fail)
error = ws.receive_json()
assert error["error"]["code"] == "LIVE_PROVIDER_PROTOCOL_ERROR"
for _ in range(3):
response = client.post("/api/v1/voice/sessions/"+str(sid)+"/close", headers=headers)
assert response.status_code == 200
assert response.json()["close_reason"] == "LIVE_PROVIDER_PROTOCOL_ERROR"
client.portal.call(until, lambda: sid not in live.ACTIVE_MEDIA_SESSIONS)
assert sid not in registry.ENTRIES and close_calls == [1]
with e.engine.connect() as conn:
row = conn.execute(text("SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id"), {"id": sid}).one()
assert row == ("failed", "LIVE_PROVIDER_PROTOCOL_ERROR", "LIVE_PROVIDER_PROTOCOL_ERROR")
assert ("CLEANUP_TIMEOUT" if cleanup == "timeout" else "CLEANUP_FAILED") in caplog.text
assert "SECRET_PROVIDER_CLOSE" not in caplog.text