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:
@@ -87,7 +87,8 @@ def test_native_tool_correlation_canonical_result_and_once_only_continuation(set
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('message', [ConnectionError('remote-private-detail'), 'x'*262145,
|
||||
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}])
|
||||
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}],
|
||||
ids=['provider_loss', 'oversized_frame', 'unexpected_interruption', 'goaway'])
|
||||
def test_provider_loss_and_limits_wake_runtime_and_close_once(runner,persisted,message):
|
||||
async def scenario():
|
||||
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Controlled-clock synchronization races and private branch attribution."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, delta, done, until, commands,
|
||||
)
|
||||
from tests.unit.test_realtime_repairs import Clock, without_ticker
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal_first", [False, True])
|
||||
@pytest.mark.parametrize("verified", [False, True])
|
||||
def test_cancel_error_requires_verified_classification_and_terminal(
|
||||
runner, persisted, caplog, terminal_first, verified):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock,
|
||||
classifier=(lambda e: e.get("code") == "verified-fixture-race") if verified else None)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref, 100)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
if terminal_first:
|
||||
await done(runtime)
|
||||
await runtime.handle(dict(type="error", error=dict(
|
||||
event_id=runtime.responses["r1"].cancel_event,
|
||||
code="verified-fixture-race", message="SECRET_PROVIDER_ERROR")))
|
||||
if not verified:
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert "reason=CANCELLATION_PROVIDER_ERROR" in caplog.text
|
||||
assert "SECRET_PROVIDER_ERROR" not in caplog.text
|
||||
return
|
||||
assert runtime.usable
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
if not terminal_first:
|
||||
await done(runtime)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
truncation = commands(transport, "conversation.item.truncate")[0]
|
||||
assert truncation["audio_end_ms"] == 420
|
||||
assert audio.frozen
|
||||
ack = dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=420)
|
||||
await runtime.handle(ack)
|
||||
await runtime.handle(dict(ack, event_id="duplicate-ack"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
assert runtime.usable and audio.state == "retired"
|
||||
assert len(commands(transport, "response.cancel")) == 1
|
||||
assert len(commands(transport, "conversation.item.truncate")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("branch,reason", [
|
||||
("response", "RESPONSE_ACK_DEADLINE"),
|
||||
("input", "INPUT_COMMIT_DEADLINE"),
|
||||
("cancel", "CANCELLATION_ACK_DEADLINE"),
|
||||
("truncate", "TRUNCATION_ACK_DEADLINE"),
|
||||
])
|
||||
def test_deadline_diagnostic_identifies_branch(runner, persisted, caplog, branch, reason):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
if branch == "input":
|
||||
await input_turn(runtime, commit=False)
|
||||
deadline = runtime.current.input_deadline
|
||||
else:
|
||||
await input_turn(runtime)
|
||||
await until(lambda: commands(transport, "response.create"))
|
||||
if branch == "response":
|
||||
deadline = runtime.intent_deadline
|
||||
else:
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
if branch == "cancel":
|
||||
deadline = runtime.responses["r1"].cancel_deadline
|
||||
else:
|
||||
await done(runtime, status="cancelled")
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
deadline = next(iter(runtime.audio.values())).cleanup_deadline
|
||||
clock.now = deadline
|
||||
await runtime.tick()
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert runtime.session_id in caplog.text
|
||||
assert f"reason={reason}" in caplog.text
|
||||
assert "deadline_remaining_ms=0" in caplog.text
|
||||
assert "pending_commands=" in caplog.text
|
||||
if branch == "truncate":
|
||||
assert "sent_bytes=48000" in caplog.text
|
||||
assert "played_ms=0" in caplog.text
|
||||
before = caplog.text
|
||||
runtime.sync_failed("SECONDARY_FAILURE")
|
||||
assert caplog.text == before
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("position", [419, 421])
|
||||
def test_truncation_mismatch_diagnostic_remains_fail_closed(
|
||||
runner, persisted, caplog, position):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await done(runtime)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
assert not commands(transport, "response.cancel")
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=position))
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert "reason=TRUNCATION_ACK_POSITION_MISMATCH" in caplog.text
|
||||
assert "played_ms=420" in caplog.text
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_numeric_diagnostics_are_allowlisted_and_bounded(caplog):
|
||||
from app.modules.voice.diagnostics import diagnostic
|
||||
diagnostic("fixture-session", "context_sync", "TRUNCATION_PROVIDER_ERROR",
|
||||
sent_bytes=10**100, played_ms=True, transcript="SECRET_TRANSCRIPT",
|
||||
tool_result="SECRET_TOOL", pending_audio=3)
|
||||
assert "sent_bytes=2147483647" in caplog.text
|
||||
assert "pending_audio=3" in caplog.text
|
||||
assert "played_ms=" not in caplog.text
|
||||
assert "SECRET" not in caplog.text
|
||||
|
||||
|
||||
# Sanitized structured fields captured with gpt-realtime-mini/shimmer on
|
||||
# 2026-10-10; no raw provider events, audio, transcript, or credentials retained.
|
||||
CAPTURED_NO_ACTIVE = dict(type="invalid_request_error",
|
||||
code="response_cancel_not_active", param=None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal_order", ["before_error", "after_error", "missing"])
|
||||
def test_captured_selected_profile_cancellation_race(runner, persisted, terminal_order):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
error = dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
|
||||
event_id=runtime.responses["r1"].cancel_event))
|
||||
if terminal_order == "before_error":
|
||||
await done(runtime)
|
||||
await runtime.handle(error)
|
||||
assert runtime.usable
|
||||
await runtime.handle(dict(error, event_id="replayed-cancel-error"))
|
||||
assert runtime.usable
|
||||
if terminal_order == "missing":
|
||||
clock.now = runtime.responses["r1"].cancel_deadline
|
||||
await runtime.tick()
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert not commands(transport, "conversation.item.truncate")
|
||||
return
|
||||
if terminal_order == "after_error":
|
||||
await done(runtime)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
assert commands(transport, "conversation.item.truncate")[0]["audio_end_ms"] == 420
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=420))
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
await response(runtime, transport, response_id="r2")
|
||||
# Late duplicate cancellation errors cannot cancel the new response.
|
||||
await runtime.handle(dict(error, event_id="late-cancel-error"))
|
||||
assert runtime.usable and audio.state == "retired"
|
||||
assert not runtime.responses["r2"].interrupted
|
||||
assert len(commands(transport, "response.cancel")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", [
|
||||
dict(code="other_error"), dict(type="server_error"), dict(param="response_id"),
|
||||
dict(code="response_cancel_not_active_EXTRA"),
|
||||
dict(message="response_cancel_not_active", code="invalid_argument"),
|
||||
])
|
||||
def test_captured_classifier_rejects_other_errors(mutation):
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
adapter = RealtimeAdapter(Transport())
|
||||
assert adapter.is_no_active(CAPTURED_NO_ACTIVE)
|
||||
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, **mutation))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("profile", [
|
||||
dict(model="unverified-model"), dict(voice="unverified-voice"),
|
||||
])
|
||||
def test_captured_classifier_is_restricted_to_verified_profile(profile):
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
assert not RealtimeAdapter(Transport(), **profile).is_no_active(CAPTURED_NO_ACTIVE)
|
||||
|
||||
@pytest.mark.parametrize("failure", ["transport", "protocol"])
|
||||
def test_receive_failure_during_sync_keeps_category_and_private_reason(
|
||||
runner, persisted, caplog, failure):
|
||||
async def scenario():
|
||||
from app.infrastructure.realtime import ProviderProtocolError
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
async def broken():
|
||||
if failure == "transport":
|
||||
raise ConnectionError("SECRET_TRANSPORT")
|
||||
raise ProviderProtocolError("SECRET_PROTOCOL")
|
||||
runtime.adapter.receive = broken
|
||||
await runtime.receive_loop()
|
||||
expected = "LIVE_CONTEXT_SYNC_FAILED" if failure == "transport" else "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert runtime.failure == expected
|
||||
assert "SECRET" not in caplog.text
|
||||
if failure == "transport":
|
||||
assert "reason=PROVIDER_TRANSPORT_LOST_DURING_SYNC" in caplog.text
|
||||
assert "exception=ConnectionError" in caplog.text
|
||||
await asyncio.gather(runtime.close(), runtime.close())
|
||||
assert runtime.failure == expected and transport.closed
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["failed", "incomplete"])
|
||||
def test_terminal_technical_failure_is_not_accepted_as_cancellation_race(
|
||||
runner, persisted, status):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await done(runtime, status=status)
|
||||
await runtime.handle(dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
|
||||
event_id=runtime.responses["r1"].cancel_event)))
|
||||
assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -10,7 +10,7 @@ from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup, input_turn as gemini_input_turn
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
|
||||
@@ -80,18 +80,30 @@ def test_actual_authority_check_deadline(runner):
|
||||
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_ten_seconds_continuous_uncommitted_silence_keeps_frozen_bound(runner,persisted):
|
||||
def test_thirty_seconds_gemini_silence_keeps_transport_bounded(runner,persisted):
|
||||
async def scenario():
|
||||
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
for _ in range(100):
|
||||
for _ in range(300):
|
||||
await r.input_audio(bytes(4800))
|
||||
await until(lambda:r.input_transport_count==0 or not r.usable)
|
||||
async with asyncio.timeout(3):
|
||||
while r.input_transport_count and r.usable:
|
||||
await asyncio.sleep(0)
|
||||
assert r.usable,r.failure
|
||||
assert r.input_dispatched_total==480000
|
||||
assert r.input_dispatched_total==1440000
|
||||
assert r.uncommitted_speech_bytes == r.input_transport_bytes == 0
|
||||
assert not r.inputs and r.input_committed_total == 0
|
||||
await r.input_audio(bytes(2))
|
||||
assert r.failure=='LIVE_BUFFER_OVERFLOW'
|
||||
await until(lambda: r.input_transport_count == 0)
|
||||
assert r.usable and r.failure is None
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
await gemini_input_turn(r, wire, start=30000)
|
||||
await wire.inbound.put({'serverContent': {'modelTurn': {'parts': [
|
||||
{'inlineData': {'mimeType': 'audio/pcm;rate=24000', 'data': 'AAA='}}
|
||||
]}}})
|
||||
await until(lambda: r.current is not None and r.current.committed or not r.usable)
|
||||
assert r.usable and r.current.stop_boundary == 30100 * 48
|
||||
assert r.input_committed_total == r.current.stop_boundary
|
||||
finally:await cleanup(r,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@@ -1005,6 +1005,8 @@ def test_asr_completion_state_bounded_by_input_mapping_and_content_layout(runner
|
||||
limits = RuntimeSettings(_env_file=None, max_input_turns=2)
|
||||
runtime.settings = runtime.adapter.settings = limits
|
||||
try:
|
||||
await runtime.input_audio(bytes(144))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
for n in range(2):
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u" + str(n), audio_start_ms=n))
|
||||
|
||||
@@ -281,10 +281,12 @@ def test_input_buffer_survives_send_and_commit_releases_only_old_prefix(runner,
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_forwarded_input_buffer_overflow_without_commit(runner, persisted):
|
||||
def test_detected_forwarded_speech_overflow_without_commit(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="bounded", audio_start_ms=0))
|
||||
for _ in range(50):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Silence and speech lifecycle bounds through real runtime sender/event paths."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
make, until, input_turn, response, delta, done, runner, persisted,
|
||||
)
|
||||
|
||||
|
||||
async def stream(runtime, frames, now):
|
||||
for _ in range(frames):
|
||||
await runtime.input_audio(bytes(960))
|
||||
async with asyncio.timeout(3):
|
||||
while runtime.input_transport_count:
|
||||
await asyncio.sleep(0)
|
||||
now[0] += .02
|
||||
assert runtime.usable
|
||||
|
||||
|
||||
def test_silence_before_during_and_between_turns_preserves_absolute_positions(runner, persisted):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, transport, output = await make(SimpleNamespace(engine=None), runner, persisted,
|
||||
clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
assert runtime.input_forwarded_total == 1440000
|
||||
assert runtime.input_transport_bytes == runtime.uncommitted_speech_bytes == 0
|
||||
first = await input_turn(runtime, start=30000)
|
||||
assert first.stop_boundary == 30100 * 48
|
||||
assert runtime.input_committed_total == first.stop_boundary
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48))
|
||||
await until(lambda: any(isinstance(e, bytes) for e in output))
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref, 1)
|
||||
await stream(runtime, 1500, now)
|
||||
assert runtime.responses["r1"].terminal is False
|
||||
await done(runtime)
|
||||
await stream(runtime, 1500, now)
|
||||
start = runtime.input_dispatched_total // 48
|
||||
second = await input_turn(runtime, item="u2", start=start)
|
||||
assert second.stop_boundary == (start + 100) * 48
|
||||
assert second.committed and runtime.usable
|
||||
assert runtime.uncommitted_speech_bytes == 0
|
||||
assert all(cmd.pcm is None for cmd in runtime.pending_commands.values())
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ["stop", "commit"])
|
||||
def test_missing_speech_events_have_fixed_deadlines(runner, persisted, missing, caplog):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted,
|
||||
clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u1", audio_start_ms=30000))
|
||||
turn = runtime.current
|
||||
if missing == "commit":
|
||||
await runtime.input_audio(bytes(9600))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_stopped",
|
||||
item_id="u1", audio_end_ms=30200))
|
||||
deadline = turn.input_deadline
|
||||
else:
|
||||
deadline = turn.speech_deadline
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u1", audio_start_ms=30000))
|
||||
assert turn.speech_deadline == deadline
|
||||
now[0] = deadline + .001
|
||||
assert not runtime.check_deadlines()
|
||||
assert runtime.failure == ("LIVE_BUFFER_OVERFLOW" if missing == "stop"
|
||||
else "LIVE_CONTEXT_SYNC_FAILED")
|
||||
assert runtime.input_transport_bytes == 0
|
||||
assert ("SPEECH_STOP_DEADLINE" if missing == "stop" else
|
||||
"INPUT_COMMIT_DEADLINE") in caplog.text
|
||||
assert runtime.session_id in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_late_commit_does_not_release_new_speech_interval(runner, persisted):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
await input_turn(runtime, item="old", start=30000, commit=False)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="new", audio_start_ms=30150))
|
||||
before = runtime.uncommitted_speech_bytes
|
||||
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="old"))
|
||||
after = runtime.uncommitted_speech_bytes
|
||||
assert before - after == 100 * 48
|
||||
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="old"))
|
||||
assert runtime.uncommitted_speech_bytes == after
|
||||
assert not runtime.current.committed
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="old", audio_start_ms=30000))
|
||||
assert runtime.current.input_id == "new" and runtime.token == 2
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("branch", ["transport", "speech", "late_start"])
|
||||
def test_capacity_diagnostics_identify_the_failure_without_payloads(runner, persisted, caplog, branch):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
||||
try:
|
||||
if branch == "transport":
|
||||
# No sender scheduling: all admitted PCM remains queued.
|
||||
for _ in range(11):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
reason = "CAPTURE_TRANSPORT_CAPACITY"
|
||||
elif branch == "late_start":
|
||||
await stream(runtime, 1500, now)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="private-input-id", audio_start_ms=0))
|
||||
reason = "UNCOMMITTED_SPEECH_BYTES"
|
||||
else:
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="private-input-id", audio_start_ms=0))
|
||||
# Fixed clock isolates the byte bound from the independent wall deadline.
|
||||
for _ in range(50):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
async with asyncio.timeout(3):
|
||||
while runtime.input_transport_count:
|
||||
await asyncio.sleep(0)
|
||||
assert runtime.uncommitted_speech_bytes == 480000
|
||||
await runtime.input_audio(bytes(2))
|
||||
reason = "UNCOMMITTED_SPEECH_BYTES"
|
||||
assert runtime.failure == "LIVE_BUFFER_OVERFLOW" and runtime.close_code == 1013
|
||||
assert runtime.input_transport_bytes == runtime.input_transport_count == 0
|
||||
assert reason in caplog.text and runtime.session_id in caplog.text
|
||||
assert "limit_bytes=" in caplog.text and "occupancy_bytes=" in caplog.text
|
||||
assert "phase=capture_transport" in caplog.text if branch == "transport" else "phase=speaking" in caplog.text
|
||||
assert "private-input-id" not in caplog.text and "delta=" not in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -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