Files
rag-technical-docs-assistant/tests/unit/test_phase2_provider_selection.py
amirhosein mazaheri a769196bfa fix(voice): correct input accounting and session termination
Separate detected speech limits from continuous microphone silence while preserving transport bounds and absolute commit fencing.

Handle verified OpenAI cancellation races and terminal items, preserve causal close outcomes, and share bounded cleanup ownership with safe diagnostics.

Add regression coverage and align the API contract and frontend handoff. Validation: 61 focused unit tests passed; staged diff whitespace checks passed. Live browser acceptance remains outstanding.
2026-10-10 17:41:11 +03:30

170 lines
9.8 KiB
Python

"""Selected-provider construction, authority truthfulness and continuous idle admission."""
import asyncio
from types import SimpleNamespace
from uuid import uuid4
import pytest
from sqlalchemy.exc import OperationalError
from app.modules.voice.configuration import VoiceSettings
from app.infrastructure import voice_provider
from app.infrastructure.gemini_live import GeminiLiveAdapter
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup, input_turn as gemini_input_turn
from tests.unit.test_realtime_phase1 import runner, persisted, until
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
def test_selected_credentials_factory_profile_and_native_audio(provider,adapter,rate,monkeypatch):
config=VoiceSettings(_env_file=None,provider=provider,**{('gemini_api_key' if provider=='gemini' else 'openai_realtime_api_key'):'fake-only'})
config.require_voice()
with pytest.raises(ValueError,match='LIVE_PROVIDER_UNAVAILABLE'):
VoiceSettings(_env_file=None,provider=provider).require_voice()
wire=FakeGoogleTransport();seen=[]
async def connect(*args):seen.append(args);return wire
monkeypatch.setattr(voice_provider,'connect_'+provider,connect)
async def scenario():
selected=await voice_provider.create_adapter(config,RuntimeSettings())
assert isinstance(selected,adapter)
assert seen[0][:3]==('fake-only',config.selected_model,config.selected_proxy)
assert config.profile()['input_sample_rate']==rate
setup=selected.setup()
if provider=='openai':
assert setup['session']['audio']['input']['format']['rate']==24000
await selected.send({'type':'input_audio_buffer.append','audio':'AAAA'})
assert wire.sent[-1]['audio']=='AAAA'
await selected.send({'type':'conversation.item.truncate','item_id':'private','content_index':0,'audio_end_ms':5})
assert wire.sent[-1]['audio_end_ms']==5
await selected.close();assert wire.closed==1
asyncio.run(scenario())
def test_provider_alias_priority_conflicts_and_embedding_independence(monkeypatch,tmp_path):
monkeypatch.setenv('PROVIDER','gemini');monkeypatch.setenv('VOICE_PROVIDER','gemini')
monkeypatch.setenv('OPENAI_API_KEY','embedding-only')
assert VoiceSettings(_env_file=None).provider=='gemini'
assert VoiceSettings(_env_file=None,provider='openai').provider=='openai'
monkeypatch.setenv('VOICE_PROVIDER','openai')
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=None)
monkeypatch.delenv('PROVIDER')
assert not VoiceSettings(_env_file=None).openai_realtime_api_key.get_secret_value()
env=tmp_path/'.env';env.write_text('PROVIDER=gemini\n')
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=env)
monkeypatch.delenv('VOICE_PROVIDER');assert VoiceSettings(_env_file=env).provider=='gemini'
with pytest.raises(ValueError,match='Conflicting'):
VoiceSettings(_env_file=None,VOICE_PROVIDER='openai',provider='gemini')
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
(ValueError('SESSION_EXPIRED'),'CONTEXT_REVOKED'),(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),
(ValueError('LIVE_SESSION_EXPIRED'),'CONTEXT_REVOKED'),
(ValueError('ACCOUNT_DISABLED'),'CONTEXT_REVOKED'),
(RuntimeError('private'),'DEPENDENCY_UNAVAILABLE')])
def test_runtime_authority_failure_truthful_and_fail_closed(runner,exc,code):
async def scenario():
wire=FakeGoogleTransport();out=[]
async def check(_):raise exc
async def emit(e):out.append(e)
r=VoiceRuntime(RealtimeAdapter(wire),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check)
await r.start()
assert not r.usable and r.failure==code and not wire.sent
await r.close()
assert all(not isinstance(e,bytes) for e in out)
asyncio.run(scenario())
def test_actual_authority_check_deadline(runner):
async def scenario():
wire=FakeGoogleTransport()
async def check(_):await asyncio.Event().wait()
async def emit(_):pass
limits=RuntimeSettings(_env_file=None,authority_timeout_seconds=.01)
r=VoiceRuntime(RealtimeAdapter(wire,settings=limits),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check,settings=limits)
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
asyncio.run(scenario())
def test_thirty_seconds_gemini_silence_keeps_transport_bounded(runner,persisted):
async def scenario():
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
try:
for _ in range(300):
await r.input_audio(bytes(4800))
async with asyncio.timeout(3):
while r.input_transport_count and r.usable:
await asyncio.sleep(0)
assert r.usable,r.failure
assert r.input_dispatched_total==1440000
assert r.uncommitted_speech_bytes == r.input_transport_bytes == 0
assert not r.inputs and r.input_committed_total == 0
await r.input_audio(bytes(2))
await until(lambda: r.input_transport_count == 0)
assert r.usable and r.failure is None
assert not any('toolResponse' in m for m in wire.sent)
await gemini_input_turn(r, wire, start=30000)
await wire.inbound.put({'serverContent': {'modelTurn': {'parts': [
{'inlineData': {'mimeType': 'audio/pcm;rate=24000', 'data': 'AAA='}}
]}}})
await until(lambda: r.current is not None and r.current.committed or not r.usable)
assert r.usable and r.current.stop_boundary == 30100 * 48
assert r.input_committed_total == r.current.stop_boundary
finally:await cleanup(r,receive)
asyncio.run(scenario())
def test_selected_openai_actual_runtime_tool_audio_continuation_and_truncation(settings,monkeypatch,runner,persisted):
from tests.unit.test_realtime_phase1 import input_turn,response,call,done,delta,commands
from tests.unit.test_search_phase2 import service,row
search=service(settings,monkeypatch,[row()]);wire=FakeGoogleTransport();out=[]
async def connect(*_):return wire
monkeypatch.setattr(voice_provider,'connect_openai',connect)
async def scenario():
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only')
adapter=await voice_provider.create_adapter(config,RuntimeSettings())
async def emit(e):out.append(e)
async def authority(execution):return execution.capture(dict(id=execution.user_id,organization_id='fixture',role='user'),1)
r=VoiceRuntime(adapter,search,runner,uuid4(),emit,authority_check=authority)
try:
await r.start();await until(lambda:commands(wire,'session.update'))
assert not r.ready
await r.handle({'type':'session.updated','session':adapter.setup()['session']});await until(lambda:r.ready)
await input_turn(r);await response(r,wire)
await r.handle(call());await done(r)
await until(lambda:len(commands(wire,'response.create'))==2)
result=commands(wire,'conversation.item.create')[0]['item']
import json
assert json.loads(result['output'])['status']=='ok'
await response(r,wire,'r2');await r.handle(delta(960,response_id='r2',item_id='a2'))
await until(lambda:any(isinstance(e,bytes) for e in out))
started=next(e for e in out if isinstance(e,dict) and e['type']=='audio_started')
await r.client_control(__import__('json').dumps(dict(type='playback_progress',audio_ref=started['audio_ref'],played_ms=5)).encode())
await input_turn(r,item='u2',start=200)
await until(lambda:commands(wire,'response.cancel'))
await done(r,'r2',status='cancelled')
await until(lambda:commands(wire,'conversation.item.truncate'))
assert commands(wire,'conversation.item.truncate')[0]['audio_end_ms']==5
assert r.usable,r.failure
finally:await r.close()
assert wire.closed==1
asyncio.run(scenario())
@pytest.mark.parametrize('phase',['release','output'])
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
(ValueError('CONTEXT_REVOKED'),'CONTEXT_REVOKED')])
def test_authority_failure_suppresses_response_release_and_output(phase,exc,code,runner,persisted):
from tests.unit.test_realtime_phase1 import make as openai_make,input_turn,response,delta,commands
async def scenario():
r,wire,out=await openai_make(SimpleNamespace(engine=None),runner,persisted)
try:
async def unavailable(_):raise exc
if phase=='release':
r.authority_check=unavailable
await input_turn(r)
else:
await input_turn(r);await response(r,wire)
r.authority_check=unavailable
await r.handle(delta(960))
await asyncio.wait_for(r.failure_signal.wait(),2)
assert r.failure==code
assert not any(isinstance(e,bytes) or (isinstance(e,dict) and e.get('type') in ('transcript','sources','audio_started')) for e in out)
if phase=='release':assert not commands(wire,'response.create')
finally:await r.close()
asyncio.run(scenario())