fix(voice): preserve interrupted searches and report used sources
Retain and revalidate interrupted searches, resolve abandoned provider calls, recover invalid source reports privately, and expose only declared sources. Improve Persian delivery and provider event replay capacity. Include regression coverage and contract updates.
This commit is contained in:
@@ -136,13 +136,23 @@ def test_native_tool_correlation_canonical_result_and_once_only_continuation(set
|
||||
answer=responses[0]['functionResponses'][0]
|
||||
assert answer['id']=='private-google-call' and answer['response']['status']==status
|
||||
assert answer['response']['sources']==next(iter(runtime.calls.values()))[1]['result']['sources']
|
||||
assert not any(isinstance(e, dict) and e.get('type') == 'sources' for e in out)
|
||||
if status == 'ok':
|
||||
await wire.inbound.put({'toolCall': {'functionCalls': [dict(id='private-report',
|
||||
name='report_used_sources', args=dict(source_refs=['S1']))]}})
|
||||
await until(lambda: len([m for m in wire.sent if 'toolResponse' in m]) == 2 or not runtime.usable)
|
||||
assert runtime.usable, runtime.failure
|
||||
await wire.inbound.put({'serverContent': {'modelTurn':{'parts':[{'inlineData':{'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(960)).decode()}}]},'outputTranscription':{'text':'پاسخ'},'turnComplete':True}})
|
||||
await until(lambda: any(isinstance(e,dict) and e.get('type')=='audio_ended' for e in out) or not runtime.usable)
|
||||
assert runtime.usable, runtime.failure
|
||||
assert any(isinstance(e,dict) and e.get('role')=='user' and e['text']=='پرسش' for e in out)
|
||||
assert any(isinstance(e,dict) and e.get('role')=='assistant' and e['status']=='completed' and e['text']=='پاسخ' for e in out)
|
||||
source_event=next(e for e in out if isinstance(e,dict) and e.get('type')=='sources')
|
||||
assert source_event['tool_call_id']!='private-google-call'
|
||||
events=[e for e in out if isinstance(e,dict) and e.get('type')=='sources']
|
||||
if status == 'ok':
|
||||
assert len(events) == 1 and events[0]['tool_call_id'] != 'private-google-call'
|
||||
assert [s['source_ref'] for s in events[0]['sources']] == ['S1']
|
||||
else:
|
||||
assert events == []
|
||||
finally:
|
||||
await cleanup(runtime,receive)
|
||||
assert wire.closed==1
|
||||
|
||||
@@ -49,7 +49,7 @@ def test_gemini_effective_policy_and_evidence_revision_are_pinned():
|
||||
asyncio.run(scenario())
|
||||
profile = VoiceSettings(_env_file=None, provider='gemini').profile()
|
||||
assert set(profile) == {'provider','model','voice','input_sample_rate','output_sample_rate','evidence_policy_revision'}
|
||||
assert profile['evidence_policy_revision'] == 'same-session-evidence-v1'
|
||||
assert profile['evidence_policy_revision'] == 'same-session-evidence-retained-v5'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('voice', ['marin', 'cedar'])
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Session replay capacity supports ordinary multi-turn provider traffic."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, make
|
||||
|
||||
|
||||
def test_session_accepts_more_than_old_event_cap_and_still_detects_replay_conflict(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
original = dict(type='rate_limits.updated', event_id='event-0', rate_limits=[])
|
||||
for index in range(4200):
|
||||
await runtime.handle(dict(original, event_id=f'event-{index}'))
|
||||
assert runtime.usable
|
||||
count = len(runtime.events)
|
||||
await runtime.handle(original)
|
||||
assert runtime.usable and len(runtime.events) == count
|
||||
await runtime.handle(dict(original, rate_limits=[dict(name='changed')]))
|
||||
assert runtime.failure == 'LIVE_PROVIDER_PROTOCOL_ERROR'
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_configured_event_cap_remains_finite_and_fails_safely(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
runtime.settings = RuntimeSettings(_env_file=None, max_events=8)
|
||||
try:
|
||||
for index in range(9):
|
||||
await runtime.handle(dict(type='rate_limits.updated', event_id=f'event-{index}', rate_limits=[]))
|
||||
assert runtime.failure == 'LIVE_BUFFER_OVERFLOW'
|
||||
assert len(runtime.events) == 8
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_event_capacity_rejects_unbounded_configuration():
|
||||
with pytest.raises(ValidationError):
|
||||
RuntimeSettings(_env_file=None, max_events=32769)
|
||||
@@ -54,11 +54,16 @@ def test_same_topic_reuses_original_retrieval_and_new_topic_searches(runner, per
|
||||
assert reused['ref'] == original['ref'] and reused['durable_id'] == original['durable_id']
|
||||
expected = dict(original['result']['sources'][0], source_ref='S2' if existing_source else 'S1')
|
||||
assert reused['result']['sources'] == [expected]
|
||||
await until(lambda: any(isinstance(e, dict) and e.get('type') == 'sources' and e.get('turn_ref') == 'live-turn-2' for e in out))
|
||||
event = next(e for e in out if isinstance(e, dict) and e.get('type') == 'sources' and e.get('turn_ref') == 'live-turn-2')
|
||||
assert event['tool_call_id'] == original['ref']
|
||||
assert not any(isinstance(e, dict) and e.get('type') == 'sources' for e in out)
|
||||
await response(runtime, wire, 'r4')
|
||||
await runtime.handle(call('r4', 'reported', name='report_used_sources',
|
||||
raw='{"source_refs":["' + expected['source_ref'] + '"]}'))
|
||||
await done(runtime, 'r4')
|
||||
await until(lambda: any(isinstance(e, dict) and e.get('type') == 'sources' for e in out))
|
||||
event = next(e for e in out if isinstance(e, dict) and e.get('type') == 'sources')
|
||||
assert event['turn_ref'] == 'live-turn-2' and event['tool_call_id'] == original['ref']
|
||||
await response(runtime, wire, 'reported-answer')
|
||||
await done(runtime, 'reported-answer')
|
||||
await input_turn(runtime, 'u3', 420)
|
||||
await response(runtime, wire, 'r5')
|
||||
await runtime.handle(call('r5', 'c3', query='new topic'))
|
||||
@@ -91,7 +96,7 @@ def test_reuse_without_valid_bundle_never_searches_or_accepts_scope(runner, pers
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_interrupted_turn_clears_evidence_before_continuation(runner, persisted):
|
||||
def test_interrupted_turn_retains_evidence_without_releasing_old_response(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
@@ -99,7 +104,7 @@ def test_interrupted_turn_clears_evidence_before_continuation(runner, persisted)
|
||||
origin = await response(runtime, wire)
|
||||
runtime.last_evidence = (origin, dict(durable_id=uuid4(), result=dict(status='ok', sources=[])))
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
assert runtime.last_evidence is None and origin.interrupted and origin.turn.cancelled.is_set()
|
||||
assert runtime.last_evidence[0] is origin and origin.interrupted and origin.turn.cancelled.is_set()
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Display declared citations, never the entire retrieval candidate set."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from app.infrastructure.realtime import canonical_json
|
||||
from app.modules.voice.durable_tools import DurableTools, DurableFailure
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, response, call, done, until
|
||||
|
||||
|
||||
def evidence():
|
||||
return dict(status='ok', warnings=[], sources=[dict(source_ref=f'S{i}',
|
||||
document_id=str(uuid4()), chunk_id=str(uuid4()), title=f'Document {i}',
|
||||
text=f'Evidence {i}', location=dict(page=i, section=None)) for i in (1, 2, 3)])
|
||||
|
||||
|
||||
def source_events(out):
|
||||
return [e for e in out if isinstance(e, dict) and e.get('type') == 'sources']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('refs', [['S2'], ['S1', 'S3'], []])
|
||||
def test_only_reported_sources_reach_ui_and_duplicate_report_is_idempotent(runner, persisted, refs):
|
||||
result = evidence()
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None,
|
||||
search=lambda *_: deepcopy(result)), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(lambda: runtime.calls['c1'][1]['sent'])
|
||||
assert source_events(out) == []
|
||||
await response(runtime, wire, 'r2')
|
||||
report = call('r2', 'report', name='report_used_sources',
|
||||
raw=canonical_json(dict(source_refs=refs)))
|
||||
await runtime.handle(report)
|
||||
await runtime.handle(dict(report, event_id='duplicate-report'))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: runtime.calls['report'][1]['sent'])
|
||||
if refs:
|
||||
await until(lambda: bool(source_events(out)))
|
||||
assert len(source_events(out)) == 1
|
||||
event = source_events(out)[0]
|
||||
assert {s['source_ref'] for s in event['sources']} == set(refs)
|
||||
assert event['tool_call_id'] == runtime.calls['c1'][1]['ref']
|
||||
for source in event['sources']:
|
||||
original = next(s for s in result['sources'] if s['source_ref'] == source['source_ref'])
|
||||
assert source['document_id'] == original['document_id']
|
||||
assert source['chunk_id'] == original['chunk_id']
|
||||
assert source['excerpt'] == original['text']
|
||||
else:
|
||||
assert source_events(out) == []
|
||||
assert runtime.usable
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('args', [dict(source_refs=['S99']), dict(source_refs=['S1','S1']),
|
||||
dict(source_refs=['S1'], document_id='forged'), dict(source_refs='S1'), {},
|
||||
dict(source_refs=[None])])
|
||||
def test_invalid_reports_never_publish_sources(runner, persisted, args):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None,
|
||||
search=lambda *_: evidence()), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(lambda: runtime.calls['c1'][1]['sent'])
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2','report',name='report_used_sources',raw=canonical_json(args)))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: runtime.calls['report'][1]['sent'])
|
||||
assert runtime.calls['report'][1]['result']['error']['code'] == 'INVALID_TOOL_ARGUMENTS'
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'error']
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_prior_turn_sources_cannot_be_reported_without_revalidated_reuse(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None, search=lambda *_: evidence()), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(lambda: runtime.calls['c1'][1]['sent'])
|
||||
await response(runtime, wire, 'r2')
|
||||
await done(runtime, 'r2')
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await response(runtime, wire, 'r3')
|
||||
await runtime.handle(call('r3','report',name='report_used_sources',raw='{"source_refs":["S1"]}'))
|
||||
await done(runtime, 'r3')
|
||||
await until(lambda: runtime.calls['report'][1]['sent'])
|
||||
assert runtime.calls['report'][1]['result']['error']['code'] == 'INVALID_TOOL_ARGUMENTS'
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'error']
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_authority_loss_before_report_delivery_suppresses_sources(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None, search=lambda *_: evidence()), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(lambda: runtime.calls['c1'][1]['sent'])
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2','report',name='report_used_sources',raw='{"source_refs":["S1"]}'))
|
||||
persisted['enabled'] = False
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: not runtime.usable)
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_report_delivery_revalidates_each_real_retrieval_and_propagates_revocation():
|
||||
async def scenario():
|
||||
calls = []
|
||||
def tool_result(user, session, durable_id, execution, **kwargs):
|
||||
calls.append(durable_id)
|
||||
if durable_id == 'revoked':
|
||||
raise ValueError('CONTEXT_REVOKED')
|
||||
return dict(status='ok', sources=[])
|
||||
store = DurableTools(SimpleNamespace(tool_result=tool_result), None, None)
|
||||
originals = [dict(durable_id=x, result=dict(status='ok', sources=[])) for x in ('valid','revoked')]
|
||||
with pytest.raises(DurableFailure) as failure:
|
||||
await store.delivery(dict(name='report_used_sources', source_origins=originals), None)
|
||||
assert failure.value.live_code == 'CONTEXT_REVOKED'
|
||||
assert calls == ['valid','revoked']
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_invalid_source_report_can_be_corrected_without_browser_error(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None, search=lambda *_: evidence()), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(lambda: runtime.calls['c1'][1]['sent'])
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2', 'bad-report', name='report_used_sources', raw='{"source_refs":["S99"]}'))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: runtime.calls['bad-report'][1]['sent'])
|
||||
result = runtime.calls['bad-report'][1]['result']
|
||||
assert result['available_source_refs'] == ['S1', 'S2', 'S3']
|
||||
assert source_events(out) == []
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'error']
|
||||
await response(runtime, wire, 'r3')
|
||||
await runtime.handle(call('r3', 'good-report', name='report_used_sources', raw='{"source_refs":["S2"]}'))
|
||||
await done(runtime, 'r3')
|
||||
await until(lambda: bool(source_events(out)))
|
||||
assert [s['source_ref'] for s in source_events(out)[0]['sources']] == ['S2']
|
||||
assert runtime.usable
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_interrupted_search_is_resolved_before_new_turn_and_can_search_again(runner, persisted):
|
||||
from threading import Event
|
||||
from tests.unit.test_realtime_phase1 import commands
|
||||
started, release = Event(), Event()
|
||||
invocations = []
|
||||
def search(execution, query, context):
|
||||
invocations.append(query)
|
||||
if len(invocations) == 1:
|
||||
started.set()
|
||||
release.wait(2)
|
||||
return evidence()
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await until(started.is_set)
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await until(lambda: len(commands(wire, 'response.create')) == 2)
|
||||
outputs = commands(wire, 'conversation.item.create')
|
||||
assert len(outputs) == 1
|
||||
item = outputs[0]['item']
|
||||
assert item['call_id'] == 'c1'
|
||||
assert __import__('json').loads(item['output'])['status'] == 'cancelled'
|
||||
assert __import__('json').loads(item['output'])['sources'] == []
|
||||
assert wire.sent.index(outputs[0]) < wire.sent.index(commands(wire, 'response.create')[1])
|
||||
assert runtime.last_evidence[1] is runtime.calls['c1'][1]
|
||||
assert not runtime.calls['c1'][1]['retrieval_cancelled'].is_set()
|
||||
assert source_events(out) == []
|
||||
release.set()
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2', 'fresh-search'))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: runtime.calls['fresh-search'][1]['sent'])
|
||||
assert len(invocations) == 2
|
||||
assert runtime.calls['fresh-search'][1]['result']['status'] == 'ok'
|
||||
assert not [e for e in out if isinstance(e, dict) and e.get('type') == 'error']
|
||||
assert runtime.usable
|
||||
finally:
|
||||
release.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Interrupted same-topic turns await one search and revalidate its real identity."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, response, call, done, until
|
||||
from tests.unit.test_voice_reported_sources import evidence, source_events
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, rejected=False):
|
||||
self.searches, self.reuses = 0, 0
|
||||
self.rejected = rejected
|
||||
async def execute(self, external_id, original, ctx, args, invoke):
|
||||
self.searches += 1
|
||||
original['durable_id'] = uuid4()
|
||||
return await invoke()
|
||||
async def delivery(self, original, execution):
|
||||
pass
|
||||
async def reuse(self, original, execution):
|
||||
self.reuses += 1
|
||||
if self.rejected:
|
||||
raise ValueError('CONTEXT_REVOKED')
|
||||
return deepcopy(original.get('retained_result', original['result']))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ready_first', [False, True])
|
||||
@pytest.mark.parametrize('tool', ['reuse_last_evidence', 'search_knowledge'])
|
||||
def test_repeated_same_question_uses_one_retained_search(runner, persisted, monkeypatch, ready_first, tool):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
started, finish = asyncio.Event(), asyncio.Event()
|
||||
store = Store()
|
||||
runtime.tool_store = store
|
||||
result = evidence()
|
||||
async def invoke(args):
|
||||
started.set()
|
||||
await finish.wait()
|
||||
return result
|
||||
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
|
||||
lambda *_: SimpleNamespace(ainvoke=invoke))
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call(query='office hours'))
|
||||
await done(runtime)
|
||||
await started.wait()
|
||||
original = runtime.calls['c1'][1]
|
||||
if ready_first:
|
||||
finish.set()
|
||||
await until(lambda: original['sent'])
|
||||
# Interrupt the next audible-answer response as well.
|
||||
await response(runtime, wire, 'answer')
|
||||
await done(runtime, 'answer')
|
||||
# Three impatient follow-ups while the same search is pending.
|
||||
for index in range(2, 5):
|
||||
await input_turn(runtime, f'u{index}', (index - 1) * 210)
|
||||
await response(runtime, wire, f'r{index}')
|
||||
await runtime.handle(call(f'r{index}', f'reuse-{index}', name=tool,
|
||||
raw='{}' if tool == 'reuse_last_evidence' else '{"query":"office hours","context":null}'))
|
||||
await done(runtime, f'r{index}')
|
||||
assert store.searches == 1
|
||||
assert not original['retrieval_cancelled'].is_set()
|
||||
assert source_events(out) == []
|
||||
finish.set()
|
||||
current = runtime.calls['reuse-4'][1]
|
||||
await until(lambda: current['sent'])
|
||||
assert current['result']['status'] == 'ok'
|
||||
assert current['ref'] == original['ref'] and current['durable_id'] == original['durable_id']
|
||||
await response(runtime, wire, 'report')
|
||||
await runtime.handle(call('report', 'used', name='report_used_sources', raw='{"source_refs":["S2"]}'))
|
||||
await done(runtime, 'report')
|
||||
await until(lambda: bool(source_events(out)))
|
||||
event = source_events(out)[0]
|
||||
assert event['turn_ref'] == 'live-turn-4'
|
||||
assert [s['source_ref'] for s in event['sources']] == ['S2']
|
||||
assert store.searches == 1
|
||||
assert runtime.usable
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_new_topic_cancels_old_search_and_never_reuses_its_result(runner, persisted, monkeypatch):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
started, finish = asyncio.Event(), asyncio.Event()
|
||||
store = Store()
|
||||
runtime.tool_store = store
|
||||
async def invoke(args):
|
||||
if args['query'] == 'old topic':
|
||||
started.set()
|
||||
await finish.wait()
|
||||
return evidence()
|
||||
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
|
||||
lambda *_: SimpleNamespace(ainvoke=invoke))
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call(query='old topic'))
|
||||
await done(runtime)
|
||||
await started.wait()
|
||||
original = runtime.calls['c1'][1]
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2', 'new', query='new topic'))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: runtime.calls['new'][1]['sent'])
|
||||
assert original['retrieval_cancelled'].is_set()
|
||||
finish.set()
|
||||
await original['retrieval_task']
|
||||
assert 'retained_result' not in original
|
||||
assert runtime.last_evidence[1] is runtime.calls['new'][1]
|
||||
assert store.searches == 2 and store.reuses == 0
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['authority', 'eligibility'])
|
||||
def test_retained_result_is_not_published_after_revocation(runner, persisted, monkeypatch, change):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
started, finish = asyncio.Event(), asyncio.Event()
|
||||
runtime.tool_store = Store(rejected=change == 'eligibility')
|
||||
async def invoke(args):
|
||||
started.set()
|
||||
await finish.wait()
|
||||
return evidence()
|
||||
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
|
||||
lambda *_: SimpleNamespace(ainvoke=invoke))
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await started.wait()
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await response(runtime, wire, 'r2')
|
||||
await runtime.handle(call('r2', 'reuse', name='reuse_last_evidence', raw='{}'))
|
||||
await done(runtime, 'r2')
|
||||
if change == 'authority':
|
||||
persisted['enabled'] = False
|
||||
finish.set()
|
||||
await until(lambda: not runtime.usable)
|
||||
assert runtime.failure == 'CONTEXT_REVOKED'
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_session_stop_cancels_independent_retained_search(runner, persisted, monkeypatch):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
started, finish = asyncio.Event(), asyncio.Event()
|
||||
async def invoke(args):
|
||||
started.set()
|
||||
await finish.wait()
|
||||
return evidence()
|
||||
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
|
||||
lambda *_: SimpleNamespace(ainvoke=invoke))
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await started.wait()
|
||||
token = runtime.calls['c1'][1]['retrieval_cancelled']
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
assert not token.is_set()
|
||||
runtime.stop_requested()
|
||||
assert token.is_set()
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_repeated_waiter_does_not_reset_original_search_deadline(runner, persisted, monkeypatch):
|
||||
import time
|
||||
current_time = [time.monotonic()]
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted,
|
||||
clock=lambda: current_time[0])
|
||||
runtime.tool_seconds = 10
|
||||
started, finish = asyncio.Event(), asyncio.Event()
|
||||
store = Store()
|
||||
runtime.tool_store = store
|
||||
async def invoke(args):
|
||||
started.set()
|
||||
await finish.wait()
|
||||
return evidence()
|
||||
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
|
||||
lambda *_: SimpleNamespace(ainvoke=invoke))
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(call())
|
||||
await done(runtime)
|
||||
await started.wait()
|
||||
await input_turn(runtime, 'u2', 210)
|
||||
await response(runtime, wire, 'r2')
|
||||
current_time[0] += 11
|
||||
await runtime.handle(call('r2', 'reuse', name='reuse_last_evidence', raw='{}'))
|
||||
await done(runtime, 'r2')
|
||||
await until(lambda: not runtime.usable)
|
||||
assert runtime.failure == 'SEARCH_TIMEOUT'
|
||||
assert store.searches == 1 and store.reuses == 0
|
||||
assert source_events(out) == []
|
||||
finally:
|
||||
finish.set()
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Old-turn durable cancellation must not terminate a healthy voice session."""
|
||||
import asyncio
|
||||
import json
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
@@ -76,10 +77,15 @@ def test_old_search_interruption_keeps_session_usable(
|
||||
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")
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
outputs = commands(transport, "conversation.item.create")
|
||||
assert len(outputs) == 1 and outputs[0]["item"]["call_id"] == "c1"
|
||||
payload = json.loads(outputs[0]["item"]["output"])
|
||||
assert payload["status"] == "cancelled" and payload["sources"] == []
|
||||
assert "Old evidence" not in outputs[0]["item"]["output"]
|
||||
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")
|
||||
assert state == dict(status="succeeded")
|
||||
assert runtime.calls["c1"][1]["retained_result"] == result
|
||||
await response(runtime, transport, response_id="r2")
|
||||
await done(runtime, "r2")
|
||||
assert runtime.usable and len(commands(transport, "response.create")) == 2
|
||||
@@ -117,13 +123,22 @@ def test_search_failure_policy(runner, persisted, supersede, exc, code):
|
||||
task = next(iter(runtime.tasks))
|
||||
if supersede:
|
||||
await input_turn(runtime, "u2", 210)
|
||||
if code == "SEARCH_CANCELLED":
|
||||
# Explicit topic discard cancels retrieval; speech alone does not.
|
||||
runtime.calls["c1"][1]["retrieval_cancelled"].set()
|
||||
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")
|
||||
outputs = commands(transport, "conversation.item.create")
|
||||
if not supersede:
|
||||
assert outputs == []
|
||||
for output in outputs:
|
||||
payload = json.loads(output["item"]["output"])
|
||||
assert output["item"]["call_id"] == "c1"
|
||||
assert payload["status"] == "cancelled" and payload["sources"] == []
|
||||
assert runtime.calls["c1"][1]["result"] is None
|
||||
finally:
|
||||
finish.set()
|
||||
@@ -189,8 +204,10 @@ def test_cancellation_decision_uses_locked_turn_state(runner, persisted, state):
|
||||
old.cancelled.set()
|
||||
else:
|
||||
await runtime.new_turn("u2")
|
||||
if state == "lock_race":
|
||||
runtime.calls["c1"][1]["retrieval_cancelled"].set()
|
||||
if state == "old_without_flag":
|
||||
old.cancelled.clear()
|
||||
runtime.calls["c1"][1]["retrieval_cancelled"].clear()
|
||||
await asyncio.wait_for(asyncio.shield(task), 3)
|
||||
if state == "lock_race":
|
||||
assert runtime.usable and runtime.failure is None
|
||||
|
||||
Reference in New Issue
Block a user