feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
@@ -0,0 +1,591 @@
|
||||
"""Real PostgreSQL ownership, concurrency, replay, completion, redaction and ASGI wiring."""
|
||||
import asyncio
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
from datetime import timedelta
|
||||
import json
|
||||
from threading import Barrier
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID, uuid4
|
||||
import pytest
|
||||
from argon2 import PasswordHasher
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from fastapi.testclient import TestClient
|
||||
from app.modules.auth.service import AuthService, COOKIE_NAME
|
||||
from app.modules.voice.lifecycle import LiveLifecycleService
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.knowledge.evidence import SearchExecution, CalibratedCutoff
|
||||
from app.modules.knowledge.service import SearchService, selection_replace
|
||||
from app.modules.knowledge.langchain_tool import SearchToolRunner
|
||||
from app.provision import provision_user
|
||||
from tests.support.search import administrator, publish, configure, QUERY
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
|
||||
@pytest.fixture
|
||||
def seeded_env(migrated_db,settings,tmp_path):
|
||||
engine,_=migrated_db
|
||||
settings=configure(settings)
|
||||
org,actor=administrator(engine)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET username=:name,password_hash=:hash WHERE id=:id"),
|
||||
dict(name=str(actor),hash=PasswordHasher().hash('fixture-password'),id=actor))
|
||||
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)
|
||||
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,
|
||||
doc=doc,lifecycle=LiveLifecycleService(engine),settings=settings)
|
||||
|
||||
def reserve(env, *, connect=True):
|
||||
conv=env.lifecycle.create_conversation(env.user,uuid4())
|
||||
session=env.lifecycle.create_live_session(env.user,UUID(conv['id']),uuid4(),execution_profile=VoiceSettings(_env_file=None).profile())
|
||||
sid=UUID(session['session_id'])
|
||||
if connect: env.lifecycle.mark_connected(env.user,sid)
|
||||
return UUID(conv['id']),sid
|
||||
|
||||
def concurrent(*functions):
|
||||
gate=Barrier(len(functions))
|
||||
def run(fn):
|
||||
gate.wait(timeout=5)
|
||||
try:return fn()
|
||||
except ValueError as exc:return str(exc)
|
||||
with ThreadPoolExecutor(max_workers=len(functions)) as pool:
|
||||
futures=[pool.submit(run,f) for f in functions]
|
||||
return [f.result(timeout=10) for f in futures]
|
||||
|
||||
@pytest.mark.parametrize('changed',[False,True])
|
||||
def test_real_concurrent_conversation_replay(seeded_env,changed):
|
||||
e=seeded_env;request=uuid4()
|
||||
results=concurrent(lambda:e.lifecycle.create_conversation(e.user,request,title='a'),
|
||||
lambda:e.lifecycle.create_conversation(e.user,request,title='b' if changed else 'a'))
|
||||
if changed:
|
||||
assert sum(r=='IDEMPOTENCY_CONFLICT' for r in results)==1
|
||||
else:
|
||||
assert results[0]['id']==results[1]['id']
|
||||
assert {r['replayed'] for r in results}=={False,True}
|
||||
|
||||
@pytest.mark.parametrize('changed',[False,True])
|
||||
def test_real_concurrent_session_replay(seeded_env,changed):
|
||||
e=seeded_env;request=uuid4()
|
||||
c1=UUID(e.lifecycle.create_conversation(e.user,uuid4())['id'])
|
||||
c2=UUID(e.lifecycle.create_conversation(e.user,uuid4())['id']) if changed else c1
|
||||
results=concurrent(lambda:e.lifecycle.create_live_session(e.user,c1,request),lambda:e.lifecycle.create_live_session(e.user,c2,request))
|
||||
if changed:assert sum(r=='IDEMPOTENCY_CONFLICT' for r in results)==1
|
||||
else:assert results[0]['session_id']==results[1]['session_id']
|
||||
|
||||
|
||||
def test_competing_active_reservations_and_expiry_replacement(seeded_env):
|
||||
e=seeded_env;c=UUID(e.lifecycle.create_conversation(e.user,uuid4())['id'])
|
||||
results=concurrent(lambda:e.lifecycle.create_live_session(e.user,c,uuid4()),lambda:e.lifecycle.create_live_session(e.user,c,uuid4()))
|
||||
assert sum(r=='LIVE_SESSION_BUSY' for r in results)==1
|
||||
old=next(r for r in results if isinstance(r,dict));sid=UUID(old['session_id'])
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text("UPDATE live_sessions SET expires_at=now()-interval '1 second' WHERE id=:id"),{'id':sid})
|
||||
new=e.lifecycle.create_live_session(e.user,c,uuid4())
|
||||
assert new['session_id']!=str(sid)
|
||||
assert e.lifecycle.get_live_session(e.user,sid)['status']=='closed'
|
||||
|
||||
|
||||
def test_forward_owner_chain_constraints(seeded_env):
|
||||
e=seeded_env;cid,sid=reserve(e)
|
||||
with e.engine.begin() as conn:
|
||||
name = 'other-'+str(uuid4())
|
||||
other=UUID(provision_user(conn,username=name,password='other-password',organization_id=e.org)['user_id'])
|
||||
_, token, _, _ = e.auth.login(name, 'other-password')
|
||||
other_auth = e.auth.get_current_user(token).auth_session_id
|
||||
for change,params in [('owner_user_id=:other',{'other':other}),('auth_session_id=:auth',{'auth':other_auth})]:
|
||||
with pytest.raises(IntegrityError):
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('UPDATE live_sessions SET '+change+' WHERE id=:id'),dict(id=sid,**params))
|
||||
other_org = uuid4()
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'scope-negative')"), {'id':other_org})
|
||||
with pytest.raises(IntegrityError):
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('''INSERT INTO tool_calls(id,organization_id,live_session_id,external_call_id,public_ref,arguments,request_hash)
|
||||
VALUES (:id,:org,:sid,'private',:ref,'{}',:hash)'''),dict(id=uuid4(),org=other_org,sid=sid,ref=uuid4(),hash='a'*64))
|
||||
|
||||
@pytest.mark.parametrize('changed',[False,True])
|
||||
def test_tool_admission_concurrent_duplicates(seeded_env,changed):
|
||||
e=seeded_env;cid,sid=reserve(e)
|
||||
args={'query':QUERY,'context':None}
|
||||
def admit(query):return e.lifecycle.admit_tool(e.user,sid,'private-google',str(uuid4()),dict(args,query=query),SearchExecution(e.actor))
|
||||
results=concurrent(lambda:admit(QUERY),lambda:admit('other' if changed else QUERY))
|
||||
if changed:assert sum(r=='IDEMPOTENCY_CONFLICT' for r in results)==1
|
||||
else:
|
||||
assert results[0]['id']==results[1]['id']
|
||||
assert {r['inserted'] for r in results}=={False,True}
|
||||
|
||||
@pytest.mark.parametrize('terminal',['close','cancel','logout','restart','selection'])
|
||||
def test_late_completion_cannot_overwrite_terminal_state(seeded_env,terminal):
|
||||
e=seeded_env;cid,sid=reserve(e);execution=SearchExecution(e.actor)
|
||||
call=e.lifecycle.admit_tool(e.user,sid,'private',str(uuid4()),{'query':QUERY},execution)
|
||||
if terminal=='close':e.lifecycle.close_live_session(e.user,sid)
|
||||
elif terminal=='cancel':e.lifecycle.cancel_tools(e.user,sid)
|
||||
elif terminal=='logout':e.auth.logout(e.token)
|
||||
elif terminal=='restart':e.lifecycle.reconcile_startup()
|
||||
else:selection_replace(e.engine,e.actor,2,[])
|
||||
try: assert not e.lifecycle.complete_tool(e.user,sid,call['id'],{'status':'no_evidence','sources':[]},execution)
|
||||
except ValueError:pass
|
||||
with e.engine.connect() as conn:
|
||||
saved=conn.execute(text('SELECT status,result_json FROM tool_calls WHERE id=:id'),{'id':call['id']}).mappings().one()
|
||||
assert saved['status']=='failed' and saved['result_json'] is None
|
||||
|
||||
|
||||
def test_poll_redacts_revoked_evidence_and_uses_public_reference(seeded_env):
|
||||
e=seeded_env;cid,sid=reserve(e);execution=SearchExecution(e.actor);ref=str(uuid4())
|
||||
call=e.lifecycle.admit_tool(e.user,sid,'private',ref,{'query':QUERY},execution)
|
||||
with e.engine.connect() as conn:
|
||||
chunk=conn.execute(text('SELECT id,text FROM document_chunks WHERE document_id=:id'),{'id':e.doc}).mappings().first()
|
||||
result={'status':'ok','sources':[dict(document_id=str(e.doc),chunk_id=str(chunk['id']),source_ref='S1',title='Pump',text=chunk['text'],location={'page':None,'section':None})]}
|
||||
assert e.lifecycle.complete_tool(e.user,sid,call['id'],result,execution)
|
||||
before=e.lifecycle.get_live_session(e.user,sid)['recent_tool_results'][0]
|
||||
assert before['tool_call_id']==ref and before['sources'][0]['available']
|
||||
selection_replace(e.engine,e.actor,2,[])
|
||||
after=e.lifecycle.get_live_session(e.user,sid)['recent_tool_results'][0]
|
||||
assert not after['sources'][0]['available'] and after['sources'][0]['excerpt'] is None
|
||||
assert after['sources'][0]['document_id']==str(e.doc)
|
||||
|
||||
|
||||
def test_selection_admission_and_completion_races(seeded_env):
|
||||
e=seeded_env;cid,sid=reserve(e);execution=SearchExecution(e.actor)
|
||||
call=e.lifecycle.admit_tool(e.user,sid,'private',str(uuid4()),{'query':QUERY},execution)
|
||||
results=concurrent(lambda:selection_replace(e.engine,e.actor,2,[]),
|
||||
lambda:e.lifecycle.complete_tool(e.user,sid,call['id'],{'status':'no_evidence','sources':[]},execution),
|
||||
lambda:e.lifecycle.create_live_session(e.user,cid,uuid4()))
|
||||
assert results[2] in ('LIVE_SESSION_BUSY','CONVERSATION_STALE')
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text('SELECT status FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()=='closed'
|
||||
|
||||
|
||||
def test_cross_organization_provisioning_preserves_account(seeded_env):
|
||||
e=seeded_env
|
||||
with e.engine.begin() as conn:
|
||||
other=uuid4();conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"),{'id':other})
|
||||
before=conn.execute(text('SELECT password_hash,role,is_enabled FROM users WHERE id=:id'),{'id':e.actor}).one()
|
||||
with pytest.raises(ValueError,match='another organization'):
|
||||
provision_user(conn,username=str(e.actor),password='forged',organization_id=other,role='user',is_enabled=False)
|
||||
assert conn.execute(text('SELECT password_hash,role,is_enabled FROM users WHERE id=:id'),{'id':e.actor}).one()==before
|
||||
|
||||
@pytest.fixture
|
||||
def api(seeded_env,monkeypatch):
|
||||
from app.main import app
|
||||
from app.api.v1 import dependencies as d
|
||||
from app.api.v1 import live
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport
|
||||
e=seeded_env;settings=e.settings
|
||||
from app.api.v1.auth import _ATTEMPTS, _LOCK
|
||||
with _LOCK: _ATTEMPTS.clear()
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile),2,'deterministic-fixture-only')
|
||||
search=SearchService(e.engine,settings,DeterministicEmbeddings(settings),cutoff=cutoff)
|
||||
e.search = search
|
||||
e.voice_config = config
|
||||
e.connections = []
|
||||
runner=SearchToolRunner(running=2,waiting=2,timeout=2)
|
||||
wire=FakeGoogleTransport()
|
||||
async def connect(*args):
|
||||
e.connections.append(1)
|
||||
return wire
|
||||
monkeypatch.setattr(live,'connect_gemini',connect)
|
||||
monkeypatch.setattr(live,'capability',lambda config:cutoff)
|
||||
monkeypatch.setattr('app.main.config',config)
|
||||
app.dependency_overrides[d.get_engine]=lambda:e.engine
|
||||
app.dependency_overrides[d.get_auth_service]=lambda:e.auth
|
||||
app.dependency_overrides[d.get_lifecycle_service]=lambda:e.lifecycle
|
||||
app.dependency_overrides[d.get_search_service]=lambda:search
|
||||
app.dependency_overrides[d.get_tool_runner]=lambda:runner
|
||||
app.dependency_overrides[d.get_voice_settings]=lambda:config
|
||||
# Lifespan uses the same real services rather than a mocked reconciliation.
|
||||
monkeypatch.setattr(d,'get_engine',lambda:e.engine)
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda engine:e.lifecycle)
|
||||
try:
|
||||
with TestClient(app,base_url='http://localhost:8000') as client:
|
||||
yield client,wire,runner,e
|
||||
finally:
|
||||
app.dependency_overrides.clear();runner.close()
|
||||
|
||||
|
||||
def login(client,e):
|
||||
response=client.post('/api/v1/auth/login',json={'username':str(e.actor),'password':'fixture-password'},headers={'Origin':'http://localhost:8000'})
|
||||
assert response.status_code==200,response.text
|
||||
return {'Origin':'http://localhost:8000','X-CSRF-Token':response.json()['csrf_token']}
|
||||
|
||||
|
||||
def session(client,e):
|
||||
headers=login(client,e)
|
||||
conv=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4()),'mode':'voice'},headers=headers)
|
||||
assert conv.status_code==201,conv.text
|
||||
body={'conversation_id':conv.json()['id'],'client_request_id':str(uuid4())}
|
||||
result=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
||||
assert result.status_code==201,result.text
|
||||
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
||||
assert replay.status_code==202 and replay.json()['session_id']==result.json()['session_id']
|
||||
return headers,result.json(),body
|
||||
|
||||
|
||||
def test_authenticated_http_schemas_recovery_logout_and_security(api):
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e)
|
||||
me=client.get('/api/v1/me')
|
||||
assert me.status_code==200 and me.json()['expires_at']
|
||||
recovered=client.get('/api/v1/voice/sessions/by-request/'+body['client_request_id'])
|
||||
assert recovered.status_code==200 and recovered.json()['session_id']==result['session_id']
|
||||
wrong=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4()),'scope':'forged'},headers=headers)
|
||||
assert wrong.status_code==422 and wrong.json()['error']['request_id']==wrong.headers['X-Request-ID']
|
||||
assert client.post('/api/v1/auth/logout',headers={'Origin':'http://localhost:8000'}).status_code==403
|
||||
assert client.post('/api/v1/auth/logout',headers=headers).status_code==204
|
||||
assert client.post('/api/v1/auth/logout',headers={'Origin':'http://localhost:8000'}).status_code==204
|
||||
assert client.get('/api/v1/me',headers={'Authorization':'Bearer '+e.token}).status_code==401
|
||||
assert not wire.sent
|
||||
|
||||
@pytest.mark.parametrize('ending',['provider_loss','http_close','logout','disable','epoch','invalid_control','oversized_audio','auth_expiry','live_expiry','shutdown'])
|
||||
def test_actual_asgi_gemini_ready_and_blocked_browser_cleanup(api,ending):
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}})
|
||||
ready=ws.receive_json()
|
||||
assert ready['type']=='session_ready' and ready['input_audio']['sample_rate']==24000
|
||||
# Readiness delivery precedes its durable connected commit. Wait on that
|
||||
# actual state transition; receiving a buffered frame is not a DB barrier.
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
current_user=e.auth.get_current_user(client.cookies.get(COOKIE_NAME))
|
||||
client.portal.call(until,lambda:e.lifecycle.get_live_session(current_user,sid)['status']=='connected')
|
||||
assert e.lifecycle.get_live_session(current_user,sid)['status']=='connected'
|
||||
if ending=='provider_loss':client.portal.call(wire.inbound.put,ConnectionError('private'))
|
||||
elif ending=='http_close':assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
|
||||
elif ending=='logout':assert client.post('/api/v1/auth/logout',headers=headers).status_code==204
|
||||
elif ending=='disable':
|
||||
with e.engine.begin() as conn:conn.execute(text('UPDATE users SET is_enabled=false WHERE id=:id'),{'id':e.actor})
|
||||
elif ending=='epoch':selection_replace(e.engine,e.actor,2,[])
|
||||
elif ending=='auth_expiry':
|
||||
with e.engine.begin() as conn:conn.execute(text("UPDATE auth_sessions SET created_at=now()-interval '2 hours',expires_at=now()-interval '1 hour' WHERE token_hash=:hash"), {'hash': __import__('app.modules.auth.service',fromlist=['hash_token']).hash_token(client.cookies.get(COOKIE_NAME))})
|
||||
elif ending=='live_expiry':
|
||||
with e.engine.begin() as conn:conn.execute(text("UPDATE live_sessions SET expires_at=now()-interval '1 second' WHERE id=:id"), {'id':sid})
|
||||
elif ending=='shutdown':
|
||||
from app.modules.voice.registry import shutdown
|
||||
client.portal.call(shutdown)
|
||||
elif ending=='invalid_control':ws.send_json({'type':'speech_started'})
|
||||
else:ws.send_bytes(bytes(9602))
|
||||
# Browser sends nothing further; provider/runtime failure must wake reception.
|
||||
try:
|
||||
while True: ws.receive_json()
|
||||
except Exception:pass
|
||||
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)
|
||||
assert wire.closed==1
|
||||
with e.engine.connect() as conn:
|
||||
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('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
|
||||
from app.modules.documents.embeddings import EmbeddingProviderError
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
query=QUERY
|
||||
if outcome=='no_evidence':
|
||||
e.search.cutoff=CalibratedCutoff(asdict(e.settings.embedding_profile),0,'fixture-no-evidence')
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text("UPDATE live_sessions SET execution_profile=jsonb_set(execution_profile,'{search}',CAST(:search AS jsonb)) WHERE id=:id"), dict(id=sid,search=json.dumps({'embedding':e.search.cutoff.profile,'calibration_id':e.search.cutoff.calibration_id,'retrieval_policy':e.search.cutoff.retrieval_policy,'distance':e.search.cutoff.distance})))
|
||||
query='unrelated query impossible evidence'
|
||||
elif outcome=='error':
|
||||
def fail(*args,**kwargs):raise EmbeddingProviderError('fake remote unavailable',retryable=True)
|
||||
e.search.provider.embed=fail
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}})
|
||||
assert ws.receive_json()['type']=='session_ready'
|
||||
ws.send_bytes(bytes(4800));ws.send_bytes(bytes(4800))
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if 'realtimeInput' in m])==2)
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
|
||||
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':query}}
|
||||
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[fn]}})
|
||||
events=[]
|
||||
while True:
|
||||
event=ws.receive_json();events.append(event)
|
||||
if event['type']=='sources':break
|
||||
client.portal.call(until,lambda:any('toolResponse' in m 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'
|
||||
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}})
|
||||
while True:
|
||||
event=ws.receive_json()
|
||||
if event.get('role')=='assistant' and event['status']=='completed':break
|
||||
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)
|
||||
assert wire.closed==1
|
||||
|
||||
@pytest.mark.parametrize('conflicting',[False,True])
|
||||
def test_durable_duplicates_share_actual_completion_without_retrieval_reexecution(seeded_env,conflicting):
|
||||
from app.modules.voice.durable_tools import DurableTools
|
||||
from app.modules.knowledge.langchain_tool import ToolContext
|
||||
import time
|
||||
e=seeded_env;cid,sid=reserve(e)
|
||||
async def scenario():
|
||||
store=DurableTools(e.lifecycle,e.user,sid);entered=asyncio.Event();release=asyncio.Event();invocations=[]
|
||||
async def invoke():
|
||||
invocations.append(1);entered.set();await release.wait()
|
||||
return {'status':'no_evidence','sources':[]}
|
||||
call1,call2={'ref':str(uuid4())},{'ref':str(uuid4())}
|
||||
ctx1,ctx2=ToolContext(SearchExecution(e.actor),time.monotonic()+5),ToolContext(SearchExecution(e.actor),time.monotonic()+5)
|
||||
first=asyncio.create_task(store.execute('private',call1,ctx1,{'query':QUERY},invoke))
|
||||
await asyncio.wait_for(entered.wait(),2)
|
||||
second=asyncio.create_task(store.execute('private',call2,ctx2,{'query':'different' if conflicting else QUERY},invoke))
|
||||
if conflicting:
|
||||
with pytest.raises(ValueError,match='IDEMPOTENCY_CONFLICT'):await second
|
||||
else:
|
||||
await asyncio.sleep(.1);assert not second.done()
|
||||
release.set();result=await first
|
||||
if not conflicting:assert await second==result and call1['ref']==call2['ref']
|
||||
assert invocations==[1]
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('cause',['expired','stale','wrong_auth','disabled','query_token'])
|
||||
def test_actual_asgi_rejects_ineligible_reservation_before_gemini(api,cause):
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
if cause=='expired':
|
||||
with e.engine.begin() as conn:conn.execute(text("UPDATE live_sessions SET expires_at=now()-interval '1 second' WHERE id=:id"),{'id':sid})
|
||||
elif cause=='stale':selection_replace(e.engine,e.actor,2,[])
|
||||
elif cause=='wrong_auth':login(client,e)
|
||||
elif cause=='disabled':
|
||||
with e.engine.begin() as conn:conn.execute(text('UPDATE users SET is_enabled=false WHERE id=:id'),{'id':e.actor})
|
||||
suffix='?token='+e.token if cause=='query_token' else ''
|
||||
with pytest.raises(WebSocketDisconnect):
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path']+suffix,headers={'Origin':'http://localhost:8000'}):pass
|
||||
assert not wire.sent
|
||||
|
||||
|
||||
def test_expired_logout_clears_cookie_without_csrf_after_origin_check(api):
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e)
|
||||
token=client.cookies.get(COOKIE_NAME);user=e.auth.get_current_user(token)
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text("UPDATE auth_sessions SET created_at=now()-interval '2 hours',expires_at=now()-interval '1 hour' WHERE id=:id"),{'id':user.auth_session_id})
|
||||
assert client.post('/api/v1/auth/logout',headers={'Origin':'http://localhost:8000'}).status_code==204
|
||||
assert COOKIE_NAME not in client.cookies
|
||||
|
||||
|
||||
def test_startup_reconciliation_failure_never_advertises_ready(seeded_env,monkeypatch):
|
||||
from app.main import app
|
||||
from app.api.v1 import dependencies as d
|
||||
e=seeded_env
|
||||
with e.engine.begin() as conn:conn.execute(text('DROP TABLE tool_calls'))
|
||||
monkeypatch.setattr(d,'get_engine',lambda:e.engine)
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda engine:e.lifecycle)
|
||||
with pytest.raises(Exception):
|
||||
with TestClient(app):pass
|
||||
assert app.state.ready is False
|
||||
|
||||
|
||||
def test_single_media_connection_before_setup_and_setup_loss_are_durable(api):
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
url='ws://localhost:8000'+result['stream_path']
|
||||
with client.websocket_connect(url,headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
with pytest.raises(WebSocketDisconnect):
|
||||
with client.websocket_connect(url,headers={'Origin':'http://localhost:8000'}):pass
|
||||
assert e.connections==[1]
|
||||
client.portal.call(wire.inbound.put,ConnectionError('setup remote lost'))
|
||||
try:
|
||||
while True:ws.receive_json()
|
||||
except WebSocketDisconnect:pass
|
||||
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
with e.engine.connect() as conn:
|
||||
row=conn.execute(text('SELECT status,connected_at FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert row[0]=='failed' and row[1] is None
|
||||
assert wire.closed==1
|
||||
|
||||
|
||||
def test_failed_application_acceptance_releases_guard_without_provider_connection(api):
|
||||
from app.api.v1.live import handle_stream_websocket, ACTIVE_MEDIA_SESSIONS
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
class Socket:
|
||||
query_params={}
|
||||
headers={'origin':'http://localhost:8000','host':'localhost:8000'}
|
||||
cookies={COOKIE_NAME:client.cookies.get(COOKIE_NAME)}
|
||||
async def accept(self):raise ConnectionError('fake application transport lost')
|
||||
async def close(self,**kwargs):pass
|
||||
client.portal.call(handle_stream_websocket,Socket(),sid,e.auth,e.lifecycle,e.engine,e.search,runner,e.voice_config)
|
||||
assert sid not in ACTIVE_MEDIA_SESSIONS and not e.connections
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text('SELECT status FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()=='failed'
|
||||
|
||||
@pytest.mark.parametrize('code',['SEARCH_TIMEOUT','SEARCH_FAILED','PROVIDER_UNAVAILABLE'])
|
||||
def test_concurrent_and_completed_technical_errors_replay_one_invocation(seeded_env,code):
|
||||
from app.modules.voice.durable_tools import DurableTools
|
||||
from app.modules.knowledge.langchain_tool import ToolContext
|
||||
import time
|
||||
e=seeded_env;_,sid=reserve(e)
|
||||
async def scenario():
|
||||
store=DurableTools(e.lifecycle,e.user,sid);entered=asyncio.Event();release=asyncio.Event();invocations=[]
|
||||
result={'status':'error','sources':[],'error':{'code':code,'message':'Technical fixture failure','request_id':str(uuid4()),'retryable':True}}
|
||||
async def invoke():invocations.append(1);entered.set();await release.wait();return result
|
||||
def ctx():return ToolContext(SearchExecution(e.actor),time.monotonic()+5)
|
||||
calls=[{'ref':str(uuid4())} for _ in range(3)]
|
||||
contexts=[ctx() for _ in range(3)]
|
||||
first=asyncio.create_task(store.execute('technical',calls[0],contexts[0],{'query':QUERY},invoke))
|
||||
await entered.wait()
|
||||
second=asyncio.create_task(store.execute('technical',calls[1],contexts[1],{'query':QUERY},invoke))
|
||||
await asyncio.sleep(.1);assert not second.done();release.set()
|
||||
assert await first==await second==result
|
||||
assert await store.execute('technical',calls[2],contexts[2],{'query':QUERY},invoke)==result
|
||||
for call,context in zip(calls,contexts):call['result']=result;await store.delivery(call,context.execution)
|
||||
assert len({c['ref'] for c in calls})==1 and invocations==[1]
|
||||
# A revoked session still cannot replay even a previously valid technical result.
|
||||
e.auth.logout(e.token)
|
||||
with pytest.raises(ValueError):await store.execute('technical',{'ref':str(uuid4())},ctx(),{'query':QUERY},invoke)
|
||||
assert invocations==[1]
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_cancelled_tool_with_saved_error_remains_ineligible(seeded_env):
|
||||
e=seeded_env;_,sid=reserve(e);execution=SearchExecution(e.actor)
|
||||
call=e.lifecycle.admit_tool(e.user,sid,'cancelled',str(uuid4()),{'query':QUERY},execution)
|
||||
result={'status':'error','sources':[],'error':{'code':'SEARCH_CANCELLED','message':'cancelled','retryable':False,'request_id':str(uuid4())}}
|
||||
assert e.lifecycle.complete_tool(e.user,sid,call['id'],result,execution)
|
||||
with pytest.raises(ValueError,match='LIVE_SESSION_UNUSABLE'):
|
||||
e.lifecycle.admit_tool(e.user,sid,'cancelled',str(uuid4()),{'query':QUERY},SearchExecution(e.actor))
|
||||
with pytest.raises(ValueError,match='LIVE_SESSION_UNUSABLE'):
|
||||
e.lifecycle.tool_result(e.user,sid,call['id'],execution,allow_technical_failure=True)
|
||||
|
||||
@pytest.mark.parametrize('title',[None,'','عنوان',' original title '])
|
||||
def test_original_phase2_hashes_survive_forward_upgrade_and_preserve_conflicts(seeded_env,migrated_db,title):
|
||||
from alembic import command
|
||||
from app.modules.voice.lifecycle import canonical_hash
|
||||
e=seeded_env;engine,config=migrated_db;creq,lreq=uuid4(),uuid4()
|
||||
conversation=e.lifecycle.create_conversation(e.user,creq,title=title);cid=UUID(conversation['id'])
|
||||
reserved=e.lifecycle.create_live_session(e.user,cid,lreq,model='pinned-original-model');sid=UUID(reserved['session_id'])
|
||||
legacy_c=canonical_hash(dict(user=str(e.actor),request=str(creq),mode='voice',title=title or ''))
|
||||
legacy_v=canonical_hash(dict(owner=str(e.actor),conversation_id=str(cid),client_request_id=str(lreq),provider='gemini',model='pinned-original-model'))
|
||||
with engine.begin() as conn:
|
||||
config.attributes['connection']=conn
|
||||
command.downgrade(config,'0004_live_lifecycle')
|
||||
conn.execute(text('UPDATE conversations SET request_hash=:hash,title=:title WHERE id=:id'),dict(hash=legacy_c,title=title,id=cid))
|
||||
conn.execute(text('UPDATE live_sessions SET request_hash=:hash WHERE id=:id'),dict(hash=legacy_v,id=sid))
|
||||
command.upgrade(config,'head')
|
||||
if title is None or title == '':
|
||||
with pytest.raises(ValueError,match='IDEMPOTENCY_CONFLICT'):
|
||||
e.lifecycle.create_conversation(e.user,creq,title='' if title is None else None)
|
||||
assert e.lifecycle.create_conversation(e.user,creq,title=title)['id']==str(cid)
|
||||
assert e.lifecycle.create_live_session(e.user,cid,lreq,model='today-different-config')['session_id']==str(sid)
|
||||
with pytest.raises(ValueError,match='IDEMPOTENCY_CONFLICT'):e.lifecycle.create_conversation(e.user,creq,title='changed')
|
||||
other=UUID(e.lifecycle.create_conversation(e.user,uuid4())['id'])
|
||||
with pytest.raises(ValueError,match='IDEMPOTENCY_CONFLICT'):e.lifecycle.create_live_session(e.user,other,lreq)
|
||||
with engine.begin() as conn:conn.execute(text('UPDATE conversations SET request_hash=:hash WHERE id=:id'),dict(hash='0'*64,id=cid))
|
||||
with pytest.raises(ValueError,match='IDEMPOTENCY_CONFLICT'):e.lifecycle.create_conversation(e.user,creq,title=title)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('active_audio',[False,True])
|
||||
def test_delivered_client_explicit_close_race_through_actual_asgi_postgres(api,active_audio):
|
||||
"""Node executes VoiceClient; a loopback bridge carries its HTTP/WS to real ASGI.
|
||||
|
||||
Only browser hardware and remote Google transport are deterministic doubles.
|
||||
"""
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from threading import Thread
|
||||
from queue import Queue, Empty
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import shutil
|
||||
client,wire,runner,e=api
|
||||
messages=Queue();state={};errors=[]
|
||||
class Bridge(BaseHTTPRequestHandler):
|
||||
def log_message(self,*args):pass
|
||||
def do_POST(self):
|
||||
try:
|
||||
body=json.loads(self.rfile.read(int(self.headers['Content-Length'])))
|
||||
if self.path=='/http':
|
||||
headers={**body.get('headers',{}),'Origin':'http://localhost:8000'}
|
||||
data=json.loads(body['body']) if body.get('body') else None
|
||||
if body['path'].endswith('/auth/login'):data['username']=str(e.actor)
|
||||
response=client.request(body['method'],body['path'],json=data,headers=headers)
|
||||
result={'status':response.status_code,'body':response.json() if response.status_code!=204 else None}
|
||||
elif self.path=='/open':
|
||||
context=client.websocket_connect('ws://localhost:8000'+body['path'],headers={'Origin':'http://localhost:8000'})
|
||||
state['context']=context;state['ws']=context.__enter__()
|
||||
def receive():
|
||||
try:
|
||||
while True:
|
||||
frame=state['ws'].receive()
|
||||
if frame.get('bytes') is not None:messages.put({'binary':base64.b64encode(frame['bytes']).decode()})
|
||||
elif frame.get('text') is not None:messages.put(json.loads(frame['text']))
|
||||
else:break
|
||||
except Exception:pass
|
||||
state['receiver']=Thread(target=receive,daemon=True);state['receiver'].start()
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}});result={}
|
||||
elif self.path=='/events':
|
||||
result=[]
|
||||
while True:
|
||||
try:result.append(messages.get_nowait())
|
||||
except Empty:break
|
||||
elif self.path=='/send':
|
||||
if 'audio' in body:state['ws'].send_bytes(base64.b64decode(body['audio']))
|
||||
else:state['ws'].send_text(body['data'])
|
||||
result={}
|
||||
elif self.path=='/generate':
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
async def generate():
|
||||
await until(lambda:any('realtimeInput' in m for m in wire.sent))
|
||||
await wire.inbound.put({'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
|
||||
await wire.inbound.put({'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
|
||||
await wire.inbound.put({'serverContent':{'modelTurn':{'parts':[{'inlineData':{'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(960)).decode()}}]}}})
|
||||
client.portal.call(generate);result={}
|
||||
elif self.path=='/disconnect':
|
||||
state.pop('context').__exit__(None,None,None);result={}
|
||||
else:raise AssertionError(self.path)
|
||||
payload=json.dumps(result).encode();self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(payload)
|
||||
except Exception as exc:
|
||||
errors.append(exc);self.send_response(500);self.end_headers();self.wfile.write(b'{}')
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Bridge);thread=Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||
try:
|
||||
node=shutil.which('node');assert node,'Node is required for delivered client acceptance'
|
||||
path=Path(__file__).resolve().parents[1]/'support/voice_client_harness.mjs'
|
||||
result=subprocess.run([node,str(path),'asgi',f'http://127.0.0.1:{server.server_port}','audio' if active_audio else 'silent'],capture_output=True,text=True,timeout=20)
|
||||
assert not errors,errors
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
with e.engine.connect() as conn:
|
||||
row=conn.execute(text('SELECT status,close_reason,error_code FROM live_sessions WHERE owner_user_id=:id'),dict(id=e.actor)).mappings().one()
|
||||
assert dict(row)==dict(status='closed',close_reason='user_requested',error_code=None)
|
||||
assert wire.closed==1
|
||||
finally:
|
||||
context=state.pop('context',None)
|
||||
if context is not None:context.__exit__(None,None,None)
|
||||
server.shutdown();server.server_close();thread.join(timeout=2)
|
||||
|
||||
|
||||
def test_real_database_dispatch_failure_is_durably_technical_not_revocation(api,monkeypatch):
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
def unavailable(*args):
|
||||
with e.engine.connect() as conn:conn.execute(text('SELECT * FROM deliberately_missing_phase2_relation'))
|
||||
monkeypatch.setattr(e.lifecycle,'admit_tool',unavailable)
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}});assert ws.receive_json()['type']=='session_ready'
|
||||
ws.send_bytes(bytes(9600))
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
client.portal.call(until,lambda:any('realtimeInput' in m for m in wire.sent))
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
|
||||
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[{'id':'c','name':'search_knowledge','args':{'query':QUERY}}]}})
|
||||
while True:
|
||||
event=ws.receive_json()
|
||||
if event['type']=='error':break
|
||||
assert event['error']['code']=='DEPENDENCY_UNAVAILABLE'
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
row=e.lifecycle.get_live_session(e.user,sid)
|
||||
assert row['status']=='failed' and row['error_code']=='DEPENDENCY_UNAVAILABLE'
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
Reference in New Issue
Block a user