Files
rag-technical-docs-assistant/tests/unit/test_gemini_live.py
amirhosein mazaheri 18e595ac93 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.
2026-10-13 14:09:20 +03:30

227 lines
11 KiB
Python

"""Actual Gemini adapter + runtime + canonical search + StructuredTool/shared runner."""
import asyncio
import base64
from contextlib import nullcontext
import json
from types import SimpleNamespace
from uuid import uuid4
import pytest
from app.infrastructure.gemini_live import GeminiLiveAdapter, PCM24To16, GeminiContextError
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.knowledge import langchain_tool as boundary
from tests.unit.test_search_phase2 import service as canonical_service, row
from tests.unit.test_realtime_phase1 import runner, persisted, until
class FakeGoogleTransport:
def __init__(self):
self.sent = []
self.inbound = asyncio.Queue()
self.closed = 0
async def send(self, value):
self.sent.append(json.loads(value))
async def recv(self):
value = await self.inbound.get()
if isinstance(value, Exception):
raise value
return json.dumps(value) if isinstance(value,dict) else value
async def close(self):
self.closed += 1
async def make(service, runner, state):
wire, output = FakeGoogleTransport(), []
adapter = GeminiLiveAdapter(wire, model='configured-model', voice='Aoede')
async def emit(value): output.append(value)
async def authority(execution):
return state['enabled'] and execution.capture(dict(id=execution.user_id, organization_id='fixture',role='user'),state['epoch'])
runtime = VoiceRuntime(adapter, service, runner, uuid4(), emit, authority_check=authority)
await runtime.start()
receive = asyncio.create_task(runtime.receive_loop())
await until(lambda: wire.sent)
assert not runtime.ready and not adapter.acknowledged(adapter.setup()['session'])
await wire.inbound.put({'setupComplete':{}})
await until(lambda: runtime.ready)
return runtime, adapter, wire, output, receive
async def input_turn(runtime, wire, start=0):
for _ in range(2):
await runtime.input_audio(bytes(4800))
await until(lambda: runtime.input_transport_count == 0)
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_START','audioOffset':f'{start/1000}s'}})
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_END','audioOffset':f'{(start+100)/1000}s'}})
async def cleanup(runtime, receive):
receive.cancel()
await asyncio.gather(receive,return_exceptions=True)
await runtime.close()
def test_close_attempts_transport_when_pump_resists_cancellation():
async def scenario():
wire = FakeGoogleTransport()
aborted = []
wire.transport = SimpleNamespace(abort=lambda: aborted.append(True))
adapter = GeminiLiveAdapter(wire, settings=RuntimeSettings(_env_file=None, send_timeout_seconds=.02))
started, release = asyncio.Event(), asyncio.Event()
async def pump():
started.set()
try:
await release.wait()
except asyncio.CancelledError:
await release.wait()
adapter._pump_task = asyncio.create_task(pump())
await started.wait()
try:
waiter = asyncio.create_task(adapter.close())
await asyncio.sleep(0)
waiter.cancel()
await asyncio.gather(waiter, return_exceptions=True)
for _ in range(2):
with pytest.raises(TimeoutError, match='pump termination'):
await asyncio.wait_for(adapter.close(), .5)
assert wire.closed == 1 and aborted == [True]
assert adapter._inbound_events.empty()
finally:
release.set()
await adapter._pump_task
asyncio.run(scenario())
def test_close_transport_deadline_does_not_wait_for_cancellation_acknowledgement():
async def scenario():
wire = FakeGoogleTransport()
started, release, cancelled = asyncio.Event(), asyncio.Event(), asyncio.Event()
aborted = []
async def close():
wire.closed += 1
started.set()
try:
await release.wait()
except asyncio.CancelledError:
cancelled.set()
await release.wait()
wire.close = close
wire.transport = SimpleNamespace(abort=lambda: aborted.append(True))
adapter = GeminiLiveAdapter(wire, settings=RuntimeSettings(_env_file=None, send_timeout_seconds=.02))
try:
with pytest.raises(TimeoutError, match='transport close'):
await asyncio.wait_for(adapter.close(), .5)
await started.wait()
await cancelled.wait()
assert wire.closed == 1 and aborted == [True]
with pytest.raises(TimeoutError, match='transport close'):
await adapter.close()
assert wire.closed == 1
finally:
release.set()
await asyncio.sleep(0)
asyncio.run(scenario())
@pytest.mark.parametrize('rows,status', [([row()],'ok'),([],'no_evidence')])
def test_native_tool_correlation_canonical_result_and_once_only_continuation(settings,monkeypatch,runner,persisted,rows,status):
service = canonical_service(settings,monkeypatch,rows)
async def scenario():
runtime,adapter,wire,out,receive = await make(service,runner,persisted)
try:
assert wire.sent[0]['setup']['model']=='models/configured-model'
assert wire.sent[0]['setup']['inputAudioTranscription']=={}
await input_turn(runtime,wire)
await wire.inbound.put({'serverContent': {'inputTranscription':{'text':'پرسش'}}})
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':'q'}}
await wire.inbound.put({'toolCall':{'functionCalls':[fn]}})
await until(lambda: any('toolResponse' in m for m in wire.sent) or not runtime.usable)
assert runtime.usable, runtime.failure
responses=[m['toolResponse'] for m in wire.sent if 'toolResponse' in m]
assert len(responses)==1
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)
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
asyncio.run(scenario())
@pytest.mark.parametrize('message', [ConnectionError('remote-private-detail'), 'x'*262145,
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}],
ids=['provider_loss', 'oversized_frame', 'unexpected_interruption', 'goaway'])
def test_provider_loss_and_limits_wake_runtime_and_close_once(runner,persisted,message):
async def scenario():
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
await wire.inbound.put(message)
await asyncio.wait_for(runtime.failure_signal.wait(),2)
await cleanup(runtime,receive)
assert wire.closed==1 and not runtime.usable
assert 'remote-private-detail' not in json.dumps([e for e in out if isinstance(e,dict)])
asyncio.run(scenario())
def test_no_fabricated_cancel_or_truncate_acknowledgement():
async def scenario():
wire=FakeGoogleTransport();adapter=GeminiLiveAdapter(wire)
with pytest.raises(GeminiContextError):
await adapter.send({'type':'response.cancel','response_id':'private'})
await adapter.close()
assert wire.closed==1 and not wire.sent and adapter._inbound_events.empty()
asyncio.run(scenario())
def test_bounded_queue_and_resampler_partition_invariance():
adapter=GeminiLiveAdapter(FakeGoogleTransport())
for i in range(adapter.settings.max_control_messages): adapter._put({'type':'test','n':i})
with pytest.raises(ValueError): adapter._put({'type':'overflow'})
pcm=bytes([1,3])*2400
assert len(PCM24To16().convert(pcm))==3200
a=PCM24To16();b=PCM24To16()
assert a.convert(pcm)==b.convert(pcm[:200])+b.convert(pcm[200:])
def test_unverified_input_boundaries_fail_closed(runner,persisted):
async def scenario():
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
await wire.inbound.put({'toolCall':{'functionCalls':[{'id':'x','name':'search_knowledge','args':{'query':'q'}}]}})
await asyncio.wait_for(runtime.failure_signal.wait(),2)
assert not runtime.calls
await cleanup(runtime,receive)
asyncio.run(scenario())
def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monkeypatch,runner,persisted,capsys):
from app import voice_smoke
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice import runtime as runtime_module
monkeypatch.setattr(runtime_module,'transaction',lambda _:nullcontext(None))
monkeypatch.setattr(runtime_module,'authority',boundary.authority)
class Scripted(FakeGoogleTransport):
async def send(self,value):
await super().send(value)
message=self.sent[-1]
if 'setup' in message:await self.inbound.put({'setupComplete':{}})
elif 'clientContent' in message:
await self.inbound.put({'toolCall':{'functionCalls':[{'id':'private','name':'search_knowledge','args':{'query':'q'}}]}})
elif 'toolResponse' in message:
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
wire=Scripted()
async def connection(*args):return wire
monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connection)
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
service=canonical_service(settings,monkeypatch,[row()])
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
assert wire.sent[0]['setup']['model']=='models/configured-model'
assert wire.closed==1
assert 'smoke_correlation' in capsys.readouterr().out