feat(voice): implement local S2S retained history and provider selection
Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling. Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
This commit is contained in:
@@ -14,7 +14,7 @@ def test_local_profile_replay_never_rewrites_frozen_components(seeded_env):
|
||||
first = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
|
||||
model=config.selected_model, execution_profile=config.profile())
|
||||
sid = UUID(first['session_id'])
|
||||
changed = local_config(local_s2s_tts_voice='different')
|
||||
changed = local_config(local_s2s_tts_voice='different', local_s2s_retain_interrupted_answers=True)
|
||||
replay = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
|
||||
model=changed.selected_model, execution_profile=changed.profile())
|
||||
assert replay['session_id'] == first['session_id'] and replay['replayed']
|
||||
|
||||
@@ -26,7 +26,9 @@ from tests.support.embedding import DeterministicEmbeddings
|
||||
@pytest.fixture
|
||||
def seeded_env(migrated_db,settings,tmp_path):
|
||||
engine,_=migrated_db
|
||||
settings=configure(settings)
|
||||
settings=configure(settings).model_copy(update=dict(
|
||||
original_directory=tmp_path/'local-s2s-test'/'originals',
|
||||
extraction_directory=tmp_path/'local-s2s-test'/'extractions'))
|
||||
org,actor=administrator(engine)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET username=:name,password_hash=:hash WHERE id=:id"),
|
||||
@@ -34,7 +36,7 @@ def seeded_env(migrated_db,settings,tmp_path):
|
||||
auth=AuthService(engine)
|
||||
_,token,csrf,expiry=auth.login(str(actor),'fixture-password')
|
||||
user=auth.get_current_user(token)
|
||||
doc=publish(engine,settings,tmp_path,actor)
|
||||
doc=publish(engine,settings,tmp_path/'local-s2s-test',actor)
|
||||
selection_replace(engine,actor,1,[doc])
|
||||
user=auth.get_current_user(token)
|
||||
return SimpleNamespace(engine=engine,org=org,actor=actor,auth=auth,user=user,token=token,csrf=csrf,
|
||||
@@ -181,10 +183,16 @@ def api(seeded_env,monkeypatch,request):
|
||||
from app.api.v1.auth import _ATTEMPTS, _LOCK
|
||||
with _LOCK: _ATTEMPTS.clear()
|
||||
provider=getattr(request,'param','gemini')
|
||||
config=VoiceSettings(_env_file=None,provider=provider,gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
|
||||
local_options = dict(local_s2s_enabled=True, voice_transport_testing=True,
|
||||
local_s2s_stt_model='fixture/stt', local_s2s_llm_model='fixture/llm',
|
||||
local_s2s_tts_model='fixture/tts', local_s2s_tts_voice='fixture',
|
||||
local_s2s_retain_interrupted_answers=True) if provider=='local_s2s' else {}
|
||||
config=VoiceSettings(_env_file=None,provider=provider,gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False,**local_options)
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile),2,'deterministic-fixture-only')
|
||||
search=SearchService(e.engine,settings,DeterministicEmbeddings(settings),cutoff=cutoff)
|
||||
e.search = search
|
||||
if provider=='local_s2s':
|
||||
monkeypatch.setattr(live,'IngestionSettings',lambda:settings)
|
||||
e.voice_config = config
|
||||
e.connections = []
|
||||
runner=SearchToolRunner(running=2,waiting=2,timeout=2)
|
||||
@@ -192,7 +200,10 @@ def api(seeded_env,monkeypatch,request):
|
||||
async def connect(*args):
|
||||
e.connections.append(1)
|
||||
return wire
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_'+provider,connect)
|
||||
if provider=='local_s2s':
|
||||
monkeypatch.setattr('app.infrastructure.local_s2s.connect_local',connect)
|
||||
else:
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_'+provider,connect)
|
||||
monkeypatch.setattr(live,'capability',lambda config:cutoff)
|
||||
monkeypatch.setattr('app.main.config',config)
|
||||
app.dependency_overrides[d.get_engine]=lambda:e.engine
|
||||
@@ -283,7 +294,7 @@ def test_actual_asgi_gemini_ready_and_blocked_browser_cleanup(api,ending):
|
||||
saved=conn.execute(text('SELECT status,connected_at FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert saved[0] in ('closed','failed') and saved[1] is not None
|
||||
|
||||
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
|
||||
@pytest.mark.parametrize('api',['gemini','openai','local_s2s'],indirect=True)
|
||||
@pytest.mark.parametrize('outcome',['ok','no_evidence','error'])
|
||||
def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
@@ -301,7 +312,17 @@ def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import call as native_call,terminal,message
|
||||
ack={'setupComplete':{}} if e.voice_config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire).setup()['session']}
|
||||
if e.voice_config.provider=='local_s2s':
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter
|
||||
from app.modules.voice.local_s2s import effective_identity
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
local_adapter=LocalS2SAdapter(wire,config=e.voice_config,settings=RuntimeSettings(_env_file=None))
|
||||
native_session=local_adapter.setup()['session']
|
||||
native_session['s2s_effective']=effective_identity(e.voice_config.components(),native_session)
|
||||
native_session['id']='fixture-native-session'
|
||||
ack={'type':'session.updated','session':native_session}
|
||||
else:
|
||||
ack={'setupComplete':{}} if e.voice_config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire).setup()['session']}
|
||||
client.portal.call(wire.inbound.put,ack)
|
||||
assert ws.receive_json()['type']=='session_ready'
|
||||
ws.send_bytes(bytes(4800));ws.send_bytes(bytes(4800))
|
||||
@@ -322,32 +343,63 @@ def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
|
||||
tool=native_call(call_id='private-google-call',query=query)
|
||||
client.portal.call(wire.inbound.put,tool)
|
||||
client.portal.call(wire.inbound.put,terminal(output=[dict(type='function_call',id=tool['item_id'],call_id=tool['call_id'],name=tool['name'],arguments=tool['arguments'])]))
|
||||
# Retrieval is private model evidence. Citations require the explicit
|
||||
# report_used_sources amendment before the subsequent answer.
|
||||
events=[]
|
||||
while True:
|
||||
event=ws.receive_json();events.append(event)
|
||||
if event['type']=='sources':break
|
||||
client.portal.call(until,lambda:any('toolResponse' in m or (m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output') for m in wire.sent))
|
||||
with e.engine.connect() as conn:
|
||||
call=conn.execute(text('SELECT * FROM tool_calls WHERE live_session_id=:id'),{'id':sid}).mappings().one()
|
||||
assert call['arguments']['query']==query
|
||||
assert call['result_json']['status']==outcome
|
||||
assert call['knowledge_revision']==2 and call['access_epoch']==1
|
||||
assert str(call['public_ref'])==events[-1]['tool_call_id']!='private-google-call'
|
||||
assert str(call['public_ref'])!='private-google-call'
|
||||
def acknowledge_openai_response(response_id, expected_count):
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='response.create'])==expected_count)
|
||||
intent=[m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create'][-1]
|
||||
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id=response_id,metadata=intent)))
|
||||
|
||||
if e.voice_config.provider=='gemini':
|
||||
answer=next(m['toolResponse']['functionResponses'][0] for m in wire.sent if 'toolResponse' in m)
|
||||
assert answer['id']=='private-google-call' and answer['response']==call['result_json']
|
||||
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
delivered=answer['response']
|
||||
else:
|
||||
answer=next(m['item'] for m in wire.sent if m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output')
|
||||
assert answer['call_id']=='private-google-call' and json.loads(answer['output'])==call['result_json']
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='response.create'])==2)
|
||||
intent=[m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create'][-1]
|
||||
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id='r2',metadata=intent)))
|
||||
client.portal.call(wire.inbound.put,dict(type='response.output_audio_transcript.done',response_id='r2',item_id='a_r2',output_index=0,content_index=0,transcript='fixture answer'))
|
||||
client.portal.call(wire.inbound.put,terminal('r2',output=[message('r2')]))
|
||||
delivered=json.loads(answer['output'])
|
||||
acknowledge_openai_response('r2',2)
|
||||
refs=[source['source_ref'] for source in delivered.get('sources',[])]
|
||||
if e.voice_config.provider=='gemini':
|
||||
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[dict(
|
||||
id='private-report',name='report_used_sources',args={'source_refs':refs})]}})
|
||||
else:
|
||||
report=native_call('r2','private-report',name='report_used_sources',raw=json.dumps({'source_refs':refs}))
|
||||
client.portal.call(wire.inbound.put,report)
|
||||
client.portal.call(wire.inbound.put,terminal('r2',output=[dict(type='function_call',
|
||||
id=report['item_id'],call_id=report['call_id'],name=report['name'],arguments=report['arguments'])]))
|
||||
client.portal.call(until,lambda:any(
|
||||
m.get('toolResponse',{}).get('functionResponses',[{}])[0].get('id')=='private-report'
|
||||
or (m.get('type')=='conversation.item.create' and m.get('item',{}).get('call_id')=='private-report')
|
||||
for m in wire.sent))
|
||||
if e.voice_config.provider=='gemini':
|
||||
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
else:
|
||||
acknowledge_openai_response('r3',3)
|
||||
client.portal.call(wire.inbound.put,dict(type='response.output_audio_transcript.done',response_id='r3',item_id='a_r3',output_index=0,content_index=0,transcript='fixture answer'))
|
||||
client.portal.call(wire.inbound.put,terminal('r3',output=[message('r3')]))
|
||||
while True:
|
||||
event=ws.receive_json()
|
||||
event=ws.receive_json();events.append(event)
|
||||
if event.get('role')=='assistant' and event['status']=='completed':break
|
||||
citations=[event for event in events if event['type']=='sources']
|
||||
if outcome=='ok':
|
||||
assert len(citations)==1
|
||||
assert citations[0]['tool_call_id']==str(call['public_ref'])
|
||||
assert {source['source_ref'] for source in citations[0]['sources']}==set(refs)
|
||||
assert {(source['document_id'],source['chunk_id']) for source in citations[0]['sources']}=={
|
||||
(source['document_id'],source['chunk_id']) for source in delivered['sources']}
|
||||
else:
|
||||
assert citations==[]
|
||||
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
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
client.portal.call(until, lambda: sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Real PostgreSQL/API selection pins provider, replay and fresh-session switch."""
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from tests.integration.test_phase2_postgres import api, seeded_env, login
|
||||
|
||||
|
||||
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
||||
def test_provider_choice_persists_conflicts_and_switches_only_in_fresh_session(api,monkeypatch):
|
||||
client,wire,runner,e=api
|
||||
from app.main import app
|
||||
from app.api.v1.dependencies import get_voice_settings
|
||||
e.voice_config=e.voice_config.model_copy(update={'voice_selectable_providers':('gemini',)})
|
||||
app.dependency_overrides[get_voice_settings]=lambda:e.voice_config
|
||||
headers=login(client,e)
|
||||
providers=client.get('/api/v1/voice/sessions/providers')
|
||||
assert providers.status_code==200 and providers.json()['connection_checked'] is False
|
||||
assert {r['id']:r['can_start'] for r in providers.json()['providers']}=={'openai':True,'local_s2s':False,'gemini':True}
|
||||
cid=client.post('/api/v1/conversations',headers=headers,json={'mode':'voice','client_request_id':str(uuid4())}).json()['id']
|
||||
body=dict(conversation_id=cid,client_request_id=str(uuid4()),provider='gemini')
|
||||
first=client.post('/api/v1/voice/sessions',headers=headers,json=body)
|
||||
assert first.status_code==201 and first.json()['provider']=='gemini'
|
||||
sid=first.json()['session_id']
|
||||
with e.engine.connect() as conn:
|
||||
saved=conn.execute(text('SELECT provider,execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert saved[0]==saved[1]['provider']=='gemini'
|
||||
assert client.post('/api/v1/voice/sessions',headers=headers,json=dict(body,provider='openai')).status_code==409
|
||||
assert client.post('/api/v1/voice/sessions',headers=headers,json=dict(body,client_request_id=str(uuid4()),provider='openai')).status_code==409
|
||||
# Replay remains pinned even when an operator removes the UI choice.
|
||||
e.voice_config=e.voice_config.model_copy(update={'voice_selectable_providers':()})
|
||||
replay=client.post('/api/v1/voice/sessions',headers=headers,json=body)
|
||||
assert replay.status_code==202 and replay.json()['provider']=='gemini'
|
||||
e.voice_config=e.voice_config.model_copy(update={'voice_selectable_providers':('gemini',)})
|
||||
async def connect_selected(*_):
|
||||
e.connections.append('gemini')
|
||||
return wire
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connect_selected)
|
||||
with client.websocket_connect('ws://localhost:8000'+first.json()['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}})
|
||||
assert ws.receive_json()['type']=='session_ready'
|
||||
assert any('setup' in message for message in wire.sent)
|
||||
assert client.post('/api/v1/voice/sessions/'+sid+'/close',headers=headers,json={}).status_code==200
|
||||
fresh=client.post('/api/v1/voice/sessions',headers=headers,json=dict(body,client_request_id=str(uuid4()),provider='openai'))
|
||||
assert fresh.status_code==201 and fresh.json()['provider']=='openai'
|
||||
assert fresh.json()['session_id']!=sid and e.connections==['gemini']
|
||||
|
||||
|
||||
def test_provider_discovery_requires_authentication(api):
|
||||
client,*_=api
|
||||
assert client.get('/api/v1/voice/sessions/providers').status_code==401
|
||||
|
||||
|
||||
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
||||
def test_competing_explicit_providers_cannot_reinterpret_one_request(api):
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from app.main import app
|
||||
from app.api.v1.dependencies import get_voice_settings
|
||||
client,wire,runner,e=api
|
||||
e.voice_config=e.voice_config.model_copy(update={'voice_selectable_providers':('gemini',)})
|
||||
app.dependency_overrides[get_voice_settings]=lambda:e.voice_config
|
||||
headers=login(client,e)
|
||||
cid=client.post('/api/v1/conversations',headers=headers,json={'mode':'voice','client_request_id':str(uuid4())}).json()['id']
|
||||
request=str(uuid4())
|
||||
def create(provider):
|
||||
return client.post('/api/v1/voice/sessions',headers=headers,json=dict(conversation_id=cid,client_request_id=request,provider=provider))
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results=list(pool.map(create,['openai','gemini']))
|
||||
assert sorted(r.status_code for r in results)==[201,409]
|
||||
winner=next(r.json() for r in results if r.status_code==201)
|
||||
with e.engine.connect() as conn:
|
||||
rows=conn.execute(text('SELECT provider FROM live_sessions WHERE conversation_id=:id'),{'id':cid}).scalars().all()
|
||||
assert rows==[winner['provider']] and not e.connections
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Shared runtime with local adapter and explicitly simulated native setup I/O."""
|
||||
from uuid import uuid4
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_local_s2s_phase2 import local_config, confirmed
|
||||
from tests.unit.test_realtime_phase1 import Transport, commands, until
|
||||
|
||||
|
||||
async def make_local(service, runner, persisted):
|
||||
wire, output = Transport(), []
|
||||
adapter = LocalS2SAdapter(wire, config=local_config(local_s2s_retain_interrupted_answers=True),
|
||||
settings=RuntimeSettings(_env_file=None))
|
||||
async def emit(event):output.append(event)
|
||||
async def authority(execution):
|
||||
return persisted['enabled'] and execution.capture(
|
||||
dict(id=execution.user_id,organization_id='fixture',role='user'),persisted['epoch'])
|
||||
runtime = VoiceRuntime(adapter,service,runner,uuid4(),emit,authority_check=authority)
|
||||
await runtime.start()
|
||||
await until(lambda:commands(wire,'session.update'))
|
||||
session=confirmed(adapter);session['id']='fixture-native-session'
|
||||
await runtime.handle(dict(type='session.updated',session=session))
|
||||
await until(lambda:runtime.ready)
|
||||
return runtime,wire,output
|
||||
@@ -0,0 +1,49 @@
|
||||
from copy import deepcopy
|
||||
import pytest
|
||||
from services.local_s2s.evaluation import scorecard, p95
|
||||
|
||||
|
||||
def observations():
|
||||
return dict(samples=[dict(provider=p,case_id='hours',success=True,critical_error=False,
|
||||
persistent_underrun=False,duplicate=False,disconnected=False,first_audible_ms=t,
|
||||
tool_ms=100,interruption_stop_ms=20) for p,t in [('openai',1000),('local_s2s',1800)]],
|
||||
charges=[dict(provider=p,id=p+kind,kind=kind,cost_usd=cost) for p,cost in [('openai','1'),('local_s2s','.2')] for kind in ('request','startup','abandoned','failed')],
|
||||
billing_complete={'openai':True,'local_s2s':True},minimum_samples_per_provider=1,
|
||||
thresholds_accepted=True,real_provider_observations=False,human_quality_accepted=False,
|
||||
rollback_verified=False,profile_sha256={'openai':'a'*64,'local_s2s':'b'*64})
|
||||
|
||||
|
||||
def test_paired_metrics_include_overhead_and_do_not_promote_fixture_data():
|
||||
report=scorecard(observations())
|
||||
assert report['providers']['openai']['total_cost_usd']=='4'
|
||||
assert report['providers']['local_s2s']['cost_per_success_usd']=='0.8'
|
||||
assert report['status']=='not_accepted' and not report['authorization_to_switch']
|
||||
assert 'real_provider_observations:pending' in report['blockers']
|
||||
assert 'cost_target_failed' not in report['blockers']
|
||||
assert p95(list(range(1,21)))==19
|
||||
|
||||
|
||||
def test_unknown_charge_is_not_zero_and_mismatched_cases_block_comparison():
|
||||
data=observations();data['charges'][0]['cost_usd']=None
|
||||
data['samples'][1]['case_id']='different'
|
||||
report=scorecard(data)
|
||||
assert report['providers']['openai']['total_cost_usd'] is None
|
||||
assert 'cases_not_paired' in report['blockers']
|
||||
assert 'openai:billing_incomplete' in report['blockers']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad',['NaN','Infinity','-1',True])
|
||||
def test_invalid_numeric_observations_are_rejected(bad):
|
||||
data=observations();data['samples'][0]['first_audible_ms']=bad
|
||||
with pytest.raises(ValueError):scorecard(data)
|
||||
|
||||
|
||||
def test_duplicate_charges_are_rejected():
|
||||
data=observations();data['charges'].append(deepcopy(data['charges'][0]))
|
||||
with pytest.raises(ValueError):scorecard(data)
|
||||
|
||||
|
||||
def test_zero_cost_baseline_does_not_claim_percentage_savings():
|
||||
data=observations()
|
||||
for row in data['charges']:row['cost_usd']='0'
|
||||
assert 'baseline_cost_not_positive' in scorecard(data)['blockers']
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Private retained-draft proof is distinct from native OpenAI truncation."""
|
||||
from copy import deepcopy
|
||||
import pytest
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter, LocalS2SContextError
|
||||
from app.modules.voice.provider import HistoryRepair
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_local_s2s_phase2 import local_config, confirmed
|
||||
from tests.unit.test_realtime_phase1 import Transport, runner, persisted
|
||||
|
||||
|
||||
def adapter():
|
||||
a=LocalS2SAdapter(Transport(),config=local_config(local_s2s_retain_interrupted_answers=True),settings=RuntimeSettings(_env_file=None))
|
||||
session=confirmed(a);session['id']='native-session'
|
||||
assert a.acknowledged(session)
|
||||
return a
|
||||
|
||||
|
||||
def receipt(a,repair,revision=1):
|
||||
request=a.history_repair_request(repair)
|
||||
return dict(request,type='conversation.item.truncated',s2s_native_type='s2s.history.retained',
|
||||
event_id='native-proof',operation_id=repair.operation_id,history_revision=revision,
|
||||
policy='retain_unheard_draft_v1',applied=True)
|
||||
|
||||
|
||||
def test_new_policy_is_frozen_without_rewriting_phase2_profile():
|
||||
old=local_config().profile()
|
||||
new=local_config(local_s2s_retain_interrupted_answers=True).profile()
|
||||
assert old['interruption_policy']=='close_until_phase3'
|
||||
assert new['interruption_policy']=='retain_unheard_draft_v1'
|
||||
assert old['local_s2s']['patch_revision']=='rag-local-s2s-phase2-v3'
|
||||
assert new['local_s2s']['patch_revision']=='rag-local-s2s-phase3-retain-v1'
|
||||
assert new['local_s2s']['contract_revision']=='rag-local-s2s-phase3-retain-v1'
|
||||
assert old['local_s2s']['contract_revision']=='rag-local-s2s-phase2-v1'
|
||||
assert old['local_s2s']['effective_config_sha256']!=new['local_s2s']['effective_config_sha256']
|
||||
assert old['local_s2s']['components']==new['local_s2s']['components']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field,value',[
|
||||
('session_id','wrong'),('engine_session_id','wrong'),('generation',99),
|
||||
('response_id','wrong'),('operation_id','wrong'),('item_id','wrong'),
|
||||
('content_index',1),('audio_end_ms',101),('applied',False),
|
||||
('policy','truncate'),('s2s_native_type','conversation.item.truncated'),
|
||||
('event_id',None),('event_id',''),('history_revision',0),('history_revision',True),('history_revision',2)])
|
||||
def test_wrong_or_unapplied_receipt_cannot_release(field,value):
|
||||
a=adapter();r=HistoryRepair('session',2,'response','op','item',0,100)
|
||||
event=receipt(a,r);event[field]=value
|
||||
with pytest.raises(LocalS2SContextError):a.confirm_history_repair(r,event)
|
||||
|
||||
|
||||
def test_applied_receipt_is_correlated_idempotent_and_revision_fenced():
|
||||
a=adapter();r=HistoryRepair('session',2,'response','op','item',0,100)
|
||||
event=receipt(a,r)
|
||||
result=a.confirm_history_repair(r,event)
|
||||
assert result.repair==r and result.provenance=='local_s2s.retained_unheard_draft'
|
||||
assert a.confirm_history_repair(r,deepcopy(event))==result
|
||||
with pytest.raises(LocalS2SContextError):a.confirm_history_repair(r,dict(event,history_revision=2))
|
||||
r2=HistoryRepair('session',3,'response2','op2','item2',0,200)
|
||||
with pytest.raises(LocalS2SContextError):a.confirm_history_repair(r2,receipt(a,r2))
|
||||
assert a.confirm_history_repair(r2,receipt(a,r2,2)).repair==r2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('completed',[False,True])
|
||||
@pytest.mark.parametrize('proof',['matching','missing','wrong'])
|
||||
def test_runtime_retained_history_barrier_before_next_response(runner,persisted,completed,proof):
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from tests.unit.test_realtime_phase1 import input_turn,response,delta,done,until,commands
|
||||
from tests.unit.test_realtime_repairs import Clock,without_ticker
|
||||
async def scenario():
|
||||
a=adapter();wire=a.transport;out=[];clock=Clock()
|
||||
async def emit(event):out.append(event)
|
||||
async def authority(execution):return execution.capture(dict(id=execution.user_id,organization_id='fixture',role='user'),1)
|
||||
r=VoiceRuntime(a,SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=authority,clock=clock)
|
||||
try:
|
||||
await r.start();await until(lambda:commands(wire,'session.update'))
|
||||
session=confirmed(a);session['id']='native-session'
|
||||
await r.handle(dict(type='session.updated',session=session))
|
||||
await until(lambda:r.ready)
|
||||
await without_ticker(r)
|
||||
await input_turn(r);await response(r,wire)
|
||||
await r.handle(delta(48000));await until(lambda:next(iter(r.audio.values())).sent==48000)
|
||||
audio=next(iter(r.audio.values()));await r.playback_progress(audio.ref,100)
|
||||
if completed:await done(r)
|
||||
await input_turn(r,'u2',10)
|
||||
assert len(commands(wire,'response.create'))==1
|
||||
if not completed:
|
||||
await until(lambda:commands(wire,'response.cancel'))
|
||||
await done(r,status='cancelled')
|
||||
clock.advance(1);await r.tick()
|
||||
await until(lambda:commands(wire,'s2s.history.retain'))
|
||||
assert not commands(wire,'conversation.item.truncate')
|
||||
assert len(commands(wire,'response.create'))==1
|
||||
if proof=='missing':
|
||||
clock.now=audio.cleanup_deadline+.01;await r.tick()
|
||||
else:
|
||||
event=receipt(a,audio.repair)
|
||||
if proof=='wrong':event['operation_id']='wrong'
|
||||
await r.handle(event)
|
||||
if proof=='matching':
|
||||
await until(lambda:len(commands(wire,'response.create'))==2)
|
||||
assert r.usable and audio.state=='retired'
|
||||
else:assert not r.usable and len(commands(wire,'response.create'))==1
|
||||
finally:await r.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -334,6 +334,50 @@ def test_hung_construction_and_hung_stop_are_bounded_and_gateway_always_closes(m
|
||||
assert logs[-1]['cleanup']['runtime_stop']==2 and server.done.is_set()
|
||||
|
||||
|
||||
def test_shutdown_cancels_provider_io_before_waiting_for_native_workers():
|
||||
entered, cancelled, stop = Event(), Event(), Event()
|
||||
|
||||
async def remote(request):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cancelled.set()
|
||||
|
||||
server = ComponentServer('fixture-key', port=0, timeout=5,
|
||||
transport=httpx.MockTransport(remote))
|
||||
thread = Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
assert server.ready.wait(2)
|
||||
|
||||
def request():
|
||||
try:
|
||||
httpx.post(f'http://127.0.0.1:{server.server_port}/v1/audio/speech',
|
||||
content=b'{}', headers={'Authorization': 'Bearer local-components'},
|
||||
timeout=5, trust_env=False)
|
||||
except httpx.HTTPError:
|
||||
pass
|
||||
|
||||
client = Thread(target=request, daemon=True)
|
||||
client.start()
|
||||
logs = []
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
def native_stop():
|
||||
assert stop.is_set()
|
||||
assert cancelled.is_set(), 'native worker still waiting for provider I/O'
|
||||
assert not cleanup(SimpleNamespace(stop=native_stop), server, thread, stop,
|
||||
timeout=2, emit=lambda value, **kw: logs.append(json.loads(value))), logs
|
||||
assert not server.requests and not thread.is_alive()
|
||||
assert logs[-1]['request_counts']['released'] == 1
|
||||
assert logs[-1]['request_counts']['shutdown_pending'] == 0
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(2)
|
||||
client.join(2)
|
||||
|
||||
|
||||
def test_downstream_disconnect_closes_upstream_and_releases_slot():
|
||||
closed=Event()
|
||||
class Stream(httpx.AsyncByteStream):
|
||||
@@ -588,3 +632,19 @@ def test_existing_provider_identifier_validators_remain_active(field):
|
||||
with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
|
||||
local_config(**{field: 'bad id'})
|
||||
assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'
|
||||
|
||||
|
||||
def test_evaluation_budget_denial_is_explicit_http_not_dropped_connection():
|
||||
from services.local_s2s.components import EvaluationBudgetExhausted
|
||||
|
||||
def denied(request):
|
||||
raise EvaluationBudgetExhausted('not a provider failure')
|
||||
|
||||
with gateway(denied, timeout=2, inactivity=1) as server:
|
||||
result = httpx.post(f'http://127.0.0.1:{server.server_port}/v1/audio/speech',
|
||||
content=b'{}', headers={'Authorization': 'Bearer local-components'},
|
||||
timeout=2, trust_env=False)
|
||||
assert result.status_code == 429
|
||||
assert server.counts['budget_rejected'] == 1
|
||||
assert server.counts['failures'] == 0
|
||||
assert result.content == b''
|
||||
|
||||
@@ -138,6 +138,9 @@ def test_transcript_ordering_repeated_words_delayed_completion_and_release(runne
|
||||
try:
|
||||
first=await input_turn(r,'u1',commit=False)
|
||||
await r.handle(user_asr('u1','نه ','delta-a',completed=False))
|
||||
# Unsent adjacent deltas may coalesce; observe the first delivery
|
||||
# before testing replay identity and a separate legitimate repetition.
|
||||
await until(lambda:sum(e.get('role')=='user' for e in out)==1)
|
||||
await r.handle(user_asr('u1','نه ','delta-a',completed=False)) # identity replay
|
||||
await r.handle(user_asr('u1','نه ','delta-b',completed=False)) # legitimate repetition
|
||||
await until(lambda:sum(e.get('role')=='user' for e in out)==2)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Server-owned per-session selection never changes an audio profile or falls back."""
|
||||
from uuid import uuid4
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
from fastapi import Response
|
||||
from app.api.v1.live import CreateLiveSessionRequest, create_voice_session, voice_providers
|
||||
from app.modules.voice.configuration import VoiceSettings, select_voice_provider
|
||||
|
||||
|
||||
def config(**kw):
|
||||
return VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='server-only',
|
||||
openai_realtime_speed=1.3,voice_transport_testing=True,**kw)
|
||||
|
||||
|
||||
def test_selection_is_allowlisted_preserves_default_and_openai_tuning():
|
||||
c=config(voice_selectable_providers=('local_s2s',),local_s2s_enabled=True,
|
||||
local_s2s_stt_model='fixture/stt',local_s2s_llm_model='fixture/llm',
|
||||
local_s2s_tts_model='fixture/tts',local_s2s_tts_voice='fixture')
|
||||
local=select_voice_provider(c,'local_s2s')
|
||||
assert local.provider=='local_s2s' and c.provider=='openai'
|
||||
restored=select_voice_provider(local.model_copy(update={'voice_selectable_providers':('openai',)}),'openai')
|
||||
assert restored.profile()==c.profile() and restored.openai_realtime_speed==1.3
|
||||
with pytest.raises(ValueError):select_voice_provider(c,'gemini')
|
||||
|
||||
|
||||
def test_missing_selected_credentials_does_not_fall_back_to_configured_provider():
|
||||
c=config(voice_selectable_providers=('gemini',))
|
||||
with pytest.raises(ValueError):select_voice_provider(c,'gemini')
|
||||
assert c.provider=='openai'
|
||||
|
||||
|
||||
def test_provider_metadata_is_secret_free_and_does_no_remote_probe(monkeypatch):
|
||||
from app.api.v1 import live
|
||||
monkeypatch.setattr(live,'capability',lambda _:None)
|
||||
result=voice_providers(object(),config(),SimpleNamespace())
|
||||
assert result['default_provider']=='openai' and not result['connection_checked']
|
||||
assert {r['id']:r['can_start'] for r in result['providers']}=={'openai':True,'local_s2s':False,'gemini':False}
|
||||
assert 'server-only' not in str(result)
|
||||
|
||||
|
||||
def test_explicit_provider_mismatch_on_replay_is_conflict_before_config_checks():
|
||||
cid=uuid4();sid=uuid4()
|
||||
lifecycle=SimpleNamespace(recover_live_session=lambda *_:dict(conversation_id=str(cid),provider='openai'))
|
||||
req=CreateLiveSessionRequest(conversation_id=cid,client_request_id=uuid4(),provider='local_s2s')
|
||||
with pytest.raises(Exception) as exc:
|
||||
create_voice_session(req,Response(),object(),lifecycle,config(),object(),None)
|
||||
assert exc.value.status_code==409
|
||||
|
||||
|
||||
def test_unreachable_selected_engine_does_not_connect_default(monkeypatch):
|
||||
import asyncio
|
||||
from app.infrastructure.voice_provider import create_adapter
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
c=config(voice_selectable_providers=('local_s2s',),local_s2s_enabled=True,
|
||||
local_s2s_stt_model='fixture/stt',local_s2s_llm_model='fixture/llm',
|
||||
local_s2s_tts_model='fixture/tts',local_s2s_tts_voice='fixture')
|
||||
async def unavailable(*_):raise ConnectionError('controlled engine down')
|
||||
async def default(*_):pytest.fail('No automatic fallback is allowed')
|
||||
monkeypatch.setattr('app.infrastructure.local_s2s.connect_local',unavailable)
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_openai',default)
|
||||
with pytest.raises(ConnectionError):
|
||||
asyncio.run(create_adapter(select_voice_provider(c,'local_s2s'),RuntimeSettings(_env_file=None)))
|
||||
@@ -4,6 +4,7 @@ from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from tests.support.local_s2s_runtime import make_local
|
||||
from app.infrastructure.realtime import canonical_json
|
||||
from app.modules.voice.durable_tools import DurableTools, DurableFailure
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, response, call, done, until
|
||||
@@ -20,10 +21,11 @@ def source_events(out):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('refs', [['S2'], ['S1', 'S3'], []])
|
||||
def test_only_reported_sources_reach_ui_and_duplicate_report_is_idempotent(runner, persisted, refs):
|
||||
@pytest.mark.parametrize('provider',['openai','local_s2s'])
|
||||
def test_only_reported_sources_reach_ui_and_duplicate_report_is_idempotent(runner, persisted, refs, provider):
|
||||
result = evidence()
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None,
|
||||
runtime, wire, out = await (make_local if provider=='local_s2s' else make)(SimpleNamespace(engine=None,
|
||||
search=lambda *_: deepcopy(result)), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
@@ -61,9 +63,10 @@ def test_only_reported_sources_reach_ui_and_duplicate_report_is_idempotent(runne
|
||||
@pytest.mark.parametrize('args', [dict(source_refs=['S99']), dict(source_refs=['S1','S1']),
|
||||
dict(source_refs=['S1'], document_id='forged'), dict(source_refs='S1'), {},
|
||||
dict(source_refs=[None])])
|
||||
def test_invalid_reports_never_publish_sources(runner, persisted, args):
|
||||
@pytest.mark.parametrize('provider',['openai','local_s2s'])
|
||||
def test_invalid_reports_never_publish_sources(runner, persisted, args, provider):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None,
|
||||
runtime, wire, out = await (make_local if provider=='local_s2s' else make)(SimpleNamespace(engine=None,
|
||||
search=lambda *_: evidence()), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
|
||||
@@ -4,6 +4,7 @@ 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
|
||||
|
||||
@@ -27,9 +28,10 @@ class Store:
|
||||
|
||||
@pytest.mark.parametrize('ready_first', [False, True])
|
||||
@pytest.mark.parametrize('tool', ['reuse_last_evidence', 'search_knowledge'])
|
||||
def test_repeated_same_question_uses_one_retained_search(runner, persisted, monkeypatch, ready_first, tool):
|
||||
@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(SimpleNamespace(engine=None), runner, persisted)
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user