Files
rag-technical-docs-assistant/tests/unit/test_realtime_remaining.py
T
amirhosein mazaheri a769196bfa 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.
2026-10-10 17:41:11 +03:30

1115 lines
54 KiB
Python

"""Remaining Phase 1 boundary defects: cleanup, identity, wire bytes and empty audio."""
import asyncio
import json
from types import SimpleNamespace
import pytest
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice import runtime as runtime_module
from app.modules.voice.settings import RuntimeSettings
from tests.unit.test_realtime_phase1 import (
runner, persisted, make, input_turn, response, done, call, commands, until,
terminal, delta,
)
from tests.unit.test_realtime_repairs import Clock, without_ticker
from tests.unit.test_search_phase2 import service as canonical_service, row
@pytest.mark.parametrize("mode", ["raises", "timeout", "before", "client", "provider", "twice"])
def test_provider_cleanup_independent_of_client_and_cancellation(runner, persisted, mode):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
client_entered, provider_entered = asyncio.Event(), asyncio.Event()
provider_done, provider_release = asyncio.Event(), asyncio.Event()
client_cancelled = asyncio.Event()
provider_calls = []
if mode == "timeout":
runtime.settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.05)
async def close_client(code):
assert code == 1011
async with runtime.lock:
client_entered.set()
if mode == "raises":
raise ConnectionError("Client close failed")
try:
await asyncio.Event().wait()
finally:
client_cancelled.set()
async def close_provider():
async with runtime.lock:
provider_calls.append("close")
provider_entered.set()
if mode in ("provider", "twice"):
await provider_release.wait()
transport.closed = True
provider_done.set()
runtime.close_client = None if mode == "provider" else close_client
transport.close = close_provider
try:
async with runtime.lock:
runtime.fail("LIVE_PROVIDER_UNAVAILABLE", writable=False)
failure_task = next(iter(runtime.tasks))
if mode == "before":
failure_task.cancel()
if mode in ("client", "twice"):
await asyncio.wait_for(client_entered.wait(), 1)
failure_task.cancel()
elif mode == "provider":
await asyncio.wait_for(provider_entered.wait(), 1)
failure_task.cancel()
if mode == "twice":
await asyncio.wait_for(provider_entered.wait(), 1)
failure_task.cancel()
result = await asyncio.wait_for(asyncio.gather(failure_task, return_exceptions=True), 1)
if mode in ("before", "client", "provider", "twice"):
assert isinstance(result[0], asyncio.CancelledError)
if mode == "timeout":
assert client_cancelled.is_set()
provider_release.set()
await asyncio.wait_for(provider_done.wait(), 1)
assert provider_calls == ["close"]
assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE" and not runtime.usable
await runtime.close()
await runtime.close()
assert provider_calls == ["close"]
finally:
provider_release.set()
await runtime.close()
asyncio.run(scenario())
def test_two_calls_cannot_share_function_item(runner, persisted):
searches = []
def search(*args):
searches.append(args)
return dict(status="no_evidence", sources=[])
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
first = call()
await runtime.handle(first)
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
await runtime.handle(dict(first, call_id="c2"))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert set(runtime.calls) == {"c1"}
assert len(searches) == 1
assert not commands(transport, "conversation.item.create")
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("invalid", ["", "x" * 129, None, 1, True, [], {}, "\u0641"])
@pytest.mark.parametrize("valid_first", [False, True])
def test_terminal_call_ids_validated_before_any_tool_work(runner, persisted, monkeypatch, invalid, valid_first):
built, searched = [], []
original = runtime_module.create_search_tool
def factory(*args):
built.append(True)
return original(*args)
def search(*args):
searched.append(True)
return dict(status="no_evidence", sources=[])
monkeypatch.setattr(runtime_module, "create_search_tool", factory)
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
output = [dict(type="function_call", id="bad-item", call_id=invalid,
name="search_knowledge", arguments='{"query":"q"}')]
if valid_first:
output.insert(0, dict(type="function_call", id="valid-item", call_id="valid",
name="search_knowledge", arguments='{"query":"q"}'))
await runtime.handle(terminal(output=output))
tasks = list(runtime.tasks)
if tasks:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 3)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert built == searched == []
assert not runtime.calls
assert not commands(transport, "conversation.item.create")
finally:
await runtime.close()
asyncio.run(scenario())
def test_four_full_persian_results_fit_actual_wire_budget(settings, monkeypatch, runner, persisted):
service = canonical_service(settings, monkeypatch, [row(text="\u0633" * 12000)])
async def scenario():
runtime, transport, _ = await make(service, runner, persisted)
entered, resume = asyncio.Event(), asyncio.Event()
wires = []
send = transport.send
async def blocked(wire):
wires.append(wire)
if json.loads(wire).get("item", {}).get("type") == "function_call_output":
entered.set()
await resume.wait()
await send(wire)
try:
await input_turn(runtime)
await response(runtime, transport)
transport.send = blocked
for n in range(4):
await runtime.handle(call(call_id="c" + str(n)))
await until(lambda: len(runtime.calls) == 4 and
all(c["result"] is not None for _, c in runtime.calls.values()))
await done(runtime)
await until(lambda: entered.is_set() or not runtime.usable)
assert runtime.usable
reserved = {cmd.event["event_id"]: cmd.size for cmd in runtime.pending_commands.values()}
assert runtime.command_bytes == sum(reserved.values())
assert runtime.command_bytes < runtime.settings.max_control_bytes
resume.set()
await until(lambda: len(commands(transport, "response.create")) == 2)
sent = [wire for wire in wires if json.loads(wire)["event_id"] in reserved]
assert len(sent) == len(reserved)
for wire in sent:
assert len(wire.encode("utf-8")) == reserved[json.loads(wire)["event_id"]]
outputs = [json.loads(e["item"]["output"]) for e in commands(transport, "conversation.item.create")]
assert len(outputs) == 4
for result in outputs:
assert result["status"] == "ok"
assert result["sources"][0]["text"] == "\u0633" * 12000
assert result["sources"][0]["source_ref"] == "S1"
assert runtime.command_bytes == runtime.command_count == 0
finally:
resume.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("empty_delta", [False, True])
def test_empty_completed_audio_seals_without_false_interruption(runner, persisted, empty_delta):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
try:
first = await input_turn(runtime)
await response(runtime, transport)
if empty_delta:
await runtime.handle(delta(0))
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
item_id="a1", output_index=0, content_index=0))
await runtime.handle(dict(type="response.output_audio_transcript.done", response_id="r1",
item_id="a1", output_index=0, content_index=0, transcript="Completed"))
await done(runtime)
# No scheduler yield: new speech can win before zero-byte markers are sent.
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u2", audio_start_ms=10))
assert not first.superseded and not runtime.responses["r1"].interrupted
audio = next(iter(runtime.audio.values()))
await until(lambda: audio.state == "retired")
assert (audio.generated, audio.sent, audio.played, audio.credit, audio.reserved) == (0, 0, 0, 0, 0)
assert audio.cleanup is None and audio.timer is None
assert not [e for e in out if isinstance(e, bytes)]
markers = [e for e in out if e.get("type") in ("audio_started", "audio_ended")]
assert [e["type"] for e in markers] == ["audio_started", "audio_ended"]
assert markers[0]["audio_ref"] == markers[1]["audio_ref"] == audio.ref
assert markers[1]["sent_bytes"] == 0
assert not [e for e in out if e.get("type") == "turn_interrupted"]
assert not commands(transport, "response.cancel")
assert not commands(transport, "conversation.item.truncate")
finally:
await runtime.close()
asyncio.run(scenario())
from app.modules.voice.serialization import bounded_json, json_size, SerializationLimit
@pytest.mark.parametrize("value", [
"ASCII", "\u0633\u0644\u0627\u0645", 'quote" and backslash\\',
"\x00\b\f\n\r\t\x1f\x7f", "\U0001f642\u2028",
])
@pytest.mark.parametrize("ascii_policy", [False, True])
def test_serialization_budget_matches_standard_json_bytes(value, ascii_policy):
event = dict(text=value, fields=[value, True, None, 1.5])
expected = json.dumps(event, ensure_ascii=ascii_policy, allow_nan=False,
separators=(",", ":"), sort_keys=True)
size = len(expected.encode("utf-8"))
assert json_size(event, size, ensure_ascii=ascii_policy) == size
assert bounded_json(event, size, ensure_ascii=ascii_policy) == expected
with pytest.raises(SerializationLimit):
bounded_json(event, size - 1, ensure_ascii=ascii_policy)
@pytest.mark.parametrize("boundary", ["frame_exact", "frame_over", "queue_exact", "queue_over"])
def test_command_budget_uses_immutable_actual_wire(runner, persisted, boundary):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
limits = RuntimeSettings(_env_file=None, max_server_event_bytes=1024,
max_provider_message_bytes=16384, max_control_bytes=32768)
runtime.settings = runtime.adapter.settings = limits
entered, resume, finished = asyncio.Event(), asyncio.Event(), asyncio.Event()
wires = []
original = transport.send
async def blocked(wire):
wires.append(wire)
entered.set()
await resume.wait()
await original(wire)
finished.set()
transport.send = blocked
event = dict(type="probe", event_id="fixed-wire-id", payload=dict(
text='\u0633"\\\n\x00\x7f\U0001f642'))
def wire(value):
return json.dumps(value, ensure_ascii=False, allow_nan=False,
separators=(",", ":"), sort_keys=True)
target = 16385 if boundary == "frame_over" else 16384
event["payload"]["text"] += "x" * (target - len(wire(event).encode("utf-8")))
expected = wire(event)
try:
async with runtime.lock:
first = runtime.command(event)
if boundary == "frame_over":
assert first is None and runtime.failure == "LIVE_FRAME_TOO_LARGE"
assert not wires
return
assert first.size == len(expected.encode("utf-8")) == 16384
# Neither reservation nor transmitted bytes may change after admission.
event["payload"]["text"] = "mutated by caller"
await asyncio.wait_for(entered.wait(), 1)
assert wires == [expected]
async with runtime.lock:
assert runtime.command_bytes == len(wires[0].encode("utf-8"))
if boundary.startswith("queue"):
second_event = json.loads(expected)
second_event["event_id"] = "next--wire-id"
# Same identifier length keeps the second actual frame at the boundary.
second = runtime.command(second_event)
assert second.size == len(wire(second_event).encode("utf-8"))
assert runtime.command_bytes == 32768 and runtime.command_count == 2
if boundary == "queue_over":
runtime.command(dict(type="probe", event_id="overflow"))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert runtime.command_bytes == runtime.command_count == 0
resume.set()
await asyncio.wait_for(finished.wait(), 1)
await until(lambda: runtime.command_count == 0)
if boundary != "queue_over":
assert runtime.usable
assert runtime.command_bytes == 0
assert sum(len(w.encode("utf-8")) for w in wires) == (
32768 if boundary == "queue_exact" else 16384)
finally:
resume.set()
await runtime.close()
assert runtime.command_count == runtime.command_bytes == 0
asyncio.run(scenario())
@pytest.mark.parametrize("change", ["call_id", "item_id"])
def test_announced_function_identity_cannot_rebind_before_dispatch(runner, persisted, change):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None,
search=lambda *_: pytest.fail("Rebound announcement reached search")), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(dict(type="response.output_item.added", response_id="r1",
output_index=0, item=dict(id="f_c1", type="function_call", call_id="c1",
name="search_knowledge", arguments="")))
bad = call()
bad[change] = "different"
await runtime.handle(bad)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert not runtime.calls
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("case", ["unfinished_response", "missing_audio_done", "bad_terminal_item"])
def test_empty_audio_does_not_bypass_terminal_or_interruption(runner, persisted, case):
async def scenario():
clock = Clock()
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
await without_ticker(runtime)
try:
first = await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(0))
if case != "missing_audio_done":
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
item_id="a1", output_index=0, content_index=0))
await runtime.handle(dict(type="response.output_audio_transcript.done", response_id="r1",
item_id="a1", output_index=0, content_index=0, transcript="Early transcript"))
if case == "bad_terminal_item":
await runtime.handle(terminal(output=[]))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
else:
if case == "missing_audio_done":
await done(runtime)
await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="u2", audio_start_ms=10))
assert first.superseded and runtime.responses["r1"].interrupted
if case == "unfinished_response":
await until(lambda: commands(transport, "response.cancel"))
assert commands(transport, "response.cancel")[-1]["response_id"] == "r1"
assert runtime.usable
assert not [e for e in out if isinstance(e, bytes)]
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("mode", ["provider_raises", "both_timeout"])
def test_cleanup_failures_have_independent_bounds_and_preserve_failure(runner, persisted, mode):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.05)
client_cancelled, provider_cancelled = asyncio.Event(), asyncio.Event()
calls = []
async def client(_):
if mode == "provider_raises":
raise ConnectionError("client")
try:
await asyncio.Event().wait()
finally:
client_cancelled.set()
async def provider():
async with runtime.lock:
calls.append("provider")
if mode == "provider_raises":
raise ConnectionError("provider")
assert client_cancelled.is_set()
try:
await asyncio.Event().wait()
finally:
provider_cancelled.set()
runtime.close_client, transport.close = client, provider
async with runtime.lock:
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR", writable=False)
task = next(iter(runtime.tasks))
await asyncio.wait_for(task, 1)
assert calls == ["provider"] and not runtime._provider_closed
assert not runtime.usable and runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
if mode == "both_timeout":
assert client_cancelled.is_set() and provider_cancelled.is_set()
for _ in range(2):
with pytest.raises((TimeoutError, ConnectionError)):
await runtime.close()
assert calls == ["provider"]
asyncio.run(scenario())
def test_cancellation_while_error_send_waits_still_closes_provider(runner, persisted):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
entered, closed = asyncio.Event(), asyncio.Event()
calls = []
async def emit(event):
if event.get("type") == "error":
entered.set()
await asyncio.Event().wait()
async def provider():
async with runtime.lock:
calls.append("close")
closed.set()
runtime.emit, transport.close = emit, provider
try:
async with runtime.lock:
runtime.fail("LIVE_PROVIDER_UNAVAILABLE")
task = next(iter(runtime.tasks))
await asyncio.wait_for(entered.wait(), 1)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await asyncio.wait_for(closed.wait(), 1)
assert calls == ["close"] and not runtime.usable
finally:
await runtime.close()
assert calls == ["close"]
asyncio.run(scenario())
# Readiness delivery and malformed Unicode model arguments.
from copy import deepcopy
from uuid import uuid4
from app.modules.voice.runtime import VoiceRuntime
from tests.unit.test_realtime_phase1 import Transport
async def pending_ready(runner, persisted, sink, clock=None, settings=None):
transport = Transport()
adapter = RealtimeAdapter(transport, settings=settings)
async def trusted(execution):
return execution.capture(dict(id=execution.user_id, organization_id="fixture", role="user"),
persisted["epoch"])
kwargs = dict(authority_check=trusted)
if clock is not None:
kwargs["clock"] = clock
runtime = VoiceRuntime(adapter, SimpleNamespace(engine=None), runner, uuid4(), sink,
**kwargs)
await runtime.start()
await until(lambda: commands(transport, "session.update"))
await runtime.handle(dict(type="session.updated", session=deepcopy(adapter.setup()["session"])))
return runtime, transport
@pytest.mark.parametrize("payload", ["audio", "control", "malformed-control", "oversized-control"])
def test_pending_readiness_rejects_payload_without_reservation(runner, persisted, payload):
async def scenario():
entered, release, completed = asyncio.Event(), asyncio.Event(), asyncio.Event()
publications = []
async def sink(event):
if event["type"] == "session_ready":
publications.append(event)
entered.set()
await release.wait()
completed.set()
runtime, transport = await pending_ready(runner, persisted, sink)
try:
await asyncio.wait_for(entered.wait(), 1)
assert not completed.is_set()
if payload == "audio":
await runtime.input_audio(bytes(48))
else:
raw = (b'{"type":"playback_progress","audio_ref":"absent","played_ms":0}'
if payload == "control" else b"{" if payload == "malformed-control" else b"x" * 4097)
await runtime.client_control(raw)
assert runtime.failure == "LIVE_NOT_READY"
assert runtime.close_code == 1008 and not runtime.ready
assert runtime.input_admitted_total == runtime.input_dispatched_total == runtime.input_forwarded_total == 0
assert runtime.input_transport_bytes == runtime.input_transport_count == 0
assert not commands(transport, "input_audio_buffer.append")
release.set()
await asyncio.wait_for(completed.wait(), 1)
await until(lambda: runtime.active_control is None)
assert not runtime.ready and not runtime.usable
assert len(publications) == 1
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
def test_successful_ready_delivery_opens_admission_once_and_keeps_private_events(runner, persisted):
async def scenario():
entered, release = asyncio.Event(), asyncio.Event()
delivered = []
async def sink(event):
if event["type"] == "session_ready":
entered.set()
await release.wait()
delivered.append(event)
runtime, transport = await pending_ready(runner, persisted, sink)
try:
await asyncio.wait_for(entered.wait(), 1)
assert not runtime.ready and runtime.usable
ack = dict(type="session.updated", session=runtime.adapter.setup()["session"])
await runtime.handle(ack)
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u1", audio_start_ms=0))
assert runtime.usable and runtime.current.input_id == "u1"
assert not runtime.pending_create
assert not commands(transport, "input_audio_buffer.append")
release.set()
await until(lambda: runtime.ready)
assert len([e for e in delivered if e["type"] == "session_ready"]) == 1
await runtime.handle(ack)
await input_turn(runtime)
await response(runtime, transport)
assert commands(transport, "input_audio_buffer.append")
assert len([e for e in delivered if e["type"] == "session_ready"]) == 1
assert runtime.usable
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("mode", ["raises", "timeout", "cancel-task", "cancel-sink", "late", "expired"])
def test_unsuccessful_ready_delivery_never_opens_admission(runner, persisted, mode):
async def scenario():
clock = Clock()
entered, release, cancelled = asyncio.Event(), asyncio.Event(), asyncio.Event()
async def sink(event):
if event["type"] != "session_ready":
return
entered.set()
try:
await release.wait()
if mode == "raises":
raise ConnectionError("uncertain readiness")
if mode == "cancel-sink":
raise asyncio.CancelledError()
finally:
cancelled.set()
settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.05) if mode == "timeout" else None
runtime, transport = await pending_ready(runner, persisted, sink, clock, settings)
try:
await asyncio.wait_for(entered.wait(), 1)
assert not runtime.ready
if mode == "cancel-task":
runtime._workers[1].cancel()
elif mode == "late":
async with runtime.lock:
runtime.fail("LIVE_PROVIDER_UNAVAILABLE", writable=False)
release.set()
elif mode == "expired":
clock.advance(runtime.settings.send_timeout_seconds)
release.set()
elif mode != "timeout":
release.set()
await until(lambda: not runtime.usable)
await asyncio.wait_for(cancelled.wait(), 1)
assert runtime.failure == ("LIVE_PROVIDER_UNAVAILABLE" if mode == "late" else "LIVE_TRANSPORT_FAILED")
assert not runtime.ready
await runtime.input_audio(bytes(48))
assert not commands(transport, "input_audio_buffer.append")
await runtime.handle(dict(type="session.updated", session=runtime.adapter.setup()["session"]))
assert not runtime.ready
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("field", ["query", "context", "extra", "extra-key"])
@pytest.mark.parametrize("surrogate", ["\ud800", "\udfff"])
@pytest.mark.parametrize("representation", ["escaped", "decoded"])
@pytest.mark.parametrize("terminal_first", [False, True])
def test_invalid_unicode_arguments_are_canonical_replayable_errors(
runner, persisted, monkeypatch, field, surrogate, representation, terminal_first):
payload = {"query": "q"}
if field == "extra-key":
payload[surrogate] = "forged"
else:
payload[field] = surrogate
raw = json.dumps(payload, ensure_ascii=representation == "escaped")
builds = []
actual = runtime_module.create_search_tool
def build(*args):
builds.append(True)
return actual(*args)
monkeypatch.setattr(runtime_module, "create_search_tool", build)
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Invalid Unicode retrieval"))
async def scenario():
runtime, transport, out = await make(service, runner, persisted)
async def wire(event):
# Receive real JSON text through the actual adapter, including escaped surrogate code units.
await transport.incoming.put(json.dumps(event, ensure_ascii=True))
await runtime.handle(await runtime.adapter.receive())
event = dict(call(raw=raw), event_id="unicode-call")
output = [dict(type="function_call", id=event["item_id"], call_id="c1",
name="search_knowledge", arguments=raw)]
ending = dict(terminal(output=output), event_id="unicode-terminal")
try:
await input_turn(runtime)
await response(runtime, transport)
await wire(ending if terminal_first else event)
assert runtime.usable and runtime.calls["c1"][1]["result"]["error"]["code"] == "INVALID_TOOL_ARGUMENTS"
await wire(ending if terminal_first else event)
if not terminal_first:
await wire(dict(event, event_id="unicode-replay"))
await wire(ending)
else:
await wire(event)
await until(lambda: len(commands(transport, "response.create")) == 2)
assert builds == []
assert runner._admitted == runner._active == 0
assert len(runtime.calls) == 1
items = [e["item"] for e in commands(transport, "conversation.item.create")]
assert len(items) == 1 and items[0]["call_id"] == "c1"
result = json.loads(items[0]["output"])
assert result == runtime.calls["c1"][1]["result"]
assert result["status"] == "error" and result["sources"] == []
assert surrogate not in items[0]["output"]
errors = [e for e in out if e["type"] == "error"]
assert all(e["error"]["code"] == "INVALID_TOOL_ARGUMENTS" for e in errors)
assert all(surrogate not in json.dumps(e) for e in errors)
assert runtime.usable
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("raw,query", [
('{"query":"\\ud83d\\ude00","context":"\\u0633\\u0644\\u0627\\u0645"}', "\U0001f600"),
(json.dumps(dict(query="\u0633\u0644\u0627\u0645"), ensure_ascii=False), "\u0633\u0644\u0627\u0645"),
])
def test_valid_unicode_uses_actual_tool_and_normalized_hash(runner, persisted, raw, query):
searches = []
expected = dict(status="no_evidence", knowledge_revision=2, sources=[], warnings=["insufficient_support"])
def search(execution, text, context=None):
searches.append((execution, text, context))
return expected
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
try:
turn = await input_turn(runtime)
await response(runtime, transport)
event = call(raw=raw)
await runtime.handle(event)
normalized = json.dumps(json.loads(raw), ensure_ascii=False, indent=2)
await runtime.handle(dict(event, arguments=normalized))
await done(runtime)
await until(lambda: len(commands(transport, "response.create")) == 2)
assert len(searches) == 1 and searches[0][0] is turn.execution and searches[0][1] == query
item = commands(transport, "conversation.item.create")[0]["item"]
assert item["call_id"] == "c1" and json.loads(item["output"]) == expected
assert runtime.usable
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("changed", ["argument", "correlation", "framing"])
def test_unicode_rejections_do_not_relax_provider_protocol(runner, persisted, changed):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
event = call(raw='{"query":"\\ud800"}')
await runtime.handle(event)
assert runtime.usable
if changed == "argument":
await runtime.handle(dict(event, arguments='{"query":"\\udfff"}'))
elif changed == "correlation":
await runtime.handle(dict(event, call_id="bad\ud800"))
else:
await transport.incoming.put('{"type":')
with pytest.raises(ValueError):
await runtime.adapter.receive()
# The runtime receive loop retains its framing error mapping.
await transport.incoming.put('{"type":')
await runtime.receive_loop()
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("path", ["arguments", "terminal", "announced"])
def test_surrogate_event_fingerprint_distinguishes_replacement_and_conflicting_replay(runner, persisted, path):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
raw = json.dumps(dict(query=chr(0xD800)), ensure_ascii=False)
if path == "arguments":
event = dict(call(raw=raw), event_id="same-event")
elif path == "terminal":
event = dict(terminal(output=[dict(type="function_call", id="f_c1", call_id="c1",
name="search_knowledge", arguments=raw)]), event_id="same-event")
else:
event = dict(type="response.output_item.added", response_id="r1", output_index=0,
item=dict(type="function_call", id="f_c1", call_id="c1",
name="search_knowledge", arguments=raw), event_id="same-event")
await runtime.handle(event)
assert runtime.usable
await runtime.handle(event)
changed = json.loads(json.dumps(event).replace("d800", "fffd"))
await runtime.handle(changed)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
finally:
await runtime.close()
asyncio.run(scenario())
def test_cancelled_delivery_before_first_step_cannot_strand_readiness(runner, persisted):
async def scenario():
transport = Transport()
async def trusted(_): return True
async def sink(_): pytest.fail("Cancelled readiness was delivered")
runtime = VoiceRuntime(RealtimeAdapter(transport), SimpleNamespace(engine=None), runner,
uuid4(), sink, authority_check=trusted)
try:
# Hold the serialized decision until cancellation is queued, before any worker can start.
async with runtime.lock:
runtime.provider_ready = True
runtime.control(dict(type="session_ready", session_id=runtime.session_id))
delivery = asyncio.create_task(runtime._delivery())
delivery.add_done_callback(runtime._delivery_finished)
runtime._workers.append(delivery)
delivery.cancel()
await until(lambda: not runtime.usable)
assert not runtime.ready and runtime.failure == "LIVE_TRANSPORT_FAILED"
await runtime.input_audio(bytes(48))
assert runtime.input_admitted_total == 0
assert not commands(transport, "input_audio_buffer.append")
finally:
await runtime.close()
asyncio.run(scenario())
# Provider wire replay budgets and per-input ASR completion identity.
from app.infrastructure.realtime import ProviderProtocolError
async def received(runtime, transport, wire):
await transport.incoming.put(wire)
await runtime.handle(await runtime.adapter.receive())
def user_asr(item, text, event_id, completed=True):
event = dict(type="conversation.item.input_audio_transcription." +
("completed" if completed else "delta"),
item_id=item, content_index=0)
event["transcript" if completed else "delta"] = text
if event_id is not None:
event["event_id"] = event_id
return event
@pytest.fixture
def replay_runner():
# Production process-wide admission: four running plus eight waiting.
from app.modules.knowledge.langchain_tool import SearchToolRunner
value = SearchToolRunner()
yield value
value.close()
def terminal_wire(event, size):
if size == 92793:
wire = json.dumps(event, ensure_ascii=False, separators=(",", ":"))
assert len(wire.encode("utf-8")) <= size
return wire + " " * (size - len(wire.encode("utf-8")))
# Shortest input float spelling can be smaller than canonical JSON.
event = dict(event, wire_number=1e-9, wire_padding="")
def encode():
return json.dumps(event, ensure_ascii=False, separators=(",", ":")).encode(
"utf-8", errors="backslashreplace").decode("utf-8").replace(
'"wire_number":1e-09', '"wire_number":1e-9')
base = encode()
assert len(base.encode("utf-8")) <= size
event["wire_padding"] = "x" * (size - len(base.encode("utf-8")))
wire = encode()
assert len(wire.encode("utf-8")) == size
return wire
@pytest.mark.parametrize("size", [92793, 262144, 262145])
@pytest.mark.parametrize("rows", [True, False])
def test_provider_utf8_multicall_wire_budget_and_matching_results(
settings, monkeypatch, replay_runner, persisted, size, rows):
service = canonical_service(settings, monkeypatch, [row()] if rows else [])
searches = []
original_search = service.search
def search(execution, query, context=None):
searches.append((execution, query, context))
return original_search(execution, query, context)
service.search = search
raw = json.dumps(dict(query="\u0633" * 1900, context="\u0645" * 1900),
ensure_ascii=False, separators=(",", ":"))
assert len(raw.encode("utf-8")) == 7625
async def scenario():
runtime, transport, _ = await make(service, replay_runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
original_send = transport.send
async def send(wire):
if json.loads(wire).get("item", {}).get("type") == "function_call_output":
entered.set()
await release.wait()
await original_send(wire)
try:
turn = await input_turn(runtime)
await response(runtime, transport)
transport.send = send
output = [dict(type="function_call", id="f_" + chr(97 + n), call_id=chr(97 + n),
name="search_knowledge", arguments=raw) for n in range(12)]
ending = dict(terminal(output=output), event_id="first")
wire = terminal_wire(ending, size)
if size > runtime.settings.max_provider_message_bytes:
await transport.incoming.put(wire)
with pytest.raises(ProviderProtocolError):
await runtime.adapter.receive()
await transport.incoming.put(wire)
await runtime.receive_loop()
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert searches == [] and runtime.calls == {}
return
await received(runtime, transport, wire)
assert runtime.usable
await asyncio.wait_for(entered.wait(), 3)
await received(runtime, transport, wire)
await received(runtime, transport, wire.replace('"event_id":"first"', '"event_id":"again"'))
# Canonically equivalent query/context still coalesce with the terminal call.
replay = call(call_id="a", raw=json.dumps(json.loads(raw), ensure_ascii=False, indent=2))
await received(runtime, transport, json.dumps(replay, ensure_ascii=False))
assert runtime.usable and len(runtime.calls) == 12
release.set()
await until(lambda: len(commands(transport, "response.create")) == 2)
items = [e["item"] for e in commands(transport, "conversation.item.create")]
assert len(items) == 12 and {item["call_id"] for item in items} == {chr(97 + n) for n in range(12)}
assert len(searches) == 12 and all(execution is turn.execution for execution, _, _ in searches)
results = [json.loads(item["output"]) for item in items]
assert all(result == results[0] for result in results)
assert results[0]["status"] == ("ok" if rows else "no_evidence")
if rows:
assert results[0]["sources"][0]["source_ref"] == "S1"
for item in items:
assert json.loads(item["output"]) == runtime.calls[item["call_id"]][1]["result"]
assert runtime.calls[item["call_id"]][0].id == "r1"
assert runtime.command_count == runtime.command_bytes == 0
# A changed same-ID terminal replay is fatal and cannot cause more retrieval/output.
changed = wire.replace("\u0633", "\u0646", 1)
await received(runtime, transport, changed)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert len(searches) == len(items) == 12
assert len(commands(transport, "response.create")) == 2
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("mutation", ["depth", "framing", "correlation"])
def test_wire_hash_retains_structural_and_protocol_limits(runner, persisted, mutation):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
if mutation == "depth":
nested = 0
for _ in range(18):
nested = [nested]
event = dict(type="rate_limits.updated", data=nested)
elif mutation == "framing":
event = dict(type="rate_limits.updated", data="\ud800")
else:
event = dict(type="input_audio_buffer.speech_started", item_id="bad\ud800", audio_start_ms=0)
wire = json.dumps(event, ensure_ascii=True)
assert len(wire.encode("utf-8")) < runtime.settings.max_provider_message_bytes
await received(runtime, transport, wire)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert not runtime.calls
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("stage", ["pending", "delivered"])
@pytest.mark.parametrize("identity", ["same", "new", "absent"])
@pytest.mark.parametrize("delayed", [False, True])
def test_asr_completion_replay_emits_once_without_advancing_work(
runner, persisted, monkeypatch, stage, identity, delayed):
async def scenario():
entered, release, delivered = asyncio.Event(), asyncio.Event(), asyncio.Event()
out = []
async def sink(event):
if event.get("role") == "user" and event["type"] == "transcript":
entered.set()
await release.wait()
delivered.set()
out.append(event)
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, emit=sink)
try:
first = await input_turn(runtime, commit=False)
if delayed:
await input_turn(runtime, "u2", 10, commit=False)
assert first.superseded
current = runtime.current
token, deadline, intent_count = runtime.token, current.input_deadline, runtime.intent_count
releases = []
original_release = runtime.release
async def track_release():
releases.append(True)
await original_release()
monkeypatch.setattr(runtime, "release", track_release)
event = user_asr("u1", "\u0633\u0644\u0627\u0645", "asr-first")
await received(runtime, transport, json.dumps(event, ensure_ascii=False))
await asyncio.wait_for(entered.wait(), 1)
if stage == "delivered":
release.set()
await asyncio.wait_for(delivered.wait(), 1)
await until(lambda: runtime.active_control is None)
before = len(releases), runtime.control_count, runtime.control_bytes
replay_id = "asr-first" if identity == "same" else "asr-again" if identity == "new" else None
for _ in range(3):
replay = user_asr("u1", event["transcript"], replay_id)
await received(runtime, transport, json.dumps(replay, ensure_ascii=False))
assert before == (len(releases), runtime.control_count, runtime.control_bytes)
assert runtime.current is current and runtime.token == token
assert current.input_deadline == deadline and runtime.intent_count == intent_count
assert not runtime.pending_create and runtime.calls == {}
assert not commands(transport, "response.create")
release.set()
await asyncio.wait_for(delivered.wait(), 1)
await until(lambda: runtime.active_control is None)
transcripts = [e for e in out if e.get("role") == "user"]
assert transcripts == [dict(type="transcript", role="user", turn_ref=first.ref,
text=event["transcript"], status="completed")]
assert runtime.usable
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("event_id", ["asr-first", "asr-again", None])
def test_asr_conflicting_completion_is_protocol_failure(runner, persisted, event_id):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
first = await input_turn(runtime, commit=False)
event = user_asr("u1", "original", "asr-first")
await received(runtime, transport, json.dumps(event))
await until(lambda: any(e.get("text") == "original" for e in out))
state = dict(first.transcript_parts)
await received(runtime, transport, json.dumps(user_asr("u1", "replacement", event_id)))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert first.transcript_parts == state
assert not any(e.get("text") == "replacement" for e in out)
assert not commands(transport, "response.create")
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("revoke", ["actor", "epoch"])
def test_delayed_asr_completion_revalidates_authority_before_delivery(runner, persisted, revoke):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
try:
first = await input_turn(runtime, commit=False)
assert await runtime.check_authority(first)
await input_turn(runtime, "u2", 10, commit=False)
original = runtime.authority_check
async def authority(execution):
if execution is first.execution:
entered.set()
await release.wait()
return await original(execution)
runtime.authority_check = authority
event = user_asr("u1", "private old speech", "asr-first")
await received(runtime, transport, json.dumps(event))
await asyncio.wait_for(entered.wait(), 1)
if revoke == "actor":
persisted["enabled"] = False
else:
persisted["epoch"] = 2
await received(runtime, transport, json.dumps(dict(event, event_id="asr-again")))
release.set()
await runtime.failure_signal.wait()
assert runtime.failure == "CONTEXT_REVOKED"
assert not any(e.get("role") == "user" for e in out)
assert not commands(transport, "response.create") and not runtime.calls
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
def test_asr_completion_state_bounded_by_input_mapping_and_content_layout(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
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))
await received(runtime, transport, json.dumps(user_asr("u" + str(n), "speech", "asr" + str(n))))
await until(lambda: sum(e.get("role") == "user" for e in out) == n + 1)
assert len(runtime.inputs) == 2
assert all(set(turn.transcript_parts) == {0} and len(turn.transcript_parts[0]) == 32
for turn in runtime.inputs.values())
state = {item: dict(turn.transcript_parts) for item, turn in runtime.inputs.items()}
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u2", audio_start_ms=2))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert {item: turn.transcript_parts for item, turn in runtime.inputs.items()} == state
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("index", [1, -1, True, "0", None])
def test_asr_unsupported_content_cannot_expand_completion_state(runner, persisted, index):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
turn = await input_turn(runtime, commit=False)
event = dict(user_asr("u1", "speech", "asr"), content_index=index)
await received(runtime, transport, json.dumps(event))
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert turn.transcript_parts == {}
finally:
await runtime.close()
asyncio.run(scenario())
def test_asr_repeated_partial_text_is_incremental_not_semantically_deduplicated(runner, persisted):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
try:
turn = await input_turn(runtime, commit=False)
text = "\u0633\u0644\u0627\u0645 "
first = user_asr("u1", text, "delta-first", completed=False)
await received(runtime, transport, json.dumps(first))
await received(runtime, transport, json.dumps(first))
await received(runtime, transport, json.dumps(dict(first, event_id="delta-again")))
complete = user_asr("u1", text + text, "asr-first")
await received(runtime, transport, json.dumps(complete))
await received(runtime, transport, json.dumps(dict(complete, event_id="asr-again")))
await until(lambda: runtime.control_count == 0)
transcripts = [e for e in out if e.get("role") == "user"]
assert [(e["text"], e["status"]) for e in transcripts] == [
(text, "partial"), (text, "partial"), (text + text, "completed")]
assert all(e["turn_ref"] == turn.ref for e in transcripts)
assert not commands(transport, "response.create") and not runtime.calls
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize("surrogate", [0xD800, 0xDFFF])
@pytest.mark.parametrize("escaped", [True, False])
def test_exact_wire_multicall_preserves_rejected_surrogate_result(
settings, monkeypatch, replay_runner, persisted, surrogate, escaped):
service = canonical_service(settings, monkeypatch, [row()])
searches = []
original_search = service.search
def search(execution, query, context=None):
searches.append(query)
return original_search(execution, query, context)
service.search = search
raw = json.dumps(dict(query="\u0633" * 1900, context="\u0645" * 1900),
ensure_ascii=False, separators=(",", ":"))
rejected = json.dumps(dict(query=chr(surrogate)), ensure_ascii=escaped)
async def scenario():
runtime, transport, _ = await make(service, replay_runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
output = [dict(type="function_call", id="f_" + chr(97 + n), call_id=chr(97 + n),
name="search_knowledge", arguments=raw if n < 11 else rejected)
for n in range(12)]
event = dict(terminal(output=output), event_id="first")
wire = terminal_wire(event, 262144)
await received(runtime, transport, wire)
await received(runtime, transport, wire)
await received(runtime, transport, wire.replace('"event_id":"first"', '"event_id":"again"'))
await until(lambda: len(commands(transport, "response.create")) == 2)
assert runtime.usable and len(searches) == 11
items = [e["item"] for e in commands(transport, "conversation.item.create")]
assert len(items) == 12
for item in items:
result = json.loads(item["output"])
assert result == runtime.calls[item["call_id"]][1]["result"]
if item["call_id"] == "l":
assert result["status"] == "error" and result["sources"] == []
assert result["error"]["code"] == "INVALID_TOOL_ARGUMENTS"
assert result["error"]["message"] == "Only query and optional context are accepted"
else:
assert result["status"] == "ok" and result["sources"][0]["source_ref"] == "S1"
# Raw surrogate and literal replacement arguments cannot share an event hash.
changed = wire.replace("\\ud800", "\\ufffd").replace("\\udfff", "\\ufffd")
if not escaped:
await received(runtime, transport, changed)
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert len(searches) == 11
finally:
await runtime.close()
asyncio.run(scenario())