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:
@@ -0,0 +1,204 @@
|
||||
"""Incident regressions with sanitized synthetic provider events."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app.modules.voice import registry
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, terminal, until,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code", [
|
||||
("timeout", "SEARCH_TIMEOUT"),
|
||||
("database", "DEPENDENCY_UNAVAILABLE"),
|
||||
("saturation", "SEARCH_SATURATED"),
|
||||
("revocation", "CONTEXT_REVOKED"),
|
||||
])
|
||||
@pytest.mark.parametrize("phase", ["startup", "release", "delivery"])
|
||||
def test_authority_category_survives_secondary_callers(runner, persisted, failure, code, phase):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
turn = await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
runtime.settings = RuntimeSettings(_env_file=None, authority_timeout_seconds=.02)
|
||||
async def unavailable(_):
|
||||
if failure == "timeout":
|
||||
await asyncio.Event().wait()
|
||||
if failure == "database":
|
||||
raise OperationalError("private sql", {}, RuntimeError("private db"))
|
||||
if failure == "saturation":
|
||||
raise ValueError("SERVICE_BUSY")
|
||||
return False
|
||||
runtime.authority_check = unavailable
|
||||
try:
|
||||
if phase == "startup":
|
||||
assert not await runtime.authorized(turn)
|
||||
elif phase == "release":
|
||||
await runtime._authorize_release(turn)
|
||||
else:
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.delta",
|
||||
response_id="r1", item_id="a1", output_index=0, content_index=0, delta="fixture"))
|
||||
await until(lambda: runtime.failure is not None)
|
||||
# Secondary failure paths must never replace the causal outcome.
|
||||
runtime.fail("CONTEXT_REVOKED")
|
||||
await until(lambda: any(isinstance(e, dict) and e["type"] == "error" for e in out))
|
||||
assert runtime.failure == code
|
||||
assert next(e["error"]["code"] for e in out if isinstance(e, dict) and e["type"] == "error") == code
|
||||
assert turn.cancelled.is_set()
|
||||
assert not any(isinstance(e, bytes) for e in out)
|
||||
assert not any(isinstance(e, dict) and e.get("role") == "assistant" for e in out)
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid", [None, "text", "extra_part", "wrong_role", "rebound"])
|
||||
def test_openai_ga_output_item_after_transcript(runner, persisted, invalid):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
await input_turn(runtime)
|
||||
result = await response(runtime, wire)
|
||||
item = dict(id="a1", type="message", role="assistant", content=[])
|
||||
try:
|
||||
await runtime.handle(dict(type="response.output_item.added", response_id="r1", output_index=0, item=deepcopy(item)))
|
||||
await runtime.handle(dict(type="response.content_part.added", response_id="r1", item_id="a1",
|
||||
output_index=0, content_index=0, part=dict(type="audio", transcript="")))
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.delta", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0, delta="Synthetic answer"))
|
||||
await until(lambda: any(isinstance(e, dict) and e.get("role") == "assistant" for e in out))
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.done", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0, transcript="Synthetic answer"))
|
||||
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0))
|
||||
item["content"] = [dict(type="output_audio", transcript="Synthetic answer")]
|
||||
if invalid == "text": item["content"][0]["type"] = "output_text"
|
||||
if invalid == "extra_part": item["content"].append(dict(type="output_audio"))
|
||||
if invalid == "wrong_role": item["role"] = "user"
|
||||
if invalid == "rebound": item["id"] = "other"
|
||||
wire_event = dict(type="response.output_item.done", response_id="r1", output_index=0,
|
||||
event_id="fixture-item-done", item=deepcopy(item))
|
||||
await runtime.handle(wire_event)
|
||||
if invalid is None:
|
||||
await runtime.handle(wire_event) # unchanged wire replay
|
||||
await runtime.handle(terminal(output=[item]))
|
||||
assert runtime.usable and result.terminal and result.status == "completed"
|
||||
assert wire_event["item"]["content"][0]["type"] == "output_audio"
|
||||
else:
|
||||
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_protocol_diagnostics_are_bounded_and_private(runner, persisted, caplog):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
try:
|
||||
await runtime.handle(dict(type="response.output_item.done", response_id="r1", output_index=0,
|
||||
item=dict(id="a1", type="message", role="assistant",
|
||||
content=[dict(type="output_text", text="SECRET_TRANSCRIPT")]),
|
||||
private="SECRET_CREDENTIAL"))
|
||||
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert "phase=provider_handle" in caplog.text
|
||||
assert "event=response.output_item.done" in caplog.text
|
||||
assert "reason=UNSUPPORTED_OUTPUT_LAYOUT" in caplog.text
|
||||
assert "exception=ValueError" in caplog.text
|
||||
assert runtime.session_id in caplog.text
|
||||
assert "SECRET" not in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_type", [{"private": "SECRET"}, "SECRET", None])
|
||||
def test_unknown_diagnostic_event_type_cannot_leak_or_raise(caplog, event_type):
|
||||
from app.modules.voice.diagnostics import diagnostic
|
||||
diagnostic(str(uuid4()), "provider_handle", "INVALID_PROVIDER_EVENT",
|
||||
event_type=event_type, exc=ValueError("SECRET"))
|
||||
assert "event=unknown" in caplog.text and "SECRET" not in caplog.text
|
||||
|
||||
|
||||
def test_http_stop_notification_is_normal_and_first_failure_stays_primary(runner, persisted):
|
||||
async def scenario():
|
||||
for failed in (False, True):
|
||||
runtime, _, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
sid = uuid4()
|
||||
registry.register(sid, "fixture", 1, uuid4(), runtime)
|
||||
try:
|
||||
if failed:
|
||||
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
registry.notify(session_id=sid, code="user_requested")
|
||||
await until(lambda: not runtime.usable)
|
||||
await asyncio.sleep(.01)
|
||||
assert runtime.failure == ("LIVE_PROVIDER_PROTOCOL_ERROR" if failed else None)
|
||||
if not failed:
|
||||
assert runtime.close_code == 1000
|
||||
assert not any(isinstance(e, dict) and e["type"] == "error" for e in out)
|
||||
finally:
|
||||
registry.unregister(sid)
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ending", ["timeout", "exception", "success"])
|
||||
def test_concurrent_shutdown_has_one_owner_and_safe_diagnostics(runner, persisted, caplog, ending):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
runtime.settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.03)
|
||||
started = asyncio.Event()
|
||||
calls = []
|
||||
async def close():
|
||||
calls.append(1)
|
||||
started.set()
|
||||
if ending == "timeout": await asyncio.Event().wait()
|
||||
if ending == "exception": raise ConnectionError("SECRET_CLOSE")
|
||||
wire.close = close
|
||||
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR", writable=False)
|
||||
waiter = asyncio.create_task(runtime.close())
|
||||
await started.wait()
|
||||
waiter.cancel()
|
||||
await asyncio.gather(waiter, return_exceptions=True)
|
||||
results = await asyncio.gather(runtime.close(), runtime.close(), return_exceptions=True)
|
||||
assert calls == [1] and runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert all(t.done() for t in runtime._workers)
|
||||
assert runtime._provider_close_task.done() and runtime._close_task.done()
|
||||
if ending == "success":
|
||||
assert results == [None, None]
|
||||
else:
|
||||
assert all(isinstance(x, (TimeoutError, ConnectionError)) for x in results)
|
||||
assert ("CLEANUP_TIMEOUT" if ending == "timeout" else "CLEANUP_FAILED") in caplog.text
|
||||
assert "SECRET_CLOSE" not in caplog.text
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_gemini_has_no_openai_item_normalization():
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport
|
||||
assert not hasattr(GeminiLiveAdapter(FakeGoogleTransport()), "normalize_output_item")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,reason", [
|
||||
("{", "MALFORMED_PROVIDER_JSON"),
|
||||
('{"type":"error","type":"session.updated"}', "DUPLICATE_PROVIDER_JSON_KEY"),
|
||||
("x" * 262145, "PROVIDER_FRAME_BOUND"),
|
||||
], ids=["malformed_json", "duplicate_key", "oversized_frame"])
|
||||
def test_provider_decode_failure_has_safe_specific_reason(caplog, raw, reason):
|
||||
from app.infrastructure.realtime import RealtimeAdapter, ProviderProtocolError
|
||||
from app.modules.voice.diagnostics import diagnostic, protocol_reason
|
||||
async def scenario():
|
||||
async def recv(): return raw
|
||||
adapter = RealtimeAdapter(SimpleNamespace(recv=recv))
|
||||
with pytest.raises(ProviderProtocolError) as error:
|
||||
await adapter.receive()
|
||||
diagnostic(str(uuid4()), "provider_receive", protocol_reason(error.value), exc=error.value)
|
||||
assert reason in caplog.text
|
||||
assert raw not in caplog.text
|
||||
asyncio.run(scenario())
|
||||
Reference in New Issue
Block a user