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
+15
View File
@@ -77,3 +77,18 @@ INGEST_MAX_EXTRACTED_BLOCKS=10000
# The example is NOT compatibility approval for an arbitrary endpoint/model. # The example is NOT compatibility approval for an arbitrary endpoint/model.
INGEST_EMBEDDING_SEND_DIMENSIONS=false INGEST_EMBEDDING_SEND_DIMENSIONS=false
INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216 INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216
# Temporary sole voice provider; independent of extraction and embedding credentials.
PROVIDER=gemini
GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede
# GEMINI_PROXY=https://trusted-proxy.example:443
TRUSTED_ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"]
TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"]
# Explicit local development only. Production requires HTTPS and true.
COOKIE_SECURE=false
AUTH_SESSION_SECONDS=28800
LIVE_SESSION_SECONDS=600
# Path to a measured, profile-compatible calibrated report; never a status placeholder.
# SEARCH_CALIBRATION_REPORT=/absolute/path/measured-report.json
+81
View File
@@ -0,0 +1,81 @@
"""A01-A03: opaque sessions, bounded login admission, and synchronizer CSRF."""
from collections import deque
import time
from threading import Lock, BoundedSemaphore
from typing import Annotated
from fastapi import APIRouter, Depends, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import get_auth_service, get_current_user, get_voice_settings, require_origin, error
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, generate_csrf_token, verify_csrf_token
from app.modules.voice.configuration import VoiceSettings
router = APIRouter(prefix='/auth', tags=['Authentication'])
identity_router = APIRouter(tags=['Authentication'])
_ATTEMPTS = deque(maxlen=120)
_LOCK = Lock()
_LOGINS = BoundedSemaphore(2)
class LoginRequest(BaseModel):
model_config = ConfigDict(extra='forbid', strict=True)
username: str = Field(min_length=1, max_length=120)
password: str = Field(min_length=1, max_length=1024)
class UserDTO(BaseModel):
id: str
username: str
role: str
organization_id: str
class AuthResponse(BaseModel):
user: UserDTO
csrf_token: str
expires_at: str
@router.post('/login', response_model=AuthResponse)
def login(req: LoginRequest, request: Request, response: Response,
auth_service: Annotated[AuthService, Depends(get_auth_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
require_origin(request, config)
stamp = time.monotonic()
with _LOCK:
while _ATTEMPTS and stamp - _ATTEMPTS[0] >= 60:
_ATTEMPTS.popleft()
if len(_ATTEMPTS) >= config.login_attempts_per_minute:
raise error('SERVICE_BUSY')
_ATTEMPTS.append(stamp)
if not _LOGINS.acquire(blocking=False):
raise error('SERVICE_BUSY')
try:
user, token, csrf, expiry = auth_service.login(req.username, req.password)
except ValueError as exc:
raise error(str(exc)) from None
finally:
_LOGINS.release()
response.set_cookie(COOKIE_NAME, token, httponly=True, secure=config.cookie_secure,
samesite='lax', expires=expiry, path='/')
return AuthResponse(user=UserDTO(**user), csrf_token=csrf, expires_at=expiry.isoformat())
@router.post('/logout', status_code=204)
def logout(request: Request, response: Response,
auth_service: Annotated[AuthService, Depends(get_auth_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
require_origin(request, config)
token = request.cookies.get(COOKIE_NAME)
try:
auth_service.get_current_user(token)
except ValueError:
pass
else:
if not verify_csrf_token(token, request.headers.get('x-csrf-token')):
raise error('CSRF_TOKEN_INVALID')
auth_service.logout(token)
response.delete_cookie(COOKIE_NAME, path='/', secure=config.cookie_secure, httponly=True, samesite='lax')
response.status_code = 204
return response
@identity_router.get('/me', response_model=AuthResponse)
@router.get('/me', response_model=AuthResponse, include_in_schema=False)
def get_me(request: Request, user: Annotated[UserContext, Depends(get_current_user)]):
return AuthResponse(user=UserDTO(id=str(user.id), organization_id=str(user.organization_id),
username=user.username, role=user.role), csrf_token=generate_csrf_token(request.cookies.get(COOKIE_NAME)),
expires_at=user.expires_at.isoformat())
+71
View File
@@ -0,0 +1,71 @@
"""Conversation management endpoints (C01)."""
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response, status
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import (
get_current_user,
get_lifecycle_service,
require_csrf,
)
from app.modules.auth.service import UserContext
from app.modules.voice.lifecycle import LiveLifecycleService
router = APIRouter(prefix="/conversations", tags=["Conversations"])
class CreateConversationRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
client_request_id: UUID
mode: str = Field(default="voice", description="Must be 'voice' in MVP")
title: str | None = Field(default=None, max_length=120)
class ConversationResponse(BaseModel):
id: str
mode: str
title: str | None = None
status: str
access_epoch: int
created_at: str
@router.post(
"",
response_model=ConversationResponse,
status_code=status.HTTP_201_CREATED,
summary="C01: Create Conversation",
description="Creates an owned voice conversation container with idempotency protection.",
)
def create_conversation(
req: CreateConversationRequest,
response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None,
) -> ConversationResponse:
try:
result = lifecycle.create_conversation(
user=user,
client_request_id=req.client_request_id,
mode=req.mode,
title=req.title,
)
except ValueError as exc:
from app.api.v1.dependencies import error
raise error(str(exc)) from None
if result.get("replayed"):
response.headers["Idempotency-Replayed"] = "true"
return ConversationResponse(
id=result["id"],
mode=result["mode"],
title=result["title"],
status=result["status"],
access_epoch=result["access_epoch"],
created_at=result["created_at"],
)
+104
View File
@@ -0,0 +1,104 @@
"""Cookie-only identity and shared backend services, lazily constructed."""
from datetime import timedelta
import json
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.engine import Engine
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, check_origin, verify_csrf_token
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.knowledge.service import SearchService
from app.modules.knowledge.langchain_tool import SearchToolRunner
from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None
def get_voice_settings():
return VoiceSettings()
def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND',
'SESSION_REVOKED':'AUTH_REQUIRED','SESSION_EXPIRED':'AUTH_REQUIRED','ACCOUNT_DISABLED':'AUTH_REQUIRED',
'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED',
'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code)
codes = {
'AUTH_REQUIRED': 401, 'INVALID_CREDENTIALS': 401, 'ACCOUNT_DISABLED': 401,
'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403,
'FORBIDDEN_ORIGIN': 403, 'CONVERSATION_NOT_FOUND': 404, 'SESSION_NOT_FOUND': 404,
'CALIBRATION_REQUIRED': 503, 'LIVE_PROVIDER_UNAVAILABLE': 503, 'SERVICE_BUSY': 429,
'MODE_MISMATCH': 409, 'CONVERSATION_CLOSED': 409, 'CONVERSATION_STALE': 409,
'LIVE_SESSION_BUSY': 409, 'LIVE_SESSION_UNUSABLE': 409, 'IDEMPOTENCY_CONFLICT': 409,
'CONTEXT_REVOKED': 409, 'LIVE_SESSION_EXPIRED':409, 'NOT_FOUND':404,'CSRF_INVALID':403,'FORBIDDEN':403,'RATE_LIMITED':429,'DEPENDENCY_UNAVAILABLE':503,
}
if code not in codes:
code = 'DEPENDENCY_UNAVAILABLE'
return HTTPException(codes.get(code, 503), detail={'code': code, 'message': 'Request could not be completed.'})
def get_engine():
global _ENGINE
if _ENGINE is None:
_ENGINE = create_database(IngestionSettings().database_url.get_secret_value())
return _ENGINE
def get_auth_service(engine: Annotated[Engine, Depends(get_engine)]):
global _AUTH_SERVICE
if _AUTH_SERVICE is None or _AUTH_SERVICE.engine is not engine:
_AUTH_SERVICE = AuthService(engine, session_lifetime=timedelta(seconds=VoiceSettings().auth_session_seconds))
return _AUTH_SERVICE
def get_lifecycle_service(engine: Annotated[Engine, Depends(get_engine)]):
global _LIFECYCLE_SERVICE
if _LIFECYCLE_SERVICE is None or _LIFECYCLE_SERVICE.engine is not engine:
_LIFECYCLE_SERVICE = LiveLifecycleService(engine, session_ttl=timedelta(seconds=VoiceSettings().live_session_seconds))
return _LIFECYCLE_SERVICE
def get_tool_runner():
global _TOOL_RUNNER
if _TOOL_RUNNER is None:
_TOOL_RUNNER = SearchToolRunner()
return _TOOL_RUNNER
def get_search_service(engine: Annotated[Engine, Depends(get_engine)]):
global _SEARCH_SERVICE
if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine:
settings = IngestionSettings()
path = VoiceSettings().search_calibration_report
cutoff = None
if path is not None:
try:
cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8')))
except (ValueError, OSError, KeyError, TypeError, AttributeError):
raise error('CALIBRATION_REQUIRED') from None
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
_SEARCH_SERVICE = SearchService(engine, settings, provider, counter, cutoff=cutoff)
return _SEARCH_SERVICE
def get_current_user(request: Request, auth_service: Annotated[AuthService, Depends(get_auth_service)]) -> UserContext:
try:
return auth_service.get_current_user(request.cookies.get(COOKIE_NAME))
except ValueError:
raise error('AUTH_REQUIRED') from None
def require_origin(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
if not check_origin(request.headers.get('origin'), request.headers.get('host'), config.trusted_origins, config.trusted_hosts, required=True):
raise error('FORBIDDEN_ORIGIN')
def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)],
x_csrf_token: Annotated[str | None, Header()] = None):
require_origin(request, config)
if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token):
raise error('CSRF_TOKEN_INVALID')
+283
View File
@@ -0,0 +1,283 @@
"""V01-V04 and supervised, cookie-authenticated Gemini stream."""
import asyncio
from dataclasses import asdict
import json
import logging
from typing import Annotated
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.gemini_live import GeminiLiveAdapter, connect_gemini
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
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):
raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff
@router.post('', response_model=LiveSessionResponse, status_code=201)
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)],
_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
cutoff = capability(config)
profile = config.profile()
profile["search"] = {"embedding": cutoff.profile, "calibration_id": cutoff.calibration_id,
"retrieval_policy": cutoff.retrieval_policy, "distance": cutoff.distance}
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.gemini_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)
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}')
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)
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)
config.require_voice()
if search_service.cutoff is None:
raise ValueError('CALIBRATION_REQUIRED')
if (info['provider'] != 'gemini' or info['model'] != config.gemini_model
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != {
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
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()
transport = await asyncio.wait_for(connect_gemini(config.gemini_api_key.get_secret_value(),
config.gemini_model, config.gemini_proxy, limits), limits.connect_timeout_seconds)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
async def authority_check(execution):
nonlocal outcome
try:
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
except ValueError as exc:
outcome = str(exc)
raise
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 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:
message = await websocket.receive()
if message['type'] == 'websocket.disconnect':
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():
nonlocal outcome
while runtime.usable:
await asyncio.sleep(.25)
try:
await blocking(lifecycle_service.validate_stream, user, session_id)
except ValueError as exc:
outcome = str(exc)
async with runtime.lock:
runtime.fail('CONTEXT_REVOKED')
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 = outcome if outcome not in ('connection_closed', 'LIVE_TRANSPORT_FAILED') else runtime.failure
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED'
failed = True
except Exception:
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
finally:
async def cleanup():
try:
for task in children:
task.cancel()
await asyncio.gather(*children, return_exceptions=True)
try:
if runtime:
await asyncio.wait_for(runtime.close(), 6)
elif adapter:
await asyncio.wait_for(adapter.close(), 6)
except Exception:
logger.warning('Bounded provider cleanup incomplete')
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
except Exception:
logger.warning('Live terminal persistence unavailable')
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)
+24
View File
@@ -0,0 +1,24 @@
"""Bounded blocking work; timed-out workers retain admission until actual completion."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from threading import BoundedSemaphore
_POOL = None
_SLOTS = BoundedSemaphore(8)
async def blocking(function, *args, **kwargs):
global _POOL
if _POOL is None:
_POOL = ThreadPoolExecutor(max_workers=8, thread_name_prefix="live-db")
if not _SLOTS.acquire(blocking=False):
raise ValueError('SERVICE_BUSY')
loop = asyncio.get_running_loop()
future = _POOL.submit(function, *args, **kwargs)
future.add_done_callback(lambda _: _SLOTS.release())
return await asyncio.wait_for(asyncio.shield(asyncio.wrap_future(future, loop=loop)), 6)
def shutdown_pool():
global _POOL
if _POOL is not None:
_POOL.shutdown(wait=False, cancel_futures=True)
_POOL = None
+7 -3
View File
@@ -9,6 +9,8 @@ from sqlalchemy.orm import sessionmaker
from app.modules.documents.types import EmbeddingProfile from app.modules.documents.types import EmbeddingProfile
LIVE_REVISION = "0005_live_owner_chain"
PREVIOUS_LIVE_REVISION = "0004_live_lifecycle"
SCHEMA_REVISION = "0003_extraction_review" SCHEMA_REVISION = "0003_extraction_review"
WORKER_REVISION = "0002_worker_artifact" WORKER_REVISION = "0002_worker_artifact"
FOUNDATION_REVISION = "0001_ingestion_foundation" FOUNDATION_REVISION = "0001_ingestion_foundation"
@@ -63,17 +65,19 @@ def check_compatibility(connection: Connection, profile: EmbeddingProfile, *, re
schema = connection.execute(text("SELECT current_schema()")).scalar_one() schema = connection.execute(text("SELECT current_schema()")).scalar_one()
assert_foundation_scope(connection, schema) assert_foundation_scope(connection, schema)
revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one() revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
allowed = (SCHEMA_REVISION,) if require_worker else (FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION) allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION) if require_worker else (
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION
)
if revision not in allowed: if revision not in allowed:
raise CompatibilityError("Unexpected ingestion schema revision") raise CompatibilityError("Unexpected ingestion schema revision")
if revision in (WORKER_REVISION, SCHEMA_REVISION): if revision in (WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
artifact_type = connection.execute(text(""" artifact_type = connection.execute(text("""
SELECT format_type(atttypid,atttypmod) FROM pg_attribute SELECT format_type(atttypid,atttypmod) FROM pg_attribute
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
""")).scalar_one_or_none() """)).scalar_one_or_none()
if artifact_type != "jsonb": if artifact_type != "jsonb":
raise CompatibilityError("Missing worker artifact attachment column") raise CompatibilityError("Missing worker artifact attachment column")
if revision == SCHEMA_REVISION: if revision in (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
definitions = connection.execute(text(""" definitions = connection.execute(text("""
SELECT pg_get_constraintdef(oid) FROM pg_constraint SELECT pg_get_constraintdef(oid) FROM pg_constraint
WHERE conrelid=to_regclass(\'audit_events\') WHERE conrelid=to_regclass(\'audit_events\')
+450
View File
@@ -0,0 +1,450 @@
"""Gemini native wire translation; synthetic provider acknowledgements are forbidden.
Native voiceActivity must provide usable input boundaries. First model/tool output
proves input consumption, independently of an OpenAI input-commit acknowledgement.
No verified sample-level context truncation exists: interruption closes safely.
"""
import asyncio
import base64
from collections import deque
import json
import math
import struct
from urllib.parse import quote
from uuid import uuid4
from app.modules.knowledge.service import SearchInput
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
from app.infrastructure.realtime import POLICY, strict_json, ProviderProtocolError
class GeminiContextError(ProviderProtocolError):
context_sync = True
class GeminiOverflow(ProviderProtocolError):
overflow = True
class PCM24To16:
"""Streaming rational 2/3 FIR resampler with bounded history and antialias filtering."""
def __init__(self):
# Filter the 48kHz zero-stuffed stream below the 16kHz output Nyquist.
count, cutoff = 31, 1/6
weights = []
for k in range(count):
x = k - (count-1)/2
sinc = 2*cutoff if x == 0 else math.sin(2*math.pi*cutoff*x)/(math.pi*x)
weights.append(sinc * (.54-.46*math.cos(2*math.pi*k/(count-1))))
self.weights = [2*w/sum(weights) for w in weights]
self.history = deque([0.0]*count, maxlen=count)
self.position = 0
def convert(self, pcm):
if not isinstance(pcm, bytes) or len(pcm) % 2:
raise ProviderProtocolError('Invalid PCM input')
out = []
for sample in struct.unpack('<' + 'h'*(len(pcm)//2), pcm):
for value in (sample, 0):
self.history.appendleft(value)
if self.position % 3 == 0:
filtered = round(sum(v*w for v,w in zip(self.history, self.weights)))
out.append(max(-32768,min(32767,filtered)))
self.position += 1
return struct.pack('<'+'h'*len(out), *out)
def _schema(value):
if isinstance(value, dict):
return {k:_schema(v) for k,v in value.items() if k not in ('title','$defs','additionalProperties')}
if isinstance(value, list):
return [_schema(v) for v in value]
return value
class GeminiLiveAdapter:
native_input_consumption = True
def __init__(self, transport, *, model='gemini-2.0-flash-exp', voice='Aoede', settings=None, no_active_classifier=None):
self.transport, self.model, self.voice = transport, model, voice
self.settings = settings or RuntimeSettings()
self.no_active_classifier = None
self._inbound_events = asyncio.Queue()
self._queued_bytes = 0
self._control_count = 0
self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self.backlog = lambda: 0
self._pump_task = self._close_task = None
self._failure = None
self._confirmed = False
self._setup_sent = False
self._intent = None
self._gate = asyncio.Event()
self._inputs = []
self._input = None
self._input_end = None
self._input_consumed = False
self._generation_complete = False
self._response = None
self._calls = {}
self._completed_calls = {}
self._diagnostic = None
self._outputs = {}
self._seen_intents = set()
self._input_text = self._output_text = ''
self._sent_samples = 0
self._resampler = PCM24To16()
def setup(self):
return dict(type='session.update', session={'provider':'gemini'})
def acknowledged(self, session):
return self._confirmed and session == {'provider':'gemini', 'setup_complete':True}
def serialize(self, event):
return bounded_json(event, self.settings.max_provider_message_bytes, ensure_ascii=False)
async def send_serialized(self, wire):
await self.send(strict_json(wire))
def _put(self, event):
# Controls and decoded PCM have independent reservations. Adjacent tiny
# deltas pack into PCM slabs while the single FIFO retains native order.
if event['type'] == 'response.output_audio.delta':
encoded = event['delta']
if not isinstance(encoded,str) or len(encoded) > self.settings.max_provider_message_bytes:
raise ProviderProtocolError('Gemini audio scratch bound')
estimate = len(encoded)//4*3 - (len(encoded)-len(encoded.rstrip('=')))
if estimate < 0 or estimate > 196608 or estimate % 2:
raise ProviderProtocolError('Gemini PCM alignment')
if self._audio_bytes + self._leased_audio + self.backlog() + estimate > self.settings.max_output_backlog_bytes:
raise GeminiOverflow('Gemini generated backlog overflow')
pcm = base64.b64decode(encoded, validate=True)
if len(pcm) != estimate or len(pcm) % 2:
raise ProviderProtocolError('Gemini PCM alignment')
if self._audio_bytes + self._leased_audio + self.backlog() + len(pcm) > self.settings.max_output_backlog_bytes:
raise GeminiOverflow('Gemini generated backlog overflow')
key = {k:v for k,v in event.items() if k != 'delta'}
queue = self._inbound_events._queue
tail = queue[-1] if queue else None
capacity = 0
if tail and tail[2] and tail[0] == key:
capacity = 9600 - len(tail[1])
slabs = (max(0, len(pcm)-capacity) + 9599)//9600
metadata = len(self.serialize(key).encode('utf-8'))
if self._audio_slabs + slabs > 512 or self._audio_metadata + slabs * metadata > 65536:
raise GeminiOverflow('Gemini audio slab overflow')
self._audio_bytes += len(pcm)
self._audio_metadata += slabs * metadata
if capacity:
take = min(capacity, len(pcm)); tail[1].extend(pcm[:take]); pcm = pcm[take:]
for offset in range(0, len(pcm), 9600):
self._inbound_events.put_nowait((key, bytearray(pcm[offset:offset+9600]), True))
self._audio_slabs += 1
return
size = len(self.serialize(event).encode('utf-8'))
if self._control_count >= self.settings.max_control_messages or self._queued_bytes + size > self.settings.max_control_bytes:
raise GeminiOverflow('Gemini control overflow')
self._queued_bytes += size
self._control_count += 1
self._inbound_events.put_nowait((event,size,False))
def consumed(self):
self._leased_audio = 0
async def _wire(self, event):
await self.transport.send(self.serialize(event))
async def send(self, event):
kind = event['type']
if kind in ('response.cancel','conversation.item.truncate'):
self._failure = GeminiContextError('Gemini context cannot be safely truncated')
await self.close()
raise self._failure
if kind == 'session.update':
if self._setup_sent:
raise ProviderProtocolError('Repeated setup')
self._setup_sent = True
await self._wire({'setup': {
'model': self.model if self.model.startswith('models/') else 'models/'+self.model,
'generationConfig': {'responseModalities':['AUDIO'], 'speechConfig': {'voiceConfig': {'prebuiltVoiceConfig': {'voiceName':self.voice}}}},
'systemInstruction': {'parts':[{'text':POLICY}]},
'realtimeInputConfig': {'activityHandling':'NO_INTERRUPTION'},
'inputAudioTranscription': {}, 'outputAudioTranscription': {},
'tools':[{'functionDeclarations':[{'name':'search_knowledge',
'description':'Retrieve authorized evidence.', 'parameters':_schema(SearchInput.model_json_schema())}]}]}})
self._pump_task = asyncio.create_task(self._read_provider_loop())
return
if not self._confirmed:
raise ProviderProtocolError('Input before Gemini readiness')
if kind == 'input_audio_buffer.append':
pcm = base64.b64decode(event['audio'], validate=True)
if len(pcm) > self.settings.max_binary_message_bytes or len(pcm) % 2:
raise ProviderProtocolError('Invalid PCM frame')
converted = self._resampler.convert(pcm)
self._sent_samples += len(pcm)//2
if converted:
await self._wire({'realtimeInput': {'audio': {'mimeType':'audio/pcm;rate=16000', 'data':base64.b64encode(converted).decode('ascii')}}})
elif kind == 'conversation.item.create':
item = event['item']
if item['type'] == 'message' and item.get('role') == 'user':
if self._input or self._diagnostic:
raise ProviderProtocolError('Diagnostic input must start fresh')
content = item.get('content')
if not isinstance(content, list) or len(content) != 1 or content[0].get('type') != 'input_text':
raise ProviderProtocolError('Invalid diagnostic input')
self._diagnostic = item
await self._wire({'clientContent': {'turns': [{'role': 'user', 'parts': [{'text': content[0]['text']}]}], 'turnComplete': True}})
return
if item['type'] != 'function_call_output':
raise ProviderProtocolError('Unsupported Gemini item')
cid = item['call_id']
if cid not in self._calls:
raise ProviderProtocolError('Unknown Gemini tool identity')
output = strict_json(item['output'])
if cid in self._outputs and self._outputs[cid] != output:
raise ProviderProtocolError('Conflicting Gemini result')
self._outputs[cid] = output
elif kind == 'response.create':
intent = event['response']['metadata']['voice_intent']
if intent in self._seen_intents:
return
if len(self._seen_intents) >= self.settings.max_intents:
raise ProviderProtocolError('Intent bound')
self._seen_intents.add(intent)
self._intent = intent
if self._calls:
if set(self._outputs) != set(self._calls):
raise ProviderProtocolError('Incomplete Gemini tool results')
outputs = [{'id':cid,'name':self._calls[cid]['name'],'response':self._outputs[cid]} for cid in self._calls]
for cid, function in self._calls.items():
self._completed_calls[cid] = function
self._calls, self._outputs, self._response = {}, {}, None
await self._wire({'toolResponse': {'functionResponses': outputs}})
self._gate.set()
else:
raise ProviderProtocolError('Unsupported Gemini command')
async def _read_provider_loop(self):
try:
while True:
raw = await self.transport.recv()
if not isinstance(raw, (str,bytes)) or len(raw.encode('utf-8') if isinstance(raw,str) else raw) > self.settings.max_provider_message_bytes:
raise ProviderProtocolError('Gemini frame limit')
msg = strict_json(raw.decode('utf-8') if isinstance(raw,bytes) else raw)
await self._translate_google_message(msg)
except asyncio.CancelledError:
raise
except Exception as exc:
self._failure = exc if isinstance(exc, ProviderProtocolError) else ConnectionError('Gemini transport lost')
# Failure supersedes queued late content and wakes the runtime immediately.
while not self._inbound_events.empty():
self._inbound_events.get_nowait()
self._queued_bytes = self._control_count = self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self._inbound_events.put_nowait((None,0,False))
async def _begin(self):
if self._response:
return
if self._diagnostic is None and (self._input is None or self._input_end is None):
raise ProviderProtocolError('Gemini input boundaries unavailable')
if not self._input_consumed:
self._input_consumed = True
if self._diagnostic:
self._put({'type':'provider.input_consumed_text','item':self._diagnostic})
else:
self._put({'type':'provider.input_consumed','item_id':self._input})
await asyncio.wait_for(self._gate.wait(), self.settings.response_ack_timeout_seconds)
self._gate.clear()
self._response = 'gemini-response-'+uuid4().hex
self._item = 'gemini-item-'+uuid4().hex
self._output_text = ''
self._message_announced = False
self._put({'type':'response.created','response':{'id':self._response,'metadata':{'voice_intent':self._intent}}})
def _audio_event(self, kind, **payload):
self._put(dict(type=kind, response_id=self._response, item_id=self._item, output_index=0, content_index=0, **payload))
def _announce(self):
if not self._message_announced:
self._message_announced = True
self._put(dict(type='response.output_item.added',response_id=self._response,output_index=0,
item=dict(id=self._item,type='message',role='assistant',content=[{'type':'audio','transcript':''}])))
async def _translate_google_message(self, msg):
if 'setupComplete' in msg:
if not self._setup_sent or not isinstance(msg['setupComplete'], dict):
raise ProviderProtocolError('Invalid Gemini setup confirmation')
if not self._confirmed:
self._confirmed = True
self._put({'type':'session.updated','session':{'provider':'gemini','setup_complete':True}})
return
if not self._confirmed:
raise ProviderProtocolError('Gemini output before setup')
if 'goAway' in msg or 'toolCallCancellation' in msg:
raise GeminiContextError('Gemini session no longer eligible')
activity = msg.get('voiceActivity')
if activity:
offset = activity.get('audioOffset')
if not isinstance(offset,str) or not offset.endswith('s'):
raise ProviderProtocolError('Gemini activity coordinates unavailable')
milliseconds = int(float(offset[:-1])*1000)
if not 0 <= milliseconds <= self._sent_samples//24:
raise ProviderProtocolError('Gemini activity coordinates invalid')
if activity.get('type') == 'ACTIVITY_START':
duplicate = any(entry['start'] == milliseconds for entry in self._inputs)
if not duplicate:
if self._input and (self._input_end is None or not self._generation_complete):
raise GeminiContextError('Gemini pending generation cannot be rebound')
if self._response or self._calls:
raise GeminiContextError('Gemini interruption requires fresh context')
if self._inputs and milliseconds < self._inputs[-1]['end']:
raise GeminiContextError('Conflicting Gemini activity start')
self._input, self._input_end = 'gemini-input-'+uuid4().hex, None
self._input_consumed = self._generation_complete = False
if len(self._inputs) >= self.settings.max_input_turns:
raise GeminiOverflow('Gemini input mapping bound')
self._inputs.append({'id':self._input, 'start':milliseconds, 'end':None})
self._input_text = ''
self._put(dict(type='input_audio_buffer.speech_started',item_id=self._input,audio_start_ms=milliseconds))
elif activity.get('type') == 'ACTIVITY_END':
duplicate = any(entry['end'] == milliseconds for entry in self._inputs)
if not duplicate:
if self._input is None or self._input_end is not None or milliseconds <= self._inputs[-1]['start']:
raise GeminiContextError('Conflicting Gemini activity end')
self._input_end = milliseconds
self._inputs[-1]['end'] = milliseconds
self._put(dict(type='input_audio_buffer.speech_stopped',item_id=self._input,audio_end_ms=milliseconds))
else:
raise ProviderProtocolError('Unknown Gemini activity')
if 'toolCall' in msg:
functions = msg['toolCall']['functionCalls']
if not isinstance(functions,list) or not 1 <= len(functions) <= 16:
raise ProviderProtocolError('Gemini tool bound')
if all(fn.get('id') in self._completed_calls for fn in functions):
if any(self._completed_calls[fn['id']] != fn for fn in functions):
raise ProviderProtocolError('Conflicting completed Gemini tool replay')
return
if len(self._completed_calls) + len(self._calls) + len(functions) > self.settings.max_tool_calls:
raise ProviderProtocolError('Gemini call bound')
if self._calls:
if functions != list(self._calls.values()):
raise ProviderProtocolError('Conflicting Gemini tool replay')
return
await self._begin()
if self._message_announced:
raise GeminiContextError('Gemini mixed audio/tool phase unsupported')
output = []
for position, fn in enumerate(functions):
cid = fn.get('id')
if not isinstance(cid,str) or not cid or len(cid)>256 or cid in self._calls:
raise ProviderProtocolError('Gemini tool identity required')
item = dict(id='gemini-call-item-'+uuid4().hex,type='function_call',call_id=cid,
name=fn['name'],arguments=bounded_json(fn['args'],self.settings.max_provider_message_bytes,ensure_ascii=False))
self._calls[cid] = fn
output.append(item)
self._put(dict(type='response.output_item.added',response_id=self._response,output_index=position,item=item))
self._put(dict(type='response.function_call_arguments.done',response_id=self._response,item_id=item['id'],
call_id=cid,name=fn['name'],arguments=item['arguments']))
# Native tool request is a suspended generation phase, not a terminal acknowledgement.
self._put(dict(type='provider.tools_requested',response=dict(id=self._response,status='waiting_tools',output=output)))
content = msg.get('serverContent')
if content:
if content.get('interrupted'):
raise GeminiContextError('Gemini unheard audio cannot be truncated')
transcription = content.get('inputTranscription')
if transcription:
if not self._input or not isinstance(transcription.get('text'),str):
raise ProviderProtocolError('Uncorrelated Gemini input transcription')
offset = transcription.get('startOffset')
if offset is None:
if len(self._inputs) != 1:
raise ProviderProtocolError('Gemini delayed transcription is ambiguous')
input_item = self._inputs[0]['id']
else:
if not isinstance(offset, str) or not offset.endswith('s'):
raise ProviderProtocolError('Invalid Gemini transcript coordinates')
position = float(offset[:-1])*1000
matches = [entry for entry in self._inputs if entry['start'] <= position
and (entry['end'] is None or position <= entry['end'])]
if len(matches) != 1:
raise ProviderProtocolError('Uncorrelated Gemini transcript coordinates')
input_item = matches[0]['id']
self._input_text += transcription['text']
if len(self._input_text.encode('utf-8')) > self.settings.max_server_event_bytes//2:
raise ProviderProtocolError('Gemini transcript bound')
self._put(dict(type='conversation.item.input_audio_transcription.delta',item_id=input_item,
content_index=0,delta=transcription['text']))
parts = content.get('modelTurn', {}).get('parts', [])
out_text = content.get('outputTranscription', {}).get('text')
if parts or out_text is not None:
if self._calls:
raise GeminiContextError('Gemini output before authorized continuation')
await self._begin()
self._announce()
for part in parts:
if 'inlineData' in part:
blob = part['inlineData']
if blob.get('mimeType') != 'audio/pcm;rate=24000':
raise ProviderProtocolError('Unexpected Gemini output format')
self._audio_event('response.output_audio.delta',delta=blob['data'])
elif part.get('text') and not part.get('thought'):
# modelTurn text is not an audio transcript; outputTranscription is.
raise ProviderProtocolError('Unexpected Gemini text modality')
if out_text is not None:
if not isinstance(out_text,str):
raise ProviderProtocolError('Invalid Gemini transcript')
self._output_text += out_text
if len(self._output_text.encode('utf-8')) > self.settings.max_server_event_bytes//2:
raise ProviderProtocolError('Gemini transcript bound')
self._audio_event('response.output_audio_transcript.delta',delta=out_text)
if content.get('turnComplete') and self._response and not self._calls:
self._announce()
self._audio_event('response.output_audio_transcript.done',transcript=self._output_text)
self._audio_event('response.output_audio.done')
item=dict(id=self._item,type='message',role='assistant',content=[{'type':'audio','transcript':self._output_text}])
self._put(dict(type='response.output_item.done',response_id=self._response,output_index=0,item=item))
self._put(dict(type='response.done',response=dict(id=self._response,status='completed',output=[item])))
self._response = None
self._generation_complete = True
async def receive(self):
if self._failure:
raise self._failure
item,size,audio = await self._inbound_events.get()
if audio:
self._audio_bytes -= len(size)
self._audio_slabs -= 1
self._audio_metadata -= len(self.serialize(item).encode('utf-8'))
self._leased_audio = len(size)
item = dict(item, delta=base64.b64encode(size).decode('ascii'))
else:
self._queued_bytes -= size
self._control_count -= 1
if self._failure:
raise self._failure
return item
def is_no_active(self, error):
return False
async def close(self):
if self._close_task is None:
async def cleanup():
if self._pump_task and self._pump_task is not asyncio.current_task():
self._pump_task.cancel()
await asyncio.gather(self._pump_task, return_exceptions=True)
try:
await asyncio.wait_for(self.transport.close(), self.settings.send_timeout_seconds)
finally:
while not self._inbound_events.empty():
self._inbound_events.get_nowait()
self._queued_bytes = self._control_count = 0
self._audio_bytes = self._audio_slabs = self._leased_audio = self._audio_metadata = 0
self._close_task = asyncio.create_task(cleanup())
await asyncio.shield(self._close_task)
async def connect_gemini(api_key, model='gemini-2.0-flash-exp', proxy=None, settings=None):
if not api_key:
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
settings = settings or RuntimeSettings()
from websockets.asyncio.client import connect
endpoint = 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent'
return await connect(endpoint+'?key='+quote(api_key,safe=''), proxy=proxy,compression=None,
max_size=settings.max_provider_message_bytes,max_queue=16,open_timeout=settings.connect_timeout_seconds,
close_timeout=settings.send_timeout_seconds,ping_interval=20,ping_timeout=20)
+110 -36
View File
@@ -1,43 +1,117 @@
"""Main FastAPI Application Entrypoint. """Modular API: startup reconciliation gates admission; no prototype imports."""
import asyncio
Initializes the FastAPI application, sets up CORS middleware, registers API routes, from contextlib import asynccontextmanager
and provides system health check endpoints. from uuid import UUID, uuid4
""" from fastapi import FastAPI, Request, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi import FastAPI from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.auth import router as auth_router, identity_router
from app.api.v1.conversations import router as conversations_router
from app.api.v1.live import router as voice_router
from app.api.v1 import dependencies
from app.infrastructure.blocking import blocking, shutdown_pool
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.registry import shutdown
from app.api.v1.chat import router as chat_router @asynccontextmanager
from app.core.config import settings async def lifespan(app):
app.state.ready = False
engine = None
startup_error = None
try:
engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(lifecycle.reconcile_startup)
app.state.ready = True
yield
except BaseException as exc:
startup_error = exc
raise
finally:
app.state.ready = False
async def cleanup():
try:
await asyncio.wait_for(shutdown(), 6)
finally:
try:
runner = dependencies._TOOL_RUNNER
if runner is not None:
await asyncio.wait_for(asyncio.to_thread(runner.close), 6)
finally:
try:
if engine is not None:
engine.dispose()
finally:
dependencies._TOOL_RUNNER = None
dependencies._ENGINE = dependencies._AUTH_SERVICE = dependencies._LIFECYCLE_SERVICE = dependencies._SEARCH_SERVICE = None
shutdown_pool()
task = asyncio.create_task(cleanup())
try:
await asyncio.shield(task)
except asyncio.CancelledError:
# Cleanup retains ownership after cancellation, including startup.
try:
await asyncio.shield(task)
except Exception:
if startup_error is None:
raise
if startup_error is None:
raise
except Exception:
if startup_error is None:
raise
# Initialize FastAPI application instance app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan)
app = FastAPI( app.state.ready = False
title=settings.app_name, config = VoiceSettings()
version=settings.app_version, app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True,
description=settings.app_description, allow_methods=['GET','POST'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID'])
docs_url="/docs",
redoc_url="/redoc",
)
# Configure Cross-Origin Resource Sharing (CORS) middleware @app.middleware('http')
app.add_middleware( async def transport(request, call_next):
CORSMiddleware, try:
allow_origins=["*"], request_id = str(UUID(request.headers.get('x-request-id', '')))
allow_credentials=True, except (ValueError, TypeError):
allow_methods=["*"], request_id = str(uuid4())
allow_headers=["*"], request.state.request_id = request_id
) if request.headers.get('host') not in config.trusted_hosts:
result = envelope(request, 'FORBIDDEN', 403)
elif not app.state.ready and request.url.path not in ('/health/live','/health/ready'):
result = envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
else:
result = await call_next(request)
result.headers['X-Request-ID'] = request_id
return result
# Register API v1 routers def envelope(request, code, status):
app.include_router(chat_router, prefix="/api/v1") return JSONResponse(status_code=status, headers={'Retry-After':'60'} if status == 429 else {}, content={'error': {'code': code,
'message': 'Request could not be completed.', 'request_id': getattr(request.state, 'request_id', str(uuid4())),
'retryable': status in (429,503)}})
@app.exception_handler(StarletteHTTPException)
@app.exception_handler(HTTPException)
async def http_error(request, exc):
detail = exc.detail if isinstance(exc.detail, dict) else {}
return envelope(request, detail.get('code', 'NOT_FOUND' if exc.status_code == 404 else 'REQUEST_FAILED'), exc.status_code)
@app.get( @app.exception_handler(RequestValidationError)
"/api/v1/health", async def dto_error(request, exc):
tags=["Health"], return envelope(request, 'VALIDATION_ERROR', 422)
summary="Health Check",
description="Check the operational health and readiness of the service.", @app.exception_handler(Exception)
) async def unexpected_error(request, exc):
async def health_check() -> dict[str, str]: return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
"""Return the service health status."""
return {"status": "healthy"} for router in (auth_router, identity_router, conversations_router, voice_router):
app.include_router(router, prefix='/api/v1')
@app.get('/health/live')
def live():
return {'status': 'ok'}
@app.get('/health/ready')
def ready():
return JSONResponse(status_code=200 if app.state.ready else 503,
content={'status': 'ready', 'ingestion': 'available'} if app.state.ready else {'status': 'not_ready'})
+1
View File
@@ -0,0 +1 @@
"""Auth and session management module."""
+245
View File
@@ -0,0 +1,245 @@
"""Authentication, session lifecycle, CSRF tokens and access validation."""
from datetime import datetime, timezone, timedelta
import hashlib
import hmac
import os
import secrets
from uuid import UUID, uuid4
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
from pydantic import BaseModel, Field
from sqlalchemy import text
COOKIE_NAME = "rag_session"
DEFAULT_SESSION_LIFETIME = timedelta(hours=8)
class UserContext(BaseModel):
id: UUID
organization_id: UUID
username: str
role: str
is_enabled: bool
auth_session_id: UUID
access_epoch: int
expires_at: datetime | None = None
def hash_token(raw_token: str) -> str:
"""Computes SHA-256 hex digest of raw session token."""
if not valid_token(raw_token):
raise ValueError("AUTH_REQUIRED")
return hashlib.sha256(raw_token.encode("ascii")).hexdigest()
def valid_token(value):
return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)
def generate_csrf_token(raw_token: str) -> str:
if not valid_token(raw_token):
raise ValueError('AUTH_REQUIRED')
return hmac.new(raw_token.encode('ascii'), b'rag-session-csrf-v1', hashlib.sha256).hexdigest()
def verify_csrf_token(raw_token: str, client_csrf: str) -> bool:
return (valid_token(raw_token) and valid_token(client_csrf)
and hmac.compare_digest(generate_csrf_token(raw_token), client_csrf))
def check_origin(origin_header, host_header, allowed_origins=None, allowed_hosts=None, *, required=False):
from app.modules.voice.configuration import VoiceSettings
config = VoiceSettings()
origins = allowed_origins if allowed_origins is not None else config.trusted_origins
hosts = allowed_hosts if allowed_hosts is not None else config.trusted_hosts
if not isinstance(host_header, str) or len(host_header) > 255 or host_header not in hosts:
return False
if origin_header is None:
return not required
return isinstance(origin_header, str) and len(origin_header) <= 512 and origin_header in origins
class AuthService:
def __init__(self, engine, session_lifetime: timedelta | None = None, session_ttl: timedelta | None = None):
self.engine = engine
self.lifetime = session_ttl or session_lifetime or DEFAULT_SESSION_LIFETIME
self._hasher = PasswordHasher()
self._dummy_hash = self._hasher.hash(secrets.token_hex(32))
def login(self, username: str, password: str) -> tuple[dict, str, str, datetime]:
"""Authenticates user and issues a new opaque cookie session.
Returns: (user_dict, raw_token, csrf_token, expires_at)
Raises: ValueError("INVALID_CREDENTIALS") or ValueError("ACCOUNT_DISABLED")
"""
if (not isinstance(username, str) or not isinstance(password, str)
or not 1 <= len(username) <= 120 or not 1 <= len(password) <= 1024
or '\x00' in username or '\x00' in password):
raise ValueError('INVALID_CREDENTIALS')
clean_user = username.strip().lower()
now = datetime.now(timezone.utc)
expires_at = now + self.lifetime
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
row = conn.execute(
text("""
SELECT u.id, u.organization_id, u.username, u.password_hash, u.role, u.is_enabled,
s.access_epoch
FROM users u
JOIN organization_settings s ON s.organization_id = u.organization_id
WHERE u.username = :username
"""),
{"username": clean_user}
).mappings().first()
if not row:
try:
self._hasher.verify(self._dummy_hash, password)
except VerificationError:
pass
raise ValueError("INVALID_CREDENTIALS")
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR SHARE'), {'org': row['organization_id']})
row = conn.execute(text('''SELECT u.id,u.organization_id,u.username,u.password_hash,u.role,u.is_enabled,s.access_epoch
FROM users u JOIN organization_settings s ON s.organization_id=u.organization_id
WHERE u.id=:id FOR SHARE OF u'''), {'id':row['id']}).mappings().first()
if row is None:
raise ValueError('INVALID_CREDENTIALS')
try:
self._hasher.verify(row["password_hash"], password)
except (VerifyMismatchError, VerificationError):
raise ValueError("INVALID_CREDENTIALS")
if not row["is_enabled"]:
raise ValueError("ACCOUNT_DISABLED")
session_id = uuid4()
raw_token = secrets.token_hex(32)
token_h = hash_token(raw_token)
csrf_token = generate_csrf_token(raw_token)
conn.execute(
text("""
INSERT INTO auth_sessions (id, organization_id, user_id, token_hash, created_at, expires_at, last_seen_at)
VALUES (:id, :org, :user, :token_hash, :created_at, :expires_at, :last_seen_at)
"""),
{
"id": session_id,
"org": row["organization_id"],
"user": row["id"],
"token_hash": token_h,
"created_at": now,
"expires_at": expires_at,
"last_seen_at": now,
}
)
user_dict = {
"id": str(row["id"]),
"username": row["username"],
"role": row["role"],
"organization_id": str(row["organization_id"]),
}
return user_dict, raw_token, csrf_token, expires_at
def get_current_user(self, raw_token: str) -> UserContext:
"""Validates session token and returns active UserContext."""
if not raw_token:
raise ValueError("AUTH_REQUIRED")
token_h = hash_token(raw_token)
now = datetime.now(timezone.utc)
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
row = conn.execute(
text("""
SELECT a.id AS auth_session_id, a.expires_at, a.revoked_at,
u.id AS user_id, u.organization_id, u.username, u.role, u.is_enabled,
s.access_epoch
FROM auth_sessions a
JOIN users u ON u.id = a.user_id AND u.organization_id = a.organization_id
JOIN organization_settings s ON s.organization_id = a.organization_id
WHERE a.token_hash = :token_hash
"""),
{"token_hash": token_h}
).mappings().first()
if not row:
raise ValueError("AUTH_REQUIRED")
if row["revoked_at"] is not None:
raise ValueError("SESSION_REVOKED")
if row["expires_at"] <= now:
raise ValueError("SESSION_EXPIRED")
if not row["is_enabled"]:
raise ValueError("ACCOUNT_DISABLED")
sess_id = row.get("auth_session_id") or row.get("id")
# Update last_seen_at
conn.execute(
text("UPDATE auth_sessions SET last_seen_at = :now WHERE id = :id"),
{"now": now, "id": sess_id}
)
return UserContext(
id=row["user_id"],
organization_id=row["organization_id"],
username=row["username"],
role=row["role"],
is_enabled=row["is_enabled"],
auth_session_id=sess_id,
access_epoch=row["access_epoch"],
expires_at=row["expires_at"],
)
def logout(self, raw_token: str | None) -> None:
"""Revokes the current auth session and closes owned live sessions."""
if not valid_token(raw_token):
return
token_h = hash_token(raw_token)
now = datetime.now(timezone.utc)
from app.modules.knowledge.service import transaction
with transaction(self.engine) as conn:
initial = conn.execute(text("SELECT organization_id FROM auth_sessions WHERE token_hash=:hash"), {"hash": token_h}).mappings().first()
if initial is None:
return
conn.execute(text("SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE"), {"org": initial["organization_id"]})
session = conn.execute(
text("SELECT id, user_id, organization_id FROM auth_sessions WHERE token_hash = :hash AND revoked_at IS NULL"),
{"hash": token_h}
).mappings().first()
if not session:
return
conn.execute(
text("UPDATE auth_sessions SET revoked_at = :now WHERE id = :id"),
{"now": now, "id": session["id"]}
)
# Close linked active live sessions
conn.execute(
text("""
UPDATE live_sessions
SET status = 'closed', closed_at = :now, close_reason = 'user_logout', updated_at = :now
WHERE auth_session_id = :session_id AND status IN ('creating', 'connecting', 'connected')
"""),
{"now": now, "session_id": session["id"]}
)
conn.execute(text("""
UPDATE tool_calls SET status='failed', completed_at=:now, error_code='SESSION_REVOKED'
WHERE status='running' AND live_session_id IN
(SELECT id FROM live_sessions WHERE auth_session_id=:auth)
"""), {'now': now, 'auth': session['id']})
from app.modules.voice.registry import notify
notify(auth_session_id=session['id'])
+13 -1
View File
@@ -158,6 +158,15 @@ def selection_replace(engine, administrator_id, expected_revision, document_ids)
UPDATE organization_settings SET knowledge_revision=:revision,access_epoch=:epoch, UPDATE organization_settings SET knowledge_revision=:revision,access_epoch=:epoch,
updated_by=:actor,updated_at=now() WHERE organization_id=:org updated_by=:actor,updated_at=now() WHERE organization_id=:org
"""), dict(org=org, actor=current["id"], revision=revision, epoch=epoch)) """), dict(org=org, actor=current["id"], revision=revision, epoch=epoch))
if removed:
conn.execute(text("""UPDATE conversations SET status='stale',updated_at=now() WHERE organization_id=:org AND access_epoch<:epoch AND status='active'"""), {'org': org, 'epoch': epoch})
conn.execute(text("""
UPDATE live_sessions
SET status = 'closed', closed_at = now(), close_reason = 'epoch_invalidated', updated_at = now()
WHERE organization_id = :org AND access_epoch < :epoch AND status IN ('creating', 'connecting', 'connected')
"""), {"org": org, "epoch": epoch})
conn.execute(text("""UPDATE tool_calls SET status='failed',completed_at=now(),error_code='CONTEXT_REVOKED'
WHERE organization_id=:org AND access_epoch<:epoch AND status='running'"""), {'org': org, 'epoch': epoch})
conn.execute(text(""" conn.execute(text("""
INSERT INTO audit_events(id,organization_id,actor_user_id,action,metadata) INSERT INTO audit_events(id,organization_id,actor_user_id,action,metadata)
VALUES (:id,:org,:actor,'selection_changed',CAST(:metadata AS jsonb)) VALUES (:id,:org,:actor,'selection_changed',CAST(:metadata AS jsonb))
@@ -165,7 +174,10 @@ def selection_replace(engine, administrator_id, expected_revision, document_ids)
metadata=json.dumps(dict(knowledge_revision=revision, access_epoch=epoch, metadata=json.dumps(dict(knowledge_revision=revision, access_epoch=epoch,
added_document_ids=[str(v) for v in sorted(wanted - old)], added_document_ids=[str(v) for v in sorted(wanted - old)],
removed_document_ids=[str(v) for v in sorted(old - wanted)])))) removed_document_ids=[str(v) for v in sorted(old - wanted)]))))
return result if changed and removed:
from app.modules.voice.registry import notify
notify(organization_id=org, new_epoch=epoch)
return result
class SearchService: class SearchService:
+65
View File
@@ -0,0 +1,65 @@
"""Deployment configuration, independent of runtime limits and embedding profiles."""
from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
from pydantic import Field, SecretStr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class VoiceSettings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True)
provider: Literal['gemini'] = 'gemini'
gemini_api_key: SecretStr = SecretStr('')
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
gemini_proxy: str | None = None
trusted_origins: tuple[str, ...] = ('http://localhost:8000', 'http://127.0.0.1:8000')
trusted_hosts: tuple[str, ...] = ('localhost:8000', '127.0.0.1:8000')
cookie_secure: bool = True
auth_session_seconds: int = Field(default=28800, ge=60, le=604800)
live_session_seconds: int = Field(default=600, ge=10, le=3600)
search_calibration_report: Path | None = None
max_provider_sessions: int = Field(default=4, ge=1, le=32)
login_attempts_per_minute: int = Field(default=12, ge=1, le=120)
@field_validator('gemini_model', 'gemini_voice')
@classmethod
def identifier(cls, value):
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
raise ValueError('Invalid voice profile identifier')
return value
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy')
@classmethod
def urls(cls, value, info):
if info.field_name == 'gemini_proxy' and value is None:
return value
values = (value,) if info.field_name == 'gemini_proxy' else value
if not values or len(values) > 20:
raise ValueError('Explicit bounded trusted endpoints required')
for entry in values:
try:
p = urlsplit('http://' + entry if info.field_name == 'trusted_hosts' else entry)
port = p.port
except ValueError:
raise ValueError('Invalid endpoint configuration') from None
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name == 'gemini_proxy' else ('http', 'https')
if (len(entry) > 512 or p.scheme not in schemes or not p.hostname or p.username
or p.password or p.path or p.query or p.fragment or '*' in entry):
raise ValueError('Invalid endpoint configuration')
return value
@model_validator(mode='after')
def cookie_policy(self):
if not self.cookie_secure and any(urlsplit(o).hostname not in ('localhost', '127.0.0.1', '::1') for o in self.trusted_origins):
raise ValueError('Insecure cookies require loopback-only development origins')
return self
def require_voice(self):
key = self.gemini_api_key.get_secret_value()
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
def profile(self):
return dict(provider=self.provider, model=self.gemini_model, voice=self.gemini_voice,
input_sample_rate=16000, output_sample_rate=24000)
+76
View File
@@ -0,0 +1,76 @@
"""Durable admission wraps actual StructuredTool work, never browser event inference."""
import asyncio
import time
from app.infrastructure.blocking import blocking
from sqlalchemy.exc import SQLAlchemyError
class DurableFailure(ValueError):
def __init__(self, code):
self.live_code = code
super().__init__(code)
class DurableTools:
def __init__(self, lifecycle, user, session_id):
self.lifecycle, self.user, self.session_id = lifecycle, user, session_id
async def execute(self, external_id, call, ctx, args, invoke):
row = await blocking(self.lifecycle.admit_tool, self.user, self.session_id,
external_id, call['ref'], args, ctx.execution)
call['ref'], call['durable_id'], call['inserted'] = str(row['public_ref']), row['id'], row['inserted']
if row['inserted']:
result = await invoke()
if ctx.cancelled.is_set():
await blocking(self.lifecycle.cancel_tools, self.user, self.session_id, [call['ref']])
raise ValueError('CANCELLED')
if not await blocking(self.lifecycle.complete_tool, self.user, self.session_id,
row['id'], result, ctx.execution):
raise ValueError('LIVE_SESSION_UNUSABLE')
return result
# Independent callers coalesce through the durable row; no second retrieval.
while True:
if time.monotonic() >= ctx.deadline:
raise TimeoutError("Tool duplicate wait expired")
if ctx.cancelled.is_set():
raise ValueError('CANCELLED')
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, row['id'], ctx.execution)
if result is not None:
return result
await asyncio.sleep(.025)
async def delivery(self, call, execution):
if 'durable_id' not in call:
return
try:
result = await blocking(self.lifecycle.tool_result, self.user, self.session_id, call['durable_id'], execution, allow_technical_failure=True)
if result != call['result']:
raise ValueError('LIVE_CONTEXT_SYNC_FAILED')
except Exception as exc:
raise DurableFailure(failure_code(exc)) from None
def failure_code(exc):
"""A persistence failure is terminal: no unverified result may continue.
Diagnostics distinguish technical failure from verified authority loss.
"""
if isinstance(exc, DurableFailure):
return exc.live_code
if isinstance(exc, SQLAlchemyError):
return 'DEPENDENCY_UNAVAILABLE'
if isinstance(exc, TimeoutError):
return 'SEARCH_TIMEOUT'
code = str(exc) if isinstance(exc, ValueError) else getattr(exc, 'code', '')
if code in ('AUTH_REQUIRED','ACCOUNT_DISABLED','SESSION_REVOKED','SESSION_EXPIRED',
'CONTEXT_REVOKED','CONVERSATION_STALE','CONVERSATION_CLOSED',
'LIVE_SESSION_EXPIRED','LIVE_SESSION_UNUSABLE'):
return 'CONTEXT_REVOKED'
if code == 'LIVE_CONTEXT_SYNC_FAILED':
return code
if code in ('CANCELLED','TOOL_CANCELLED','SEARCH_CANCELLED'):
return 'SEARCH_CANCELLED'
if code == 'IDEMPOTENCY_CONFLICT':
return 'LIVE_PROVIDER_PROTOCOL_ERROR'
if code in ('SERVICE_BUSY','SEARCH_SATURATED'):
return 'SEARCH_SATURATED'
# Database/connectivity/provider availability never masquerades as revocation.
return 'LIVE_PROVIDER_UNAVAILABLE'
+327
View File
@@ -0,0 +1,327 @@
"""Settings-first durable Live transactions. Remote work runs after commit."""
from datetime import datetime, timezone, timedelta
import hashlib
import json
from uuid import UUID, uuid4
from sqlalchemy import text
from app.modules.knowledge.service import SearchInput, authority, transaction, KnowledgeError
ACTIVE = ('creating', 'connecting', 'connected')
TECHNICAL_ERRORS = frozenset(('SEARCH_TIMEOUT','SEARCH_FAILED','SEARCH_SATURATED',
'PROVIDER_TIMEOUT','PROVIDER_UNAVAILABLE','DEPENDENCY_UNAVAILABLE',
'SERVICE_UNAVAILABLE','DATABASE_UNAVAILABLE','SEARCH_UNAVAILABLE',
'CALIBRATION_REQUIRED','PROFILE_MISMATCH','INVALID_CONFIGURATION','INVALID_VECTOR'))
def replayable_error(row):
result = row['result_json']
return (row['status'] == 'failed' and isinstance(result, dict)
and result.get('status') == 'error'
and row['error_code'] in TECHNICAL_ERRORS
and (result.get('error') or {}).get('code') == row['error_code'])
def canonical_hash(data):
return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')).hexdigest()
def now():
return datetime.now(timezone.utc)
class LiveLifecycleService:
def __init__(self, engine, session_ttl=timedelta(minutes=10)):
self.engine, self.session_ttl = engine, session_ttl
def _actor(self, conn, user):
try:
current, settings = authority(conn, user.id, exclusive=True)
except KnowledgeError as exc:
raise ValueError("ACCOUNT_DISABLED" if exc.code == "ACTOR_UNAVAILABLE" else "AUTH_REQUIRED") from None
if current['organization_id'] != user.organization_id:
raise ValueError('AUTH_REQUIRED')
auth = conn.execute(text('''SELECT * FROM auth_sessions WHERE id=:auth
AND organization_id=:org AND user_id=:owner FOR SHARE'''),
dict(auth=user.auth_session_id, org=user.organization_id, owner=user.id)).mappings().first()
if auth is None:
raise ValueError('AUTH_REQUIRED')
if auth['revoked_at'] is not None:
raise ValueError('SESSION_REVOKED')
if auth['expires_at'] <= now():
raise ValueError('SESSION_EXPIRED')
return current, settings
def _conversation(self, conn, user, cid, settings):
row = conn.execute(text('''SELECT * FROM conversations WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner FOR UPDATE'''),
dict(id=cid, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('CONVERSATION_NOT_FOUND')
if row['mode'] != 'voice':
raise ValueError('MODE_MISMATCH')
if row['status'] == 'closed':
raise ValueError('CONVERSATION_CLOSED')
if row['status'] != 'active' or row['access_epoch'] != settings['access_epoch']:
raise ValueError('CONVERSATION_STALE')
return row
def _session(self, conn, user, sid, settings, *, connected=False):
initial = conn.execute(text('''SELECT conversation_id FROM live_sessions WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner'''),
dict(id=sid, org=user.organization_id, owner=user.id)).mappings().first()
if initial is None:
raise ValueError('SESSION_NOT_FOUND')
self._conversation(conn, user, initial['conversation_id'], settings)
row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id FOR UPDATE'), {'id': sid}).mappings().one()
if row['expires_at'] <= now():
raise ValueError('LIVE_SESSION_EXPIRED')
if (row['auth_session_id'] != user.auth_session_id or row['status'] not in ACTIVE
or row['expires_at'] <= now() or row['access_epoch'] != settings['access_epoch']
or (connected and row['status'] != 'connected')):
raise ValueError('LIVE_SESSION_UNUSABLE')
return row
@staticmethod
def _shape(row, *, replayed=False, eligible=True):
sid = str(row['id'])
return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'],
stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None,
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed)
@staticmethod
def _terminal(conn, sid, reason, *, failed=False):
stamp = now()
conn.execute(text('''UPDATE live_sessions SET status=:status, closed_at=:now,
close_reason=:reason,error_code=:error,updated_at=:now
WHERE id=:id AND status IN ('creating','connecting','connected')'''),
dict(id=sid, status='failed' if failed else 'closed', now=stamp, reason=reason, error=reason if failed else None))
conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=:now,error_code=:reason
WHERE live_session_id=:id AND status='running' '''), dict(id=sid, now=stamp, reason=reason))
def expire_reservations(self, user):
# Cleanup commits independently so a later creation conflict cannot undo it.
with transaction(self.engine) as conn:
self._actor(conn, user)
rows = conn.execute(text('''SELECT id FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND status IN ('creating','connecting','connected') AND expires_at<=:now
ORDER BY conversation_id,id'''), dict(org=user.organization_id, owner=user.id, now=now())).scalars().all()
for sid in rows:
self._terminal(conn, sid, 'LIVE_SESSION_EXPIRED')
def create_conversation(self, user, client_request_id, mode='voice', title=None):
if mode != 'voice':
raise ValueError('MODE_MISMATCH')
legacy_title = title
title = title.strip() if title is not None else None
digest = canonical_hash(dict(mode=mode, title=title))
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM conversations WHERE owner_user_id=:owner
AND organization_id=:org AND client_request_id=:req'''),
dict(owner=user.id, org=user.organization_id, req=client_request_id)).mappings().first()
replayed = row is not None
if row is not None and row['request_hash'] != digest:
legacy = canonical_hash(dict(user=str(user.id), request=str(client_request_id),
mode=mode, title=legacy_title or ''))
if row['request_hash'] != legacy or row['mode'] != mode or row['title'] != legacy_title:
raise ValueError('IDEMPOTENCY_CONFLICT')
conn.execute(text('UPDATE conversations SET request_hash=:hash WHERE id=:id'),
dict(hash=digest, id=row['id']))
if row is None:
row = conn.execute(text('''INSERT INTO conversations
(id,organization_id,owner_user_id,client_request_id,request_hash,mode,title,access_epoch)
VALUES (:id,:org,:owner,:req,:hash,'voice',:title,:epoch) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, owner=user.id, req=client_request_id,
hash=digest, title=title, epoch=settings['access_epoch'])).mappings().one()
return dict(id=str(row['id']), mode=row['mode'], title=row['title'], status=row['status'],
access_epoch=row['access_epoch'], created_at=row['created_at'].isoformat(), replayed=replayed)
def create_live_session(self, user, conversation_id, client_request_id, provider='gemini',
model='gemini-2.0-flash-exp', execution_profile=None):
self.expire_reservations(user)
digest = canonical_hash(dict(conversation_id=str(conversation_id)))
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND client_request_id=:req'''),
dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first()
if row is not None:
if row['request_hash'] != digest:
# Original Phase 2 included server configuration in V01's hash.
# Verify against the original pinned row, never today's config.
legacy = canonical_hash(dict(owner=str(user.id), conversation_id=str(conversation_id),
client_request_id=str(client_request_id), provider=row['provider'], model=row['model']))
if row['request_hash'] != legacy or row['conversation_id'] != conversation_id:
raise ValueError('IDEMPOTENCY_CONFLICT')
conn.execute(text('UPDATE live_sessions SET request_hash=:hash WHERE id=:id'),
dict(hash=digest, id=row['id']))
self._session(conn, user, row['id'], settings)
return self._shape(row, replayed=True)
self._conversation(conn, user, conversation_id, settings)
if conn.execute(text('''SELECT id FROM live_sessions WHERE conversation_id=:id
AND status IN ('creating','connecting','connected')'''), {'id': conversation_id}).first():
raise ValueError('LIVE_SESSION_BUSY')
row = conn.execute(text('''INSERT INTO live_sessions
(id,organization_id,conversation_id,owner_user_id,auth_session_id,client_request_id,request_hash,
provider,model,status,settings_revision,knowledge_revision,access_epoch,execution_profile,expires_at)
VALUES (:id,:org,:conv,:owner,:auth,:req,:hash,:provider,:model,'connecting',
:revision,:knowledge,:epoch,CAST(:profile AS jsonb),:expires) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, conv=conversation_id, owner=user.id,
auth=user.auth_session_id, req=client_request_id, hash=digest, provider=provider, model=model,
revision=settings['revision'], knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'],
profile=json.dumps(execution_profile or {}), expires=now()+self.session_ttl)).mappings().one()
return self._shape(row)
def recover_live_session(self, user, client_request_id):
self.expire_reservations(user)
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE organization_id=:org
AND owner_user_id=:owner AND client_request_id=:req'''),
dict(org=user.organization_id, owner=user.id, req=client_request_id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
try:
self._session(conn, user, row['id'], settings)
eligible = row['status'] == 'connecting'
except ValueError:
eligible = False
return self._shape(row, eligible=eligible)
def validate_stream(self, user, session_id, execution=None, *, initial=False):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
row = self._session(conn, user, session_id, settings)
if initial and row['status'] != 'connecting':
raise ValueError('LIVE_SESSION_UNUSABLE')
if execution is not None and not execution.capture(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
return dict(row)
def mark_connected(self, user, session_id):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings)
conn.execute(text('''UPDATE live_sessions SET status='connected',connected_at=COALESCE(connected_at,now()),
updated_at=now() WHERE id=:id'''), {'id': session_id})
def finish_session(self, user, session_id, reason='user_requested', *, failed=False):
with transaction(self.engine) as conn:
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id})
row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id
AND organization_id=:org AND owner_user_id=:owner'''),
dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
self._terminal(conn, session_id, reason, failed=failed)
row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id'), {'id': session_id}).mappings().one()
from app.modules.voice.registry import notify
notify(session_id=session_id)
return dict(session_id=str(session_id), status=row['status'], close_reason=row['close_reason'])
def close_live_session(self, user, session_id, reason='user_requested'):
return self.finish_session(user, session_id, reason)
def _sources(self, conn, org, sources):
result = []
for source in sources:
copied = dict(source)
row = conn.execute(text('''SELECT d.id FROM documents d JOIN document_chunks c
ON c.organization_id=d.organization_id AND c.document_id=d.id
WHERE d.organization_id=:org AND d.id=:doc AND c.id=:chunk
AND d.status='ready' AND d.is_active AND d.deleted_at IS NULL AND d.content_purged_at IS NULL'''),
dict(org=org, doc=UUID(source['document_id']), chunk=UUID(source['chunk_id']))).first()
copied['available'] = row is not None
copied['excerpt'] = copied.pop('text', copied.get('excerpt')) if row else None
if row is None:
copied.pop('text', None)
result.append(copied)
return result
def get_live_session(self, user, session_id):
self.expire_reservations(user)
with transaction(self.engine) as conn:
self._actor(conn, user)
row = conn.execute(text('''SELECT * FROM live_sessions WHERE id=:id AND organization_id=:org
AND owner_user_id=:owner'''), dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first()
if row is None:
raise ValueError('SESSION_NOT_FOUND')
calls = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:id
AND organization_id=:org ORDER BY created_at DESC,id DESC LIMIT 20'''),
dict(id=session_id, org=user.organization_id)).mappings().all()
results = [dict(tool_call_id=str(c['public_ref']), status=c['status'], created_at=c['created_at'].isoformat(),
error_code=c['error_code'], sources=self._sources(conn, user.organization_id, (c['result_json'] or {}).get('sources', [])))
for c in reversed(calls)]
return dict(session_id=str(row['id']), status=row['status'], close_reason=row['close_reason'],
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results)
def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
arguments = SearchInput.model_validate(arguments).model_dump()
digest = canonical_hash(arguments)
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.capture(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
row = conn.execute(text('''SELECT * FROM tool_calls WHERE live_session_id=:sid
AND external_call_id=:ext FOR UPDATE'''), dict(sid=session_id, ext=external_call_id)).mappings().first()
if row:
if row['request_hash'] != digest:
raise ValueError('IDEMPOTENCY_CONFLICT')
if (row['status'] == 'failed' and not replayable_error(row)) or row['access_epoch'] != settings['access_epoch']:
raise ValueError('LIVE_SESSION_UNUSABLE')
if row['result_json'] and any(not s['available'] for s in self._sources(conn, user.organization_id, row['result_json'].get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
return dict(row, inserted=False)
row = conn.execute(text('''INSERT INTO tool_calls
(id,organization_id,live_session_id,external_call_id,public_ref,arguments,request_hash,knowledge_revision,access_epoch)
VALUES (:id,:org,:sid,:ext,:ref,CAST(:args AS jsonb),:hash,:knowledge,:epoch) RETURNING *'''),
dict(id=uuid4(), org=user.organization_id, sid=session_id, ext=external_call_id, ref=UUID(public_ref),
args=json.dumps(arguments), hash=digest, knowledge=settings['knowledge_revision'], epoch=settings['access_epoch'])).mappings().one()
return dict(row, inserted=True)
def tool_result(self, user, session_id, call_id, execution, *, allow_technical_failure=False):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.matches(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
row = conn.execute(text('SELECT * FROM tool_calls WHERE id=:id AND live_session_id=:sid'), dict(id=call_id, sid=session_id)).mappings().one()
if row['status'] == 'failed' and not replayable_error(row):
raise ValueError('LIVE_SESSION_UNUSABLE')
result = row['result_json']
if result and any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
return result
def complete_tool(self, user, session_id, call_id, result, execution):
with transaction(self.engine) as conn:
current, settings = self._actor(conn, user)
self._session(conn, user, session_id, settings, connected=True)
if not execution.matches(current, settings['access_epoch']):
raise ValueError('CONTEXT_REVOKED')
if any(not s['available'] for s in self._sources(conn, user.organization_id, result.get('sources', []))):
raise ValueError('CONTEXT_REVOKED')
code = (result.get('error') or {}).get('code') if result.get('status') == 'error' else None
return bool(conn.execute(text('''UPDATE tool_calls SET status=:status,result_json=CAST(:result AS jsonb),
error_code=:error,completed_at=now() WHERE id=:id AND live_session_id=:sid
AND status='running' AND access_epoch=:epoch RETURNING id'''),
dict(id=call_id, sid=session_id, epoch=settings['access_epoch'], status='failed' if code else 'succeeded',
result=json.dumps(result), error=code)).first())
def cancel_tools(self, user, session_id, refs=None, code='TOOL_CANCELLED'):
with transaction(self.engine) as conn:
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE'), {'org': user.organization_id})
conn.execute(text('''UPDATE tool_calls SET status='failed',completed_at=now(),error_code=:code
WHERE live_session_id=:sid AND organization_id=:org AND status='running'
AND (:all OR public_ref=ANY(CAST(:refs AS uuid[])))'''),
dict(sid=session_id, org=user.organization_id, code=code, all=refs is None, refs=refs or []))
def reconcile_startup(self):
from app.infrastructure.database import LIVE_REVISION
with transaction(self.engine) as conn:
if conn.execute(text('SELECT version_num FROM alembic_version')).scalar_one() != LIVE_REVISION:
raise ValueError('SCHEMA_UNAVAILABLE')
conn.execute(text('SELECT organization_id FROM organization_settings ORDER BY organization_id FOR UPDATE'))
result = conn.execute(text('''UPDATE live_sessions SET status='failed',closed_at=now(),
close_reason='API_RESTARTED',error_code='API_RESTARTED',updated_at=now()
WHERE status IN ('creating','connecting','connected')'''))
conn.execute(text("UPDATE tool_calls SET status='failed',completed_at=now(),error_code='ABANDONED' WHERE status='running'"))
return result.rowcount
+49
View File
@@ -0,0 +1,49 @@
"""Post-commit notifications marshal mutations onto the owning event loop."""
import asyncio
from dataclasses import dataclass, field
from threading import RLock
@dataclass
class Entry:
organization_id: object
epoch: int
auth_session_id: object
runtime: object
loop: asyncio.AbstractEventLoop
finished: asyncio.Event = field(default_factory=asyncio.Event)
ENTRIES = {}
_LOCK = RLock()
def register(session_id, organization_id, epoch, auth_session_id, runtime):
with _LOCK:
ENTRIES[session_id] = Entry(organization_id, epoch, auth_session_id, runtime, asyncio.get_running_loop())
def unregister(session_id):
with _LOCK:
entry = ENTRIES.pop(session_id, None)
if entry:
entry.finished.set()
def notify(*, organization_id=None, new_epoch=None, auth_session_id=None, session_id=None, code='CONTEXT_REVOKED'):
with _LOCK:
selected = [e for sid, e in ENTRIES.items()
if (organization_id is None or e.organization_id == organization_id)
and (new_epoch is None or e.epoch < new_epoch)
and (auth_session_id is None or e.auth_session_id == auth_session_id)
and (session_id is None or sid == session_id)]
async def fail(entry):
async with entry.runtime.lock:
entry.runtime.fail(code)
for entry in selected:
if not entry.loop.is_closed():
entry.loop.call_soon_threadsafe(lambda e=entry: asyncio.create_task(fail(e)))
return len(selected)
async def shutdown():
with _LOCK:
entries = list(ENTRIES.values())
for entry in entries:
async with entry.runtime.lock:
entry.runtime.fail('LIVE_SERVER_SHUTDOWN')
await asyncio.gather(*(e.finished.wait() for e in entries), return_exceptions=True)
+64 -23
View File
@@ -51,7 +51,7 @@ def provider_event_digest(event, limit):
item = event.get("item") item = event.get("item")
if isinstance(item, dict) and item.get("type") == "function_call": if isinstance(item, dict) and item.get("type") == "function_call":
event = dict(event, item=arguments(item)) event = dict(event, item=arguments(item))
elif kind == "response.done": elif kind in ("response.done", "provider.tools_requested"):
response = event.get("response") response = event.get("response")
if isinstance(response, dict) and isinstance(response.get("output"), list): if isinstance(response, dict) and isinstance(response.get("output"), list):
output = [arguments(item) if isinstance(item, dict) and item.get("type") == "function_call" output = [arguments(item) if isinstance(item, dict) and item.get("type") == "function_call"
@@ -158,7 +158,7 @@ class VoiceRuntime:
""" """
def __init__(self, adapter, service, runner, user_id, emit, *, def __init__(self, adapter, service, runner, user_id, emit, *,
authority_check=None, clock=time.monotonic, tool_seconds=None, authority_check=None, clock=time.monotonic, tool_seconds=None,
session_id=None, max_calls=None, settings=None, close_client=None): session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings() self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
if not isinstance(self.settings, RuntimeSettings): if not isinstance(self.settings, RuntimeSettings):
raise ValueError("Validated runtime settings required") raise ValueError("Validated runtime settings required")
@@ -168,6 +168,7 @@ class VoiceRuntime:
if (type(tool_seconds) not in (int, float) or not 0 < tool_seconds <= self.settings.tool_timeout_seconds if (type(tool_seconds) not in (int, float) or not 0 < tool_seconds <= self.settings.tool_timeout_seconds
or type(max_calls) is not int or not 1 <= max_calls <= self.settings.max_tool_calls): or type(max_calls) is not int or not 1 <= max_calls <= self.settings.max_tool_calls):
raise ValueError("Invalid backend tool deadline/call bound") raise ValueError("Invalid backend tool deadline/call bound")
self.tool_store = tool_store
self.close_client = close_client self.close_client = close_client
self.adapter, self.service, self.runner = adapter, service, runner self.adapter, self.service, self.runner = adapter, service, runner
self.user_id, self.emit, self.clock = user_id, emit, clock self.user_id, self.emit, self.clock = user_id, emit, clock
@@ -210,6 +211,7 @@ class VoiceRuntime:
self.intent_count = 0 self.intent_count = 0
self.provider_ready = False self.provider_ready = False
self.ready = False self.ready = False
self.ready_signal = asyncio.Event()
self.usable = True self.usable = True
self.failure = None self.failure = None
self.setup_deadline = None self.setup_deadline = None
@@ -495,6 +497,8 @@ class VoiceRuntime:
audio.state, audio.timer, audio.stall_deadline = "retired", None, None audio.state, audio.timer, audio.stall_deadline = "retired", None, None
async def start(self): async def start(self):
if hasattr(self.adapter, "backlog"):
self.adapter.backlog = lambda: sum(len(a.data) + a.reserved + a.credit for a in self.audio.values())
async with self.lock: async with self.lock:
if self._workers: if self._workers:
raise RuntimeError("Runtime already started") raise RuntimeError("Runtime already started")
@@ -522,9 +526,10 @@ class VoiceRuntime:
await self.handle(await self.adapter.receive()) await self.handle(await self.adapter.receive())
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except (ProviderProtocolError, ValueError, TypeError, RecursionError): except (ProviderProtocolError, ValueError, TypeError, RecursionError) as exc:
async with self.lock: async with self.lock:
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR") self.fail("LIVE_BUFFER_OVERFLOW" if getattr(exc, "overflow", False) else
"LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_PROVIDER_PROTOCOL_ERROR")
except Exception: except Exception:
async with self.lock: async with self.lock:
self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending() self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending()
@@ -554,9 +559,22 @@ class VoiceRuntime:
continue continue
if kind in ("response.create", "conversation.item.create") and owner: if kind in ("response.create", "conversation.item.create") and owner:
valid = await self.check_authority(owner) valid = await self.check_authority(owner)
failure = "CONTEXT_REVOKED"
if valid and self.tool_store:
try:
if kind == "conversation.item.create" and event["item"]["type"] == "function_call_output":
await self.tool_store.delivery(self.calls[event["item"]["call_id"]][1], owner.execution)
elif kind == "response.create":
origin = self.origin_intents.get(event["response"]["metadata"]["voice_intent"])
if origin:
for call in self.responses[origin].calls.values():
await self.tool_store.delivery(call, owner.execution)
except Exception as exc:
from app.modules.voice.durable_tools import failure_code
valid, failure = False, failure_code(exc)
async with self.lock: async with self.lock:
if not valid: if not valid:
self.fail("CONTEXT_REVOKED", turn=owner) self.fail(failure, turn=owner)
continue continue
if not self.check_deadlines() or owner is not self.current or owner.superseded: if not self.check_deadlines() or owner is not self.current or owner.superseded:
self.release_command(cmd) self.release_command(cmd)
@@ -593,9 +611,9 @@ class VoiceRuntime:
cmd = None cmd = None
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except Exception: except Exception as exc:
async with self.lock: async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None) self.fail("LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
finally: finally:
if cmd: if cmd:
async with self.lock: async with self.lock:
@@ -690,7 +708,7 @@ class VoiceRuntime:
responses = [r for r in self.responses.values() if r.turn is turn] responses = [r for r in self.responses.values() if r.turn is turn]
return (turn.initial and responses and return (turn.initial and responses and
not (self.pending_create and self.pending_create[1] is turn) and not (self.pending_create and self.pending_create[1] is turn) and
all(r.terminal and r.status == "completed" all(r.terminal and r.status in ("completed", "waiting_tools")
and (not r.calls or r.continued) for r in responses) and (not r.calls or r.continued) for r in responses)
and all(a.state == "retired" or ( and all(a.state == "retired" or (
a.done and a.generated == a.sent == a.played == 0 a.done and a.generated == a.sent == a.played == 0
@@ -787,7 +805,7 @@ class VoiceRuntime:
continue continue
if not response.terminal or any(c["result"] is None for c in response.calls.values()): if not response.terminal or any(c["result"] is None for c in response.calls.values()):
continue continue
if response.status != "completed": if response.status not in ("completed", "waiting_tools"):
self.fail("LIVE_PROVIDER_UNAVAILABLE") self.fail("LIVE_PROVIDER_UNAVAILABLE")
return return
for call_id, call in response.calls.items(): for call_id, call in response.calls.items():
@@ -1000,6 +1018,7 @@ class VoiceRuntime:
if entry: if entry:
if self.usable and event["type"] == "session_ready": if self.usable and event["type"] == "session_ready":
self.ready = True self.ready = True
self.ready_signal.set()
if self.usable and event["type"] == "audio_ended": if self.usable and event["type"] == "audio_ended":
self.audio[event["audio_ref"]].ended = True self.audio[event["audio_ref"]].ended = True
if (self.usable and entry.completed_transcript and entry.response and if (self.usable and entry.completed_transcript and entry.response and
@@ -1016,9 +1035,9 @@ class VoiceRuntime:
async with self.lock: async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False) self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False)
raise raise
except Exception: except Exception as exc:
async with self.lock: async with self.lock:
self.fail("LIVE_TRANSPORT_FAILED", turn=owner, writable=False) self.fail(getattr(exc, "live_code", "LIVE_TRANSPORT_FAILED"), turn=owner, writable=False)
finally: finally:
async with self.lock: async with self.lock:
if entry: if entry:
@@ -1104,6 +1123,8 @@ class VoiceRuntime:
async def handle(self, event): async def handle(self, event):
async with self.lock: async with self.lock:
if hasattr(self.adapter, "consumed"):
self.adapter.consumed()
if not self.check_deadlines(): if not self.check_deadlines():
return return
affected = None affected = None
@@ -1134,6 +1155,8 @@ class VoiceRuntime:
kind = event["type"] kind = event["type"]
if not isinstance(kind, str): if not isinstance(kind, str):
raise ValueError("Event type required") raise ValueError("Event type required")
if kind.startswith("provider.") and not getattr(self.adapter, "native_input_consumption", False):
raise ValueError("Unsupported native adapter event")
if not self.provider_ready and kind not in ("session.created", "session.updated", "error"): if not self.provider_ready and kind not in ("session.created", "session.updated", "error"):
raise ValueError("Event before readiness") raise ValueError("Event before readiness")
if kind == "session.updated": if kind == "session.updated":
@@ -1171,9 +1194,9 @@ class VoiceRuntime:
turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds
if turn.commit_ack: if turn.commit_ack:
self.acknowledge_input(turn) self.acknowledge_input(turn)
elif kind == "input_audio_buffer.committed": elif kind in ("input_audio_buffer.committed", "provider.input_consumed"):
self.acknowledge_input(self.inputs[event["item_id"]]) self.acknowledge_input(self.inputs[event["item_id"]])
elif kind in ("conversation.item.added", "conversation.item.created"): elif kind in ("conversation.item.added", "conversation.item.created", "provider.input_consumed_text"):
item = event["item"] item = event["item"]
turn = self.inputs.get(item["id"]) turn = self.inputs.get(item["id"])
if turn and turn.diagnostic is not None: if turn and turn.diagnostic is not None:
@@ -1224,8 +1247,10 @@ class VoiceRuntime:
or len(content) > 1 or or len(content) > 1 or
(content and content[0]["type"] != "audio")): (content and content[0]["type"] != "audio")):
raise ValueError("Unsupported output layout") raise ValueError("Unsupported output layout")
elif kind == "response.done": elif kind in ("response.done", "provider.tools_requested"):
wire = event["response"] wire = event["response"]
if wire["status"] == "waiting_tools" and kind != "provider.tools_requested":
raise ValueError("Invalid native tool phase")
response = self.responses[wire["id"]] response = self.responses[wire["id"]]
if response.terminal and response.status != wire["status"]: if response.terminal and response.status != wire["status"]:
raise ValueError("Conflicting terminal") raise ValueError("Conflicting terminal")
@@ -1262,7 +1287,7 @@ class VoiceRuntime:
raise ValueError("Terminal call-set mismatch") raise ValueError("Terminal call-set mismatch")
response.terminal, response.status = True, wire["status"] response.terminal, response.status = True, wire["status"]
self.wake.set() self.wake.set()
if wire["status"] not in ("completed", "cancelled"): if wire["status"] not in ("completed", "cancelled", "waiting_tools"):
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn) self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
elif wire["status"] == "cancelled" and not response.interrupted: elif wire["status"] == "cancelled" and not response.interrupted:
raise ValueError("Unexpected cancellation") raise ValueError("Unexpected cancellation")
@@ -1287,7 +1312,7 @@ class VoiceRuntime:
if estimate < 0 or estimate % 2: if estimate < 0 or estimate % 2:
raise ValueError("PCM alignment") raise ValueError("PCM alignment")
backlog = sum(len(a.data) + a.reserved + a.credit for a in self.audio.values()) backlog = sum(len(a.data) + a.reserved + a.credit for a in self.audio.values())
if audio.state != "finalizing" and backlog + estimate > self.settings.max_output_backlog_bytes: if audio.state != "finalizing" and backlog + estimate + getattr(self.adapter, "_audio_bytes", 0) > self.settings.max_output_backlog_bytes:
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn) self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn)
return return
decoded = base64.b64decode(encoded, validate=True) decoded = base64.b64decode(encoded, validate=True)
@@ -1349,7 +1374,8 @@ class VoiceRuntime:
response.transcript_parts[key] = fingerprint response.transcript_parts[key] = fingerprint
elif key in response.transcript_parts: elif key in response.transcript_parts:
raise ValueError("Transcript delta after completion") raise ValueError("Transcript delta after completion")
if not response.interrupted and not response.turn.superseded: if (not response.interrupted and not response.turn.superseded
and (response.turn is self.current or response.status == "completed")):
response.visible = True response.visible = True
entry = self.control(dict(type="transcript", turn_ref=response.turn.ref, role="assistant", entry = self.control(dict(type="transcript", turn_ref=response.turn.ref, role="assistant",
text=text, status="completed" if completed else "partial"), text=text, status="completed" if completed else "partial"),
@@ -1417,7 +1443,7 @@ class VoiceRuntime:
name=name, raw=raw, item=item_id, ref=str(uuid4())) name=name, raw=raw, item=item_id, ref=str(uuid4()))
self.calls[call_id] = (response, call) self.calls[call_id] = (response, call)
response.calls[call_id] = call response.calls[call_id] = call
if response.interrupted or response.turn.superseded: if response.interrupted or response.turn.superseded or response.turn is not self.current:
return return
ctx = ToolContext(response.turn.execution, self.clock() + self.tool_seconds, ctx = ToolContext(response.turn.execution, self.clock() + self.tool_seconds,
response.turn.cancelled) response.turn.cancelled)
@@ -1434,16 +1460,31 @@ class VoiceRuntime:
task.add_done_callback(self.tasks.discard) task.add_done_callback(self.tasks.discard)
async def _search(self, response, call, ctx, args): async def _search(self, response, call, ctx, args):
async def invoke():
try:
tool = create_search_tool(self.service, ctx, self.runner)
return await tool.ainvoke(args)
except asyncio.CancelledError:
raise
except Exception:
return self.runner.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
try: try:
tool = create_search_tool(self.service, ctx, self.runner) if self.tool_store:
result = await tool.ainvoke(args) external_id = next(cid for cid, c in response.calls.items() if c is call)
result = await asyncio.wait_for(self.tool_store.execute(external_id, call, ctx, args, invoke),
self.tool_seconds + 2 * self.settings.authority_timeout_seconds)
else:
result = await invoke()
except asyncio.CancelledError: except asyncio.CancelledError:
return return
except Exception: except Exception as exc:
result = self.runner.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed") from app.modules.voice.durable_tools import failure_code
async with self.lock:
self.fail(failure_code(exc), turn=response.turn)
return
async with self.lock: async with self.lock:
if (self.usable and not response.interrupted and not response.turn.superseded if (self.usable and not response.interrupted and not response.turn.superseded
and not ctx.cancelled.is_set()): and response.turn is self.current and not ctx.cancelled.is_set()):
call["result"] = result call["result"] = result
await self.release() await self.release()
+147
View File
@@ -0,0 +1,147 @@
"""Trusted maintenance tool for provisioning demo and operator accounts.
No public signup or user management UI is exposed; only trusted maintenance
commands or scripts provision accounts.
"""
import argparse
from getpass import getpass
import json
import sys
from uuid import UUID, uuid4
from argon2 import PasswordHasher
from sqlalchemy import text
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
def provision_user(
connection,
*,
username: str,
password: str,
role: str = "user",
organization_id: UUID | str | None = None,
is_enabled: bool = True,
) -> dict:
username = username.strip().lower()
if not username or len(username) > 120:
raise ValueError("Username must contain 1-120 characters")
if role not in ("admin", "user"):
raise ValueError("Role must be 'admin' or 'user'")
if not password:
raise ValueError("Password cannot be empty")
# If organization_id not provided, look up existing organization
if organization_id is None:
org_row = connection.execute(
text("SELECT id FROM organizations ORDER BY created_at ASC LIMIT 1")
).mappings().first()
if not org_row:
raise ValueError("No organization exists. Run bootstrap first.")
org_id = org_row["id"]
else:
org_id = UUID(str(organization_id))
org_row = connection.execute(
text("SELECT id FROM organizations WHERE id = :org_id"),
{"org_id": org_id}
).mappings().first()
if not org_row:
raise ValueError(f"Organization {organization_id} not found.")
password_hash = PasswordHasher().hash(password)
# Check if user already exists
existing = connection.execute(
text("SELECT id, organization_id, role, is_enabled FROM users WHERE username = :username"),
{"username": username}
).mappings().first()
if existing:
if existing["organization_id"] != org_id:
raise ValueError("Username belongs to another organization")
user_id = existing["id"]
connection.execute(
text("""
UPDATE users
SET password_hash = :hash, role = :role, is_enabled = :enabled, updated_at = now()
WHERE id = :id AND organization_id = :org_id
"""),
{"id": user_id, "org_id": org_id, "hash": password_hash, "role": role, "enabled": is_enabled}
)
return {
"status": "updated",
"user_id": str(user_id),
"organization_id": str(existing["organization_id"]),
"username": username,
"role": role,
"is_enabled": is_enabled,
}
else:
user_id = uuid4()
connection.execute(
text("""
INSERT INTO users (id, organization_id, username, password_hash, role, is_enabled)
VALUES (:id, :org_id, :username, :hash, :role, :enabled)
"""),
{
"id": user_id,
"org_id": org_id,
"username": username,
"hash": password_hash,
"role": role,
"enabled": is_enabled,
}
)
return {
"status": "created",
"user_id": str(user_id),
"organization_id": str(org_id),
"username": username,
"role": role,
"is_enabled": is_enabled,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--username", required=True, help="Username (1-120 characters)")
parser.add_argument("--role", default="user", choices=["admin", "user"], help="User role")
parser.add_argument("--organization-id", help="Organization UUID (defaults to first org)")
parser.add_argument("--disabled", action="store_true", help="Provision user as disabled")
parser.add_argument("--password-stdin", action="store_true", help="Read password from stdin")
args = parser.parse_args()
if args.password_stdin:
password = sys.stdin.readline().rstrip("\r\n")
else:
if not sys.stdin.isatty():
parser.error("Use an interactive terminal or explicitly select --password-stdin")
password = getpass("Account password: ")
if password != getpass("Confirm password: "):
parser.error("Passwords do not match")
engine = None
try:
settings = IngestionSettings()
engine = create_database(settings.database_url.get_secret_value())
with engine.begin() as connection:
result = provision_user(
connection,
username=args.username,
password=password,
role=args.role,
organization_id=args.organization_id,
is_enabled=not args.disabled,
)
print(json.dumps(result))
except Exception as exc:
parser.exit(1, f"Account provisioning failed: {exc}\n")
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
main()
+16 -17
View File
@@ -1,4 +1,4 @@
"""Operator-only diagnostic Realtime/search smoke; no HTTP/text-chat route.""" """Operator-only diagnostic Gemini/search smoke; no HTTP/text-chat route."""
import argparse import argparse
import asyncio import asyncio
from dataclasses import asdict from dataclasses import asdict
@@ -7,12 +7,9 @@ from pathlib import Path
import sys import sys
from uuid import UUID from uuid import UUID
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import text from sqlalchemy import text
from app.infrastructure.database import create_database, check_compatibility from app.infrastructure.database import create_database, check_compatibility
from app.infrastructure.realtime import RealtimeAdapter, connect
from app.modules.documents.settings import IngestionSettings from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.calibration import load_cutoff from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.langchain_tool import SearchToolRunner from app.modules.knowledge.langchain_tool import SearchToolRunner
@@ -21,13 +18,7 @@ from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json from app.modules.voice.serialization import bounded_json
class VoiceSettings(BaseSettings): from app.modules.voice.configuration import VoiceSettings
model_config = SettingsConfigDict(env_file=".env", extra="ignore", hide_input_in_errors=True)
openai_api_key: SecretStr
openai_realtime_model: str = Field(default="gpt-realtime-mini", min_length=1)
openai_proxy: str | None = None
runtime_settings: RuntimeSettings = Field(default_factory=RuntimeSettings)
search_calibration_report: Path
def preflight(engine, settings, actor, cutoff): def preflight(engine, settings, actor, cutoff):
if cutoff.profile != asdict(settings.embedding_profile): if cutoff.profile != asdict(settings.embedding_profile):
@@ -59,15 +50,20 @@ async def run(service, runner, actor, config, query, seconds, max_calls):
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr) print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
return 1 return 1
async def create_adapter(config, limits):
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
config.require_voice()
transport = await connect_gemini(config.gemini_api_key.get_secret_value(), config.gemini_model, config.gemini_proxy, limits)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
return adapter
async def _run(service, runner, actor, config, query, max_calls, limits): async def _run(service, runner, actor, config, query, max_calls, limits):
transport = await connect(config.openai_api_key.get_secret_value(), adapter = await create_adapter(config, limits)
config.openai_realtime_model, config.openai_proxy,
limits)
async def emit(event): async def emit(event):
if isinstance(event, bytes): if isinstance(event, bytes):
return # No playback assertion: diagnostic smoke never claims heard audio. return # No playback assertion: diagnostic smoke never claims heard audio.
print(bounded_json(event, limits.max_server_event_bytes), flush=True) print(bounded_json(event, limits.max_server_event_bytes), flush=True)
runtime = VoiceRuntime(RealtimeAdapter(transport, model=config.openai_realtime_model, settings=limits), runtime = VoiceRuntime(adapter,
service, runner, actor, emit, max_calls=max_calls, service, runner, actor, emit, max_calls=max_calls,
settings=limits) settings=limits)
receiver = None receiver = None
@@ -98,7 +94,7 @@ async def _run(service, runner, actor, config, query, max_calls, limits):
actual = [(cid, r, c) for cid, (r, c) in runtime.calls.items() actual = [(cid, r, c) for cid, (r, c) in runtime.calls.items()
if r.turn is current] if r.turn is current]
if (not actual or any(not c["sent"] or c["result"] is None or if (not actual or any(not c["sent"] or c["result"] is None or
not r.terminal or r.status != "completed" or r.interrupted not r.terminal or r.status not in ("completed", "waiting_tools") or r.interrupted
for _, r, c in actual)): for _, r, c in actual)):
continue continue
chain, cursor = set(), answer chain, cursor = set(), answer
@@ -133,7 +129,7 @@ def main(argv=None):
parser.add_argument("--user-id", type=UUID, required=True) parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True) parser.add_argument("--query", required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True, parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize Realtime plus up to --max-tool-calls query embeddings") help="Authorize Gemini Live plus up to --max-tool-calls query embeddings")
parser.add_argument("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600") parser.add_argument("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600")
parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10") parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
args = parser.parse_args(argv) args = parser.parse_args(argv)
@@ -143,6 +139,9 @@ def main(argv=None):
if not args.query.strip() or len(args.query) > 2000: if not args.query.strip() or len(args.query) > 2000:
raise ValueError("Bounded query required") raise ValueError("Bounded query required")
settings, config = IngestionSettings(), VoiceSettings() settings, config = IngestionSettings(), VoiceSettings()
config.require_voice()
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"))) cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding="utf-8")))
if settings.embedding_timeout_seconds > 75: if settings.embedding_timeout_seconds > 75:
raise ValueError("Smoke embedding timeout must not exceed 75 seconds") raise ValueError("Smoke embedding timeout must not exceed 75 seconds")
+53
View File
@@ -1,5 +1,16 @@
# Phase 1 agent reference map # Phase 1 agent reference map
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](guides/realtime-agent-phase2-repair.md).
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current voice contract amended 2026-10-08 by Realtime Phase 0; English revision 1.3 remains the broader scope baseline. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence. Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current voice contract amended 2026-10-08 by Realtime Phase 0; English revision 1.3 remains the broader scope baseline. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence.
## Authority and document resolution ## Authority and document resolution
@@ -1818,3 +1829,45 @@ and fixture-correction reruns are recorded separately in the guide.
Real provider, browser playback/Persian speech and isolated PostgreSQL acceptance Real provider, browser playback/Persian speech and isolated PostgreSQL acceptance
remain unrun. Existing authorization, actor/corpus/profile/calibration gates and remain unrun. Existing authorization, actor/corpus/profile/calibration gates and
fail-closed cancellation classification still apply; no Phase 2 work was added. fail-closed cancellation classification still apply; no Phase 2 work was added.
## Current Phase 2 repair inventory (2026-10-09)
- Deployment configuration: `app/modules/voice/configuration.py`; finite limits
remain in `app/modules/voice/settings.py`.
- Cookie auth and C01/V01-V04/WSS: `app/api/v1/auth.py`, `dependencies.py`,
`conversations.py`, `live.py`; bounded blocking work in
`app/infrastructure/blocking.py`; application lifecycle in `app/main.py`.
- Durable admission/completion: `app/modules/voice/lifecycle.py`,
`durable_tools.py`; post-commit loop notifications in `registry.py`.
- Forward owner-chain repair: `migrations/versions/0005_live_owner_chain.py`.
Revisions 0001-0004 are preserved.
- Gemini adapter: `app/infrastructure/gemini_live.py`; shared canonical search,
StructuredTool and SearchToolRunner are retained.
- Exercised developer audio example: `examples/voice-client.js`,
`examples/voice-audio-worklet.js`; guide linked in the repair report.
- This Linux environment uses `.venv/bin/python`, not the historical Windows
`.venv/Scripts/python`. Existing timeout validation creates a local socket;
sandbox denial must be distinguished from an application validation defect.
Exact executed checks, remaining provider limitations and preservation evidence
are recorded in the [Phase 2 repair report](guides/realtime-agent-phase2-repair.md).
## Remaining Phase 2 defects checkpoint (2026-10-09)
The [current repair record](guides/realtime-agent-phase2-repair.md#remaining-defect-repair-2026-10-09)
supersedes affected initial Phase 2 behavior. Native pending generations retain
their input identity; ambiguous overlapping speech closes safely. Gemini PCM
admission uses packed bounded slabs separately from controls and shares the
runtime aggregate backlog. Durable canonical technical errors coalesce/replay
with fresh eligibility checks. Legacy creation hashes are verified against
persisted payload/configuration before atomic normalization; migrations 0001-0005
remain immutable. The delivered VoiceClient now owns resources by connection
generation, coordinates V04 before transport teardown, and attempts logout
independently of close failure. Partial application startup always cleans up.
Regression sources add `tests/unit/test_phase2_remaining.py` and executable
`tests/support/voice_client_harness.mjs`. Actual client/ASGI/PostgreSQL close
acceptance uses a local transport bridge; Node executes the delivered client and
worklet. Exact results and unrun real-provider/browser prerequisites are in the
repair record. No selected-model multi-turn or frontend readiness claim is made.
@@ -0,0 +1,73 @@
# Authenticated Gemini voice integration
Gemini Live is temporarily the sole voice provider because an OpenAI Realtime
voice key is unavailable. Extraction, embeddings, calibration and canonical
search retain their existing providers and frozen profiles. The browser never
receives a provider credential, event, model selector or private call ID.
Use the [client module](../../examples/voice-client.js) and
[audio worklet](../../examples/voice-audio-worklet.js), served on the configured
same origin. This is a developer example, not a production interface.
```js
import {VoiceClient} from './voice-client.js';
const client = new VoiceClient(event => console.log(event.type));
await client.login(username, password); // supply credentials from your local form
await client.reserve(); // retain request IDs for identical retries/recovery
await client.connect(); // call from a user gesture permitting AudioContext
// On explicit stop: await client.close(); await client.poll();
// On media loss: await client.recover(); await client.freshSession();
// On logout: await client.logout();
```
`GET /api/v1/me` refreshes actual expiry and CSRF. HTTP mutations use the opaque
cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin.
The API accepts no bearer or query token. Preserve the same normalized payload
and request ID after ambiguous creation; V03 recovers without opening Gemini.
Connected/terminal recovery does not restore media/provider context. Close the
old reservation before requesting a fresh conversation and session.
The exercised schemas are `session_ready`, `transcript` (role user/assistant,
status partial/completed), `sources`, `user_speech_started`, `audio_started`,
`audio_ended`, `turn_interrupted`, `error`, and the sole client control
`playback_progress` with `audio_ref` and cumulative `played_ms`. Transcripts
and sources are retrieved/current-session information, not durable full history.
The client waits for `session_ready` before opening the microphone. It verifies
an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes
channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context
rates fail explicitly. Sending is bounded by WebSocket buffered bytes. Ordered
binary playback belongs to the last audio_started reference and is sealed by
audio_ended. The playback worklet bounds samples and reports the floor of actual
consumed samples / 24, never estimated elapsed time or generated samples.
Interruption flushes queued audio and reports each reference's final consumed
position. Explicit close stops capture and tracks, flushes actual final playback progress
while the socket is usable, commits HTTP V04, and then closes transport/audio.
Requests wait at most five seconds each, flush at most 250 ms and AudioContext
close at most one second; a genuine transport loss stays a failure.
Connection generations own their audio, tracks and callbacks. Late permission
results are stopped immediately, cleanup is coalesced, and callbacks from an old
socket cannot close a newer session. Logout always attempts A02 even if identity
refresh or V04 fails, then clears local resources and identity. Valid sessions
retain CSRF enforcement; expired/repeated logout still validates Origin.
Canonical search errors for an eligible turn are displayed while its authorized
spoken explanation and later interaction continue. Setup/transport/overflow,
authority and context synchronization failures stop resources. Error fatality is
not inferred from retryable alone. The client does not retry tool execution.
Identical durable technical results replay only after fresh backend eligibility
checks; cancelled/revoked/stale-parent results cannot continue.
Gemini setup readiness requires native setupComplete, not an echoed requested
configuration. This profile requires native voiceActivity with usable offsets;
missing boundaries fail safely. Input transcripts without offsets become
ambiguous after more than one input; that fails rather than rebinding delayed
speech. Output transcripts use outputTranscription. There is no verified
sample-level Gemini context truncation: interruption/context cleanup closes the
session and requires freshSession. Seamless barge-in is not certified. Diagnostic text smoke uses native clientContent; first correlated model/tool
output proves input consumption. It never fabricates an item acknowledgement.
Technical fake-wire/worklet checks, retrieval quality and real-browser speech
acceptance are separate. Real microphone/Persian audio/network behavior remains
unverified until explicit provider opt-in, approved corpus, measured compatible
calibration and budgets are supplied. See the [repair report](realtime-agent-phase2-repair.md).
+11
View File
@@ -1,5 +1,16 @@
# Realtime Phase 1 operator/runtime integration # Realtime Phase 1 operator/runtime integration
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](realtime-agent-phase2-repair.md).
Phase 1 adds the private [wire adapter](../../app/infrastructure/realtime.py), Phase 1 adds the private [wire adapter](../../app/infrastructure/realtime.py),
[application runtime](../../app/modules/voice/runtime.py), [application runtime](../../app/modules/voice/runtime.py),
[operator smoke command](../../app/voice_smoke.py) and [operator smoke command](../../app/voice_smoke.py) and
+317
View File
@@ -0,0 +1,317 @@
# Phase 2 repair and acceptance record
Initial repair checkpoint: 2026-10-09. The [remaining-defect repair](#remaining-defect-repair-2026-10-09)
below supersedes affected behavior and validation totals. Gemini Live is the temporary sole voice provider
because an OpenAI Realtime voice key is unavailable. This decision changes voice
only. Extraction, embeddings, frozen profiles, calibration inputs, the canonical
search pipeline and the shared bounded SearchToolRunner are preserved.
The implementation and technical acceptance below are distinct from real Gemini
access, retrieval quality and browser/Persian voice acceptance. This report does
not certify frontend readiness or seamless interruption.
## Findings → fixes → regressions
| Finding / work package | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| Credentials/model read from RuntimeSettings; hardcoded calibration status path (1) | Validated VoiceSettings supplies Gemini credentials, configured model/voice/proxy, exact origins/hosts, explicit cookie security, lifetimes and measured report path. RuntimeSettings retains finite bounds. Reservation snapshots actual voice, calibration and embedding metadata and revisions. No OpenAI voice key is required. | Configuration rejection/selection tests in test_phase2_lifecycle; actual configured Gemini operator test in test_gemini_live; real reservation/stream in test_phase2_postgres. |
| Synthetic configuration and tool terminal acknowledgements; missing correlation (2) | Native setupComplete confirms setup without copying requested settings. Native voiceActivity offsets identify inputs; first correlated native output proves consumption. Native tool requests produce a private waiting_tools phase, not a fabricated terminal event. Matching toolResponse IDs carry complete canonical results once, with bounded translation and duplicate admission. Native outputTranscription supplies assistant transcripts. | Actual Gemini adapter + VoiceRuntime + canonical SearchService + StructuredTool/shared runner unit cases; actual ASGI/durable tool cases for ok/no_evidence/error. |
| Audio format mismatch and unsafe interruption (2/7) | Browser PCM16LE mono remains 24 kHz. Bounded streaming 2/3 FIR conversion supplies 16 kHz Gemini input; output MIME/rate/alignment are verified. Unsupported cancellation/truncation closes context safely and suppresses late output. Provider loss independently wakes and closes reception. | Resampler partition/count tests; provider-loss/frame/queue/context-error tests; blocked-browser cleanup and setup-loss PostgreSQL/ASGI cases. |
| Permissive auth/CORS/token transports and malformed CSRF (3) | Cookie-only opaque sessions store hashes; constant-time bounded CSRF checks; exact configured Host/Origin; restricted credentialed CORS; explicit Secure/HttpOnly/SameSite policy. Canonical /me returns real expiry. Valid logout needs CSRF; missing/expired/repeated logout clears cookies after Origin. Bounded global login/provider admission. Strict DTOs and safe correlated HTTP envelopes. | Malformed token/CSRF/Origin/DTO unit tests; actual login/me/logout/replay/security/expiry and query-token rejection against PostgreSQL. |
| Missing owner chain and concurrent creation/expiry races (4) | Forward 0005 adds conversation/auth owner-chain constraints and distinct public tool references. Settings-first serialization rechecks enabled actor/auth/owner/epoch/expiry inside admission. Same normalized creation replays; changed payload conflicts; competing reservations are busy. Expired rows/calls terminalize before replacement. V03 is owner-only and never opens a provider. | Independent connections and start barriers for identical/changed C01/V01, competing reservations and tool admission; actual wrong-owner/auth FK rejection, expiry replacement and V03 replay tests. |
| Persistence inferred from sources and ON CONFLICT-only dispatch (5) | DurableTools wraps actual validated StructuredTool invocation. Insert owns execution; running duplicates poll shared durable completion; completed duplicates replay only after fresh checks; conflicts never retrieve. Full canonical results/revisions/epochs are persisted. Completion is fenced against call/parent/auth/expiry/epoch and cancellation. Result/source/continuation delivery rechecks eligibility. | Real duplicate completion with one invocation; conflicting arguments; cancellation/close/logout/restart/selection late completion tests; actual ASGI persistence and matching private/public identities. |
| Saved evidence exposed without redaction (6) | Poll returns at most 20 rows ordered deterministically by timestamp/id, chronological, with public UUID references and normalized diagnostics. Current document/chunk scope and ready/active/undeleted availability govern excerpts; unavailable identities remain, excerpts are redacted. | Real revoked-source redaction and public-reference test. |
| Snapshot-only authority, blocked receive, stranded media guard and readiness races (7) | Persisted session and per-turn SearchExecution authority is captured/rechecked. One media guard covers acceptance/setup/stream/cleanup. Independent cleanup survives ASGI cancellation. Browser/provider/runtime/expiry/revocation/shutdown are supervised. connected_at follows native setup plus successful application readiness delivery. Immediate post-ready PCM waits for the verified readiness transition. | Real authenticated ASGI first-frame/tool cases; provider loss while browser blocks; HTTP close/logout/disablement/auth and Live expiry/epoch/shutdown; duplicate media before setup; failed acceptance and setup-loss tests. |
| Thread-unsafe notifications and swallowed startup reconciliation (8) | Logout/selection transactionally terminalize running calls; selection stales old conversations. Post-commit notifications marshal to owning loops and filter pinned epochs. Persisted checks also cover separate maintenance processes. Startup requires 0005/reconciliation and never advertises readiness on failure. DB/password work is off audio reception through bounded blocking admission; shutdown bounds waits and disposes resources. | Notification thread/epoch unit test; actual selection/completion race, restart/logout and dropped-table startup failure; actual shutdown cleanup. |
| Incomplete/mismatched frontend example and cross-org provisioning (9) | Executable client/audio worklet implements aligned capture, bounded sending/playback, actual consumed-sample progress, final flush and cleanup, login/expiry/CSRF, replay/poll/recovery and fresh-session behavior. Provisioning refuses an existing username in another organization before any password/role/enablement update. | Node executes capture/playback/flush accounting; JS syntax checks; frozen schemas exercised by actual ASGI tests; real cross-org account preservation test. |
| Invalid PostgreSQL fixtures and sequential “concurrency” claims (10) | Phase 2 fixtures use actual accounts/password hashes/auth rows/settings and deterministically published ready documents/chunks. Independent SQLAlchemy connections and synchronization barriers test real constraints and races. Remote Gemini/embedding transports are deterministic; the lifecycle/runtime/tool/search boundaries are real. | Mandatory isolated PostgreSQL/pgvector suite and targeted provider-free suite below. |
## Files and boundaries
- Configuration/auth: [.env.example](../../.env.example),
[configuration.py](../../app/modules/voice/configuration.py),
[auth service](../../app/modules/auth/service.py),
[auth routes](../../app/api/v1/auth.py),
[dependencies](../../app/api/v1/dependencies.py),
[provisioning](../../app/provision.py).
- Lifecycle/transport: [forward migration](../../migrations/versions/0005_live_owner_chain.py),
[database compatibility](../../app/infrastructure/database.py),
[lifecycle](../../app/modules/voice/lifecycle.py),
[durable tools](../../app/modules/voice/durable_tools.py),
[registry](../../app/modules/voice/registry.py),
[blocking execution](../../app/infrastructure/blocking.py),
[conversation routes](../../app/api/v1/conversations.py),
[Live routes](../../app/api/v1/live.py), [application](../../app/main.py).
- Provider/runtime: [Gemini adapter](../../app/infrastructure/gemini_live.py),
[runtime](../../app/modules/voice/runtime.py), [operator smoke](../../app/voice_smoke.py).
The existing [search service](../../app/modules/knowledge/service.py) changes
only selection invalidation; retrieval remains the same.
- Handoff: [frontend guide](frontend-voice-integration-example.md),
[client](../../examples/voice-client.js), [worklet](../../examples/voice-audio-worklet.js).
Narrow current-provider notices update the reference map, plan, current operator
guide and API/database/implementation specifications; historical evidence remains.
- Regressions: test_gemini_live.py, test_phase2_auth.py,
test_phase2_lifecycle.py, test_voice_client_example.py and
tests/integration/test_phase2_postgres.py. Existing operator tests in
test_realtime_phase1.py/test_realtime_repairs.py inject the private adapter
factory, preserving their provider-neutral runtime assertions.
No deferred text/history tables, production UI, provider selector, Redis, new
agent framework, retrieval replacement or document-content versioning is added.
## Exact checks and outcomes
Commands run from the repository root. This Linux environment has
`.venv/bin/python`; the historical Windows `.venv/Scripts/python` does not exist.
Tests require normal local socket creation for the existing timeout validation
probe, so they ran outside the network-restricted shell sandbox. No remote AI
calls were made.
- Targeted final provider-free command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **358 passed**, zero skips.
- Final targeted PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **41 passed**, zero skips, isolated database with pgvector.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1604 passed**, two existing Windows path-alias skips,
352 PostgreSQL cases deselected.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **352 passed**, zero skips, 1606 provider-free cases deselected.
The final affected PostgreSQL rerun also passed all **41** cases after the
bounded duplicate-wait and authority-diagnostic refinements.
- Missing-configuration gate:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=no`
— expected exit 1 / one fixture error. This is prerequisite evidence only.
- `.venv/bin/python -m pip check` — unavailable: this environment has no pip.
Fallback `UV_CACHE_DIR=/tmp/phase2-uv-cache uv pip check --python .venv/bin/python`
— **61 packages checked; all compatible**.
- `.venv/bin/python -m app.voice_smoke --help` — passed, explicit provider opt-in
and bounded call/time arguments retained. No real smoke call was authorized.
- `node --input-type=module --check < examples/voice-client.js` and
`node --check examples/voice-audio-worklet.js` — passed.
- `git diff --check`, scoped new-file whitespace/UTF-8, Python ASTs (UTF-8-sig
for existing BOM files), TOML, links and SHA-256 preservation — **passed**. Final inspection covers all scoped tracked and new files:
27 intended baseline changes, nine new files and 175 byte-identical baseline files.
CLI help for app.provision and safe missing-Gemini-key/calibration capability
preflight also passed.
Initial checks exposed and corrected actual readiness/cleanup races. Other
failed runs were kept separate: sandbox denied the existing socket-timeout
probe; early ASGI fixtures used TestClient's untrusted default WebSocket host;
login admission persisted across test lifespans; a no-evidence fixture changed
its cutoff without updating the pinned snapshot. Fixtures now use explicit
trusted WebSocket URLs, isolated limiter state, valid measured-fixture snapshots
and cleanup barriers. None of these fixture repairs weakens production policy.
## Preservation and environment
Before editing, SHA-256 inventory captured **202 existing repository files**;
**27 intended baseline files changed, 175 remained byte-identical**. The manifest
is `/tmp/phase2-preservation.json`. Protected migrations 0001-0004 are unchanged;
0001-0003 also match HEAD. Revision 0004 was initially untracked and is treated
as potentially applied. Only forward 0005 repairs persisted ownership.
The initially modified pyproject.toml and test_migrations.py remain byte-identical
to the start-of-task baseline. The shared runner, RealtimeAdapter, RuntimeSettings,
proof scripts, frozen calibration/evaluation inputs and captured original documents
are unchanged. Unrelated working-tree edits are retained. No real ingestion,
calibration, embedding or voice calls were executed. Ignored external originals
and credentials were not edited; the manifest does not claim hashes for files
excluded from its initial repository inventory.
The system filesystem filled during implementation and prevented sandbox mounts.
Disposable repository/venv bytecode was removed; the venv temporarily moved to
/tmp and was restored at its original path. The user explicitly approved removal
of regenerable pip/uv caches outside the repository. Source and document content
were preserved. Acceptance uses a task-created PostgreSQL container/database with
application schemas isolated from public; final cleanup is recorded below.
## Remaining Gemini capabilities and external prerequisites
The existing intended configured Gemini model is preserved, including environment
overrides. Model availability and its actual native event layouts have **not**
been proven by live access. SetupComplete proves setup completion; it does not
return an echoed configuration. Native voiceActivity must contain usable audio
coordinates; absent/unsupported boundaries fail safely before tool/output release.
Input transcripts with offsets can retain their original turn; after multiple
inputs, missing coordinates are ambiguous and close rather than guess a binding.
Partial user transcription is supported without inventing a final ASR ack.
Mixed audio/tool phases without a safe layout also fail closed.
Google documents native [Live messages, activity, setup and tools](https://ai.google.dev/api/live)
and [audio formats/capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
These provide no verified sample-level unheard-audio context truncation for this
selected profile. Cancellation/truncation or native interruption therefore closes
and requires a fresh session. No synthetic terminal/cancel/truncate/input-commit
acknowledgement or seamless continuation claim is made.
Real calibrated retrieval quality, selected-model tool/transcription/event
behavior, Persian speech, latency, microphone/playback/hardware timing and full
browser acceptance are **unrun**. They require explicit real-provider opt-ins,
approved inputs/corpus, a measured profile-compatible calibration report and
budgets. The Node worklet test proves accounting/capture code, not heard audio;
ASGI tests prove application wiring with deterministic remotes, not Google service
availability. Final API shutdown waits are bounded; already-running synchronous
search work retains its runner slot until its actual bounded provider/database
work completes. Threads are not forcibly terminated or reported as erased.
Deploy forward 0005 before admission. It refuses preexisting inconsistent owner
chains rather than silently reassigning them. Configure production HTTPS trusted
origins/hosts, Secure cookies, Gemini access and the measured report. HTTP local
development requires explicit loopback-only COOKIE_SECURE=false. Health never
calls an AI provider. No production deployment was performed.
## Final cleanup
Acceptance used `pgvector/pgvector:pg17` in the task-created
`rag-phase2-acceptance` container, a loopback-only port and tmpfs database data.
TEST_DATABASE_URL pointed only to `rag_phase2_test`, with disposable application
schemas isolated from public. Before removal, queries confirmed **zero disposable
application schemas and zero public application tables**. The task-created
container/volumes were removed; preexisting containers were preserved. Temporary
logs and preservation inventories remain under /tmp for this session. No shared
or production database was migrated, reconciled or altered.
## Remaining-defect repair (2026-10-09)
This checkpoint supersedes the affected initial behavior above. Gemini remains
selected; model, voice, native interruption safe-close policy, browser 24 kHz
mono PCM16LE, public events/HTTP schemas and canonical search outcomes are
unchanged. No new migration or dependency is necessary.
### Verified findings, repairs and regressions
| Requested finding | Repair and observable coverage |
| --- | --- |
| 1. Pending input/generation rebound | A second distinct activity start while the first input/generation remains unfinished fails `LIVE_CONTEXT_SYNC_FAILED` before replacing its identity or releasing old output. Native completion allows ordinary sequential turns in deterministic tests. Runtime dispatch/result/transcript gates recheck turn eligibility; normally completed delayed transcripts remain eligible under the frozen contract. Delayed user transcription with coordinates retains its original input; ambiguous optional offsets still fail closed. `test_pending_input_cannot_be_replaced_before_first_output`, `test_actual_runtime_suppresses_delayed_first_output_after_new_speech`, and `test_sequential_native_turns_and_delayed_transcript_keep_original_identity`. |
| 2. Audio charged to controls | Adapter audio uses decoded, packed <=9600-byte slabs, with the existing aggregate 1440000-byte backlog, 512-slab and 65536-byte metadata bounds. A transfer reservation connects adapter backlog with runtime G/T/R; controls retain their independent count/byte admission and native FIFO order. Scratch bounds apply before decoding. Tiny adjacent deltas coalesce; capacity failure normalizes to `LIVE_BUFFER_OVERFLOW`. Tests admit a five-second burst, 120000 two-byte deltas, exact aggregate boundary, interleaved controls, slow consumption and actual runtime pacing. |
| 3. Client asynchronous ownership | Each connection generation owns its AudioContext, nodes, socket, callbacks, readiness and tracks. Cancellation checks follow preparation/readiness/acquisition; stale returned tracks stop immediately. Cleanup coalesces and remains idempotent; old callbacks cannot mutate a newer session. Executable VoiceClient scenarios cover pending permission, resolution during flush, acquisition rejection, preparation cancellation, concurrent cleanup, stale callbacks and a stalled AudioContext close promise. |
| 4. Canonical technical-error replay | A failed row containing a recognized canonical technical error with matching saved error code is eligible for coalesced/replayed completion after fresh authority, epoch, parent and source checks. Cancellation/revocation/abandonment never becomes eligible through a saved error. PostgreSQL barrier tests prove one invocation and equivalent original, running-duplicate and completed-duplicate results for `SEARCH_TIMEOUT`, `SEARCH_FAILED` and `PROVIDER_UNAVAILABLE`; logout and saved cancellation remain ineligible. Existing late-completion/source revocation regressions continue to run. |
| 5. Duplicate activity drops content | Duplicate START/END suppresses only boundary handling; accompanying native transcription, audio, tool requests and completion still run. Conflicting coordinates fail safely. Eight combined-message cases plus conflicting-coordinate coverage exercise the actual adapter. |
| 6. Nonterminal client errors | Eligible canonical search failures are displayed while authorized explanation and subsequent interaction continue. Setup, transport, overflow, authority and synchronization failures stop resources; socket close is independently terminal. Classification uses known contract codes and turn/readiness context, not `retryable` alone. Executable VoiceClient scenarios prove speech continuation and fatal cleanup. |
| 7. Logout depends on close | A02 is attempted independently when identity refresh or V04 fails. Local identity/resources clear afterward. Valid CSRF/Origin enforcement is unchanged. Executable client tests cover expired/revoked identities, close failure, valid and repeated logout; actual HTTP expired/repeated/valid logout acceptance remains in the PostgreSQL suite. |
| 8. Explicit close races transport | Capture stops and playback flushes actual final progress before V04; intentional socket teardown follows the HTTP operation. HTTP waits are bounded at five seconds each, flush at 250 ms, AudioContext-close waiting at one second. Actual Node VoiceClient/ASGI/PostgreSQL cases cover silent and active-playback close. The active case executes the delivered playback worklet, consumes 120 samples and sends its actual 5 ms progress. Both preserve `closed/user_requested`; existing genuine transport-loss/terminal-state tests remain. Hardware and Google transport are deterministic doubles. |
| 9. Blanket revocation diagnostics | Execution and delivery classify authority loss, cancellation, changed arguments, technical timeout, busy admission and SQL availability separately. No unverified result or continuation is released. Delivery mismatch is a context synchronization failure. Real SQL fault injection through ASGI proves `DEPENDENCY_UNAVAILABLE`, a durably failed session and zero toolResponse; runtime execution/delivery cases assert normalized failures rather than false revocation. |
| 10. Repair-upgrade replay | Verified original creation hashes are accepted only if the original persisted payload/pinned configuration also matches. Under the existing settings lock they normalize atomically to the current format. Representative rows at revision 0004 upgrade through immutable 0005 and replay with the same IDs, including null, empty, Unicode and original whitespace titles. Changed payloads, null/empty collisions and unknown hashes still conflict. No ownership, provider/model snapshot or row is reassigned/discarded. |
| 11. Partial lifespan leaks | Engine acquisition, lifecycle construction and reconciliation are inside cleanup ownership. Startup failure/cancellation leaves readiness false, disposes acquired engine, closes runner, clears service globals and shuts down blocking admission. Independent cleanup preserves the original startup error even if disposal also fails. Tests cover failure, cancellation, normal shutdown and subsequent startup, including an actual running bounded worker that retains its slot until completion. No thread is claimed forcibly terminated. |
Regression sources are [native/runtime/startup tests](../../tests/unit/test_phase2_remaining.py),
[executed client/worklet tests](../../tests/unit/test_voice_client_example.py),
[client harness](../../tests/support/voice_client_harness.mjs), and
[PostgreSQL/ASGI acceptance](../../tests/integration/test_phase2_postgres.py).
The harness loads the delivered [VoiceClient](../../examples/voice-client.js)
and [worklet](../../examples/voice-audio-worklet.js); it does not replace the
client implementation with a test-only imitation.
### Original hash evidence and upgrade limits
The earlier-session tool inspection at `2026-10-09T09:04:03.658Z` retained the
original lifecycle source. Its algorithm is SHA-256 over sorted compact JSON,
`ensure_ascii=False`, encoded as UTF-8. Original C01 fields were
`{user, request, mode, title: title or ""}`; original V01 fields were
`{owner, conversation_id, client_request_id, provider, model}`. Current C01
hashes normalized mode/title; current V01 hashes conversation identity only.
Compatibility reconstructs only those verified formats. C01 also compares the
original stored title exactly, preventing null/empty hash collisions from
weakening conflict detection. V01 uses the persisted provider/model, not current
configuration. Unknown hashes still fail. The tests upgrade isolated schemas;
no shared database or migration file was changed. Normal startup reconciliation
still terminalizes old media: compatible request identity is not recoverable
provider context.
Official Google [Live schema](https://ai.google.dev/api/live) was consulted for
activity accompanying native content, completion semantics and independently
ordered transcription with optional coordinates. The [capabilities guide](https://ai.google.dev/gemini-api/docs/live-api/capabilities)
was also consulted. These references do not prove the configured model's actual
ordinary multi-turn layout. Deterministic multi-turn tests are technical evidence
only; real model capability and ambiguity handling remain external acceptance.
### Executed checks
Final full-suite results below supersede preceding failed/interrupted runs.
Commands use `.venv/bin/python` in this Linux environment, `-p no:cacheprovider`,
and no real AI providers. PostgreSQL commands use only the task-created
`rag_phase2_test` database and independently disposable application schemas.
- Targeted runtime/auth/client/shared-runner command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **400 passed**, zero skips. The client harness additionally reran after its
bounded AudioContext-close case was added and passed.
- Final affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **52 passed**, zero skips.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1646 passed**, two existing Windows path-alias skips, 363 PostgreSQL
cases deselected; 147.64 seconds.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **363 passed**, zero skips, 1648 provider-free cases deselected;
314.26 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_concurrent_and_completed_technical_errors_replay_one_invocation -m postgres --require-postgres -q -p no:cacheprovider --tb=no`
— expected exit 1, **three prerequisite errors**, zero database passes/skips.
- `node tests/support/voice_client_harness.mjs unit`, client/worklet/harness
JavaScript syntax checks, and
`UV_CACHE_DIR=/tmp/phase2-remaining-uv-cache uv pip check --python .venv/bin/python`
— passed; **61 installed packages compatible**. CLI help for app.voice_smoke
and app.provision, git diff --check, scoped Python AST/UTF-8, TOML, local
documentation links and protected-file hashes also passed.
Failed/interrupted runs remain separate from acceptance. The initial sandboxed
check had 19 passes and three existing socket-timeout validation setup errors;
normal local socket access resolved those. A subsequent sandboxed startup test
run was interrupted rather than claimed successful. One targeted run had 393
passes and one failure after an overly strict newly added guard suppressed a
normally completed delayed transcript; the guard was corrected and the 400-test
run passed. A full provider-free run was interrupted during that correction
(344 passes are not full acceptance).
The first active-playback bridge fixture lacked its base64 import and did not
close the outstanding test WebSocket on fixture failure: one case timed out;
the 48 passing cases were not called full acceptance. Both fixture issues were
fixed and silent/active cases reran with two passes. The first full PostgreSQL
run had 359 passes and one readiness-state assertion race: a delivered buffered
session_ready frame could be received before its documented subsequent durable
connected commit. The affected fixture now waits on that actual transition,
keeping the same connected assertion and existing three-second test barrier;
no production ordering or unrelated timing test was weakened.
### Preservation and remaining acceptance
The start-of-task inventory `/tmp/phase2-remaining-baseline.json` covers **211
existing repository files**. Final hashes show **13 intended baseline files
changed and 198 byte-identical**, with two scoped new regression files. All
migrations 0001-0005, extraction/embedding configuration, shared SearchService,
StructuredTool/SearchToolRunner, RuntimeSettings, RealtimeAdapter, original/proof
files and frozen inputs in that inventory are unchanged. Ignored credentials and
originals were not edited; inventory hashes are not claimed for excluded files.
Inherited working-tree edits are retained.
Changed baseline paths: Gemini adapter, VoiceRuntime, Live lifecycle, DurableTools,
Live routes, application lifespan, VoiceClient, its unit test and PostgreSQL
acceptance, frontend guide, this report, the plan and reference map. New paths:
`tests/unit/test_phase2_remaining.py` and
`tests/support/voice_client_harness.mjs`. No dependency, migration, production UI,
public chat/history, Redis, retrieval replacement or new agent framework is added.
Real selected-Gemini-model audio/tool/transcription/multi-turn layouts,
microphone/playback hardware, Persian speech, retrieval quality, latency and
full browser acceptance remain **unrun**. They require explicit provider opt-ins,
Gemini/model access, an approved eligible actor/corpus, a measured compatible
calibration report, approved inputs and call/time budgets. No real provider calls
or production deployment were made. Safe-close interruption remains disclosed;
this checkpoint does not certify frontend readiness.
Final cleanup for this remaining-defect checkpoint: the task-created
`rag-phase2-remaining-acceptance` container and its disposable data/volumes were
removed. Before removal, queries found **one disposable schema left by the
interrupted fixture run and zero public application tables**. That residue was
confined to this disposable container and was removed with it; it is not claimed
as clean fixture teardown. Preexisting containers and shared databases were
untouched. Executed logs and preservation inventories remain under /tmp.
+15
View File
@@ -1,5 +1,16 @@
# OpenAI Realtime Agent — Fast MVP Implementation Plan # OpenAI Realtime Agent — Fast MVP Implementation Plan
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
## 1. Goal and implementation decisions ## 1. Goal and implementation decisions
Deliver a working backend for this browser workflow: Deliver a working backend for this browser workflow:
@@ -217,6 +228,10 @@ Do not add a new agent framework or rebuild ingestion/search.
### Phase 2 — Add trusted identity and durable Live lifecycle ### Phase 2 — Add trusted identity and durable Live lifecycle
Remaining-defect implementation and executed acceptance are recorded in the
[updated repair report](../guides/realtime-agent-phase2-repair.md#remaining-defect-repair-2026-10-09).
Real selected-model multi-turn behavior and frontend readiness remain unverified.
**Purpose:** Make the working runtime safely callable by the frontend. **Purpose:** Make the working runtime safely callable by the frontend.
**Implementation:** **Implementation:**
+28 -2
View File
@@ -1,5 +1,16 @@
# RAG Assistant — Phase 1 API Catalog # RAG Assistant — Phase 1 API Catalog
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational. Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1. Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
@@ -265,9 +276,15 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost. Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — OpenAI Realtime; frozen application audio/events ## 7. Voice contract — Gemini Live temporarily; frozen application audio/events
The initial provider is direct OpenAI Realtime managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID. The current provider is Gemini Live managed by the backend. Earlier OpenAI-specific
provider mechanisms below describe the retained Realtime adapter; the Gemini
adapter uses native setupComplete, voiceActivity, toolCall/toolResponse and
transcription. Missing verified input boundaries fail safely. Interruption
requiring unheard-audio context repair closes the session rather than inventing
a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono
PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP) ### V01 — Create session (HTTP)
@@ -531,3 +548,12 @@ Inside persisted jobs/sessions/tool calls, normalized codes include PROVIDER_TIM
Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context. Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses. Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
Current temporary Gemini capability failures before reservation are 503
`LIVE_PROVIDER_UNAVAILABLE` for missing voice credentials/profile access and
`CALIBRATION_REQUIRED` for a missing/invalid/incompatible measured report.
A configured profile is a prerequisite, not proof of provider access. These
safe codes never return keys or native provider errors. HTTP authentication
failures normalize to `AUTH_REQUIRED`, CSRF to `CSRF_INVALID`, hidden resources
to `NOT_FOUND`, admission throttling to `RATE_LIMITED` with Retry-After, and
unexpected dependency failures to `DEPENDENCY_UNAVAILABLE`.
@@ -1,5 +1,16 @@
# RAG Assistant — Phase 1 Database Design # RAG Assistant — Phase 1 Database Design
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations. Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization, existing ingestion foundation, retained review decisions and owned voice/session/tool metadata. Durable text turns/messages/citations are deferred. No deployed database was queried; the repository foundation migration was inspected statically for this documentation update. Only seven foundation tables are currently implemented; compare this complete proposal with actual migrations before applying it. Live tables/SDP fields are not applied foundation schema. Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization, existing ingestion foundation, retained review decisions and owned voice/session/tool metadata. Durable text turns/messages/citations are deferred. No deployed database was queried; the repository foundation migration was inspected statically for this documentation update. Only seven foundation tables are currently implemented; compare this complete proposal with actual migrations before applying it. Live tables/SDP fields are not applied foundation schema.
@@ -1,5 +1,16 @@
# RAG Assistant — Phase 1 Implementation Guide # RAG Assistant — Phase 1 Implementation Guide
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence. Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged. Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.
+67
View File
@@ -0,0 +1,67 @@
/* Application PCM16LE/24kHz contract. The context must actually run at 24kHz. */
class Capture extends AudioWorkletProcessor {
constructor() {
super(); this.samples = []; this.active = true; this.pending = 0;
this.port.onmessage = e => { if (e.data.type === 'stop') this.active = false; else if (e.data.type === 'accepted') this.pending = Math.max(0, this.pending - 1); };
}
process(inputs) {
if (!this.active) return false;
const channels = inputs[0];
if (!channels?.length) return true;
for (let i = 0; i < channels[0].length; i++) {
let mono = 0; for (const channel of channels) mono += channel[i] / channels.length;
this.samples.push(Math.max(-32768, Math.min(32767, Math.round(mono * 32768))));
if (this.samples.length === 240) {
if (this.pending >= 100) {this.port.postMessage({type: 'overflow'}); this.active = false; return false;}
this.pending++;
const bytes = new ArrayBuffer(480), view = new DataView(bytes);
this.samples.forEach((value, index) => view.setInt16(index * 2, value, true));
this.samples.length = 0;
this.port.postMessage({type: 'pcm', bytes}, [bytes]);
}
}
return true;
}
}
class Playback extends AudioWorkletProcessor {
constructor() {
super(); this.queue = []; this.refs = new Map(); this.queued = 0;
this.port.onmessage = ({data}) => {
if (data.type === 'start') {
if (!this.refs.has(data.ref)) this.refs.set(data.ref, {played: 0, sealed: false});
} else if (data.type === 'pcm') {
const samples = new Float32Array(data.samples);
if (!this.refs.has(data.ref) || this.queued + samples.length > 48000) {
this.port.postMessage({type: 'overflow'}); return;
}
this.queue.push({ref: data.ref, samples, position: 0}); this.queued += samples.length;
} else if (data.type === 'end') {
const ref = this.refs.get(data.ref); if (ref) {ref.sealed = true; this.report(data.ref);}
} else if (data.type === 'flush') {
this.queue.length = 0; this.queued = 0;
for (const [ref] of this.refs) this.report(ref);
this.refs.clear(); this.port.postMessage({type: 'flushed', id: data.id});
}
};
}
report(ref) {
const state = this.refs.get(ref); if (!state) return;
this.port.postMessage({type: 'progress', ref, played_ms: Math.floor(state.played / 24)});
if (state.sealed && !this.queue.some(part => part.ref === ref)) this.refs.delete(ref);
}
process(inputs, outputs) {
const output = outputs[0]?.[0]; if (!output) return true;
output.fill(0);
const touched = new Set();
for (let i = 0; i < output.length && this.queue.length; i++) {
const part = this.queue[0], state = this.refs.get(part.ref);
output[i] = part.samples[part.position++]; this.queued--; state.played++; touched.add(part.ref);
if (part.position === part.samples.length) this.queue.shift();
}
// Reports count only samples actually consumed by this output process callback.
for (const ref of touched) this.report(ref);
return true;
}
}
registerProcessor('rag-capture', Capture);
registerProcessor('rag-playback', Playback);
+184
View File
@@ -0,0 +1,184 @@
/* Same-origin developer integration; persistent provider credentials stay server-side. */
const SEARCH_ERRORS = new Set(['SEARCH_TIMEOUT', 'SEARCH_FAILED', 'SEARCH_SATURATED',
'PROVIDER_TIMEOUT', 'PROVIDER_UNAVAILABLE', 'INVALID_TOOL_ARGUMENTS', 'VALIDATION_ERROR',
'CALIBRATION_REQUIRED', 'PROFILE_MISMATCH', 'INVALID_CONFIGURATION', 'INVALID_VECTOR']);
async function closeContext(context) {
let timer;
try {
await Promise.race([context.close(), new Promise(resolve => {timer = setTimeout(resolve, 1000);})]);
} finally {clearTimeout(timer);}
}
export class VoiceClient {
constructor(onEvent, workletURL = './voice-audio-worklet.js') {
this.onEvent = onEvent; this.workletURL = workletURL; this.csrf = null;
this.socket = null; this.session = null; this.connection = null; this.generation = 0;
this.ready = false; this.stopping = false;
}
async request(path, method = 'GET', body) {
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch('/api/v1' + path, {method, credentials: 'same-origin', signal: controller.signal,
headers: {'Content-Type': 'application/json', ...(method !== 'GET' && this.csrf ? {'X-CSRF-Token': this.csrf} : {})},
...(body === undefined ? {} : {body: JSON.stringify(body)})});
if (response.status === 204) return null;
const result = await response.json();
if (!response.ok) throw Object.assign(new Error(result.error?.code || 'REQUEST_FAILED'), {status: response.status});
return result;
} finally {clearTimeout(timeout);}
}
async login(username, password) {
const identity = await this.request('/auth/login', 'POST', {username, password});
this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity;
}
async refreshIdentity() {
const identity = await this.request('/me');
this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity;
}
async reserve(conversationRequestID = crypto.randomUUID(), sessionRequestID = crypto.randomUUID()) {
await this.refreshIdentity();
this.conversation = await this.request('/conversations', 'POST', {client_request_id: conversationRequestID, mode: 'voice'});
this.requestID = sessionRequestID;
this.session = await this.request('/voice/sessions', 'POST', {conversation_id: this.conversation.id, client_request_id: sessionRequestID});
return this.session;
}
async recover(requestID = this.requestID) {return this.request('/voice/sessions/by-request/' + requestID);}
async poll() {return this.request('/voice/sessions/' + this.session.session_id);}
eligible(c) {return this.connection === c && c.generation === this.generation && !c.stopping;}
progress(ref, played_ms, c = this.connection) {
// Flush reports remain valid during cleanup; an old connection owns only its socket.
if (c?.socket?.readyState === WebSocket.OPEN) c.socket.send(JSON.stringify({type: 'playback_progress', audio_ref: ref, played_ms}));
}
async prepareAudio(c) {
c.context = new AudioContext({sampleRate: 24000});
if (c.context.sampleRate !== 24000) throw new Error('AUDIO_CONTRACT_MISMATCH');
await c.context.audioWorklet.addModule(this.workletURL);
if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED');
c.playback = new AudioWorkletNode(c.context, 'rag-playback', {outputChannelCount: [1]});
c.playback.port.onmessage = ({data}) => {
if (data.type === 'progress') this.progress(data.ref, data.played_ms, c);
else if (data.type === 'flushed') {c.pendingFlush.get(data.id)?.(); c.pendingFlush.delete(data.id);}
else if (data.type === 'overflow' && this.eligible(c)) void this.cleanup(c);
};
c.playback.connect(c.context.destination); await c.context.resume();
if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED');
}
async connect() {
if (!this.session?.stream_path || this.connection) throw new Error('Fresh eligible reservation required');
const c = {generation: ++this.generation, session: this.session, pendingFlush: new Map(), ready: false, stopping: false};
this.connection = c; this.stopping = false;
try {
await this.prepareAudio(c);
if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED');
const url = new URL(c.session.stream_path, location.origin); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
c.socket = new WebSocket(url); c.socket.binaryType = 'arraybuffer'; this.socket = c.socket;
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('SESSION_READY_TIMEOUT')), 35000);
c.cancelReady = () => {clearTimeout(timeout); reject(new Error('CONNECTION_CANCELLED'));};
c.socket.onerror = () => {if (this.eligible(c)) {clearTimeout(timeout); reject(new Error('MEDIA_LOST')); void this.cleanup(c);}};
c.socket.onclose = () => {
clearTimeout(timeout);
if (!this.eligible(c)) return;
reject(new Error('MEDIA_LOST')); void this.cleanup(c); this.onEvent({type: 'media_lost'});
};
c.socket.onmessage = ({data}) => {
if (!this.eligible(c)) return;
try {
if (typeof data !== 'string') {
if (!c.ready || !c.audioRef || data.byteLength > 9600 || data.byteLength % 2) throw new Error('LIVE_PROTOCOL_ERROR');
const view = new DataView(data), samples = new Float32Array(data.byteLength / 2);
for (let i = 0; i < samples.length; i++) samples[i] = view.getInt16(i * 2, true) / 32768;
c.playback.port.postMessage({type: 'pcm', ref: c.audioRef, samples: samples.buffer}, [samples.buffer]); return;
}
const event = JSON.parse(data);
if (event.type === 'session_ready') {
if (c.ready || event.session_id !== c.session.session_id || event.input_audio.sample_rate !== 24000 || event.output_audio.sample_rate !== 24000) throw new Error('AUDIO_CONTRACT_MISMATCH');
c.ready = this.ready = true; clearTimeout(timeout); resolve();
} else if (event.type === 'audio_started') {
c.audioRef = event.audio_ref; c.playback.port.postMessage({type: 'start', ref: c.audioRef});
} else if (event.type === 'audio_ended') {
c.playback.port.postMessage({type: 'end', ref: event.audio_ref}); c.audioRef = null;
} else if (event.type === 'turn_interrupted') {
c.audioRef = null; void this.flush(c);
} else if (event.type === 'error' && (!c.ready || !event.turn_ref || !SEARCH_ERRORS.has(event.error.code))) {
clearTimeout(timeout); reject(new Error(event.error.code)); void this.cleanup(c);
}
this.onEvent(event);
} catch (error) {clearTimeout(timeout); reject(error); void this.cleanup(c);}
};
});
if (!this.eligible(c)) throw new Error('CONNECTION_CANCELLED');
// A stale permission result must be stopped even if cleanup already finished.
const media = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1, echoCancellation: true}, video: false});
if (!this.eligible(c)) {media.getTracks().forEach(track => track.stop()); throw new Error('CONNECTION_CANCELLED');}
c.media = media; c.capture = new AudioWorkletNode(c.context, 'rag-capture');
c.capture.port.onmessage = ({data}) => {
if (!this.eligible(c)) return;
if (data.type === 'overflow') {void this.cleanup(c); return;}
if (data.type !== 'pcm') return;
c.capture.port.postMessage({type: 'accepted'});
if (!c.ready) return;
if (c.socket.readyState !== WebSocket.OPEN || c.socket.bufferedAmount + data.bytes.byteLength > 96000) {void this.cleanup(c); return;}
c.socket.send(data.bytes);
};
c.input = c.context.createMediaStreamSource(media); c.input.connect(c.capture);
c.mute = c.context.createGain(); c.mute.gain.value = 0;
c.capture.connect(c.mute); c.mute.connect(c.context.destination);
} catch (error) {await this.cleanup(c); throw error;}
}
async flush(c = this.connection) {
if (!c?.playback || c.context?.state === 'closed') return;
const id = crypto.randomUUID();
await new Promise(resolve => {
const timer = setTimeout(() => {c.pendingFlush.delete(id); resolve();}, 250);
c.pendingFlush.set(id, () => {clearTimeout(timer); resolve();});
c.playback.port.postMessage({type: 'flush', id});
});
}
cleanup(c = this.connection, beforeTransportClose) {
if (!c) return Promise.resolve();
if (c.cleaning) return c.cleaning;
c.stopping = true; c.ready = false; c.cancelReady?.();
if (this.connection === c) {this.stopping = true; this.ready = false; ++this.generation;}
c.cleaning = (async () => {
try {
c.capture?.port.postMessage({type: 'stop'});
c.media?.getTracks().forEach(track => track.stop());
c.input?.disconnect(); c.capture?.disconnect(); c.mute?.disconnect();
await this.flush(c);
if (beforeTransportClose) await beforeTransportClose();
} finally {
try {c.playback?.disconnect(); if (c.context && c.context.state !== 'closed') await closeContext(c.context);}
finally {
c.socket?.close();
if (this.connection === c) {this.connection = null; this.socket = null;}
}
}
})();
return c.cleaning;
}
close() {
if (this.closing) return this.closing;
const session = this.session;
const durableClose = async () => {
if (session) {await this.refreshIdentity(); return this.request('/voice/sessions/' + session.session_id + '/close', 'POST');}
};
const c = this.connection;
this.closing = (async () => {
// V04 commits before the intentional transport close, after final progress.
if (c && !c.cleaning) return this.cleanup(c, durableClose);
await this.cleanup(c); return durableClose();
})().finally(() => {this.closing = null;});
return this.closing;
}
async logout() {
try {
try {await this.close();} catch (_) { /* Logout remains independently required. */ }
return await this.request('/auth/logout', 'POST');
} finally {await this.cleanup(); this.csrf = this.expiresAt = this.session = this.conversation = this.requestID = null;}
}
async freshSession() {
await this.close(); const recovered = await this.recover();
if (!['closed', 'failed'].includes(recovered.status)) throw new Error('OLD_SESSION_NOT_TERMINAL');
await this.reserve(); return this.connect();
}
}
+122
View File
@@ -0,0 +1,122 @@
"""Live voice session lifecycle, auth sessions, conversations and tool calls.
Revision ID: 0004_live_lifecycle
Revises: 0003_extraction_review
Create Date: 2026-10-09
"""
from alembic import op
revision = "0004_live_lifecycle"
down_revision = "0003_extraction_review"
branch_labels = None
depends_on = None
def upgrade(**kwargs):
# 1. auth_sessions table
op.execute("""
CREATE TABLE auth_sessions (
id uuid PRIMARY KEY,
organization_id uuid NOT NULL,
user_id uuid NOT NULL,
token_hash char(64) NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
last_seen_at timestamptz NOT NULL DEFAULT now(),
revoked_at timestamptz,
FOREIGN KEY (organization_id, user_id) REFERENCES users(organization_id, id) ON DELETE CASCADE,
CHECK (expires_at > created_at)
);
CREATE INDEX idx_auth_sessions_expires_at ON auth_sessions(expires_at);
CREATE INDEX idx_auth_sessions_user_id ON auth_sessions(user_id);
""")
# 2. conversations table (voice-first for MVP)
op.execute("""
CREATE TABLE conversations (
id uuid PRIMARY KEY,
organization_id uuid NOT NULL,
owner_user_id uuid NOT NULL,
client_request_id uuid NOT NULL,
request_hash char(64) NOT NULL,
mode text NOT NULL DEFAULT 'voice' CHECK (mode IN ('voice', 'text')),
title varchar(120),
status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'stale', 'closed')),
access_epoch bigint NOT NULL DEFAULT 1 CHECK (access_epoch >= 1),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
FOREIGN KEY (organization_id, owner_user_id) REFERENCES users(organization_id, id) ON DELETE CASCADE,
UNIQUE (owner_user_id, client_request_id),
UNIQUE (organization_id, id)
);
CREATE INDEX idx_conversations_owner_created ON conversations(owner_user_id, created_at, id);
""")
# 3. live_sessions table
op.execute("""
CREATE TABLE live_sessions (
id uuid PRIMARY KEY,
organization_id uuid NOT NULL,
conversation_id uuid NOT NULL,
owner_user_id uuid NOT NULL,
auth_session_id uuid NOT NULL,
client_request_id uuid NOT NULL,
request_hash char(64) NOT NULL,
provider text NOT NULL DEFAULT 'openai',
model text NOT NULL DEFAULT 'gpt-realtime-mini',
provider_session_id text,
status text NOT NULL DEFAULT 'creating' CHECK (status IN ('creating', 'connecting', 'connected', 'closed', 'failed')),
settings_revision bigint NOT NULL DEFAULT 1 CHECK (settings_revision >= 1),
knowledge_revision bigint NOT NULL DEFAULT 1 CHECK (knowledge_revision >= 1),
access_epoch bigint NOT NULL DEFAULT 1 CHECK (access_epoch >= 1),
execution_profile jsonb NOT NULL DEFAULT '{}'::jsonb,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
connected_at timestamptz,
closed_at timestamptz,
close_reason text,
error_code text,
FOREIGN KEY (organization_id, conversation_id) REFERENCES conversations(organization_id, id) ON DELETE CASCADE,
FOREIGN KEY (organization_id, owner_user_id) REFERENCES users(organization_id, id) ON DELETE CASCADE,
FOREIGN KEY (auth_session_id) REFERENCES auth_sessions(id) ON DELETE CASCADE,
UNIQUE (owner_user_id, client_request_id),
UNIQUE (organization_id, id),
CHECK ((status IN ('closed', 'failed') AND closed_at IS NOT NULL) OR (status NOT IN ('closed', 'failed')))
);
CREATE UNIQUE INDEX uq_live_sessions_active_conversation
ON live_sessions (conversation_id)
WHERE status IN ('creating', 'connecting', 'connected');
CREATE INDEX idx_live_sessions_expires_at ON live_sessions(expires_at);
""")
# 4. tool_calls table (voice-only MVP)
op.execute("""
CREATE TABLE tool_calls (
id uuid PRIMARY KEY,
organization_id uuid NOT NULL,
live_session_id uuid NOT NULL,
external_call_id text NOT NULL,
tool_name text NOT NULL DEFAULT 'search_knowledge' CHECK (tool_name = 'search_knowledge'),
arguments jsonb NOT NULL,
request_hash char(64) NOT NULL,
status text NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'succeeded', 'failed')),
knowledge_revision bigint NOT NULL DEFAULT 1 CHECK (knowledge_revision >= 1),
access_epoch bigint NOT NULL DEFAULT 1 CHECK (access_epoch >= 1),
result_json jsonb,
error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
FOREIGN KEY (organization_id, live_session_id) REFERENCES live_sessions(organization_id, id) ON DELETE CASCADE,
UNIQUE (live_session_id, external_call_id),
CHECK ((status IN ('succeeded', 'failed') AND completed_at IS NOT NULL) OR (status = 'running' AND completed_at IS NULL))
);
CREATE INDEX idx_tool_calls_session_created ON tool_calls(live_session_id, created_at);
""")
def downgrade(**kwargs):
op.execute("DROP TABLE IF EXISTS tool_calls CASCADE;")
op.execute("DROP TABLE IF EXISTS live_sessions CASCADE;")
op.execute("DROP TABLE IF EXISTS conversations CASCADE;")
op.execute("DROP TABLE IF EXISTS auth_sessions CASCADE;")
@@ -0,0 +1,31 @@
"""Enforce the Live owner chain without rewriting applied revision 0004."""
from alembic import op
revision = '0005_live_owner_chain'
down_revision = '0004_live_lifecycle'
branch_labels = None
depends_on = None
def upgrade(**kwargs):
op.execute('''
ALTER TABLE conversations ADD CONSTRAINT uq_conversation_owner UNIQUE (organization_id, owner_user_id, id);
ALTER TABLE auth_sessions ADD CONSTRAINT uq_auth_owner UNIQUE (organization_id, user_id, id);
ALTER TABLE live_sessions ADD CONSTRAINT fk_live_conversation_owner
FOREIGN KEY (organization_id, owner_user_id, conversation_id)
REFERENCES conversations (organization_id, owner_user_id, id) ON DELETE CASCADE;
ALTER TABLE live_sessions ADD CONSTRAINT fk_live_auth_owner
FOREIGN KEY (organization_id, owner_user_id, auth_session_id)
REFERENCES auth_sessions (organization_id, user_id, id) ON DELETE CASCADE;
ALTER TABLE tool_calls ADD COLUMN public_ref uuid;
UPDATE tool_calls SET public_ref=id;
ALTER TABLE tool_calls ALTER COLUMN public_ref SET NOT NULL;
ALTER TABLE tool_calls ADD CONSTRAINT uq_tool_public_ref UNIQUE (public_ref);
''')
def downgrade(**kwargs):
op.execute('''
ALTER TABLE tool_calls DROP COLUMN public_ref;
ALTER TABLE live_sessions DROP CONSTRAINT fk_live_auth_owner;
ALTER TABLE live_sessions DROP CONSTRAINT fk_live_conversation_owner;
ALTER TABLE auth_sessions DROP CONSTRAINT uq_auth_owner;
ALTER TABLE conversations DROP CONSTRAINT uq_conversation_owner;
''')
+1
View File
@@ -14,6 +14,7 @@ dependencies = [
] ]
[project.optional-dependencies] [project.optional-dependencies]
api = ["fastapi>=0.115,<1", "uvicorn>=0.34,<1", "httpx>=0.27,<1"]
search = ["langchain-core>=1,<2"] search = ["langchain-core>=1,<2"]
voice = ["langchain-core>=1,<2", "websockets>=15,<18"] voice = ["langchain-core>=1,<2", "websockets>=15,<18"]
embedding = ["tiktoken>=0.8,<1"] embedding = ["tiktoken>=0.8,<1"]
+1
View File
@@ -19,6 +19,7 @@ def test_empty_migration_tables_and_pinned_profile(migrated_db, settings):
assert set(tables) == { assert set(tables) == {
"alembic_version", "organizations", "users", "organization_settings", "alembic_version", "organizations", "users", "organization_settings",
"documents", "ingestion_jobs", "document_chunks", "audit_events", "documents", "ingestion_jobs", "document_chunks", "audit_events",
"auth_sessions", "conversations", "live_sessions", "tool_calls",
} }
for changed in ( for changed in (
replace(settings.embedding_profile, model="different-model"), replace(settings.embedding_profile, model="different-model"),
+591
View File
@@ -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)
+165
View File
@@ -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));
}
+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"))) 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))) await self.incoming.put(canonical_json(terminal(rid, output=output)))
transport = Scripted() transport = Scripted()
async def connection(*_): async def connection(config, limits):
return transport return RealtimeAdapter(transport, settings=limits)
monkeypatch.setattr(voice_smoke, "connect", connection) monkeypatch.setattr(voice_smoke, "create_adapter", connection)
config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"), config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"),
openai_realtime_model="gpt-realtime-mini", openai_proxy=None) openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0 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: for event in events:
await transport.incoming.put(canonical_json(event)) await transport.incoming.put(canonical_json(event))
transport.send = send transport.send = send
async def connection(*_): return transport async def connection(config, limits): return RealtimeAdapter(transport, settings=limits)
monkeypatch.setattr(voice_smoke, "connect", connection) monkeypatch.setattr(voice_smoke, "create_adapter", connection)
original_runtime = voice_smoke.VoiceRuntime original_runtime = voice_smoke.VoiceRuntime
if failure == "delivery": if failure == "delivery":
def runtime_factory(adapter, service, shared_runner, actor, emit, **kwargs): 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): def test_invalid_smoke_configuration_never_connects(runner, monkeypatch):
from app import voice_smoke from app import voice_smoke
async def forbidden(*_): pytest.fail("Provider connection before valid configuration") 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}) config = SimpleNamespace(runtime_settings={"setup_timeout_seconds": 0})
with pytest.raises(ValueError): with pytest.raises(ValueError):
asyncio.run(voice_smoke.run(SimpleNamespace(), runner, uuid4(), config, "q", 3, 4)) 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