feat(voice): add bounded Realtime knowledge runtime

Connect OpenAI Realtime to the existing async StructuredTool and shared
SearchToolRunner with backend-owned authority and per-turn source references.
Add an operator-only smoke harness with persisted actor and provider opt-in.

Enforce confirmed readiness delivery, strict function identity, canonical
results and once-only continuations. Bound and pace generated audio, preserve
turn correlation, and require acknowledged cleanup before response release.
Handle Unicode arguments, UTF-8 replay budgets and user-ASR completion replays.

Validate with 318 voice/runner/shutdown tests and 1563 provider-free tests.
Three Windows symlink tests skip; 311 PostgreSQL tests are deselected.
Real-provider, browser playback and PostgreSQL acceptance remain unrun.
This commit is contained in:
amirhosein mazaheri
2026-10-08 18:06:03 +03:30
parent b50c920bfc
commit 9dac244590
13 changed files with 5303 additions and 0 deletions
+704
View File
@@ -0,0 +1,704 @@
"""Phase 1 repairs: provider events and budgets at explicit state boundaries."""
import asyncio
import base64
from copy import deepcopy
from types import SimpleNamespace
from uuid import uuid4
import pytest
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.runtime import VoiceRuntime
from tests.unit.test_realtime_phase1 import (
Transport, runner, persisted, make, input_turn, response, delta, done, until,
)
class Clock:
def __init__(self):
import time
self.now = time.monotonic()
def __call__(self):
return self.now
def advance(self, seconds):
self.now += seconds
def test_terminal_audio_cannot_become_playable_after_new_speech(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await done(runtime)
await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="u2", audio_start_ms=10))
await runtime.handle(delta(48))
assert not runtime.usable
assert not any(a.data for a in runtime.audio.values())
assert not [e for e in out if isinstance(e, bytes)]
finally:
await runtime.close()
asyncio.run(scenario())
def test_malformed_transcript_cannot_confirm_completion(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(dict(type="response.output_audio_transcript.done",
response_id="r1", item_id="a1", output_index=0, content_index=0,
transcript=["malformed"]))
assert not runtime.usable
assert not runtime.responses["r1"].transcript_completed
finally:
await runtime.close()
asyncio.run(scenario())
def test_setup_ack_after_deadline_cannot_beat_ticker(runner, persisted):
async def scenario():
clock, transport = Clock(), Transport()
async def trusted(_):
return True
async def sink(_):
pass
adapter = RealtimeAdapter(transport)
runtime = VoiceRuntime(adapter, SimpleNamespace(engine=None), runner,
uuid4(), sink, clock=clock, authority_check=trusted)
try:
await runtime.start()
await until(lambda: transport.sent)
clock.advance(31)
await runtime.handle(dict(type="session.updated", session=adapter.setup()["session"]))
assert not runtime.ready and not runtime.usable
finally:
await runtime.close()
asyncio.run(scenario())
def test_oversized_control_classified_before_schema_lookup(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await runtime.client_control(b"x" * 4097)
assert runtime.failure == "LIVE_FRAME_TOO_LARGE"
finally:
await runtime.close()
asyncio.run(scenario())
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json, json_size, SerializationLimit
from app.infrastructure.realtime import canonical_json
from tests.unit.test_realtime_phase1 import commands, terminal, message, call
async def without_ticker(runtime):
task = runtime._workers[-1]
task.cancel()
await asyncio.gather(task, return_exceptions=True)
@pytest.mark.parametrize("mutation", [
{"transcript": None}, {"transcript": 1}, {"transcript": {}},
{"content_index": True}, {"content_index": 1},
{"output_index": True}, {"output_index": 1},
{"item_id": "different"}, {"response_id": "unknown"},
])
def test_transcript_rebounds_and_types_never_complete(runner, persisted, mutation):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48))
event = dict(type="response.output_audio_transcript.done", response_id="r1",
item_id="a1", output_index=0, content_index=0, transcript="Valid")
event.update(mutation)
await runtime.handle(event)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert not runtime.responses["r1"].transcript_completed
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("condition", ["intent", "commit", "diagnostic", "cancel", "truncate"])
def test_late_acknowledgements_fail_before_ticker(runner, persisted, condition):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
try:
if condition == "diagnostic":
await runtime.diagnostic_text("Question")
await until(lambda: commands(transport, "conversation.item.create"))
turn = runtime.current
item = commands(transport, "conversation.item.create")[-1]["item"]
deadline = turn.input_deadline
event = dict(type="conversation.item.added", item=item)
elif condition == "commit":
await input_turn(runtime, commit=False)
turn = runtime.current
deadline = turn.input_deadline
event = dict(type="input_audio_buffer.committed", item_id="u1")
elif condition == "intent":
await input_turn(runtime)
await until(lambda: commands(transport, "response.create"))
turn = runtime.current
deadline = runtime.intent_deadline
event = dict(type="response.created", response=dict(id="late",
metadata=dict(voice_intent=runtime.pending_create[0])))
else:
turn = await input_turn(runtime)
await response(runtime, transport)
if condition == "truncate":
await runtime.handle(delta(48))
await until(lambda: next(iter(runtime.audio.values())).sent == 48)
await input_turn(runtime, "u2", 10)
await until(lambda: commands(transport, "response.cancel"))
old = runtime.responses["r1"]
if condition == "cancel":
deadline = old.cancel_deadline
event = terminal(status="cancelled")
else:
await done(runtime, status="cancelled")
clock.advance(1)
await runtime.tick()
await until(lambda: commands(transport, "conversation.item.truncate"))
audio = next(iter(runtime.audio.values()))
deadline = audio.cleanup_deadline
event = dict(type="conversation.item.truncated", item_id="a1",
content_index=0, audio_end_ms=0)
assert deadline is not None
clock.now = deadline
await runtime.handle(event)
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
errors = [entry.event for entry in runtime.controls if entry.event["type"] == "error"]
assert errors and errors[-1]["turn_ref"] == turn.ref
assert errors[-1]["error"]["retryable"] is False
assert len(commands(transport, "response.create")) <= 1
finally:
await runtime.close()
asyncio.run(scenario())
def test_setup_deadline_starts_at_dispatch_and_duplicate_ack_cannot_reset(runner):
async def scenario():
clock, transport = Clock(), Transport()
async def trusted(_): return True
async def sink(_): pass
runtime = VoiceRuntime(RealtimeAdapter(transport), SimpleNamespace(engine=None),
runner, uuid4(), sink, clock=clock, authority_check=trusted)
# Queue setup while the serialized sender is prevented from starting.
async with runtime.lock:
runtime.command(runtime.adapter.setup())
assert runtime.setup_deadline is None
clock.advance(4)
task = asyncio.create_task(runtime._sender())
try:
await until(lambda: transport.sent)
assert runtime.setup_deadline == clock.now + 30
clock.advance(29)
ack = dict(type="session.updated", session=runtime.adapter.setup()["session"])
await runtime.handle(ack)
await runtime.handle(ack)
assert runtime.provider_ready and not runtime.ready and runtime.usable and runtime.setup_deadline is None
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await runtime.close()
asyncio.run(scenario())
def test_queued_dispatch_expiry_cannot_be_rescued(runner):
async def scenario():
clock, transport = Clock(), Transport()
async def trusted(_): return True
async def sink(_): pass
runtime = VoiceRuntime(RealtimeAdapter(transport), SimpleNamespace(engine=None),
runner, uuid4(), sink, clock=clock, authority_check=trusted)
async with runtime.lock:
runtime.command(runtime.adapter.setup())
clock.advance(5)
assert runtime.setup_deadline is None
task = asyncio.create_task(runtime._sender())
try:
await runtime.failure_signal.wait()
assert runtime.failure == "LIVE_TRANSPORT_FAILED"
assert not transport.sent
finally:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("budget", ["bytes", "count"])
def test_input_admission_counts_inflight_before_encoding(runner, persisted, monkeypatch, budget):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
original = transport.send
async def blocked(wire):
if '"input_audio_buffer.append"' in wire:
entered.set()
await release.wait()
await original(wire)
transport.send = blocked
try:
size = 9600 if budget == "bytes" else 2
await runtime.input_audio(bytes(size))
await entered.wait()
count = 10 if budget == "bytes" else 100
for _ in range(count - 1):
await runtime.input_audio(bytes(size))
assert runtime.input_transport_count == count
assert runtime.input_transport_bytes == count * size
monkeypatch.setattr(base64, "b64encode", lambda _: pytest.fail("Rejected PCM encoded"))
await runtime.input_audio(bytes(size))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert runtime.input_transport_count == runtime.input_transport_bytes == 0
await runtime.close()
assert runtime.input_buffer_bytes == 0
await runtime.close()
assert runtime.input_transport_count == runtime.input_transport_bytes == 0
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
def test_input_buffer_survives_send_and_commit_releases_only_old_prefix(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
for _ in range(3):
await runtime.input_audio(bytes(9600))
await until(lambda: runtime.input_transport_count == 0)
assert runtime.input_buffer_bytes == runtime.forwarded_buffer_bytes == 28800
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="old", audio_start_ms=0))
await runtime.handle(dict(type="input_audio_buffer.speech_stopped", item_id="old", audio_end_ms=200))
await runtime.input_audio(bytes(9600))
await until(lambda: runtime.input_transport_count == 0)
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="new", audio_start_ms=300))
commit = dict(type="input_audio_buffer.committed", item_id="old")
await runtime.handle(commit)
await runtime.handle(commit)
assert runtime.input_buffer_bytes == runtime.forwarded_buffer_bytes == 28800
assert not runtime.current.committed and runtime.usable
finally:
await runtime.close()
asyncio.run(scenario())
def test_forwarded_input_buffer_overflow_without_commit(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
for _ in range(50):
await runtime.input_audio(bytes(9600))
await until(lambda: runtime.input_transport_count == 0)
assert runtime.forwarded_buffer_bytes == 480000
await runtime.input_audio(bytes(2))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert runtime.input_transport_bytes == runtime.input_buffer_bytes == 0
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("text", ["ط·آ·ط¢آ³ط·آ¸أ¢â‚¬â€چط·آ·ط¢آ§ط·آ¸أ¢â‚¬آ¦", "ط¸â€¹ط¹ط›ط¹آ©أ¢â€ڑآ¬", "\\\"\n", "a\x00b"])
def test_serialization_exact_escaping_bounds(text):
value = {"text": text}
wire = bounded_json(value, 1000)
assert len(wire.encode("utf-8")) == json_size(value, 1000)
assert __import__("json").loads(wire) == value
with pytest.raises(SerializationLimit):
bounded_json(value, len(wire.encode("utf-8")) - 1)
assert bounded_json(value, len(wire.encode("utf-8"))) == wire
@pytest.mark.parametrize("budget", ["count", "bytes", "event"])
def test_server_control_budget_includes_inflight_and_reserved_error(runner, persisted, budget):
async def scenario():
entered, release = asyncio.Event(), asyncio.Event()
out = []
async def sink(event):
if isinstance(event, dict) and event.get("type") == "probe":
entered.set()
await release.wait()
out.append(event)
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, emit=sink)
try:
await until(lambda: runtime.control_count == 0)
async with runtime.lock:
first = runtime.control(dict(type="probe", text="x"))
await entered.wait()
assert runtime.control_count == 1 and runtime.control_bytes == first.size
async with runtime.lock:
if budget == "count":
for _ in range(62):
runtime.control(dict(type="probe", text="x"))
assert runtime.usable and runtime.control_count == 63
runtime.control(dict(type="probe", text="overflow"))
elif budget == "event":
runtime.control(dict(type="probe", text="ط¸â€¹ط¹ط›ط¹آ©أ¢â€ڑآ¬" * 6000))
else:
for _ in range(5):
runtime.control(dict(type="probe", text="x" * 60000))
assert runtime.failure == ("LIVE_FRAME_TOO_LARGE" if budget == "event" else "LIVE_BUFFER_OVERFLOW")
assert runtime.control_count == 2 # in-flight and reserved failure only
assert runtime.control_bytes <= runtime.settings.max_control_bytes
release.set()
await runtime.error_delivered.wait()
error = next(e for e in out if e.get("type") == "error")
assert error["turn_ref"] is None and error["error"]["retryable"] is False
finally:
release.set()
await runtime.close()
assert runtime.control_count == runtime.control_bytes == 0
asyncio.run(scenario())
@pytest.mark.parametrize("changes", [
{"setup_timeout_seconds": 0}, {"setup_timeout_seconds": float("nan")},
{"send_timeout_seconds": float("inf")}, {"tool_timeout_seconds": 76},
{"max_binary_message_bytes": 9599}, {"max_binary_message_bytes": 9602},
{"output_credit_window_bytes": 2}, {"max_refs": 2, "max_unretired_refs": 3},
{"max_control_bytes": 2048}, {"max_control_messages": True},
{"max_provider_message_bytes": 4096},
{"setup_timeout_seconds": 1e20},
{"max_binary_message_bytes": 2, "output_credit_window_bytes": 2},
])
def test_invalid_runtime_settings_rejected(changes):
with pytest.raises(ValueError):
RuntimeSettings(_env_file=None, **changes)
def test_documented_setup_environment(monkeypatch):
assert RuntimeSettings(_env_file=None).setup_timeout_seconds == 30
monkeypatch.setenv("LIVE_SETUP_TIMEOUT_SECONDS", "12")
assert RuntimeSettings(_env_file=None).setup_timeout_seconds == 12
monkeypatch.setenv("LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS", "3")
limits = RuntimeSettings(_env_file=None)
assert limits.cancellation_timeout_seconds == limits.truncation_ack_timeout_seconds == 3
def test_control_readiness_precedes_size_and_parsing(runner):
async def scenario():
async def trusted(_): return True
async def sink(_): pass
runtime = VoiceRuntime(RealtimeAdapter(Transport()), SimpleNamespace(engine=None), runner,
uuid4(), sink, authority_check=trusted)
try:
await runtime.client_control(b"x" * 5000)
assert runtime.failure == "LIVE_NOT_READY"
assert runtime.close_code == 1008
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("kind,expected", [
("malformed", "LIVE_PROVIDER_PROTOCOL_ERROR"),
("unavailable", "LIVE_PROVIDER_UNAVAILABLE"),
("cleanup", "LIVE_CONTEXT_SYNC_FAILED"),
("send", "LIVE_TRANSPORT_FAILED"),
])
def test_separate_safe_failure_envelopes(runner, persisted, kind, expected):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
receiver = None
try:
turn = await input_turn(runtime)
await response(runtime, transport)
if kind == "cleanup":
await input_turn(runtime, "u2", 10)
if kind == "send":
async def broken(_): raise ConnectionError("PRIVATE provider response identifier")
transport.send = broken
await runtime.input_audio(bytes(48))
await runtime.failure_signal.wait()
else:
async def broken():
if kind == "malformed": return "not-json"
raise ConnectionError("PRIVATE provider response identifier")
transport.recv = broken
receiver = asyncio.create_task(runtime.receive_loop())
await runtime.failure_signal.wait()
assert runtime.failure == expected and runtime.close_code == 1011
await runtime.error_delivered.wait()
error = next(e for e in out if isinstance(e, dict) and e["type"] == "error")
assert error["turn_ref"] in (turn.ref, runtime.current.ref)
assert error["error"]["retryable"] is False
assert "PRIVATE" not in canonical_json(error)
finally:
if receiver:
receiver.cancel()
await asyncio.gather(receiver, return_exceptions=True)
await runtime.close()
asyncio.run(scenario())
from contextlib import nullcontext
from pydantic import SecretStr
from app.modules.knowledge import langchain_tool as boundary
@pytest.mark.parametrize("failure", ["failed", "incomplete", "session_error", "new_speech", "delivery"])
def test_smoke_never_succeeds_from_early_transcript(runner, persisted, monkeypatch, capsys, failure):
from app import voice_smoke
from app.modules.voice import runtime as runtime_module
monkeypatch.setattr(runtime_module, "transaction", lambda _: nullcontext(None))
monkeypatch.setattr(runtime_module, "authority", boundary.authority)
async def scenario():
entered, release = asyncio.Event(), asyncio.Event()
transport = Transport()
original_send = transport.send
async def send(raw):
await original_send(raw)
event = transport.sent[-1]
kind = event["type"]
events = []
if kind == "session.update":
events = [dict(type="session.updated", session=event["session"])]
elif kind == "conversation.item.create" and event["item"]["type"] == "message":
events = [dict(type="conversation.item.added", item=event["item"])]
elif kind == "response.create":
number = len(commands(transport, kind))
rid = "r" + str(number)
events = [dict(type="response.created", response=dict(id=rid,
metadata=event["response"]["metadata"]))]
if number == 1:
tool = call(response_id=rid)
events += [tool, terminal(rid, output=[dict(type="function_call",
id=tool["item_id"], call_id=tool["call_id"],
name=tool["name"], arguments=tool["arguments"])])]
else:
events += [dict(type="response.output_audio_transcript.done",
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0,
transcript="Early completed transcript")]
status = failure if failure in ("failed", "incomplete") else "completed"
events += [terminal(rid, status, [message(rid)])]
if failure == "session_error":
events += [dict(type="error", error=dict(code="fixture_unavailable"))]
elif failure == "new_speech":
events += [dict(type="input_audio_buffer.speech_started",
item_id="replacement", audio_start_ms=0)]
for event in events:
await transport.incoming.put(canonical_json(event))
transport.send = send
async def connection(*_): return transport
monkeypatch.setattr(voice_smoke, "connect", connection)
original_runtime = voice_smoke.VoiceRuntime
if failure == "delivery":
def runtime_factory(adapter, service, shared_runner, actor, emit, **kwargs):
async def gated(event):
if isinstance(event, dict) and event.get("role") == "assistant":
entered.set()
await release.wait()
raise ConnectionError("uncertain transcript delivery")
await emit(event)
return original_runtime(adapter, service, shared_runner, actor, gated, **kwargs)
monkeypatch.setattr(voice_smoke, "VoiceRuntime", runtime_factory)
config = SimpleNamespace(openai_api_key=SecretStr("not-a-key"),
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
service = SimpleNamespace(engine=None, search=lambda *_: dict(status="no_evidence", sources=[]))
task = asyncio.create_task(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4))
if failure == "delivery":
await asyncio.wait_for(entered.wait(), 2)
assert not task.done()
assert "smoke_correlation" not in capsys.readouterr().out
release.set()
assert await task == 1
assert "smoke_correlation" not in capsys.readouterr().out
assert transport.closed
asyncio.run(scenario())
@pytest.mark.parametrize("kind", ["cancel", "truncate"])
def test_cleanup_ack_deadline_belongs_to_actual_dispatch(runner, persisted, kind):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
entered, release = asyncio.Event(), asyncio.Event()
original = transport.send
async def blocked(wire):
if '"input_audio_buffer.append"' in wire:
entered.set()
await release.wait()
await original(wire)
try:
await input_turn(runtime)
await response(runtime, transport)
if kind == "truncate":
await runtime.handle(delta(50))
await until(lambda: next(iter(runtime.audio.values())).sent == 50)
await runtime.playback_progress(next(iter(runtime.audio.values())).ref, 1)
transport.send = blocked
await runtime.input_audio(bytes(48))
await entered.wait()
if kind == "cancel":
await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="u2", audio_start_ms=10))
target = runtime.responses["r1"]
assert target.cancel_deadline is None
else:
await runtime.handle(dict(type="response.output_audio.done",
response_id="r1", item_id="a1", output_index=0, content_index=0))
await done(runtime)
target = next(iter(runtime.audio.values()))
await until(lambda: target.cleanup is not None)
assert target.cleanup_deadline is None
clock.advance(4)
release.set()
await until(lambda: commands(transport, "response.cancel" if kind == "cancel"
else "conversation.item.truncate"))
deadline = target.cancel_deadline if kind == "cancel" else target.cleanup_deadline
assert deadline == clock.now + 5 and runtime.usable
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
def test_input_send_uncertainty_and_teardown_release_once(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
async def broken(_):
entered.set()
await release.wait()
raise ConnectionError("uncertain")
transport.send = broken
try:
await runtime.input_audio(bytes(9600))
await entered.wait()
await runtime.input_audio(bytes(9600))
assert runtime.input_transport_bytes == runtime.input_buffer_bytes == 19200
release.set()
await runtime.failure_signal.wait()
assert runtime.failure == "LIVE_TRANSPORT_FAILED"
assert runtime.input_transport_bytes == runtime.input_transport_count == 0
finally:
release.set()
await runtime.close()
await runtime.close()
assert runtime.command_bytes == runtime.command_count == 0
assert runtime.input_transport_bytes == runtime.input_transport_count == 0
asyncio.run(scenario())
def test_failure_close_survives_cancellation_and_runs_once(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
closes = []
async def blocked_close():
closes.append("close")
entered.set()
await release.wait()
transport.closed = True
transport.close = blocked_close
async with runtime.lock:
runtime.fail("LIVE_PROVIDER_UNAVAILABLE")
await entered.wait()
task = asyncio.create_task(runtime.close())
release.set()
await task
await runtime.close()
assert transport.closed and closes == ["close"]
assert runtime.control_bytes == runtime.control_count == 0
asyncio.run(scenario())
def test_queue_duration_environment_and_consistency(monkeypatch):
monkeypatch.setenv("LIVE_MAX_QUEUED_AUDIO_SECONDS", "1.5")
limits = RuntimeSettings(_env_file=None)
assert limits.max_queued_audio_bytes == 72000
monkeypatch.setenv("LIVE_MAX_QUEUED_AUDIO_SECONDS", "1")
with pytest.raises(ValueError):
RuntimeSettings(_env_file=None)
assert RuntimeSettings(_env_file=None, output_credit_window_bytes=48000).max_queued_audio_bytes == 48000
def test_invalid_smoke_configuration_never_connects(runner, monkeypatch):
from app import voice_smoke
async def forbidden(*_): pytest.fail("Provider connection before valid configuration")
monkeypatch.setattr(voice_smoke, "connect", forbidden)
config = SimpleNamespace(runtime_settings={"setup_timeout_seconds": 0})
with pytest.raises(ValueError):
asyncio.run(voice_smoke.run(SimpleNamespace(), runner, uuid4(), config, "q", 3, 4))
def test_duplicate_stop_does_not_restart_input_commit_deadline(runner, persisted):
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, commit=False)
deadline = runtime.current.input_deadline
clock.advance(5)
await runtime.handle(dict(type="input_audio_buffer.speech_stopped",
item_id="u1", audio_end_ms=100))
assert runtime.current.input_deadline == deadline
clock.now = deadline
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u1"))
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("budget", ["bytes", "count"])
def test_provider_command_queue_counts_inflight(runner, persisted, budget):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
original = transport.send
async def blocked(raw):
entered.set()
await release.wait()
await original(raw)
transport.send = blocked
try:
async with runtime.lock:
runtime.command(dict(type="probe", data="x"))
await entered.wait()
assert runtime.command_count == 1 and runtime.command_bytes > 0
async with runtime.lock:
if budget == "count":
for _ in range(63):
runtime.command(dict(type="probe", data="x"))
assert runtime.command_count == 64 and runtime.usable
runtime.command(dict(type="probe", data="overflow"))
else:
for _ in range(5):
runtime.command(dict(type="probe", data="x" * 60000))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert runtime.command_count == runtime.command_bytes == 0
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
def test_duplicate_audio_done_after_terminal_is_consistent(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48))
await until(lambda: next(iter(runtime.audio.values())).sent == 48)
event = dict(type="response.output_audio.done", response_id="r1",
item_id="a1", output_index=0, content_index=0)
await runtime.handle(event)
await done(runtime)
await runtime.handle(event)
assert runtime.usable
await runtime.handle(delta(48))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert next(iter(runtime.audio.values())).generated == 48
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("declared_type", ["message", "function_call"])
def test_transcript_cannot_replace_provider_announced_output(runner, persisted, declared_type):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
item = dict(id="announced", type=declared_type, role="assistant", content=[])
if declared_type == "function_call":
item["call_id"] = "announced-call"
await runtime.handle(dict(type="response.output_item.added", response_id="r1",
output_index=0, item=item))
assert runtime.usable
await runtime.handle(dict(type="response.output_audio_transcript.done", response_id="r1",
output_index=0, content_index=0,
item_id="substitute" if declared_type == "message" else "announced",
transcript="Invalid correlation"))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert not runtime.responses["r1"].transcript_completed
finally:
await runtime.close()
asyncio.run(scenario())