- Specialize voice assistant identity and agent system prompt for «شرکت شهرکهای صنعتی اصفهان» (English instructions with Persian proper names) - Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events - Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event - Handle old-turn search cancellation safely on turn supersession - Add end-to-end search tracing pipeline and diagnostic CLI - Add database organization title and settings update script
154 lines
9.4 KiB
Python
154 lines
9.4 KiB
Python
"""Persisted Phase 1 quality profiles exercised through authenticated HTTP/ASGI."""
|
|
from copy import deepcopy
|
|
import json
|
|
from uuid import UUID
|
|
import pytest
|
|
from sqlalchemy import text
|
|
from starlette.websockets import WebSocketDisconnect
|
|
from app.api.v1 import dependencies
|
|
from app.infrastructure.realtime import RealtimeAdapter
|
|
from tests.integration.test_phase2_postgres import seeded_env,api,login,session
|
|
from tests.unit.test_realtime_phase1 import until
|
|
from tests.unit.test_openai_speech_configuration import CANDIDATE
|
|
|
|
pytestmark=pytest.mark.postgres
|
|
|
|
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
|
@pytest.mark.parametrize('change',['legacy','legacy_limit','limit','asr','vad','noise','prompt','keywords','style_revision','effective_instructions_digest'])
|
|
def test_incompatible_profile_replay_retains_identity_and_rejects_before_open(api,change):
|
|
client,wire,runner,e=api
|
|
headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
|
with e.engine.connect() as conn:
|
|
original=conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
|
pinned=deepcopy(original.execution_profile)
|
|
if change in ('legacy','legacy_limit','style_revision','effective_instructions_digest'):
|
|
if change=='legacy':
|
|
pinned.pop('audio_input')
|
|
elif change=='legacy_limit':
|
|
pinned.pop('max_output_tokens')
|
|
else:
|
|
pinned[change]='obsolete'
|
|
with e.engine.begin() as conn:
|
|
conn.execute(text('UPDATE live_sessions SET execution_profile=CAST(:profile AS jsonb) WHERE id=:id'),
|
|
{'id':sid,'profile':json.dumps(pinned)})
|
|
config=e.voice_config
|
|
else:
|
|
updates={'limit':dict(openai_realtime_max_output_tokens=128),'asr':CANDIDATE,'vad':dict(openai_realtime_vad_silence_duration_ms=800),
|
|
'noise':dict(openai_realtime_noise_reduction='far_field'),
|
|
'prompt':dict(openai_realtime_asr_prompt='Technical support.'),
|
|
'keywords':dict(CANDIDATE,openai_realtime_asr_keywords=('new-term',))}[change]
|
|
config=e.voice_config.model_copy(update=updates)
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
|
|
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
|
assert replay.status_code==202 and replay.json()['session_id']==str(sid)
|
|
assert replay.headers['Idempotency-Replayed']=='true'
|
|
recovery=client.get('/api/v1/voice/sessions/by-request/'+body['client_request_id'])
|
|
assert recovery.json()['session_id']==str(sid)
|
|
with pytest.raises(WebSocketDisconnect) as lost:
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}):pass
|
|
assert lost.value.code==1008 and not e.connections and not wire.sent
|
|
with e.engine.connect() as conn:
|
|
saved=conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
|
assert saved.execution_profile==pinned and saved.request_hash==original.request_hash
|
|
|
|
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
|
@pytest.mark.parametrize('mismatch',[False,True,'limit'])
|
|
def test_candidate_profile_is_frozen_and_readiness_requires_provider_ack(api,mismatch):
|
|
client,wire,runner,e=api
|
|
config=e.voice_config.model_copy(update=dict(CANDIDATE,openai_realtime_noise_reduction='near_field',openai_realtime_max_output_tokens=128))
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
|
|
headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
|
with e.engine.connect() as conn:
|
|
frozen=conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()
|
|
assert frozen['audio_input']==config.audio_input()
|
|
assert frozen['max_output_tokens']==128
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}) as ws:
|
|
ack=RealtimeAdapter(wire,input_settings=config).setup()['session']
|
|
if mismatch == 'limit':ack['max_output_tokens']=256
|
|
elif mismatch:ack['audio']['input']['turn_detection']['silence_duration_ms']=800
|
|
client.portal.call(wire.inbound.put,dict(type='session.updated',session=ack))
|
|
event=ws.receive_json()
|
|
if mismatch:
|
|
assert event['type']=='error' and event['error']['code']=='LIVE_PROVIDER_PROTOCOL_ERROR'
|
|
else:
|
|
assert event['type']=='session_ready'
|
|
client.portal.call(until,lambda:bool(wire.sent))
|
|
assert wire.sent[0]['session']['audio']['input']==frozen['audio_input']
|
|
assert wire.sent[0]['session']['max_output_tokens']==frozen['max_output_tokens']
|
|
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
|
|
try:
|
|
while True:ws.receive_json()
|
|
except WebSocketDisconnect:pass
|
|
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
|
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
|
with e.engine.connect() as conn:
|
|
saved=conn.execute(text('SELECT execution_profile,status FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
|
assert saved.execution_profile==frozen
|
|
assert saved.status==('failed' if mismatch else 'closed')
|
|
|
|
|
|
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
|
@pytest.mark.parametrize('change', ['missing', 'effort', 'disabled', 'model'])
|
|
def test_reasoning_snapshot_replay_rejected_before_open(api, change):
|
|
client, wire, runner, e = api
|
|
config = e.voice_config.model_copy(update=dict(openai_realtime_model='gpt-realtime-2.1',
|
|
openai_realtime_reasoning_effort='low'))
|
|
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
|
|
headers, result, body = session(client, e); sid = UUID(result['session_id'])
|
|
with e.engine.connect() as conn:
|
|
original = conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'), {'id':sid}).one()
|
|
pinned = deepcopy(original.execution_profile)
|
|
assert pinned['reasoning'] == {'effort':'low'}
|
|
if change == 'missing':
|
|
del pinned['reasoning']
|
|
with e.engine.begin() as conn:
|
|
conn.execute(text('UPDATE live_sessions SET execution_profile=CAST(:profile AS jsonb) WHERE id=:id'),
|
|
{'id':sid,'profile':json.dumps(pinned)})
|
|
else:
|
|
updates = {'effort':dict(openai_realtime_reasoning_effort='medium'),
|
|
'disabled':dict(openai_realtime_reasoning_effort=None),
|
|
'model':dict(openai_realtime_model='gpt-realtime-2.1-mini')}[change]
|
|
config = config.model_copy(update=updates)
|
|
replay = client.post('/api/v1/voice/sessions', json=body, headers=headers)
|
|
assert replay.status_code == 202 and replay.json()['session_id'] == str(sid)
|
|
assert replay.headers['Idempotency-Replayed'] == 'true'
|
|
with pytest.raises(WebSocketDisconnect) as lost:
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':headers['Origin']}): pass
|
|
assert lost.value.code == 1008 and not e.connections and not wire.sent
|
|
with e.engine.connect() as conn:
|
|
saved = conn.execute(text('SELECT execution_profile,request_hash FROM live_sessions WHERE id=:id'), {'id':sid}).one()
|
|
assert saved.execution_profile == pinned and saved.request_hash == original.request_hash
|
|
|
|
|
|
@pytest.mark.parametrize('api',['openai'],indirect=True)
|
|
@pytest.mark.parametrize('model', ['gpt-realtime-2.1', 'gpt-realtime-2.1-mini'])
|
|
@pytest.mark.parametrize('mismatch', [False, True])
|
|
def test_reasoning_readiness_requires_matching_ack(api, model, mismatch):
|
|
client, wire, runner, e = api
|
|
config = e.voice_config.model_copy(update=dict(openai_realtime_model=model, openai_realtime_reasoning_effort='low'))
|
|
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
|
|
headers, result, body = session(client, e); sid = UUID(result['session_id'])
|
|
with e.engine.connect() as conn:
|
|
frozen = conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'), {'id':sid}).scalar_one()
|
|
assert frozen['reasoning'] == {'effort':'low'}
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'], headers={'Origin':headers['Origin']}) as ws:
|
|
ack = RealtimeAdapter(wire, model=model, input_settings=config).setup()['session']
|
|
if mismatch: ack['reasoning']['effort'] = 'medium'
|
|
client.portal.call(wire.inbound.put, dict(type='session.updated',session=ack))
|
|
event = ws.receive_json()
|
|
if mismatch:
|
|
assert event['type']=='error' and event['error']['code']=='LIVE_PROVIDER_PROTOCOL_ERROR'
|
|
else:
|
|
assert event['type']=='session_ready'
|
|
assert wire.sent[0]['session']['reasoning'] == frozen['reasoning']
|
|
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
|
|
try:
|
|
while True: ws.receive_json()
|
|
except WebSocketDisconnect: pass
|
|
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
|
client.portal.call(until, lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
|
with e.engine.connect() as conn:
|
|
saved = conn.execute(text('SELECT execution_profile,status FROM live_sessions WHERE id=:id'), {'id':sid}).one()
|
|
assert saved.execution_profile == frozen
|
|
assert saved.status == ('failed' if mismatch else 'closed')
|