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
@@ -84,3 +84,119 @@ def test_reuse_rechecks_revision_at_delivery_boundary(seeded_env):
conn.execute(text('UPDATE organization_settings SET knowledge_revision=knowledge_revision+1 WHERE organization_id=:org'), {'org': e.org})
with pytest.raises(ValueError, match='CONTEXT_REVOKED'):
asyncio.run(store.delivery(dict(original, reused_result=result), execution))
@pytest.mark.parametrize('change', ['none', 'deactivate', 'delete', 'epoch', 'reuse_revision'])
def test_declared_source_delivery_revalidates_original_postgres_evidence(seeded_env, change):
e = seeded_env
sid, original = saved_evidence(e)
store = DurableTools(e.lifecycle, e.user, sid)
execution = SearchExecution(e.actor)
if change == 'reuse_revision':
original['reused_result'] = asyncio.run(store.reuse(original, execution))
else:
e.lifecycle.validate_stream(e.user, sid, execution)
with e.engine.begin() as conn:
if change == 'deactivate':
conn.execute(text('UPDATE documents SET is_active=false WHERE id=:id'), {'id': e.doc})
elif change == 'delete':
conn.execute(text('UPDATE documents SET is_active=false,deleted_at=now() WHERE id=:id'), {'id': e.doc})
elif change == 'epoch':
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:id'), {'id': e.org})
elif change == 'reuse_revision':
conn.execute(text('UPDATE organization_settings SET knowledge_revision=knowledge_revision+1 WHERE organization_id=:id'), {'id': e.org})
report = dict(name='report_used_sources', source_origins=[original])
if change == 'none':
asyncio.run(store.delivery(report, execution))
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM tool_calls WHERE live_session_id=:sid'), {'sid': sid}).scalar_one() == 1
else:
from app.modules.voice.durable_tools import DurableFailure
with pytest.raises(DurableFailure):
asyncio.run(store.delivery(report, execution))
@pytest.mark.parametrize('change', ['none', 'revision', 'deactivate', 'epoch'])
def test_interrupted_pending_search_reuses_one_postgres_row(seeded_env, monkeypatch, change):
from copy import deepcopy
from types import SimpleNamespace
from app.infrastructure.blocking import blocking
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.knowledge.langchain_tool import SearchToolRunner
from app.modules.voice.runtime import VoiceRuntime
from tests.unit.test_realtime_phase1 import Transport, input_turn, response, call, done, until, commands
e = seeded_env
_, sid = reserve(e)
with e.engine.connect() as conn:
chunk = conn.execute(text('SELECT id,text,location FROM document_chunks WHERE document_id=:id'), {'id': e.doc}).mappings().first()
revision = conn.execute(text('SELECT knowledge_revision FROM organization_settings WHERE organization_id=:id'), {'id': e.org}).scalar_one()
result = dict(status='ok', knowledge_revision=revision, warnings=[], sources=[dict(
document_id=str(e.doc), chunk_id=str(chunk['id']), source_ref='S1', title='Fixture',
text=chunk['text'], location=chunk['location'])])
runner = SearchToolRunner(running=1, waiting=1, timeout=2)
async def scenario():
wire, events = Transport(), []
started, finish = asyncio.Event(), asyncio.Event()
store = DurableTools(e.lifecycle, e.user, sid)
async def authority(execution):
await blocking(e.lifecycle.validate_stream, e.user, sid, execution)
return True
async def emit(event):
if isinstance(event, dict) and event['type'] == 'turn_interrupted':
await blocking(e.lifecycle.cancel_tools, e.user, sid, event['cancelled_tool_call_ids'])
events.append(event)
runtime = VoiceRuntime(RealtimeAdapter(wire), SimpleNamespace(engine=e.engine), runner,
e.actor, emit, authority_check=authority, tool_store=store, session_id=str(sid))
async def invoke(args):
started.set()
await finish.wait()
return deepcopy(result)
monkeypatch.setattr('app.modules.voice.runtime.create_search_tool',
lambda *_: SimpleNamespace(ainvoke=invoke))
try:
await runtime.start()
await until(lambda: bool(commands(wire, 'session.update')))
await runtime.handle(dict(type='session.updated', session=deepcopy(runtime.adapter.setup()['session'])))
await until(lambda: runtime.ready)
await input_turn(runtime)
await response(runtime, wire)
await runtime.handle(call())
await done(runtime)
await started.wait()
original = runtime.calls['c1'][1]
runtime.responses['r1'].visible = True
await input_turn(runtime, 'u2', 210)
await response(runtime, wire, 'r2')
with e.engine.connect() as conn:
assert conn.execute(text('SELECT status FROM tool_calls WHERE id=:id'), {'id': original['durable_id']}).scalar_one() == 'running'
await runtime.handle(call('r2', 'reuse', name='reuse_last_evidence', raw='{}'))
await done(runtime, 'r2')
with e.engine.begin() as conn:
if change == 'revision':
conn.execute(text('UPDATE organization_settings SET knowledge_revision=knowledge_revision+1 WHERE organization_id=:id'), {'id': e.org})
elif change == 'deactivate':
conn.execute(text('UPDATE documents SET is_active=false WHERE id=:id'), {'id': e.doc})
elif change == 'epoch':
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:id'), {'id': e.org})
finish.set()
if change == 'none':
await until(lambda: runtime.calls['reuse'][1]['sent'])
reused = runtime.calls['reuse'][1]
assert reused['durable_id'] == original['durable_id']
assert reused['ref'] == original['ref']
assert reused['result']['sources'][0]['chunk_id'] == str(chunk['id'])
await store.delivery(reused, runtime.current.execution)
assert runtime.usable
else:
await until(lambda: not runtime.usable)
assert runtime.failure == 'CONTEXT_REVOKED'
assert not [event for event in events if isinstance(event, dict) and event['type'] == 'sources']
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM tool_calls WHERE live_session_id=:id'), {'id': sid}).scalar_one() == 1
finally:
finish.set()
await runtime.close()
try:
asyncio.run(scenario())
finally:
runner.close()