- Specialize voice assistant identity and agent system prompt for «شرکت شهرکهای صنعتی اصفهان» (English instructions with Persian proper names) - Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events - Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event - Handle old-turn search cancellation safely on turn supersession - Add end-to-end search tracing pipeline and diagnostic CLI - Add database organization title and settings update script
883 lines
44 KiB
Python
883 lines
44 KiB
Python
"""Fake wire transport with the actual StructuredTool and shared runner."""
|
|
import asyncio
|
|
import base64
|
|
from contextlib import nullcontext
|
|
from copy import deepcopy
|
|
import json
|
|
from threading import Event
|
|
import time
|
|
from types import SimpleNamespace
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
|
|
from app.infrastructure.realtime import RealtimeAdapter, canonical_json, strict_json
|
|
from app.modules.knowledge import langchain_tool as boundary
|
|
from app.modules.voice.runtime import VoiceRuntime
|
|
from tests.unit.test_search_phase2 import service as canonical_service, row
|
|
|
|
class Transport:
|
|
def __init__(self):
|
|
self.sent = []
|
|
self.incoming = asyncio.Queue()
|
|
self.closed = False
|
|
|
|
async def send(self, value):
|
|
self.sent.append(json.loads(value))
|
|
|
|
async def recv(self):
|
|
return await self.incoming.get()
|
|
|
|
async def close(self):
|
|
self.closed = True
|
|
|
|
@pytest.fixture
|
|
def runner():
|
|
# Match API startup: framework imports precede voice/tool deadlines.
|
|
boundary.prepare_search_tools()
|
|
value = boundary.SearchToolRunner(running=2, waiting=2, timeout=2)
|
|
yield value
|
|
value.close()
|
|
|
|
@pytest.fixture
|
|
def persisted(monkeypatch):
|
|
state = dict(enabled=True, epoch=1)
|
|
def current(conn, actor):
|
|
if not state["enabled"]:
|
|
from app.modules.knowledge.service import KnowledgeError
|
|
raise KnowledgeError("ACTOR_UNAVAILABLE", "Unavailable")
|
|
return dict(id=actor, organization_id="fixture", role="user"), dict(access_epoch=state["epoch"])
|
|
monkeypatch.setattr(boundary, "transaction", lambda _: nullcontext(None))
|
|
monkeypatch.setattr(boundary, "authority", current)
|
|
return state
|
|
|
|
async def until(predicate):
|
|
async with asyncio.timeout(3):
|
|
while not predicate():
|
|
await asyncio.sleep(.001)
|
|
|
|
def commands(transport, kind):
|
|
return [e for e in transport.sent if e["type"] == kind]
|
|
|
|
async def make(service, runner, persisted, *, clock=time.monotonic, classifier=None, emit=None):
|
|
transport = Transport()
|
|
output = []
|
|
async def sink(event):
|
|
output.append(event)
|
|
async def trusted(execution):
|
|
if not persisted["enabled"]:
|
|
return False
|
|
return execution.capture(dict(id=execution.user_id, organization_id="fixture", role="user"),
|
|
persisted["epoch"])
|
|
adapter = RealtimeAdapter(transport, no_active_classifier=classifier)
|
|
runtime = VoiceRuntime(adapter, service, runner, uuid4(), emit or sink,
|
|
authority_check=trusted, clock=clock, tool_seconds=2)
|
|
await runtime.start()
|
|
await until(lambda: commands(transport, "session.update"))
|
|
ack = deepcopy(adapter.setup()["session"])
|
|
ack["audio"]["input"]["turn_detection"]["threshold"] = .5
|
|
await runtime.handle(dict(type="session.updated", session=ack))
|
|
await until(lambda: runtime.ready or not runtime.usable)
|
|
return runtime, transport, output
|
|
|
|
async def input_turn(runtime, item="u1", start=0, *, commit=True):
|
|
target = (start + 200) * 48
|
|
while runtime.usable and runtime.input_dispatched_total < target:
|
|
await runtime.input_audio(bytes(min(9600, target - runtime.input_dispatched_total)))
|
|
await until(lambda: runtime.input_transport_count == 0)
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id=item,
|
|
audio_start_ms=start))
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_stopped", item_id=item, audio_end_ms=start + 100))
|
|
if commit:
|
|
await runtime.handle(dict(type="input_audio_buffer.committed", item_id=item))
|
|
return runtime.current
|
|
|
|
async def response(runtime, transport, response_id="r1"):
|
|
await until(lambda: runtime.pending_create is not None)
|
|
intent = runtime.pending_create[0]
|
|
await until(lambda: any(e.get("response", {}).get("metadata", {}).get("voice_intent") == intent
|
|
for e in commands(transport, "response.create")))
|
|
await runtime.handle(dict(type="response.created",
|
|
response=dict(id=response_id, metadata=dict(voice_intent=intent))))
|
|
return runtime.responses[response_id]
|
|
|
|
def call(response_id="r1", call_id="c1", query="q", raw=None, name="search_knowledge"):
|
|
return dict(type="response.function_call_arguments.done", response_id=response_id,
|
|
item_id="f_" + call_id, call_id=call_id, name=name,
|
|
arguments=raw if raw is not None else canonical_json(dict(query=query)))
|
|
|
|
def message(response_id="r1", item_id=None):
|
|
return dict(type="message", id=item_id or ("a1" if response_id == "r1" else "a_" + response_id),
|
|
role="assistant", content=[dict(type="audio", transcript="")])
|
|
|
|
def terminal(response_id="r1", status="completed", output=None):
|
|
return dict(type="response.done", response=dict(id=response_id, status=status,
|
|
output=output if output is not None else [message(response_id)]))
|
|
|
|
async def done(runtime, response_id="r1", status="completed"):
|
|
output = [dict(type="function_call", id=c["item"], call_id=cid, name=c["name"], arguments=c["raw"])
|
|
for cid, c in runtime.responses[response_id].calls.items()]
|
|
existing = [message(response_id, item) for item, owner in runtime.output_items.items()
|
|
if owner is runtime.responses[response_id] and runtime.item_types.get(item) == "message"]
|
|
output += existing or ([] if output else [message(response_id)])
|
|
await runtime.handle(terminal(response_id, status, output))
|
|
|
|
def delta(size, response_id="r1", item_id="a1", event_id=None):
|
|
event = dict(type="response.output_audio.delta", response_id=response_id,
|
|
item_id=item_id, output_index=0, content_index=0, delta=base64.b64encode(bytes(size)).decode())
|
|
if event_id:
|
|
event["event_id"] = event_id
|
|
return event
|
|
|
|
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
|
|
def test_actual_canonical_tool_and_duplicate_continuation(settings, monkeypatch, runner, persisted, rows, status):
|
|
service = canonical_service(settings, monkeypatch, rows)
|
|
async def scenario():
|
|
runtime, transport, out = await make(service, runner, persisted)
|
|
try:
|
|
turn = await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
event = call()
|
|
event["event_id"] = "tool"
|
|
await runtime.handle(event)
|
|
await runtime.handle(event)
|
|
await runtime.handle(dict(event, event_id="semantic-duplicate"))
|
|
assert runtime.calls["c1"][1]["result"] is None
|
|
assert not commands(transport, "conversation.item.create")
|
|
await done(runtime)
|
|
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
|
|
await until(lambda: commands(transport, "conversation.item.create"))
|
|
await done(runtime)
|
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
|
outputs = [e["item"] for e in commands(transport, "conversation.item.create")]
|
|
assert len(outputs) == 1 and outputs[0]["call_id"] == "c1"
|
|
result = json.loads(outputs[0]["output"])
|
|
assert result == service.search(turn.execution, "q")
|
|
assert result["status"] == status
|
|
assert runtime.calls["c1"][0].turn is turn
|
|
assert len(commands(transport, "response.create")) == 2
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("raw,name", [
|
|
('{"query":"q","user_id":"forged"}', "search_knowledge"),
|
|
('{"query":"q","access_epoch":9}', "search_knowledge"),
|
|
('{"query":"q","document_id":"forged"}', "search_knowledge"),
|
|
('{"query":"q","query":"other"}', "search_knowledge"),
|
|
('{"query":NaN}', "search_knowledge"), ("[]", "search_knowledge"),
|
|
('{"query":1}', "search_knowledge"), ("{", "search_knowledge"),
|
|
('{"query":"q"}', "forged_tool"),
|
|
])
|
|
def test_malformed_forged_arguments_canonical_error_without_io(runner, persisted, raw, name):
|
|
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Forged search ran"))
|
|
async def scenario():
|
|
runtime, transport, out = await make(service, runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call(raw=raw, name=name))
|
|
await done(runtime)
|
|
await until(lambda: commands(transport, "conversation.item.create"))
|
|
item = commands(transport, "conversation.item.create")[0]["item"]
|
|
result = json.loads(item["output"])
|
|
assert result["status"] == "error" and result["sources"] == []
|
|
assert result["error"]["code"] == "INVALID_TOOL_ARGUMENTS"
|
|
assert runtime.usable
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("code", ["CALIBRATION_REQUIRED", "PROVIDER_UNAVAILABLE", "SEARCH_FAILED"])
|
|
def test_technical_results_unchanged(runner, persisted, code):
|
|
async def scenario():
|
|
expected = dict(status="error", sources=[], error=dict(code=code, message="Safe",
|
|
retryable=True, request_id="canonical-request"))
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None, search=lambda *_: expected),
|
|
runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call())
|
|
await done(runtime)
|
|
await until(lambda: commands(transport, "conversation.item.create"))
|
|
assert json.loads(commands(transport, "conversation.item.create")[0]["item"]["output"]) == expected
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_shared_refs_across_multiple_calls_and_one_batch_continuation(settings, monkeypatch, runner, persisted):
|
|
service = canonical_service(settings, monkeypatch, [row()])
|
|
async def scenario():
|
|
runtime, transport, out = await make(service, runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call(call_id="c1"))
|
|
await runtime.handle(call(call_id="c2", query="follow-up"))
|
|
await done(runtime)
|
|
await until(lambda: len(commands(transport, "conversation.item.create")) == 2)
|
|
results = [json.loads(e["item"]["output"]) for e in commands(transport, "conversation.item.create")]
|
|
assert [r["sources"][0]["source_ref"] for r in results] == ["S1", "S1"]
|
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
|
assert len(commands(transport, "response.create")) == 2
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_retrieval_does_not_block_receive_and_interruption_cancels(runner, persisted):
|
|
entered, finish = Event(), Event()
|
|
def search(*_):
|
|
entered.set()
|
|
assert finish.wait(3)
|
|
return dict(status="no_evidence", sources=[], warnings=["insufficient_support"], knowledge_revision=1)
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call())
|
|
assert not entered.is_set()
|
|
await done(runtime)
|
|
await until(entered.is_set)
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u2", audio_start_ms=10))
|
|
assert runtime.inputs["u1"].cancelled.is_set()
|
|
assert runtime.responses["r1"].terminal
|
|
assert not commands(transport, "response.cancel")
|
|
finish.set()
|
|
await until(lambda: not runtime.tasks)
|
|
assert not commands(transport, "conversation.item.create")
|
|
finally:
|
|
finish.set()
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_delayed_transcript_original_turn_and_suppressed_interrupted_assistant(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
first = await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u2", audio_start_ms=10))
|
|
await runtime.handle(dict(type="conversation.item.input_audio_transcription.completed",
|
|
item_id="u1", content_index=0, transcript="Original"))
|
|
await runtime.handle(dict(type="response.output_audio_transcript.done",
|
|
response_id="r1", item_id="a1", output_index=0, content_index=0, transcript="Late assistant"))
|
|
await until(lambda: any(e.get("text") == "Original" for e in out if isinstance(e, dict)))
|
|
transcripts = [e for e in out if isinstance(e, dict) and e.get("type") == "transcript"]
|
|
assert transcripts == [dict(type="transcript", turn_ref=first.ref, role="user",
|
|
text="Original", status="completed")]
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_normal_completion_preserves_delayed_assistant_transcript(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
first = await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await done(runtime)
|
|
await input_turn(runtime, "u2", 10, commit=False)
|
|
assert not first.superseded
|
|
await runtime.handle(dict(type="response.output_audio_transcript.done",
|
|
response_id="r1", item_id="a1", output_index=0, content_index=0, transcript="Normally complete"))
|
|
await until(lambda: any(e.get("text") == "Normally complete" for e in out if isinstance(e, dict)))
|
|
assert not [e for e in out if isinstance(e, dict) and e["type"] == "turn_interrupted"]
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_setup_flags_ack_and_diagnostic_creation_gates(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
flags = commands(transport, "session.update")[0]["session"]["audio"]["input"]["turn_detection"]
|
|
assert flags["create_response"] is flags["interrupt_response"] is False
|
|
await runtime.diagnostic_text("A question")
|
|
await until(lambda: commands(transport, "conversation.item.create"))
|
|
assert not commands(transport, "response.create")
|
|
item = commands(transport, "conversation.item.create")[0]["item"]
|
|
await runtime.handle(dict(type="conversation.item.added", item=item))
|
|
await until(lambda: len(commands(transport, "response.create")) == 1)
|
|
await runtime.handle(dict(type="conversation.item.added", item=item))
|
|
assert len(commands(transport, "response.create")) == 1
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("flag", ["create_response", "interrupt_response"])
|
|
def test_bad_setup_ack_is_fatal(runner, persisted, flag):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
bad = deepcopy(runtime.adapter.setup()["session"])
|
|
bad["audio"]["input"]["turn_detection"][flag] = True
|
|
await runtime.handle(dict(type="session.updated", session=bad))
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_six_second_burst_paced_and_progress_evidence(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
for index in range(3):
|
|
await runtime.handle(delta(96000, event_id=str(index)))
|
|
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
|
|
item_id="a1", output_index=0, content_index=0))
|
|
await done(runtime)
|
|
await until(lambda: sum(len(e) for e in out if isinstance(e, bytes)) == 72000)
|
|
audio = next(iter(runtime.audio.values()))
|
|
assert audio.generated == 288000 and audio.sent == audio.credit == 72000
|
|
assert len(audio.data) == 216000 and not audio.ended
|
|
await runtime.playback_progress(audio.ref, 1000)
|
|
await until(lambda: audio.sent == 120000)
|
|
assert audio.played == 1000 and audio.credit == 72000
|
|
assert audio.generated == 288000 and runtime.usable
|
|
await runtime.playback_progress(audio.ref, 1000)
|
|
assert audio.credit == 72000
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_cleanup_deadlines_timer_identity_latest_turn_and_once_retirement(runner, persisted):
|
|
async def scenario():
|
|
now = [time.monotonic()]
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted,
|
|
clock=lambda: now[0],
|
|
classifier=lambda e: e.get("code") == "verified-fixture-race")
|
|
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()))
|
|
stale_timer = audio.timer
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u2", audio_start_ms=10))
|
|
assert audio.state == "finalizing" and audio.timer is None
|
|
await runtime.playback_progress(audio.ref, 420)
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_stopped", item_id="u2", audio_end_ms=runtime.input_dispatched_total // 48))
|
|
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u2"))
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u3", audio_start_ms=20))
|
|
assert runtime.inputs["u2"].superseded
|
|
await until(lambda: commands(transport, "response.cancel"))
|
|
cancel = runtime.responses["r1"].cancel_event
|
|
await runtime.handle(dict(type="error", error=dict(event_id=cancel, code="verified-fixture-race")))
|
|
assert runtime.usable and not runtime.responses["r1"].terminal
|
|
now[0] += 4.8
|
|
await done(runtime, status="cancelled")
|
|
await until(lambda: commands(transport, "conversation.item.truncate"))
|
|
trunc = commands(transport, "conversation.item.truncate")[0]
|
|
assert trunc["audio_end_ms"] == 420
|
|
assert audio.credit == 27840
|
|
await runtime.stall_callback(audio.ref, stale_timer)
|
|
assert runtime.usable
|
|
now[0] += 4.8
|
|
ack = dict(type="conversation.item.truncated", item_id="a1", content_index=0, audio_end_ms=420)
|
|
await runtime.handle(ack)
|
|
await runtime.handle(ack)
|
|
assert audio.state == "retired" and audio.credit == 0
|
|
assert (audio.generated, audio.sent, audio.played) == (48000, 48000, 420)
|
|
assert len(commands(transport, "response.create")) == 1
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_stopped", item_id="u3", audio_end_ms=runtime.input_dispatched_total // 48))
|
|
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u3"))
|
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
|
assert runtime.pending_create[1] is runtime.inputs["u3"]
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("terminal_confirmed", [False, True])
|
|
def test_race_does_not_substitute_terminal_confirmation(runner, persisted, terminal_confirmed):
|
|
async def scenario():
|
|
now = [time.monotonic()]
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted,
|
|
clock=lambda: now[0], classifier=lambda e: e.get("code") == "verified-fixture-race")
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await input_turn(runtime, "u2", 10)
|
|
await until(lambda: commands(transport, "response.cancel"))
|
|
await runtime.handle(dict(type="error", error=dict(
|
|
event_id=runtime.responses["r1"].cancel_event, code="verified-fixture-race")))
|
|
if terminal_confirmed:
|
|
await done(runtime, status="cancelled")
|
|
now[0] += 5.1
|
|
await runtime.tick()
|
|
assert runtime.usable is terminal_confirmed
|
|
if not terminal_confirmed:
|
|
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_stall_progress_renewal_new_interval_and_tail_cleanup(runner, persisted):
|
|
async def scenario():
|
|
now = [time.monotonic()]
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(delta(50))
|
|
await until(lambda: next(iter(runtime.audio.values())).sent == 50)
|
|
audio = next(iter(runtime.audio.values()))
|
|
first = audio.timer
|
|
await runtime.playback_progress(audio.ref, 1)
|
|
assert audio.timer is None
|
|
now[0] += 10
|
|
await runtime.handle(delta(48))
|
|
await until(lambda: audio.sent == 98)
|
|
assert audio.timer != first and audio.stall_deadline == now[0] + 5
|
|
await runtime.stall_callback(audio.ref, first)
|
|
assert runtime.usable
|
|
await runtime.playback_progress(audio.ref, 2)
|
|
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
|
|
item_id="a1", output_index=0, content_index=0))
|
|
await done(runtime)
|
|
await until(lambda: audio.cleanup is not None)
|
|
assert audio.state == "finalizing" and audio.timer is None
|
|
assert not runtime.responses["r1"].interrupted
|
|
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
|
content_index=0, audio_end_ms=2))
|
|
assert audio.sent == 98 and audio.played == 2 and audio.credit == 0
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_genuine_stall_fails_and_cannot_revive(runner, persisted):
|
|
async def scenario():
|
|
now = [time.monotonic()]
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(delta(48))
|
|
await until(lambda: next(iter(runtime.audio.values())).sent == 48)
|
|
audio = next(iter(runtime.audio.values()))
|
|
token = audio.timer
|
|
now[0] += 5
|
|
await runtime.stall_callback(audio.ref, token)
|
|
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
|
|
await input_turn(runtime, "u2", 10)
|
|
assert not runtime.usable
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("played", [True, 1.5, -1, 2, "1"])
|
|
def test_invalid_progress_rejected_without_clamping(runner, persisted, played):
|
|
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(50))
|
|
await until(lambda: next(iter(runtime.audio.values())).sent == 50)
|
|
audio = next(iter(runtime.audio.values()))
|
|
await runtime.playback_progress(audio.ref, played)
|
|
assert runtime.failure == "LIVE_PROTOCOL_ERROR" and audio.played == 0
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_authority_revocation_gates_continuation(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
|
search=lambda *_: dict(status="no_evidence", sources=[])), runner, persisted)
|
|
entered, resume = asyncio.Event(), asyncio.Event()
|
|
trusted = runtime.authority_check
|
|
async def continuation_authority(execution):
|
|
entered.set()
|
|
await resume.wait()
|
|
return await trusted(execution)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call())
|
|
assert runtime.calls["c1"][1]["result"] is None
|
|
runtime.authority_check = continuation_authority
|
|
await done(runtime)
|
|
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
|
|
await until(entered.is_set)
|
|
persisted["epoch"] += 1
|
|
resume.set()
|
|
await until(lambda: runtime.failure is not None)
|
|
assert runtime.failure == "CONTEXT_REVOKED"
|
|
assert not commands(transport, "conversation.item.create")
|
|
finally:
|
|
resume.set()
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_bounded_provider_decode_and_strict_json():
|
|
with pytest.raises(ValueError):
|
|
strict_json('{"a":1,"a":2}')
|
|
with pytest.raises(ValueError):
|
|
canonical_json(dict(a=float("nan")))
|
|
async def scenario():
|
|
transport = Transport()
|
|
await transport.incoming.put(" " * 262145)
|
|
with pytest.raises(ValueError):
|
|
await RealtimeAdapter(transport).receive()
|
|
asyncio.run(scenario())
|
|
|
|
def test_missing_terminal_call_set_and_rebound_call_fail(runner, persisted):
|
|
async def scenario():
|
|
for rebound in (False, True):
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
|
search=lambda *_: dict(status="no_evidence", sources=[])), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call())
|
|
if rebound:
|
|
await runtime.handle(call(query="different"))
|
|
else:
|
|
await runtime.handle(terminal(output=[]))
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
|
assert not commands(transport, "conversation.item.create")
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_semantic_duplicate_call_json_formatting_coalesces(runner, persisted):
|
|
searches = []
|
|
def search(*args):
|
|
searches.append(args)
|
|
return dict(status="no_evidence", sources=[])
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call(raw='{"query":"q","context":null}'))
|
|
await runtime.handle(call(raw='{ "context": null, "query": "q" }'))
|
|
await done(runtime)
|
|
await until(lambda: commands(transport, "conversation.item.create"))
|
|
assert len(searches) == 1 and runtime.usable
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_audio_item_creation_does_not_bypass_commit(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
await input_turn(runtime, commit=False)
|
|
await runtime.handle(dict(type="conversation.item.added", item=dict(
|
|
id="u1", role="user", type="message", content=[])))
|
|
assert not runtime.current.committed and not commands(transport, "response.create")
|
|
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u1"))
|
|
await until(lambda: len(commands(transport, "response.create")) == 1)
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_replayed_start_does_not_supersede_and_conflict_fails(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u1", audio_start_ms=0))
|
|
assert runtime.token == 1
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_started", item_id="u1", audio_start_ms=1))
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR" and runtime.token == 1
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("mode", ["cleanup_timeout", "wrong_ack", "unverified_cancel_error"])
|
|
def test_cleanup_failure_never_releases_current_input(runner, persisted, mode):
|
|
async def scenario():
|
|
now = [time.monotonic()]
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
|
try:
|
|
await input_turn(runtime)
|
|
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)
|
|
if mode == "unverified_cancel_error":
|
|
await runtime.handle(dict(type="error", error=dict(
|
|
event_id=runtime.responses["r1"].cancel_event,
|
|
message="No active response", code="unverified")))
|
|
else:
|
|
now[0] += 1.1
|
|
await done(runtime, status="cancelled")
|
|
await until(lambda: commands(transport, "conversation.item.truncate"))
|
|
if mode == "wrong_ack":
|
|
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
|
content_index=0, audio_end_ms=1))
|
|
else:
|
|
now[0] += 5.1
|
|
await runtime.tick()
|
|
assert not runtime.usable
|
|
assert len(commands(transport, "response.create")) == 1
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_reservoir_overflow_before_decode_and_unsupported_layout(runner, persisted):
|
|
async def scenario():
|
|
for overflow in (False, True):
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
if overflow:
|
|
for _ in range(15):
|
|
await runtime.handle(delta(96000))
|
|
await runtime.handle(delta(48))
|
|
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
|
|
else:
|
|
event = delta(48)
|
|
event["content_index"] = 1
|
|
await runtime.handle(event)
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_tool_budget_and_unsolicited_response_fail_closed(runner, persisted):
|
|
async def scenario():
|
|
for budget in (False, True):
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
|
search=lambda *_: dict(status="no_evidence", sources=[])), runner, persisted)
|
|
try:
|
|
if budget:
|
|
runtime.max_calls = 1
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call(call_id="c1"))
|
|
await runtime.handle(call(call_id="c2"))
|
|
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
|
|
else:
|
|
await runtime.handle(dict(type="response.created", response=dict(id="unexpected")))
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
|
await until(lambda: commands(transport, "response.cancel"))
|
|
assert commands(transport, "response.cancel")[0]["response_id"] == "unexpected"
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_smoke_opt_in_and_time_call_caps_before_configuration(monkeypatch):
|
|
from app import voice_smoke
|
|
monkeypatch.setattr(voice_smoke, "IngestionSettings", lambda: pytest.fail("No setup before opt-in"))
|
|
for args in (
|
|
["--user-id", str(uuid4()), "--query", "q"],
|
|
["--user-id", str(uuid4()), "--query", "q", "--allow-provider-calls", "--seconds", "601"],
|
|
["--user-id", str(uuid4()), "--query", "q", "--allow-provider-calls", "--max-tool-calls", "11"],
|
|
):
|
|
with pytest.raises(SystemExit):
|
|
voice_smoke.main(args)
|
|
|
|
def test_pending_continuation_superseded_before_provider_ack(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
|
search=lambda *_: dict(status="no_evidence", sources=[])), runner, persisted)
|
|
try:
|
|
first = await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(call())
|
|
await done(runtime)
|
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
|
old_intent = runtime.pending_create[0]
|
|
await input_turn(runtime, "u2", 10)
|
|
assert first.superseded and first.cancelled.is_set()
|
|
await runtime.handle(dict(type="response.created", response=dict(
|
|
id="late-r2", metadata=dict(voice_intent=old_intent))))
|
|
await until(lambda: commands(transport, "response.cancel"))
|
|
assert commands(transport, "response.cancel")[-1]["response_id"] == "late-r2"
|
|
assert runtime.responses["late-r2"].interrupted
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_new_speech_during_normal_tail_cleanup_preserves_completion(runner, persisted):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
first = await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(delta(50))
|
|
await until(lambda: next(iter(runtime.audio.values())).sent == 50)
|
|
audio = next(iter(runtime.audio.values()))
|
|
await runtime.playback_progress(audio.ref, 1)
|
|
await runtime.handle(dict(type="response.output_audio.done",
|
|
response_id="r1", item_id="a1", output_index=0, content_index=0))
|
|
await done(runtime)
|
|
await until(lambda: audio.cleanup is not None)
|
|
await input_turn(runtime, "u2", 10)
|
|
assert not first.superseded and not runtime.responses["r1"].interrupted
|
|
assert len(commands(transport, "response.create")) == 1
|
|
await runtime.handle(dict(type="response.output_audio_transcript.done",
|
|
response_id="r1", item_id="a1", output_index=0, content_index=0, transcript="Completed before new turn"))
|
|
await runtime.handle(dict(type="conversation.item.truncated",
|
|
item_id="a1", content_index=0, audio_end_ms=1))
|
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
|
assert not [e for e in out if isinstance(e, dict) and e["type"] == "turn_interrupted"]
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
|
|
def test_operator_harness_actual_fake_transport_tool_correlation(
|
|
settings, monkeypatch, runner, persisted, capsys, rows, status):
|
|
from app.modules.voice.configuration import VoiceSettings
|
|
from app import voice_smoke
|
|
from app.modules.voice import runtime as runtime_module
|
|
service = canonical_service(settings, monkeypatch, rows)
|
|
monkeypatch.setattr(runtime_module, "transaction", lambda _: nullcontext(None))
|
|
monkeypatch.setattr(runtime_module, "authority", boundary.authority)
|
|
class Scripted(Transport):
|
|
async def send(self, raw):
|
|
await super().send(raw)
|
|
event = self.sent[-1]
|
|
kind = event["type"]
|
|
if kind == "session.update":
|
|
await self.incoming.put(canonical_json(dict(type="session.updated", session=event["session"])))
|
|
elif kind == "conversation.item.create" and event["item"]["type"] == "message":
|
|
await self.incoming.put(canonical_json(dict(type="conversation.item.added", item=event["item"])))
|
|
elif kind == "response.create":
|
|
number = len(commands(self, kind))
|
|
rid = "real-fake-r" + str(number)
|
|
await self.incoming.put(canonical_json(dict(type="response.created",
|
|
response=dict(id=rid, metadata=event["response"]["metadata"]))))
|
|
if number == 1:
|
|
tool = call(response_id=rid, call_id="real-fake-c")
|
|
await self.incoming.put(canonical_json(tool))
|
|
output = [dict(type="function_call", id=tool["item_id"], call_id=tool["call_id"],
|
|
name=tool["name"], arguments=tool["arguments"])]
|
|
else:
|
|
output = [message(rid)]
|
|
await self.incoming.put(canonical_json(dict(type="response.output_audio_transcript.done",
|
|
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer")))
|
|
await self.incoming.put(canonical_json(terminal(rid, output=output)))
|
|
transport = Scripted()
|
|
async def connection(*args):
|
|
return transport
|
|
monkeypatch.setattr("app.infrastructure.voice_provider.connect_openai", connection)
|
|
config = VoiceSettings(_env_file=None, provider="openai", openai_realtime_api_key="fake-only")
|
|
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0
|
|
logs = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
|
|
correlation = next(e for e in logs if e["type"] == "smoke_correlation")
|
|
assert correlation["calls"][0]["call_id"] == "real-fake-c"
|
|
assert correlation["calls"][0]["response_id"] == "real-fake-r1"
|
|
assert correlation["calls"][0]["status"] == status
|
|
assert correlation["final_response_id"] == "real-fake-r2"
|
|
assert correlation["transcript_delivered"] is True
|
|
assert correlation["calls"][0]["continuation_response_id"] == "real-fake-r2"
|
|
assert correlation["audio_playback_verified"] is False
|
|
if rows:
|
|
assert correlation["calls"][0]["sources"][0]["document_id"] == str(rows[0]["document_id"])
|
|
assert correlation["calls"][0]["sources"][0]["chunk_id"] == str(rows[0]["chunk_id"])
|
|
assert transport.closed
|
|
|
|
@pytest.mark.parametrize("raw", [
|
|
b'{"type":"playback_progress","audio_ref":"unknown","played_ms":1e0}',
|
|
b'{"type":"playback_progress","audio_ref":"unknown","played_ms":true}',
|
|
b'{"type":"response.create"}',
|
|
b'{"type":"playback_progress","audio_ref":"x","played_ms":0,"extra":1}',
|
|
b'{"type":"playback_progress","audio_ref":"x","played_ms":0,"played_ms":1}',
|
|
b"x" * 4097,
|
|
])
|
|
def test_client_control_strict_admission(runner, persisted, raw):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
try:
|
|
await runtime.client_control(raw)
|
|
assert runtime.failure == ("LIVE_FRAME_TOO_LARGE" if len(raw) > 4096 else "LIVE_PROTOCOL_ERROR")
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("mode", ["release", "delivery"])
|
|
def test_authority_io_off_receive_loop_and_latest_token_recheck(runner, persisted, mode):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
|
entered, resume = asyncio.Event(), asyncio.Event()
|
|
original = runtime.authority_check
|
|
blocked = False
|
|
async def gated(execution):
|
|
nonlocal blocked
|
|
if not blocked:
|
|
blocked = True
|
|
entered.set()
|
|
await resume.wait()
|
|
return await original(execution)
|
|
try:
|
|
if mode == "delivery":
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
runtime.authority_check = gated
|
|
if mode == "release":
|
|
await input_turn(runtime)
|
|
else:
|
|
await runtime.handle(delta(48000))
|
|
await asyncio.wait_for(entered.wait(), 1)
|
|
# Provider control must progress while persisted I/O is still pending.
|
|
await asyncio.wait_for(runtime.handle(dict(type="input_audio_buffer.speech_started",
|
|
item_id="u2", audio_start_ms=10)), 1)
|
|
assert runtime.current.input_id == "u2"
|
|
if mode == "delivery":
|
|
assert next(iter(runtime.audio.values())).state == "finalizing"
|
|
await done(runtime, status="cancelled")
|
|
await runtime.handle(dict(type="input_audio_buffer.speech_stopped", item_id="u2", audio_end_ms=runtime.input_dispatched_total // 48))
|
|
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u2"))
|
|
resume.set()
|
|
if mode == "release":
|
|
await until(lambda: runtime.pending_create is not None)
|
|
assert runtime.pending_create[1] is runtime.inputs["u2"]
|
|
await until(lambda: commands(transport, "response.create"))
|
|
assert len(commands(transport, "response.create")) == 1
|
|
else:
|
|
await until(lambda: next(iter(runtime.audio.values())).reserved == 0)
|
|
assert not [e for e in out if isinstance(e, bytes)]
|
|
finally:
|
|
resume.set()
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
def test_uncertain_send_releases_reservation_without_manufacturing_sent_audio(runner, persisted):
|
|
async def scenario():
|
|
async def broken_sink(event):
|
|
if isinstance(event, bytes):
|
|
raise RuntimeError("Uncertain transport send")
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted, emit=broken_sink)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
await runtime.handle(delta(48000))
|
|
await until(lambda: not runtime.usable)
|
|
audio = next(iter(runtime.audio.values()))
|
|
assert runtime.failure == "LIVE_TRANSPORT_FAILED"
|
|
assert (audio.generated, audio.sent, audio.played, audio.credit, audio.reserved) == (48000, 0, 0, 0, 0)
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|
|
|
|
@pytest.mark.parametrize("identity_kind", ["response", "call_item"])
|
|
def test_changed_provider_identity_replay_fails(runner, persisted, identity_kind):
|
|
async def scenario():
|
|
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
|
search=lambda *_: dict(status="no_evidence", sources=[])), runner, persisted)
|
|
try:
|
|
await input_turn(runtime)
|
|
await response(runtime, transport)
|
|
if identity_kind == "response":
|
|
await runtime.handle(dict(type="response.created", response=dict(
|
|
id="r1", metadata=dict(voice_intent="forged"))))
|
|
else:
|
|
await runtime.handle(call())
|
|
replay = call()
|
|
replay["item_id"] = "different-output-item"
|
|
await runtime.handle(replay)
|
|
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
|
finally:
|
|
await runtime.close()
|
|
asyncio.run(scenario())
|