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:
amirhosein mazaheri
2026-10-13 14:09:20 +03:30
parent 9cc9f0bc01
commit 18e595ac93
21 changed files with 1346 additions and 60 deletions
+218
View File
@@ -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())