feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
@@ -0,0 +1,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())
|
||||
Reference in New Issue
Block a user