"""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.support.local_s2s_runtime import make_local 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']) @pytest.mark.parametrize('provider',['openai','local_s2s']) def test_repeated_same_question_uses_one_retained_search(runner, persisted, monkeypatch, ready_first, tool, provider): async def scenario(): runtime, wire, out = await (make_local if provider=='local_s2s' else 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())