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:
11linear11
2026-10-09 07:59:02 -04:00
parent 07245cd5ca
commit 996435d2ae
42 changed files with 4551 additions and 88 deletions
+153
View File
@@ -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
+194
View File
@@ -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)
+53
View File
@@ -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'})
+273
View File
@@ -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())
+3 -3
View File
@@ -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
+3 -3
View File
@@ -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))
+43
View File
@@ -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