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:
@@ -19,6 +19,7 @@ def test_empty_migration_tables_and_pinned_profile(migrated_db, settings):
|
||||
assert set(tables) == {
|
||||
"alembic_version", "organizations", "users", "organization_settings",
|
||||
"documents", "ingestion_jobs", "document_chunks", "audit_events",
|
||||
"auth_sessions", "conversations", "live_sessions", "tool_calls",
|
||||
}
|
||||
for changed in (
|
||||
replace(settings.embedding_profile, model="different-model"),
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,165 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import vm from 'node:vm';
|
||||
export const {VoiceClient} = await import('data:text/javascript;base64,' + fs.readFileSync(new URL('../../examples/voice-client.js', import.meta.url)).toString('base64'));
|
||||
export const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
export const deferred = () => {let resolve, reject; const promise = new Promise((a,b) => {resolve=a;reject=b;}); return {promise,resolve,reject};};
|
||||
export function environment() {
|
||||
const sockets=[],contexts=[],tracks=[],requests=[];
|
||||
let permission=deferred(),module=Promise.resolve(),flush=Promise.resolve();
|
||||
globalThis.location={origin:'http://localhost:8000',protocol:'http:'};
|
||||
Object.defineProperty(globalThis,'navigator',{configurable:true,value:{mediaDevices:{getUserMedia:()=>permission.promise}}});
|
||||
globalThis.AudioContext=class {
|
||||
constructor(){this.sampleRate=24000;this.state='running';this.destination={};this.audioWorklet={addModule:()=>module};contexts.push(this);}
|
||||
async resume(){} async close(){this.state='closed';this.closed=(this.closed||0)+1;}
|
||||
createMediaStreamSource(){return {connect(){},disconnect(){}};}
|
||||
createGain(){return {gain:{value:1},connect(){},disconnect(){}};}
|
||||
};
|
||||
globalThis.AudioWorkletNode=class {
|
||||
constructor(context,name){this.name=name;this.port={postMessage:m=>{
|
||||
if(m.type==='flush') {
|
||||
this.port.onmessage?.({data:{type:'progress',ref:'audio',played_ms:5}});
|
||||
flush.then(()=>this.port.onmessage?.({data:{type:'flushed',id:m.id}}));
|
||||
}
|
||||
}};}
|
||||
connect(){} disconnect(){}
|
||||
};
|
||||
globalThis.WebSocket=class {
|
||||
static OPEN=1;
|
||||
constructor(){this.readyState=1;this.bufferedAmount=0;this.sent=[];sockets.push(this);}
|
||||
send(m){this.sent.push(m);}
|
||||
close(){this.readyState=3;this.closes=(this.closes||0)+1;this.onclose?.();}
|
||||
};
|
||||
globalThis.fetch=async(path,options)=>{
|
||||
requests.push({path,options});
|
||||
return {status:200,ok:true,json:async()=>path.endsWith('/me')?{csrf_token:'valid',expires_at:'actual'}:{status:'closed'}};
|
||||
};
|
||||
const media=()=>{const track={stops:0,stop(){this.stops++;}};tracks.push(track);return {getTracks:()=>[track]};};
|
||||
const client=()=>{const c=new VoiceClient(()=>{});c.session={session_id:'sid',stream_path:'/stream'};return c;};
|
||||
const ready=()=>sockets.at(-1).onmessage({data:JSON.stringify({type:'session_ready',session_id:'sid',input_audio:{sample_rate:24000},output_audio:{sample_rate:24000}})});
|
||||
return {sockets,contexts,tracks,requests,media,client,ready,
|
||||
permission:()=>permission, resetPermission:()=>permission=deferred(),setModule:p=>module=p,setFlush:p=>flush=p};
|
||||
}
|
||||
export async function unitScenarios() {
|
||||
// Permission resolves while cleanup is flushing, and after cleanup has completed.
|
||||
for(const during of [false,true]) {
|
||||
const e=environment(),c=e.client(),flush=deferred();
|
||||
if(during)e.setFlush(flush.promise);
|
||||
const connecting=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
||||
const cleaning=c.cleanup(),again=c.cleanup();assert.equal(cleaning,again);
|
||||
if(!during)await cleaning;
|
||||
const media=e.media();e.permission().resolve(media);await connecting;
|
||||
flush.resolve();await cleaning;
|
||||
assert.equal(e.tracks[0].stops,1);assert.equal(e.contexts[0].closed,1);assert.equal(e.sockets[0].closes,1);
|
||||
}
|
||||
// Preparation cancellation must not create a socket after addModule completes.
|
||||
{
|
||||
const e=environment(),c=e.client(),module=deferred();e.setModule(module.promise);
|
||||
const pending=c.connect().catch(e=>e);await tick();await c.cleanup();module.resolve();await pending;
|
||||
assert.equal(e.sockets.length,0);assert.equal(e.contexts[0].closed,1);
|
||||
}
|
||||
// A browser close promise cannot indefinitely retain cleanup ownership.
|
||||
{
|
||||
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
||||
e.contexts[0].close=()=>new Promise(()=>{});
|
||||
await c.cleanup();assert.equal(c.connection,null);assert.equal(e.sockets[0].closes,1);
|
||||
e.permission().resolve(e.media());await pending;assert.equal(e.tracks[0].stops,1);
|
||||
}
|
||||
// Rejected acquisition releases context/socket without pretending capture exists.
|
||||
{
|
||||
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
||||
e.permission().reject(new Error('permission denied'));assert.equal((await pending).message,'permission denied');
|
||||
assert.equal(c.connection,null);assert.equal(e.contexts[0].closed,1);
|
||||
}
|
||||
// Old callbacks are inert after a new generation owns media.
|
||||
{
|
||||
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
||||
const old=e.sockets[0],onclose=old.onclose,onmessage=old.onmessage;
|
||||
await c.cleanup();e.permission().resolve(e.media());await pending;
|
||||
e.resetPermission();const newer=c.connect();await tick();e.ready();e.permission().resolve(e.media());await newer;
|
||||
onclose();onmessage({data:JSON.stringify({type:'error',error:{code:'LIVE_TRANSPORT_FAILED'}})});
|
||||
assert.equal(c.socket,e.sockets[1]);assert.equal(c.socket.readyState,1);await c.cleanup();
|
||||
}
|
||||
// Nonterminal errors preserve authorized speech and later capture; fatal errors stop.
|
||||
for(const code of ['SEARCH_TIMEOUT','SEARCH_FAILED','LIVE_BUFFER_OVERFLOW','CONTEXT_REVOKED']) {
|
||||
const e=environment(),c=e.client(),events=[];c.onEvent=e=>events.push(e);
|
||||
const pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
||||
e.sockets[0].onmessage({data:JSON.stringify({type:'error',turn_ref:'turn',error:{code,retryable:false}})});await tick();
|
||||
if(code.startsWith('SEARCH_')) {
|
||||
assert.equal(c.ready,true);
|
||||
e.sockets[0].onmessage({data:JSON.stringify({type:'transcript',role:'assistant',text:'explanation'})});
|
||||
assert.equal(events.at(-1).text,'explanation');await c.cleanup();
|
||||
} else assert.equal(c.connection,null);
|
||||
}
|
||||
// Logout must reach backend even when identity is expired/revoked or V04 fails.
|
||||
for(const failure of ['expired','revoked','close','none']) {
|
||||
const e=environment(),c=e.client();c.csrf='old';
|
||||
globalThis.fetch=async(path,options)=> {
|
||||
e.requests.push({path,options});
|
||||
if(path.endsWith('/me')&&['expired','revoked'].includes(failure))return {status:401,ok:false,json:async()=>({error:{code:'AUTH_REQUIRED'}})};
|
||||
if(path.endsWith('/close')&&failure==='close')throw new Error('lost close');
|
||||
return {status:path.endsWith('/logout')?204:200,ok:true,json:async()=>({csrf_token:'fresh'})};
|
||||
};
|
||||
await c.logout();await c.logout();
|
||||
assert.equal(e.requests.filter(r=>r.path.endsWith('/logout')).length,2);assert.equal(c.csrf,null);
|
||||
if(failure==='none')assert.equal(e.requests.find(r=>r.path.endsWith('/logout')).options.headers['X-CSRF-Token'],'fresh');
|
||||
}
|
||||
// Explicit close sends final progress, then commits V04, then closes transport.
|
||||
{
|
||||
const e=environment(),c=e.client(),pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
||||
const order=[],socket=c.socket;socket.send=m=>order.push(JSON.parse(m).type);socket.close=()=>order.push('transport-close');
|
||||
globalThis.fetch=async(path)=>{order.push(path.endsWith('/close')?'V04':'me');return {status:200,ok:true,json:async()=>({csrf_token:'fresh'})};};
|
||||
await c.close();assert.deepEqual(order,['playback_progress','me','V04','transport-close']);
|
||||
}
|
||||
}
|
||||
if(process.argv[2]==='unit') {await unitScenarios();console.log('VoiceClient ownership, errors, logout and close scenarios passed');}
|
||||
|
||||
if(process.argv[2]==='asgi') {
|
||||
const bridge=process.argv[3], nativeFetch=globalThis.fetch, e=environment();
|
||||
const processors={}, played=deferred();
|
||||
globalThis.AudioWorkletProcessor=class {constructor(){this.port={postMessage:m=>this.emit?.(m)};}};
|
||||
globalThis.registerProcessor=(name,processor)=>processors[name]=processor;
|
||||
vm.runInThisContext(fs.readFileSync(new URL('../../examples/voice-audio-worklet.js',import.meta.url),'utf8'));
|
||||
globalThis.AudioWorkletNode=class {
|
||||
constructor(context,name){
|
||||
const processor=new processors[name]();
|
||||
processor.emit=m=>{this.port.onmessage?.({data:m});if(m.type==='progress')played.resolve();};
|
||||
this.port={postMessage:m=>{
|
||||
processor.port.onmessage({data:m});
|
||||
if(m.type==='pcm')processor.process([],[[new Float32Array(120)]]);
|
||||
}};
|
||||
}
|
||||
connect(){} disconnect(){}
|
||||
};
|
||||
async function rpc(path,body) {
|
||||
const response=await nativeFetch(bridge+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{})});
|
||||
return response.json();
|
||||
}
|
||||
globalThis.fetch=async(path,options={})=>{
|
||||
const r=await rpc('/http',{path,method:options.method||'GET',headers:options.headers,body:options.body});
|
||||
return {status:r.status,ok:r.status<400,json:async()=>r.body};
|
||||
};
|
||||
globalThis.WebSocket=class {
|
||||
static OPEN=1;
|
||||
constructor(url) {
|
||||
this.readyState=1;this.bufferedAmount=0;this.chain=Promise.resolve();this.polling=false;
|
||||
rpc('/open',{path:new URL(url).pathname}).then(()=>{
|
||||
this.timer=setInterval(async()=>{
|
||||
if(this.polling||this.readyState!==1)return;
|
||||
this.polling=true;
|
||||
try {const messages=await rpc('/events');for(const data of messages){const payload=data.binary?Uint8Array.from(Buffer.from(data.binary,'base64')).buffer:JSON.stringify(data);this.onmessage?.({data:payload});}}
|
||||
finally {this.polling=false;}
|
||||
},5);
|
||||
});
|
||||
}
|
||||
send(data) {const body=typeof data==='string'?{data}:{audio:Buffer.from(data).toString('base64')};this.chain=this.chain.then(()=>rpc('/send',body));}
|
||||
close() {clearInterval(this.timer);this.readyState=3;this.done=this.chain.then(()=>rpc('/disconnect'));}
|
||||
};
|
||||
const c=new VoiceClient(()=>{});
|
||||
await c.login('fixture','fixture-password');await c.reserve();e.permission().resolve(e.media());await c.connect();
|
||||
const socket=c.socket;
|
||||
if(process.argv[4]==='audio') {socket.send(new ArrayBuffer(9600));await socket.chain;await rpc('/generate');await played.promise;}
|
||||
await c.close();await socket.done;
|
||||
const state=await c.poll();assert.equal(state.status,'closed');assert.equal(state.close_reason,'user_requested');
|
||||
console.log(JSON.stringify(state));
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Actual Gemini adapter + runtime + canonical search + StructuredTool/shared runner."""
|
||||
import asyncio
|
||||
import base64
|
||||
from contextlib import nullcontext
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, PCM24To16, GeminiContextError
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.knowledge import langchain_tool as boundary
|
||||
from tests.unit.test_search_phase2 import service as canonical_service, row
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
class FakeGoogleTransport:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self.inbound = asyncio.Queue()
|
||||
self.closed = 0
|
||||
async def send(self, value):
|
||||
self.sent.append(json.loads(value))
|
||||
async def recv(self):
|
||||
value = await self.inbound.get()
|
||||
if isinstance(value, Exception):
|
||||
raise value
|
||||
return json.dumps(value) if isinstance(value,dict) else value
|
||||
async def close(self):
|
||||
self.closed += 1
|
||||
|
||||
async def make(service, runner, state):
|
||||
wire, output = FakeGoogleTransport(), []
|
||||
adapter = GeminiLiveAdapter(wire, model='configured-model', voice='Aoede')
|
||||
async def emit(value): output.append(value)
|
||||
async def authority(execution):
|
||||
return state['enabled'] and execution.capture(dict(id=execution.user_id, organization_id='fixture',role='user'),state['epoch'])
|
||||
runtime = VoiceRuntime(adapter, service, runner, uuid4(), emit, authority_check=authority)
|
||||
await runtime.start()
|
||||
receive = asyncio.create_task(runtime.receive_loop())
|
||||
await until(lambda: wire.sent)
|
||||
assert not runtime.ready and not adapter.acknowledged(adapter.setup()['session'])
|
||||
await wire.inbound.put({'setupComplete':{}})
|
||||
await until(lambda: runtime.ready)
|
||||
return runtime, adapter, wire, output, receive
|
||||
|
||||
async def input_turn(runtime, wire, start=0):
|
||||
for _ in range(2):
|
||||
await runtime.input_audio(bytes(4800))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_START','audioOffset':f'{start/1000}s'}})
|
||||
await wire.inbound.put({'voiceActivity': {'type':'ACTIVITY_END','audioOffset':f'{(start+100)/1000}s'}})
|
||||
|
||||
async def cleanup(runtime, receive):
|
||||
receive.cancel()
|
||||
await asyncio.gather(receive,return_exceptions=True)
|
||||
await runtime.close()
|
||||
|
||||
@pytest.mark.parametrize('rows,status', [([row()],'ok'),([],'no_evidence')])
|
||||
def test_native_tool_correlation_canonical_result_and_once_only_continuation(settings,monkeypatch,runner,persisted,rows,status):
|
||||
service = canonical_service(settings,monkeypatch,rows)
|
||||
async def scenario():
|
||||
runtime,adapter,wire,out,receive = await make(service,runner,persisted)
|
||||
try:
|
||||
assert wire.sent[0]['setup']['model']=='models/configured-model'
|
||||
assert wire.sent[0]['setup']['inputAudioTranscription']=={}
|
||||
await input_turn(runtime,wire)
|
||||
await wire.inbound.put({'serverContent': {'inputTranscription':{'text':'پرسش'}}})
|
||||
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':'q'}}
|
||||
await wire.inbound.put({'toolCall':{'functionCalls':[fn]}})
|
||||
await until(lambda: any('toolResponse' in m for m in wire.sent) or not runtime.usable)
|
||||
assert runtime.usable, runtime.failure
|
||||
responses=[m['toolResponse'] for m in wire.sent if 'toolResponse' in m]
|
||||
assert len(responses)==1
|
||||
answer=responses[0]['functionResponses'][0]
|
||||
assert answer['id']=='private-google-call' and answer['response']['status']==status
|
||||
assert answer['response']['sources']==next(iter(runtime.calls.values()))[1]['result']['sources']
|
||||
await wire.inbound.put({'serverContent': {'modelTurn':{'parts':[{'inlineData':{'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(960)).decode()}}]},'outputTranscription':{'text':'پاسخ'},'turnComplete':True}})
|
||||
await until(lambda: any(isinstance(e,dict) and e.get('type')=='audio_ended' for e in out) or not runtime.usable)
|
||||
assert runtime.usable, runtime.failure
|
||||
assert any(isinstance(e,dict) and e.get('role')=='user' and e['text']=='پرسش' for e in out)
|
||||
assert any(isinstance(e,dict) and e.get('role')=='assistant' and e['status']=='completed' and e['text']=='پاسخ' for e in out)
|
||||
source_event=next(e for e in out if isinstance(e,dict) and e.get('type')=='sources')
|
||||
assert source_event['tool_call_id']!='private-google-call'
|
||||
finally:
|
||||
await cleanup(runtime,receive)
|
||||
assert wire.closed==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('message', [ConnectionError('remote-private-detail'), 'x'*262145,
|
||||
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}])
|
||||
def test_provider_loss_and_limits_wake_runtime_and_close_once(runner,persisted,message):
|
||||
async def scenario():
|
||||
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
await wire.inbound.put(message)
|
||||
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
||||
await cleanup(runtime,receive)
|
||||
assert wire.closed==1 and not runtime.usable
|
||||
assert 'remote-private-detail' not in json.dumps([e for e in out if isinstance(e,dict)])
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_no_fabricated_cancel_or_truncate_acknowledgement():
|
||||
async def scenario():
|
||||
wire=FakeGoogleTransport();adapter=GeminiLiveAdapter(wire)
|
||||
with pytest.raises(GeminiContextError):
|
||||
await adapter.send({'type':'response.cancel','response_id':'private'})
|
||||
await adapter.close()
|
||||
assert wire.closed==1 and not wire.sent and adapter._inbound_events.empty()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_bounded_queue_and_resampler_partition_invariance():
|
||||
adapter=GeminiLiveAdapter(FakeGoogleTransport())
|
||||
for i in range(adapter.settings.max_control_messages): adapter._put({'type':'test','n':i})
|
||||
with pytest.raises(ValueError): adapter._put({'type':'overflow'})
|
||||
pcm=bytes([1,3])*2400
|
||||
assert len(PCM24To16().convert(pcm))==3200
|
||||
a=PCM24To16();b=PCM24To16()
|
||||
assert a.convert(pcm)==b.convert(pcm[:200])+b.convert(pcm[200:])
|
||||
|
||||
|
||||
def test_unverified_input_boundaries_fail_closed(runner,persisted):
|
||||
async def scenario():
|
||||
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
await wire.inbound.put({'toolCall':{'functionCalls':[{'id':'x','name':'search_knowledge','args':{'query':'q'}}]}})
|
||||
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
||||
assert not runtime.calls
|
||||
await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monkeypatch,runner,persisted,capsys):
|
||||
from app import voice_smoke
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.voice import runtime as runtime_module
|
||||
monkeypatch.setattr(runtime_module,'transaction',lambda _:nullcontext(None))
|
||||
monkeypatch.setattr(runtime_module,'authority',boundary.authority)
|
||||
class Scripted(FakeGoogleTransport):
|
||||
async def send(self,value):
|
||||
await super().send(value)
|
||||
message=self.sent[-1]
|
||||
if 'setup' in message:await self.inbound.put({'setupComplete':{}})
|
||||
elif 'clientContent' in message:
|
||||
await self.inbound.put({'toolCall':{'functionCalls':[{'id':'private','name':'search_knowledge','args':{'query':'q'}}]}})
|
||||
elif 'toolResponse' in message:
|
||||
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
wire=Scripted()
|
||||
async def connection(*args):return wire
|
||||
monkeypatch.setattr('app.infrastructure.gemini_live.connect_gemini',connection)
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
|
||||
service=canonical_service(settings,monkeypatch,[row()])
|
||||
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
|
||||
assert wire.sent[0]['setup']['model']=='models/configured-model'
|
||||
assert wire.closed==1
|
||||
assert 'smoke_correlation' in capsys.readouterr().out
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Phase 2 Auth unit tests: opaque cookies, stored hashes, CSRF, Origin, and endpoints."""
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from unittest.mock import MagicMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from argon2 import PasswordHasher
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
from app.modules.auth.service import (
|
||||
AuthService,
|
||||
COOKIE_NAME,
|
||||
UserContext,
|
||||
check_origin,
|
||||
generate_csrf_token,
|
||||
verify_csrf_token,
|
||||
hash_token,
|
||||
)
|
||||
from app.api.v1.dependencies import get_auth_service
|
||||
|
||||
|
||||
class DummyMapping:
|
||||
def __init__(self, data):
|
||||
self._data = data
|
||||
|
||||
def mappings(self):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._data
|
||||
|
||||
def all(self):
|
||||
return [self._data] if self._data else []
|
||||
|
||||
|
||||
class DummyConn:
|
||||
def __init__(self, query_results=None):
|
||||
self.query_results = query_results or []
|
||||
self.executed = []
|
||||
|
||||
def execute(self, statement, params=None):
|
||||
self.executed.append((str(statement), params))
|
||||
sql = str(statement).strip()
|
||||
if sql.startswith('SET ') or sql.startswith('SELECT organization_id FROM organization_settings'):
|
||||
return DummyMapping(None)
|
||||
if sql.startswith('SELECT u.id,u.organization_id'):
|
||||
return DummyMapping(getattr(self, '_last', None))
|
||||
if self.query_results:
|
||||
res = self.query_results.pop(0)
|
||||
self._last = res
|
||||
return DummyMapping(res)
|
||||
return DummyMapping(None)
|
||||
|
||||
|
||||
class DummyEngine:
|
||||
def __init__(self, conn):
|
||||
self.conn = conn
|
||||
|
||||
def begin(self):
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def ctx():
|
||||
yield self.conn
|
||||
return ctx()
|
||||
|
||||
|
||||
def test_csrf_generation_and_verification():
|
||||
raw_token = "a" * 64
|
||||
csrf = generate_csrf_token(raw_token)
|
||||
assert csrf and isinstance(csrf, str)
|
||||
assert verify_csrf_token(raw_token, csrf) is True
|
||||
# Tampered csrf
|
||||
assert verify_csrf_token(raw_token, "wrong-csrf-token") is False
|
||||
# Different token
|
||||
assert verify_csrf_token("different-token-1234", csrf) is False
|
||||
|
||||
|
||||
def test_check_origin():
|
||||
# Valid matching origins
|
||||
assert check_origin("https://api.example.com", "api.example.com", ["https://api.example.com"], ["api.example.com"]) is True
|
||||
assert check_origin("http://localhost:8000", "localhost:8000") is True
|
||||
assert check_origin("http://127.0.0.1:8000/docs", "127.0.0.1:8000") is False
|
||||
# Untrusted origin
|
||||
assert check_origin("https://evil.com", "api.example.com") is False
|
||||
assert check_origin("https://api.example.com.evil.com", "api.example.com") is False
|
||||
# Missing origin/referer allowed (same-origin browser GET / native curl)
|
||||
assert check_origin(None, "localhost:8000") is True
|
||||
|
||||
|
||||
def test_auth_service_login_and_validation():
|
||||
user_id = uuid4()
|
||||
org_id = uuid4()
|
||||
hasher = PasswordHasher()
|
||||
hashed_pwd = hasher.hash("secretpass")
|
||||
|
||||
# Mock user row in DB
|
||||
user_row = {
|
||||
"id": user_id,
|
||||
"organization_id": org_id,
|
||||
"username": "testuser",
|
||||
"password_hash": hashed_pwd,
|
||||
"role": "user",
|
||||
"is_enabled": True,
|
||||
"access_epoch": 1,
|
||||
}
|
||||
|
||||
conn = DummyConn(query_results=[user_row])
|
||||
engine = DummyEngine(conn)
|
||||
auth = AuthService(engine, session_ttl=timedelta(hours=1))
|
||||
|
||||
# 1. Successful login
|
||||
user_dict, raw_token, csrf, expires = auth.login("testuser", "secretpass")
|
||||
assert user_dict["username"] == "testuser"
|
||||
assert user_dict["role"] == "user"
|
||||
assert len(raw_token) == 64
|
||||
assert verify_csrf_token(raw_token, csrf) is True
|
||||
|
||||
# 2. Invalid password
|
||||
conn_bad = DummyConn(query_results=[user_row])
|
||||
auth_bad = AuthService(DummyEngine(conn_bad))
|
||||
with pytest.raises(ValueError, match="INVALID_CREDENTIALS"):
|
||||
auth_bad.login("testuser", "wrongpassword")
|
||||
|
||||
# 3. Disabled account
|
||||
disabled_row = dict(user_row, is_enabled=False)
|
||||
conn_dis = DummyConn(query_results=[disabled_row])
|
||||
auth_dis = AuthService(DummyEngine(conn_dis))
|
||||
with pytest.raises(ValueError, match="ACCOUNT_DISABLED"):
|
||||
auth_dis.login("testuser", "secretpass")
|
||||
|
||||
# 4. Unknown user
|
||||
conn_none = DummyConn(query_results=[None])
|
||||
auth_none = AuthService(DummyEngine(conn_none))
|
||||
with pytest.raises(ValueError, match="INVALID_CREDENTIALS"):
|
||||
auth_none.login("nobody", "secretpass")
|
||||
|
||||
|
||||
def test_auth_service_session_verification():
|
||||
user_id = uuid4()
|
||||
org_id = uuid4()
|
||||
session_id = uuid4()
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Active session row
|
||||
session_row = {
|
||||
"id": session_id,
|
||||
"user_id": user_id,
|
||||
"organization_id": org_id,
|
||||
"username": "alice",
|
||||
"role": "admin",
|
||||
"is_enabled": True,
|
||||
"access_epoch": 2,
|
||||
"expires_at": now + timedelta(hours=2),
|
||||
"revoked_at": None,
|
||||
}
|
||||
|
||||
conn = DummyConn(query_results=[session_row])
|
||||
auth = AuthService(DummyEngine(conn))
|
||||
raw_token = "b" * 64
|
||||
|
||||
user_ctx = auth.get_current_user(raw_token)
|
||||
assert user_ctx.id == user_id
|
||||
assert user_ctx.username == "alice"
|
||||
assert user_ctx.role == "admin"
|
||||
assert user_ctx.access_epoch == 2
|
||||
assert user_ctx.auth_session_id == session_id
|
||||
|
||||
# Expired session
|
||||
expired_row = dict(session_row, expires_at=now - timedelta(seconds=1))
|
||||
conn_exp = DummyConn(query_results=[expired_row])
|
||||
auth_exp = AuthService(DummyEngine(conn_exp))
|
||||
with pytest.raises(ValueError, match="SESSION_EXPIRED"):
|
||||
auth_exp.get_current_user(raw_token)
|
||||
|
||||
# Revoked session
|
||||
revoked_row = dict(session_row, revoked_at=now - timedelta(seconds=1))
|
||||
conn_rev = DummyConn(query_results=[revoked_row])
|
||||
auth_rev = AuthService(DummyEngine(conn_rev))
|
||||
with pytest.raises(ValueError, match="SESSION_REVOKED"):
|
||||
auth_rev.get_current_user(raw_token)
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize('token', [None,'','é'*64,'a'*65,'a'*63,'G'*64,'\ud800'*64])
|
||||
def test_malformed_session_and_csrf_rejected(token):
|
||||
assert not verify_csrf_token(token,'b'*64)
|
||||
assert not verify_csrf_token('b'*64,token)
|
||||
with pytest.raises(ValueError,match='AUTH_REQUIRED'):
|
||||
hash_token(token)
|
||||
|
||||
@pytest.mark.parametrize('origin,host', [('http://evil:8000','localhost:8000'),('http://localhost:9999','localhost:8000'),('http://localhost:8000','evil'),('http://localhost:bad','localhost:8000'),('http://localhost:8000/','localhost:8000'),(None,'evil')])
|
||||
def test_exact_origin_and_host(origin,host):
|
||||
assert not check_origin(origin,host)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Provider-free configuration, notification threading, and strict transport DTOs."""
|
||||
import asyncio
|
||||
from threading import Thread
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.voice import registry
|
||||
from app.modules.voice.lifecycle import canonical_hash
|
||||
from app.api.v1.live import CreateLiveSessionRequest
|
||||
from app.api.v1.auth import LoginRequest
|
||||
from app.api.v1.conversations import CreateConversationRequest
|
||||
|
||||
|
||||
def test_gemini_configuration_requires_no_openai_voice_key(monkeypatch):
|
||||
monkeypatch.delenv('OPENAI_API_KEY',raising=False)
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fixture',gemini_model='intended-profile',gemini_voice='Aoede')
|
||||
config.require_voice()
|
||||
assert config.provider=='gemini' and config.profile()['model']=='intended-profile'
|
||||
assert 'fixture' not in repr(config)
|
||||
|
||||
@pytest.mark.parametrize('changes', [{'provider':'openai'},{'trusted_origins':['http://evil/path']},
|
||||
{'trusted_hosts':['*']},{'gemini_proxy':'https://user:secret@proxy'},
|
||||
{'trusted_origins':['https://prod.example'],'cookie_secure':False},{'live_session_seconds':0}])
|
||||
def test_invalid_configuration_fails_before_remote_setup(changes):
|
||||
with pytest.raises(ValidationError): VoiceSettings(_env_file=None,**changes)
|
||||
|
||||
@pytest.mark.parametrize('model,payload',[(CreateLiveSessionRequest,{'conversation_id':str(uuid4()),'client_request_id':str(uuid4())}),
|
||||
(CreateConversationRequest,{'client_request_id':str(uuid4()),'mode':'voice'}),
|
||||
(LoginRequest,{'username':'a','password':'p'})])
|
||||
def test_strict_dto_rejects_extra_scope(model,payload):
|
||||
with pytest.raises(ValidationError): model.model_validate(dict(payload,organization_id=str(uuid4())))
|
||||
|
||||
|
||||
def test_epoch_notification_runs_on_owner_loop_and_skips_new_sessions():
|
||||
async def scenario():
|
||||
org=uuid4();called=[]
|
||||
class Runtime:
|
||||
def __init__(self):self.lock=asyncio.Lock()
|
||||
def fail(self,code):called.append((self,asyncio.get_running_loop(),code))
|
||||
old,new=Runtime(),Runtime();sid1,sid2=uuid4(),uuid4()
|
||||
registry.register(sid1,org,1,uuid4(),old);registry.register(sid2,org,2,uuid4(),new)
|
||||
try:
|
||||
thread=Thread(target=lambda:registry.notify(organization_id=org,new_epoch=2));thread.start();thread.join()
|
||||
await asyncio.sleep(.01)
|
||||
assert called==[(old,asyncio.get_running_loop(),'CONTEXT_REVOKED')]
|
||||
finally:
|
||||
registry.unregister(sid1);registry.unregister(sid2)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_canonical_argument_hash_is_order_independent():
|
||||
assert canonical_hash({'query':'q','context':None})==canonical_hash({'context':None,'query':'q'})
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Native correlation, admission and partial-startup regression boundaries."""
|
||||
import asyncio
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, GeminiContextError, GeminiOverflow
|
||||
from app.modules.voice.durable_tools import failure_code
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, input_turn, cleanup
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
|
||||
def adapter():
|
||||
a = GeminiLiveAdapter(FakeGoogleTransport()); a._confirmed = True; a._sent_samples = 24000
|
||||
return a
|
||||
|
||||
async def activity(a, kind, offset, **fields):
|
||||
await a._translate_google_message(dict(voiceActivity=dict(type=kind,audioOffset=offset),**fields))
|
||||
|
||||
@pytest.mark.parametrize('late',['audio','tool'])
|
||||
def test_pending_input_cannot_be_replaced_before_first_output(late):
|
||||
async def scenario():
|
||||
a=adapter()
|
||||
await activity(a,'ACTIVITY_START','0s');await activity(a,'ACTIVITY_END','0.1s')
|
||||
original=a._input
|
||||
with pytest.raises(GeminiContextError):await activity(a,'ACTIVITY_START','0.2s')
|
||||
assert a._input==original and len(a._inputs)==1 and not a._input_consumed
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('kind,offset',[('ACTIVITY_START','0s'),('ACTIVITY_END','0.1s')])
|
||||
@pytest.mark.parametrize('payload',['transcript','audio','tool','complete'])
|
||||
def test_repeated_activity_preserves_accompanying_native_content(kind,offset,payload):
|
||||
async def scenario():
|
||||
a=adapter();await activity(a,'ACTIVITY_START','0s');await activity(a,'ACTIVITY_END','0.1s')
|
||||
a._gate.set();a._intent='intent'
|
||||
if payload=='transcript':fields={'serverContent':{'inputTranscription':{'text':'q'}}}
|
||||
elif payload=='tool':fields={'toolCall':{'functionCalls':[{'id':'c','name':'search_knowledge','args':{'query':'q'}}]}}
|
||||
elif payload=='audio':fields={'serverContent':{'modelTurn':{'parts':[{'inlineData':{'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(48)).decode()}}]}}}
|
||||
else:
|
||||
await a._translate_google_message({'serverContent':{'outputTranscription':{'text':'a'}}})
|
||||
fields={'serverContent':{'turnComplete':True}}
|
||||
await activity(a,kind,offset,**fields)
|
||||
events=[]
|
||||
while not a._inbound_events.empty():events.append(await a.receive());a.consumed()
|
||||
expected={'transcript':'conversation.item.input_audio_transcription.delta','tool':'provider.tools_requested',
|
||||
'audio':'response.output_audio.delta','complete':'response.done'}[payload]
|
||||
assert any(e['type']==expected for e in events)
|
||||
assert sum(e['type']=='input_audio_buffer.speech_started' for e in events)==1
|
||||
assert sum(e['type']=='input_audio_buffer.speech_stopped' for e in events)==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('size,count',[(9600,25),(48,5000),(2,120000)])
|
||||
def test_five_second_audio_burst_packs_without_consuming_control_budget(size,count):
|
||||
a=adapter();event=dict(type='response.output_audio.delta',response_id='r',item_id='i',output_index=0,content_index=0,delta=base64.b64encode(bytes(size)).decode())
|
||||
for _ in range(count):a._put(event)
|
||||
assert a._audio_bytes==240000 and a._audio_slabs==25 and a._control_count==0
|
||||
a._put({'type':'response.done'})
|
||||
assert a._control_count==1
|
||||
|
||||
|
||||
def test_audio_exact_aggregate_boundary_and_interleaved_order():
|
||||
a=adapter();event=dict(type='response.output_audio.delta',response_id='r',delta=base64.b64encode(bytes(9600)).decode())
|
||||
a.backlog=lambda:72000
|
||||
for _ in range((1440000-72000)//9600):a._put(event)
|
||||
a._put(dict(event,delta=base64.b64encode(bytes(4800)).decode()))
|
||||
assert a._audio_bytes+a.backlog()==1440000
|
||||
with pytest.raises(GeminiOverflow):a._put(dict(event,delta='AAA='))
|
||||
async def ordered():
|
||||
a=adapter();a._put(event);a._put({'type':'control'});a._put(event)
|
||||
assert [(await a.receive())['type'] for _ in range(3)]==['response.output_audio.delta','control','response.output_audio.delta']
|
||||
asyncio.run(ordered())
|
||||
|
||||
|
||||
def test_conflicting_activity_coordinates_fail_closed():
|
||||
async def scenario():
|
||||
a=adapter();await activity(a,'ACTIVITY_START','0s')
|
||||
with pytest.raises(GeminiContextError):await activity(a,'ACTIVITY_START','0.01s')
|
||||
await activity(a,'ACTIVITY_END','0.1s')
|
||||
with pytest.raises(GeminiContextError):await activity(a,'ACTIVITY_END','0.11s')
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('exc,code',[(TimeoutError(),'SEARCH_TIMEOUT'),(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(ValueError('IDEMPOTENCY_CONFLICT'),'LIVE_PROVIDER_PROTOCOL_ERROR'),(ValueError('CANCELLED'),'SEARCH_CANCELLED'),
|
||||
(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),(ConnectionError('private-db-detail'),'LIVE_PROVIDER_UNAVAILABLE')])
|
||||
def test_durable_failures_are_classified_truthfully(exc,code):assert failure_code(exc)==code
|
||||
|
||||
@pytest.mark.parametrize('phase',['reconcile','service','cancel','normal'])
|
||||
def test_partial_lifespan_cleans_resources_and_preserves_error(monkeypatch,phase):
|
||||
from app.main import lifespan
|
||||
from app.api.v1 import dependencies as d
|
||||
import app.main as main
|
||||
disposed=[];closed=[];pools=[];entered=asyncio.Event()
|
||||
engine=SimpleNamespace(dispose=lambda:disposed.append(1))
|
||||
marker=RuntimeError('original startup error')
|
||||
def get_service(engine):
|
||||
if phase=='service':raise marker
|
||||
return SimpleNamespace(reconcile_startup=lambda:None)
|
||||
async def blocking(fn):
|
||||
entered.set()
|
||||
if phase=='cancel':await asyncio.Event().wait()
|
||||
if phase=='reconcile':raise marker
|
||||
fn()
|
||||
async def shutdown():pass
|
||||
monkeypatch.setattr(d,'get_engine',lambda:engine);monkeypatch.setattr(d,'get_lifecycle_service',get_service)
|
||||
monkeypatch.setattr(main,'blocking',blocking);monkeypatch.setattr(main,'shutdown',shutdown)
|
||||
monkeypatch.setattr(main,'shutdown_pool',lambda:pools.append(1))
|
||||
monkeypatch.setattr(d,'_TOOL_RUNNER',SimpleNamespace(close=lambda:closed.append(1)))
|
||||
monkeypatch.setattr(d,'_ENGINE',engine)
|
||||
app=SimpleNamespace(state=SimpleNamespace(ready=True))
|
||||
async def run():
|
||||
async with lifespan(app):assert app.state.ready
|
||||
async def scenario():
|
||||
if phase=='cancel':
|
||||
task=asyncio.create_task(run());await entered.wait();task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):await task
|
||||
elif phase in ('reconcile','service'):
|
||||
with pytest.raises(RuntimeError) as caught:await run()
|
||||
assert caught.value is marker
|
||||
else:await run()
|
||||
assert disposed==closed==pools==[1] and not app.state.ready
|
||||
assert all(getattr(d,n) is None for n in ('_ENGINE','_AUTH_SERVICE','_LIFECYCLE_SERVICE','_SEARCH_SERVICE','_TOOL_RUNNER'))
|
||||
# Subsequent startup receives a new valid lifecycle; no stale globals.
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda e:SimpleNamespace(reconcile_startup=lambda:None))
|
||||
async def healthy(fn):fn()
|
||||
monkeypatch.setattr(main,'blocking',healthy)
|
||||
await run();assert disposed==[1,1]
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('late',['audio','tool'])
|
||||
def test_actual_runtime_suppresses_delayed_first_output_after_new_speech(runner,persisted,late):
|
||||
async def scenario():
|
||||
runtime,a,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
await input_turn(runtime,wire)
|
||||
await wire.inbound.put({'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0.15s'}})
|
||||
message=({'toolCall':{'functionCalls':[{'id':'late','name':'search_knowledge','args':{'query':'q'}}]}}
|
||||
if late=='tool' else {'serverContent':{'outputTranscription':{'text':'old answer'}}})
|
||||
await wire.inbound.put(message)
|
||||
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
||||
assert runtime.failure=='LIVE_CONTEXT_SYNC_FAILED' and not runtime.calls
|
||||
assert not any(isinstance(e,bytes) or isinstance(e,dict) and e.get('role')=='assistant' for e in out)
|
||||
finally:await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_sequential_native_turns_and_delayed_transcript_keep_original_identity(runner,persisted):
|
||||
async def scenario():
|
||||
runtime,a,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
await input_turn(runtime,wire)
|
||||
await wire.inbound.put({'serverContent':{'outputTranscription':{'text':'one'},'turnComplete':True}})
|
||||
await until(lambda:any(isinstance(e,dict) and e.get('text')=='one' and e.get('status')=='completed' for e in out))
|
||||
first=runtime.current.ref
|
||||
await input_turn(runtime,wire,200)
|
||||
await wire.inbound.put({'serverContent':{'inputTranscription':{'text':'delayed first','startOffset':'0.01s'}}})
|
||||
await wire.inbound.put({'serverContent':{'outputTranscription':{'text':'two'},'turnComplete':True}})
|
||||
await until(lambda:any(isinstance(e,dict) and e.get('text')=='two' and e.get('status')=='completed' for e in out) or not runtime.usable)
|
||||
assert runtime.usable,runtime.failure
|
||||
transcript=next(e for e in out if isinstance(e,dict) and e.get('text')=='delayed first')
|
||||
assert transcript['turn_ref']==first and runtime.current.ref!=first
|
||||
finally:await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_actual_runtime_five_second_burst_keeps_controls_responsive_and_paces_output(runner,persisted):
|
||||
async def scenario():
|
||||
runtime,a,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
await input_turn(runtime,wire)
|
||||
blob={'mimeType':'audio/pcm;rate=24000','data':base64.b64encode(bytes(4800)).decode()}
|
||||
for _ in range(50):await wire.inbound.put({'serverContent':{'modelTurn':{'parts':[{'inlineData':blob}]}}})
|
||||
await wire.inbound.put({'serverContent':{'outputTranscription':{'text':'burst complete'}}})
|
||||
await until(lambda:any(isinstance(e,dict) and e.get('text')=='burst complete' for e in out) or not runtime.usable)
|
||||
assert runtime.usable,runtime.failure
|
||||
assert sum(audio.generated for audio in runtime.audio.values())==240000
|
||||
assert sum(len(e) for e in out if isinstance(e,bytes))<=72000
|
||||
audio=next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref,audio.sent//48)
|
||||
await until(lambda:sum(len(e) for e in out if isinstance(e,bytes))>72000 or not runtime.usable)
|
||||
assert runtime.usable
|
||||
finally:await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('exc,code',[(TimeoutError(),'SEARCH_TIMEOUT'),(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(ValueError('IDEMPOTENCY_CONFLICT'),'LIVE_PROVIDER_PROTOCOL_ERROR'),(ValueError('CANCELLED'),'SEARCH_CANCELLED'),
|
||||
(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),(ConnectionError('private'),'LIVE_PROVIDER_UNAVAILABLE')])
|
||||
def test_actual_runtime_durable_failure_never_releases_unverified_continuation(runner,persisted,exc,code):
|
||||
async def scenario():
|
||||
runtime,a,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
async def execute(*args):raise exc
|
||||
runtime.tool_store=SimpleNamespace(execute=execute)
|
||||
try:
|
||||
await input_turn(runtime,wire)
|
||||
await wire.inbound.put({'toolCall':{'functionCalls':[{'id':'c','name':'search_knowledge','args':{'query':'q'}}]}})
|
||||
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
||||
assert runtime.failure==code
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
finally:await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_cancelled_startup_keeps_running_blocking_work_owned_until_actual_completion(monkeypatch):
|
||||
from threading import Event
|
||||
from app.main import lifespan
|
||||
from app.api.v1 import dependencies as d
|
||||
import app.main as main
|
||||
from app.infrastructure.blocking import blocking, shutdown_pool
|
||||
entered,release,finished=Event(),Event(),Event();disposed=[]
|
||||
def reconcile():
|
||||
entered.set()
|
||||
try:assert release.wait(5)
|
||||
finally:finished.set()
|
||||
engine=SimpleNamespace(dispose=lambda:disposed.append(1))
|
||||
monkeypatch.setattr(d,'get_engine',lambda:engine)
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda e:SimpleNamespace(reconcile_startup=reconcile))
|
||||
monkeypatch.setattr(main,'blocking',blocking)
|
||||
monkeypatch.setattr(d,'_TOOL_RUNNER',None)
|
||||
app=SimpleNamespace(state=SimpleNamespace(ready=False))
|
||||
async def run():
|
||||
async with lifespan(app):pass
|
||||
async def scenario():
|
||||
task=asyncio.create_task(run())
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait,2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):await task
|
||||
assert disposed==[1] and not app.state.ready and not finished.is_set()
|
||||
# New initialization works while the old, cancelled caller's worker
|
||||
# retains its own admission until its real completion.
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda e:SimpleNamespace(reconcile_startup=lambda:None))
|
||||
await run();assert disposed==[1,1]
|
||||
finally:
|
||||
release.set();assert await asyncio.to_thread(finished.wait,2);shutdown_pool()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_cleanup_failure_does_not_replace_original_startup_exception(monkeypatch):
|
||||
from app.main import lifespan
|
||||
from app.api.v1 import dependencies as d
|
||||
import app.main as main
|
||||
marker=RuntimeError('original reconciliation failure')
|
||||
def dispose():raise RuntimeError('secondary disposal error')
|
||||
monkeypatch.setattr(d,'get_engine',lambda:SimpleNamespace(dispose=dispose))
|
||||
monkeypatch.setattr(d,'get_lifecycle_service',lambda e:SimpleNamespace(reconcile_startup=lambda:None))
|
||||
monkeypatch.setattr(d,'_TOOL_RUNNER',None)
|
||||
async def blocking(fn):raise marker
|
||||
monkeypatch.setattr(main,'blocking',blocking)
|
||||
app=SimpleNamespace(state=SimpleNamespace(ready=False))
|
||||
async def scenario():
|
||||
with pytest.raises(RuntimeError) as caught:
|
||||
async with lifespan(app):pytest.fail('Startup must not reach readiness')
|
||||
assert caught.value is marker and not app.state.ready and d._ENGINE is None
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_database_availability_is_not_provider_or_authority_loss():
|
||||
from sqlalchemy.exc import OperationalError
|
||||
assert failure_code(OperationalError(None,None,RuntimeError('private database detail'))) == 'DEPENDENCY_UNAVAILABLE'
|
||||
|
||||
@pytest.mark.parametrize('code',['SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','LIVE_CONTEXT_SYNC_FAILED'])
|
||||
def test_durable_delivery_failure_blocks_tool_response_and_continuation(runner,persisted,code):
|
||||
from app.modules.voice.durable_tools import DurableFailure
|
||||
async def scenario():
|
||||
runtime,a,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
async def execute(*args):return {'status':'no_evidence','sources':[]}
|
||||
async def delivery(*args):raise DurableFailure(code)
|
||||
runtime.tool_store=SimpleNamespace(execute=execute,delivery=delivery)
|
||||
try:
|
||||
await input_turn(runtime,wire)
|
||||
await wire.inbound.put({'toolCall':{'functionCalls':[{'id':'c','name':'search_knowledge','args':{'query':'q'}}]}})
|
||||
await asyncio.wait_for(runtime.failure_signal.wait(),2)
|
||||
assert runtime.failure==code and not any('toolResponse' in m for m in wire.sent)
|
||||
finally:await cleanup(runtime,receive)
|
||||
asyncio.run(scenario())
|
||||
@@ -742,9 +742,9 @@ def test_operator_harness_actual_fake_transport_tool_correlation(
|
||||
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer")))
|
||||
await self.incoming.put(canonical_json(terminal(rid, output=output)))
|
||||
transport = Scripted()
|
||||
async def connection(*_):
|
||||
return transport
|
||||
monkeypatch.setattr(voice_smoke, "connect", connection)
|
||||
async def connection(config, limits):
|
||||
return RealtimeAdapter(transport, settings=limits)
|
||||
monkeypatch.setattr(voice_smoke, "create_adapter", connection)
|
||||
config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"),
|
||||
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
|
||||
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0
|
||||
|
||||
@@ -470,8 +470,8 @@ def test_smoke_never_succeeds_from_early_transcript(runner, persisted, monkeypat
|
||||
for event in events:
|
||||
await transport.incoming.put(canonical_json(event))
|
||||
transport.send = send
|
||||
async def connection(*_): return transport
|
||||
monkeypatch.setattr(voice_smoke, "connect", connection)
|
||||
async def connection(config, limits): return RealtimeAdapter(transport, settings=limits)
|
||||
monkeypatch.setattr(voice_smoke, "create_adapter", connection)
|
||||
original_runtime = voice_smoke.VoiceRuntime
|
||||
if failure == "delivery":
|
||||
def runtime_factory(adapter, service, shared_runner, actor, emit, **kwargs):
|
||||
@@ -603,7 +603,7 @@ def test_queue_duration_environment_and_consistency(monkeypatch):
|
||||
def test_invalid_smoke_configuration_never_connects(runner, monkeypatch):
|
||||
from app import voice_smoke
|
||||
async def forbidden(*_): pytest.fail("Provider connection before valid configuration")
|
||||
monkeypatch.setattr(voice_smoke, "connect", forbidden)
|
||||
monkeypatch.setattr(voice_smoke, "create_adapter", forbidden)
|
||||
config = SimpleNamespace(runtime_settings={"setup_timeout_seconds": 0})
|
||||
with pytest.raises(ValueError):
|
||||
asyncio.run(voice_smoke.run(SimpleNamespace(), runner, uuid4(), config, "q", 3, 4))
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Execute the example worklet to prove consumed-sample accounting and capture bytes."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import pytest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def test_worklet_capture_playback_and_interruption(tmp_path):
|
||||
node=shutil.which('node')
|
||||
if not node: pytest.fail('Node is required to exercise the delivered audio example')
|
||||
script=r'''
|
||||
const fs=require('fs'),vm=require('vm'),assert=require('assert');
|
||||
const processors={};
|
||||
global.AudioWorkletProcessor=class {constructor(){this.messages=[];this.port={postMessage:m=>this.messages.push(m)};}};
|
||||
global.registerProcessor=(name,processor)=>processors[name]=processor;
|
||||
vm.runInThisContext(fs.readFileSync(process.argv[2],'utf8'));
|
||||
const capture=new processors['rag-capture']();
|
||||
capture.process([[new Float32Array(240).fill(.5)]],[]);
|
||||
assert.equal(capture.messages.length,1);assert.equal(capture.messages[0].bytes.byteLength,480);
|
||||
assert.equal(new DataView(capture.messages[0].bytes).getInt16(0,true),16384);
|
||||
const playback=new processors['rag-playback']();
|
||||
const message=data=>playback.port.onmessage({data});
|
||||
message({type:'start',ref:'a'});message({type:'pcm',ref:'a',samples:new Float32Array(240).buffer});
|
||||
assert.equal(playback.messages.length,0);
|
||||
playback.process([],[[new Float32Array(120)]]);
|
||||
assert.equal(playback.messages.at(-1).played_ms,5);
|
||||
message({type:'flush',id:'flush'});
|
||||
assert.equal(playback.messages.at(-2).played_ms,5);assert.equal(playback.queue.length,0);
|
||||
assert.equal(playback.messages.at(-1).type,'flushed');
|
||||
message({type:'start',ref:'b'});message({type:'pcm',ref:'b',samples:new Float32Array(240).buffer});
|
||||
message({type:'end',ref:'b'});playback.process([],[[new Float32Array(240)]]);
|
||||
assert.equal(playback.messages.at(-1).played_ms,10);assert.equal(playback.refs.size,0);
|
||||
'''
|
||||
path=tmp_path/'worklet-test.cjs';path.write_text(script)
|
||||
subprocess.run([node,str(path),str(ROOT/'examples/voice-audio-worklet.js')],check=True,capture_output=True,timeout=10)
|
||||
|
||||
|
||||
def test_delivered_voice_client_async_ownership_errors_logout_and_close():
|
||||
node=shutil.which('node')
|
||||
if not node:pytest.fail('Node is required to exercise VoiceClient')
|
||||
result=subprocess.run([node,str(ROOT/'tests/support/voice_client_harness.mjs'),'unit'],capture_output=True,text=True,timeout=20)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
Reference in New Issue
Block a user