feat(voice): specialize prompt for Isfahan Industrial Parks, emit source excerpts, and bound generation
- 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
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
"""Offline token-limit lifecycle coverage; no hosted provider or browser claims."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
import time
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.configuration import VoiceSettings, OpenAIInputSettings
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
Transport, runner, persisted, make, input_turn, response, commands, until,
|
||||
terminal, message, delta, call, done,
|
||||
)
|
||||
|
||||
def limited(output=None, **changes):
|
||||
event = terminal(status='incomplete', output=output)
|
||||
event['response'].update(status_details=dict(type='incomplete', reason='max_output_tokens'),
|
||||
max_output_tokens=256)
|
||||
event['response'].update(changes)
|
||||
return event
|
||||
|
||||
async def audio_done(runtime):
|
||||
await runtime.handle(dict(type='response.output_audio.done', response_id='r1',
|
||||
item_id='a1', output_index=0, content_index=0))
|
||||
|
||||
@pytest.mark.parametrize('value', [1, 256, 512, 4096])
|
||||
def test_limit_is_pinned_and_acknowledged(value):
|
||||
config = VoiceSettings(_env_file=None, provider='openai', openai_realtime_max_output_tokens=value)
|
||||
adapter = RealtimeAdapter(Transport(), input_settings=config)
|
||||
setup = adapter.setup()['session']
|
||||
assert setup['max_output_tokens'] == config.profile()['max_output_tokens'] == value
|
||||
assert adapter.acknowledged(deepcopy(setup))
|
||||
for bad in (None, 'inf', True, value + 1):
|
||||
ack = deepcopy(setup); ack['max_output_tokens'] = bad
|
||||
assert not adapter.acknowledged(ack)
|
||||
ack = deepcopy(setup); del ack['max_output_tokens']
|
||||
assert not adapter.acknowledged(ack)
|
||||
gemini = VoiceSettings(_env_file=None, provider='gemini')
|
||||
assert gemini.model_copy(update={'openai_realtime_max_output_tokens':value}).profile() == gemini.profile()
|
||||
|
||||
@pytest.mark.parametrize('value', [0, 4097, True, False, 256.0, 1.5, 'inf', '-1', '1.5'])
|
||||
def test_invalid_generation_limits(value):
|
||||
with pytest.raises(ValidationError):
|
||||
OpenAIInputSettings(openai_realtime_max_output_tokens=value)
|
||||
|
||||
def test_limit_environment(monkeypatch):
|
||||
monkeypatch.setenv('OPENAI_REALTIME_MAX_OUTPUT_TOKENS', '128')
|
||||
assert VoiceSettings(_env_file=None, provider='openai').profile()['max_output_tokens'] == 128
|
||||
|
||||
@pytest.mark.parametrize('transcript_first', [False, True])
|
||||
def test_limited_audio_drains_and_next_turn_releases_once(runner, persisted, transcript_first):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
first = await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
transcript = dict(type='response.output_audio_transcript.done', response_id='r1',
|
||||
item_id='a1', output_index=0, content_index=0, transcript='Exact generated words')
|
||||
for _ in range(10):
|
||||
await runtime.handle(delta(48000))
|
||||
await audio_done(runtime)
|
||||
if transcript_first:
|
||||
await runtime.handle(transcript)
|
||||
assert not any(isinstance(e, dict) and e.get('status') == 'completed' for e in out)
|
||||
ending = limited()
|
||||
await runtime.handle(ending)
|
||||
await runtime.handle(dict(ending, event_id='duplicate-terminal'))
|
||||
if not transcript_first:
|
||||
await runtime.handle(transcript)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await until(lambda: audio.sent > 0)
|
||||
while audio.sent < audio.generated or audio.played < audio.sent // 48:
|
||||
sent = audio.sent
|
||||
old = audio.played
|
||||
credit = audio.credit
|
||||
await runtime.playback_progress(audio.ref, sent // 48)
|
||||
# Delivery cannot mutate counters until this coroutine yields.
|
||||
assert credit - audio.credit == 48 * (sent // 48 - old)
|
||||
credit = audio.credit
|
||||
await runtime.playback_progress(audio.ref, sent // 48)
|
||||
assert audio.credit == credit
|
||||
if audio.sent < audio.generated:
|
||||
await until(lambda: audio.sent > sent)
|
||||
await until(lambda: audio.state == 'retired')
|
||||
await until(lambda: any(isinstance(e, dict) and e.get('type') == 'transcript' for e in out))
|
||||
assert runtime.usable and runtime.responses['r1'].status == 'incomplete'
|
||||
assert runtime.responses['r1'].limited
|
||||
assert audio.generated == audio.sent == 48 * audio.played == 480000
|
||||
assert audio.credit == audio.reserved == 0
|
||||
assert len([e for e in out if isinstance(e, dict) and e.get('type') == 'answer_limited']) == 1
|
||||
assert [e['status'] for e in out if isinstance(e, dict) and e.get('role') == 'assistant'] == ['limited']
|
||||
assert runtime.normal(first)
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await until(lambda: len(commands(transport, 'response.create')) == 2)
|
||||
await runtime.handle(dict(type='input_audio_buffer.committed', item_id='u2'))
|
||||
await runtime.handle(dict(ending, event_id='third-terminal'))
|
||||
await asyncio.sleep(.01)
|
||||
assert len(commands(transport, 'response.create')) == 2
|
||||
assert not any(isinstance(e, dict) and e.get('type') == 'turn_interrupted' for e in out)
|
||||
assert not commands(transport, 'response.cancel')
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('status,details', [
|
||||
('failed', dict(type='failed', error={'code':'server_error'})),
|
||||
('incomplete', dict(type='incomplete', reason='content_filter')),
|
||||
('incomplete', dict(type='incomplete', reason='other')),
|
||||
('incomplete', None),
|
||||
('incomplete', dict(type='failed', reason='max_output_tokens')),
|
||||
('incomplete', dict(type='incomplete', reason='max_output_tokens', error={})),
|
||||
])
|
||||
def test_other_terminal_outcomes_fail(runner, persisted, status, details):
|
||||
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(limited(status=status, status_details=details))
|
||||
assert runtime.failure == 'LIVE_PROVIDER_UNAVAILABLE'
|
||||
assert not any(isinstance(e, dict) and e.get('type') == 'answer_limited' for e in out)
|
||||
assert len(commands(transport, 'response.create')) == 1
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('raw', ['{"query":', '{"query":"q"}'])
|
||||
@pytest.mark.parametrize('argument_done', [False, True])
|
||||
def test_limited_tools_never_execute_or_continue(runner, persisted, raw, argument_done):
|
||||
async def scenario():
|
||||
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail('Cut-off tool executed'))
|
||||
runtime, transport, out = await make(service, runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime); await response(runtime, transport)
|
||||
event = call(raw=raw)
|
||||
if argument_done: await runtime.handle(event)
|
||||
item = dict(type='function_call', id=event['item_id'], call_id='c1',
|
||||
name='search_knowledge', arguments=raw, status='incomplete')
|
||||
await runtime.handle(limited(output=[item]))
|
||||
assert runtime.failure == 'LIVE_PROVIDER_UNAVAILABLE'
|
||||
assert runner._active == runner._admitted == 0
|
||||
assert not commands(transport, 'conversation.item.create')
|
||||
assert len(commands(transport, 'response.create')) == 1
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('terminal_first', [False, True])
|
||||
def test_limited_interruption_waits_for_truncation_and_current_commit(runner, persisted, terminal_first):
|
||||
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)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await audio_done(runtime)
|
||||
if terminal_first: await runtime.handle(limited())
|
||||
await runtime.handle(dict(type='input_audio_buffer.speech_started', item_id='u2', audio_start_ms=10))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
if not terminal_first:
|
||||
await until(lambda: bool(commands(transport, 'response.cancel')))
|
||||
await runtime.handle(limited())
|
||||
else: assert not commands(transport, 'response.cancel')
|
||||
now[0] += 1.01
|
||||
await runtime.tick()
|
||||
await until(lambda: audio.cleanup_dispatched)
|
||||
assert audio.played == 420 and audio.credit == 48000 - 420 * 48
|
||||
await runtime.handle(dict(type='conversation.item.truncated', item_id='a1', content_index=0, audio_end_ms=420))
|
||||
assert audio.state == 'retired' and audio.credit == 0
|
||||
assert audio.sent == audio.generated == 48000 and audio.played == 420
|
||||
assert len(commands(transport, 'response.create')) == 1
|
||||
await runtime.handle(dict(type='input_audio_buffer.speech_stopped', item_id='u2', audio_end_ms=100))
|
||||
assert len(commands(transport, 'response.create')) == 1
|
||||
await runtime.handle(dict(type='input_audio_buffer.committed', item_id='u2'))
|
||||
await until(lambda: len(commands(transport, 'response.create')) == 2)
|
||||
await runtime.handle(dict(type='conversation.item.truncated', item_id='a1', content_index=0, audio_end_ms=420))
|
||||
await asyncio.sleep(.01)
|
||||
assert runtime.usable and len(commands(transport, 'response.create')) == 2
|
||||
assert len([e for e in out if isinstance(e, dict) and e.get('type') == 'turn_interrupted']) == 1
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('mode', ['stall', 'overflow', 'missing_audio_done', 'changed_terminal'])
|
||||
def test_limits_and_protocol_failures_still_enforced(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)
|
||||
if mode == 'missing_audio_done':
|
||||
await runtime.handle(limited())
|
||||
assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR'
|
||||
elif mode == 'overflow':
|
||||
for _ in range(30): await runtime.handle(delta(48000))
|
||||
assert runtime.failure == 'LIVE_BUFFER_OVERFLOW'
|
||||
else:
|
||||
await audio_done(runtime); await runtime.handle(limited())
|
||||
if mode == 'stall':
|
||||
now[0] += 5.01; await runtime.tick()
|
||||
assert runtime.failure == 'LIVE_BUFFER_OVERFLOW'
|
||||
else:
|
||||
await runtime.handle(limited(status_details=dict(type='incomplete', reason='content_filter')))
|
||||
assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR'
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('size', [0, 50])
|
||||
def test_limited_empty_or_rounded_tail_does_not_fake_interruption(runner, persisted, size):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
first = await input_turn(runtime); await response(runtime, transport)
|
||||
if size:
|
||||
await runtime.handle(delta(size))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == size)
|
||||
await runtime.playback_progress(next(iter(runtime.audio.values())).ref, 1)
|
||||
await audio_done(runtime); await runtime.handle(limited())
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
if size:
|
||||
await until(lambda: audio.cleanup_dispatched)
|
||||
else: await until(lambda: audio.state == 'retired')
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
assert not first.superseded and not runtime.responses['r1'].interrupted
|
||||
if size:
|
||||
assert len(commands(transport, 'response.create')) == 1
|
||||
assert audio.credit == 2
|
||||
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 audio.generated == audio.sent == size
|
||||
assert audio.played == size // 48 and audio.credit == 0
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'turn_interrupted']
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_successful_response_cannot_execute_incomplete_tool_item(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None,
|
||||
search=lambda *_: pytest.fail('Incomplete item executed')), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime); await response(runtime, transport)
|
||||
event = call(); await runtime.handle(event)
|
||||
output = [dict(type='function_call', id=event['item_id'], call_id='c1',
|
||||
name='search_knowledge', arguments=event['arguments'], status='incomplete')]
|
||||
await runtime.handle(terminal(output=output))
|
||||
assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR'
|
||||
assert runner._active == runner._admitted == 0
|
||||
assert not commands(transport, 'conversation.item.create')
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('finish', ['limited', 'interrupted', 'failed', 'closed'])
|
||||
def test_deferred_transcript_uses_and_releases_existing_control_budget(runner, persisted, finish):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime); r = await response(runtime, transport)
|
||||
await until(lambda: runtime.control_count == 0)
|
||||
event = dict(type='response.output_audio_transcript.done', response_id='r1',
|
||||
item_id='a1', output_index=0, content_index=0, transcript='Generated final text')
|
||||
await runtime.handle(event)
|
||||
held = r.pending_transcript
|
||||
assert held is not None and held.accounted
|
||||
assert runtime.control_count == 1 and runtime.control_bytes == held.size
|
||||
await runtime.handle(dict(event, event_id='duplicate-transcript'))
|
||||
assert runtime.control_count == 1
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'transcript']
|
||||
if finish == 'limited': await runtime.handle(limited())
|
||||
elif finish == 'interrupted':
|
||||
await runtime.handle(dict(type='input_audio_buffer.speech_started', item_id='u2', audio_start_ms=10))
|
||||
elif finish == 'failed': await runtime.handle(limited(status='failed'))
|
||||
else: await runtime.close()
|
||||
assert not held.accounted and r.pending_transcript is None
|
||||
finally: await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -142,9 +142,10 @@ def test_actual_canonical_tool_and_duplicate_continuation(settings, monkeypatch,
|
||||
await runtime.handle(event)
|
||||
await runtime.handle(event)
|
||||
await runtime.handle(dict(event, event_id="semantic-duplicate"))
|
||||
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
|
||||
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)
|
||||
@@ -236,11 +237,13 @@ def test_retrieval_does_not_block_receive_and_interruption_cancels(runner, persi
|
||||
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()
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
assert commands(transport, "response.cancel")[0]["response_id"] == "r1"
|
||||
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")
|
||||
@@ -485,17 +488,28 @@ 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())
|
||||
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
|
||||
persisted["epoch"] += 1
|
||||
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())
|
||||
|
||||
|
||||
@@ -94,11 +94,11 @@ def test_two_calls_cannot_share_function_item(runner, persisted):
|
||||
await response(runtime, transport)
|
||||
first = call()
|
||||
await runtime.handle(first)
|
||||
await until(lambda: runtime.calls["c1"][1]["result"] is not None)
|
||||
assert runtime.calls["c1"][1]["result"] is 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 searches == []
|
||||
assert not commands(transport, "conversation.item.create")
|
||||
finally:
|
||||
await runtime.close()
|
||||
@@ -159,9 +159,10 @@ def test_four_full_persian_results_fit_actual_wire_budget(settings, monkeypatch,
|
||||
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()))
|
||||
assert len(runtime.calls) == 4
|
||||
assert all(c["result"] is None for _, c in runtime.calls.values())
|
||||
await done(runtime)
|
||||
await until(lambda: all(c["result"] is not None for _, c in runtime.calls.values()))
|
||||
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()}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Old-turn durable cancellation must not terminate a healthy voice session."""
|
||||
import asyncio
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from app.modules.voice.durable_tools import DurableTools
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, call, done, until, commands,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal_first", [False, True])
|
||||
@pytest.mark.parametrize("completion", ["cancelled", "late_result"])
|
||||
def test_old_search_interruption_keeps_session_usable(
|
||||
runner, persisted, monkeypatch, terminal_first, completion):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
entered, finish = asyncio.Event(), asyncio.Event()
|
||||
completing, publish = Event(), Event()
|
||||
state = {}
|
||||
result = dict(status="ok", sources=[dict(source_ref="S1",
|
||||
document_id=str(uuid4()), chunk_id=str(uuid4()), title="Old source",
|
||||
excerpt="Old evidence", location=None)])
|
||||
|
||||
async def invoke(args):
|
||||
entered.set()
|
||||
await finish.wait()
|
||||
return result
|
||||
|
||||
monkeypatch.setattr("app.modules.voice.runtime.create_search_tool",
|
||||
lambda *args: SimpleNamespace(ainvoke=invoke))
|
||||
|
||||
def admit(*args):
|
||||
state["status"] = "running"
|
||||
return dict(id=uuid4(), public_ref=uuid4(), inserted=True)
|
||||
|
||||
def cancel(*args):
|
||||
state.update(status="failed", error_code="TOOL_CANCELLED")
|
||||
|
||||
def complete(*args):
|
||||
completing.set()
|
||||
assert publish.wait(3)
|
||||
state["status"] = "succeeded"
|
||||
return True
|
||||
|
||||
runtime.tool_store = DurableTools(SimpleNamespace(
|
||||
admit_tool=admit, cancel_tools=cancel, complete_tool=complete), None, runtime.session_id)
|
||||
try:
|
||||
old = await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(call())
|
||||
# Start trusted retrieval while generation is active; terminal
|
||||
# confirmation then races with genuine speech and search completion.
|
||||
event = call()
|
||||
async with runtime.lock:
|
||||
await runtime.dispatch(runtime.responses["r1"], event["call_id"],
|
||||
event["name"], event["arguments"], event["item_id"])
|
||||
await asyncio.wait_for(entered.wait(), 3)
|
||||
task = next(iter(runtime.tasks))
|
||||
if completion == "late_result":
|
||||
finish.set()
|
||||
await until(completing.is_set)
|
||||
if terminal_first:
|
||||
await done(runtime)
|
||||
await input_turn(runtime, "u2", 210)
|
||||
if not terminal_first:
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
await done(runtime, status="cancelled")
|
||||
assert old.superseded and old.cancelled.is_set()
|
||||
finish.set()
|
||||
publish.set()
|
||||
await asyncio.wait_for(asyncio.shield(task), 3)
|
||||
assert runtime.usable and runtime.failure is None
|
||||
assert runtime.calls["c1"][1]["result"] is None
|
||||
assert not commands(transport, "conversation.item.create")
|
||||
assert not any(isinstance(e, dict) and e.get("type") == "sources" for e in out)
|
||||
if completion == "cancelled":
|
||||
assert state == dict(status="failed", error_code="TOOL_CANCELLED")
|
||||
await response(runtime, transport, response_id="r2")
|
||||
await done(runtime, "r2")
|
||||
assert runtime.usable and len(commands(transport, "response.create")) == 2
|
||||
assert not runtime.responses["r1"].continued
|
||||
finally:
|
||||
finish.set()
|
||||
publish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("supersede", [False, True])
|
||||
@pytest.mark.parametrize("exc,code", [
|
||||
(ValueError("CANCELLED"), "SEARCH_CANCELLED"),
|
||||
(ValueError("SESSION_REVOKED"), "CONTEXT_REVOKED"),
|
||||
(SQLAlchemyError("private persistence failure"), "DEPENDENCY_UNAVAILABLE"),
|
||||
(TimeoutError(), "SEARCH_TIMEOUT"),
|
||||
(ConnectionError("private provider failure"), "LIVE_PROVIDER_UNAVAILABLE"),
|
||||
])
|
||||
def test_search_failure_policy(runner, persisted, supersede, exc, code):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
entered, finish = asyncio.Event(), asyncio.Event()
|
||||
async def execute(*args):
|
||||
entered.set()
|
||||
await finish.wait()
|
||||
raise exc
|
||||
runtime.tool_store = SimpleNamespace(execute=execute)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await asyncio.wait_for(entered.wait(), 3)
|
||||
task = next(iter(runtime.tasks))
|
||||
if supersede:
|
||||
await input_turn(runtime, "u2", 210)
|
||||
finish.set()
|
||||
await asyncio.wait_for(asyncio.shield(task), 3)
|
||||
if supersede and code == "SEARCH_CANCELLED":
|
||||
assert runtime.usable and runtime.failure is None
|
||||
else:
|
||||
assert not runtime.usable and runtime.failure == code
|
||||
assert not commands(transport, "conversation.item.create")
|
||||
assert runtime.calls["c1"][1]["result"] is None
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("known", [False, True])
|
||||
def test_unverified_profile_cancellation_diagnostics(runner, persisted, caplog, known):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
runtime.adapter.model = "gpt-realtime-2.1"
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await input_turn(runtime, "u2", 210)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await runtime.handle(dict(type="error", error=dict(
|
||||
event_id=runtime.responses["r1"].cancel_event,
|
||||
type="invalid_request_error" if known else "PRIVATE_TYPE",
|
||||
code="response_cancel_not_active" if known else "PRIVATE_CODE",
|
||||
param=None if known else "PRIVATE_PARAM", message="PRIVATE_MESSAGE")))
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert "cancellation_profile_2_1_shimmer=1" in caplog.text
|
||||
for field in ("type", "code", "param"):
|
||||
assert f"cancellation_{field}_match={int(known)}" in caplog.text
|
||||
assert "PRIVATE" not in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["lock_race", "current_flag", "old_without_flag"])
|
||||
def test_cancellation_decision_uses_locked_turn_state(runner, persisted, state):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
entered, finish, raising = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
async def execute(*args):
|
||||
entered.set()
|
||||
await finish.wait()
|
||||
raising.set()
|
||||
raise ValueError("CANCELLED")
|
||||
runtime.tool_store = SimpleNamespace(execute=execute)
|
||||
try:
|
||||
old = await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await asyncio.wait_for(entered.wait(), 3)
|
||||
task = next(iter(runtime.tasks))
|
||||
async with runtime.lock:
|
||||
finish.set()
|
||||
await asyncio.wait_for(raising.wait(), 3)
|
||||
# The exception path is now waiting for this same runtime lock.
|
||||
if state == "current_flag":
|
||||
old.cancelled.set()
|
||||
else:
|
||||
await runtime.new_turn("u2")
|
||||
if state == "old_without_flag":
|
||||
old.cancelled.clear()
|
||||
await asyncio.wait_for(asyncio.shield(task), 3)
|
||||
if state == "lock_race":
|
||||
assert runtime.usable and runtime.failure is None
|
||||
else:
|
||||
assert runtime.failure == "SEARCH_CANCELLED" and not runtime.usable
|
||||
assert runtime.calls["c1"][1]["result"] is None
|
||||
assert not commands(transport, "conversation.item.create")
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
Reference in New Issue
Block a user