Files
rag-technical-docs-assistant/app/api/v1/live.py
T
amirhosein mazaheri 8d348f0ba1 feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
2026-10-15 12:28:17 +03:30

350 lines
18 KiB
Python

"""V01-V04 and supervised, cookie-authenticated selected-provider stream."""
import asyncio
from dataclasses import asdict
import json
import logging
from typing import Annotated, Literal
from uuid import UUID
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, ConfigDict
from app.api.v1.dependencies import (get_auth_service, get_current_user, get_engine,
get_lifecycle_service, get_search_service, get_tool_runner, get_voice_settings, require_csrf, error)
from app.infrastructure.blocking import blocking
from app.modules.auth.service import COOKIE_NAME, UserContext, check_origin
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools
from app.modules.voice import registry
from app.infrastructure.voice_provider import create_adapter
from app.modules.voice.authority import authority_failure_code
from app.modules.voice.diagnostics import diagnostic, terminal_failed
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.modules.documents.settings import IngestionSettings
logger = logging.getLogger(__name__)
router = APIRouter(prefix='/voice/sessions', tags=['Voice Sessions'])
ACTIVE_MEDIA_SESSIONS = set()
# Event-loop-local guard mutation has no await between membership check and insertion.
def close_affected_runtimes(organization_id, new_epoch=0):
return registry.notify(organization_id=organization_id, new_epoch=new_epoch)
class CreateLiveSessionRequest(BaseModel):
model_config = ConfigDict(extra='forbid')
conversation_id: UUID
client_request_id: UUID
class LiveSessionResponse(BaseModel):
session_id: str
conversation_id: str
status: str
stream_path: str | None
expires_at: str
poll_url: str
calibration_status: Literal["calibrated", "uncalibrated", "unknown"] = "unknown"
class CloseLiveSessionResponse(BaseModel):
session_id: str
status: str
close_reason: str | None = None
def capability(config):
config.require_voice()
try:
if config.search_calibration_report is None:
raise ValueError('CALIBRATION_REQUIRED')
cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding='utf-8')))
if (cutoff.profile != asdict(IngestionSettings().embedding_profile)
or cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise ValueError('CALIBRATION_REQUIRED')
except (OSError, ValueError, KeyError, TypeError, AttributeError):
if config.voice_transport_testing:
return None
raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff
def search_profile(cutoff, settings=None):
if cutoff is None:
return dict(embedding=asdict((settings or IngestionSettings()).embedding_profile),
calibration_status='uncalibrated', mode='transport_testing',
retrieval_policy=RETRIEVAL_POLICY)
return dict(embedding=cutoff.profile, calibration_id=cutoff.calibration_id,
retrieval_policy=cutoff.retrieval_policy, distance=cutoff.distance)
@router.post(
'',
response_model=LiveSessionResponse,
status_code=201,
summary='Create Realtime Voice Session',
description='Allocate a new bidirectional realtime voice session for an active conversation. Returns stream_path and poll_url.',
)
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
engine: Annotated[object, Depends(get_engine)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
# Recover replay before capability checks: a configuration change cannot alter identity.
try:
result = lifecycle.recover_live_session(user, req.client_request_id)
except ValueError as exc:
if str(exc) != 'SESSION_NOT_FOUND':
raise
else:
if result['conversation_id'] != str(req.conversation_id):
raise ValueError('IDEMPOTENCY_CONFLICT')
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id)
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, IngestionSettings(), database_url=engine.url)
cutoff = capability(config)
profile = config.profile()
# Construct configured embedding transport only after replay recovery.
# Construction validates identity/limits/credentials without inference.
search_settings = get_search_service(engine).settings if cutoff is None else None
profile["search"] = search_profile(cutoff, search_settings)
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.selected_model, execution_profile=profile)
except ValueError as exc:
raise error(str(exc)) from None
if result['replayed']:
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
@router.get(
'/by-request/{client_request_id}',
response_model=LiveSessionResponse,
summary='Recover Voice Session by Request ID',
description='Idempotently look up or recover an existing voice session using the client_request_id.',
)
def recover(client_request_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.recover_live_session(user, client_request_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.get(
'/{session_id}',
summary='Poll Voice Session Status',
description='Poll current session lifecycle status, stream connection state, and expiry.',
)
def poll(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.get_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.post(
'/{session_id}/close',
response_model=CloseLiveSessionResponse,
summary='Close Voice Session',
description='Explicitly close an active voice session and release provider allocations.',
)
def close(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
return lifecycle.close_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle_service,
engine, search_service, tool_runner, config=None):
config = config or VoiceSettings()
if (websocket.query_params or not check_origin(websocket.headers.get('origin'), websocket.headers.get('host'),
config.trusted_origins, config.trusted_hosts, required=True)):
await websocket.close(code=1008, reason='Stream unavailable')
return
try:
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, search_service.settings, database_url=engine.url)
config.require_voice()
if search_service.cutoff is None and not config.voice_transport_testing:
raise ValueError('CALIBRATION_REQUIRED')
if (info['provider'] != config.provider or info['model'] != config.selected_model
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != search_profile(search_service.cutoff, search_service.settings)):
raise ValueError('LIVE_SESSION_UNUSABLE')
except Exception as exc:
logger.info('Stream admission rejected: %s', type(exc).__name__)
await websocket.close(code=1008, reason='Stream unavailable')
return
if session_id in ACTIVE_MEDIA_SESSIONS or len(ACTIVE_MEDIA_SESSIONS) >= config.max_provider_sessions:
await websocket.close(code=1008, reason='Stream unavailable')
return
ACTIVE_MEDIA_SESSIONS.add(session_id)
runtime = adapter = None
children = []
outcome, failed = 'LIVE_TRANSPORT_FAILED', True
client_closed = False
ready_sent = asyncio.Event()
async def close_client(code=1000):
nonlocal client_closed
if not client_closed:
client_closed = True
try:
await websocket.close(code=code, reason='Voice session stopped')
except (RuntimeError, WebSocketDisconnect):
pass
try:
# Guard is released even if accept fails.
await websocket.accept()
limits = RuntimeSettings.for_provider(config.provider)
adapter = await create_adapter(config, limits)
async def authority_check(execution):
await blocking(lifecycle_service.validate_stream, user, session_id, execution,
session_execution=runtime.session_execution)
return True
store = DurableTools(lifecycle_service, user, session_id)
async def emit(event):
if isinstance(event,bytes):
await websocket.send_bytes(event)
else:
if event['type'] == 'sources':
for response, call in runtime.calls.values():
if response.turn.ref == event['turn_ref'] and call['ref'] == event['tool_call_id']:
await store.delivery(call, response.turn.execution)
if event['type'] == 'turn_interrupted':
await blocking(lifecycle_service.cancel_tools, user, session_id, event['cancelled_tool_call_ids'])
await websocket.send_text(json.dumps(event,ensure_ascii=False))
if event['type'] == 'session_ready':
ready_sent.set()
await blocking(lifecycle_service.mark_connected, user, session_id)
runtime = VoiceRuntime(adapter, search_service, tool_runner, user.id, emit,
authority_check=authority_check, session_id=str(session_id), settings=limits,
close_client=close_client, tool_store=store)
registry.register(session_id, user.organization_id, info['access_epoch'], user.auth_session_id, runtime)
await runtime.start()
async def browser():
while runtime.usable:
# Keep the delivered binary message in the transport budget until
# its provider send completes. Don't add a second runtime backlog
# on top of the parser's eight queued + one assembling messages.
while runtime.usable and runtime.input_transport_count:
await asyncio.sleep(.001)
if not runtime.usable:
return
message = await websocket.receive()
if message['type'] == 'websocket.disconnect':
code = {1009: 'LIVE_FRAME_TOO_LARGE', 1002: 'LIVE_PROTOCOL_ERROR',
1007: 'LIVE_PROTOCOL_ERROR'}.get(message.get('code'))
if code:
async with runtime.lock:
runtime.fail(code, writable=False)
return
if not runtime.ready and ready_sent.is_set():
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds)
if message.get('bytes') is not None:
await runtime.input_audio(message['bytes'])
elif message.get('text') is not None:
await runtime.client_control(message['text'].encode('utf-8'))
async def monitor():
while runtime.usable:
await asyncio.sleep(.25)
try:
await blocking(lifecycle_service.validate_stream, user, session_id)
except Exception as exc:
async with runtime.lock:
code = authority_failure_code(exc)
diagnostic(str(session_id), "authority_monitor", "AUTHORITY_CHECK_FAILED", exc=exc, code=code)
runtime.fail(code)
return
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
done, pending = await asyncio.wait(children, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if not task.cancelled():
exc = task.exception()
if exc:
raise exc
if runtime.failure:
# Give its terminal-error delivery its bounded opportunity before cancellation.
try:
await asyncio.wait_for(runtime.error_delivered.wait(), limits.send_timeout_seconds)
except TimeoutError:
pass
outcome = runtime.failure
failed = terminal_failed(outcome)
elif not runtime.usable and runtime.close_code == 1000:
outcome, failed = "user_requested", False
except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED'
failed = True
except Exception as exc:
if runtime and runtime.failure:
outcome = runtime.failure
else:
outcome = 'LIVE_SETUP_FAILED' if runtime is None or not runtime.ready else 'LIVE_TRANSPORT_FAILED'
failed = True
http_status = getattr(getattr(exc, 'response', None), 'status_code', None)
diagnostic(str(session_id), 'stream_setup' if outcome == 'LIVE_SETUP_FAILED' else 'stream_transport',
'STREAM_EXCEPTION', exc=exc, code=outcome, http_status=http_status)
finally:
async def cleanup():
try:
for task in children:
task.cancel()
if children:
_, pending_children = await asyncio.wait(children, timeout=5)
if pending_children:
diagnostic(str(session_id), "stream_cleanup", "CLEANUP_TIMEOUT",
code=outcome, pending_tasks=len(pending_children))
try:
# Saturation must not strand the durable terminal outcome once admission frees.
deadline = asyncio.get_running_loop().time() + 6
while True:
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
break
except ValueError as exc:
if str(exc) != 'SERVICE_BUSY' or asyncio.get_running_loop().time() >= deadline:
raise
await asyncio.sleep(.025)
except Exception as exc:
diagnostic(str(session_id), "terminal_persistence", "TERMINAL_PERSISTENCE_FAILED",
exc=exc, code=outcome)
try:
if runtime:
await runtime.close()
elif adapter:
await asyncio.wait_for(adapter.close(), 6)
except Exception as exc:
diagnostic(str(session_id), "stream_cleanup",
"CLEANUP_TIMEOUT" if isinstance(exc, TimeoutError) else "CLEANUP_FAILED",
exc=exc, code=outcome)
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
finally:
registry.unregister(session_id)
ACTIVE_MEDIA_SESSIONS.discard(session_id)
# An ASGI disconnect can cancel its route after close was delivered. Cleanup
# owns a separate task so cancellation cannot strand the media guard.
cleaning = asyncio.create_task(cleanup())
try:
await asyncio.shield(cleaning)
except asyncio.CancelledError:
# Owning-loop registry/shutdown tracks this independent completion.
raise
@router.websocket('/{session_id}/stream')
async def stream(websocket: WebSocket, session_id: UUID,
engine=Depends(get_engine), auth_service=Depends(get_auth_service), lifecycle=Depends(get_lifecycle_service),
runner=Depends(get_tool_runner), search=Depends(get_search_service), config=Depends(get_voice_settings)):
if not websocket.app.state.ready:
await websocket.close(code=1013,reason='Service unavailable')
return
await handle_stream_websocket(websocket,session_id,auth_service,lifecycle,engine,search,runner,config)