"""Same-connection tool ordering; persisted eligibility is tested on PostgreSQL.""" 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, commands @pytest.mark.parametrize('existing_source', [False, True]) def test_same_topic_reuses_original_retrieval_and_new_topic_searches(runner, persisted, existing_source): searches, reuses = [], [] result = dict(status='ok', knowledge_revision=1, warnings=[], sources=[dict( source_ref='S1', document_id=str(uuid4()), chunk_id=str(uuid4()), title='Fixture', text='Verified fixture facts', location=dict(page=1, section=None))]) def search(execution, query, context): searches.append(query) return deepcopy(result) class Store: async def execute(self, external_id, record, ctx, args, invoke): record['durable_id'] = uuid4() return await invoke() async def delivery(self, record, execution): pass async def reuse(self, original, execution): reuses.append(original['durable_id']) return deepcopy(original['result']) async def scenario(): runtime, wire, out = await make(SimpleNamespace(engine=None, search=search), runner, persisted) runtime.tool_store = Store() try: await input_turn(runtime) await response(runtime, wire) await runtime.handle(call(query='first topic')) await done(runtime) await until(lambda: runtime.last_evidence is not None) original = runtime.calls['c1'][1] await response(runtime, wire, 'r2') await done(runtime, 'r2') await input_turn(runtime, 'u2', 210) await response(runtime, wire, 'r3') if existing_source: runtime.current.execution.sources([dict(result['sources'][0], document_id=uuid4(), chunk_id=uuid4())]) reuse = call('r3', 'c2', name='reuse_last_evidence', raw='{}') await runtime.handle(reuse) await runtime.handle(dict(reuse, event_id='duplicate-reuse')) await done(runtime, 'r3') await until(lambda: runtime.calls['c2'][1]['sent']) assert searches == ['first topic'] and reuses == [original['durable_id']] reused = runtime.calls['c2'][1] 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] 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')) await done(runtime, 'r5') await until(lambda: runtime.calls['c3'][1]['sent']) assert searches == ['first topic', 'new topic'] and len(reuses) == 1 finally: await runtime.close() assert runtime.last_evidence is None asyncio.run(scenario()) @pytest.mark.parametrize('raw', ['{}', '{"user_id":"forged"}', '{"query":"q"}', 'null', '[]']) def test_reuse_without_valid_bundle_never_searches_or_accepts_scope(runner, persisted, raw): async def scenario(): runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted) try: await input_turn(runtime) await response(runtime, wire) await runtime.handle(call(name='reuse_last_evidence', raw=raw)) await done(runtime) await until(lambda: runtime.calls['c1'][1]['result'] is not None) result = runtime.calls['c1'][1]['result'] if raw == '{}': assert result['status'] == 'no_evidence' and result['warnings'] == ['fresh_search_required'] else: assert result['error']['code'] == 'INVALID_TOOL_ARGUMENTS' finally: await runtime.close() asyncio.run(scenario()) 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: await input_turn(runtime) 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[0] is origin and origin.interrupted and origin.turn.cancelled.is_set() finally: await runtime.close() asyncio.run(scenario())