feat(backend): deliver Phase 3 document and voice integration

Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
+133 -3
View File
@@ -1,6 +1,10 @@
"""Cookie-only identity and shared backend services, lazily constructed."""
import asyncio
from datetime import timedelta
import json
import tempfile
from pathlib import Path
from app.infrastructure.json_processing import (JSON_SLOTS, INLINE_BYTES, owned_io, validate_json, validate_spool)
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.engine import Engine
@@ -10,22 +14,41 @@ from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, chec
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.langchain_tool import SearchToolRunner, prepare_search_tools
from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None
# ReviewDecision: 10,000 group IDs + 16 checks, each <=500 characters,
# note <=2,000 characters. A Unicode scalar needs at most 12 JSON bytes
# (escaped surrogate pair), exceeding raw UTF-8 and other escape forms.
# Include quotes/commas, fixed fields and 1 KiB of formatting allowance.
MAX_DECISION_BYTES = (10000 + 16) * (500 * 12 + 3) + 2000 * 12 + 1024
MAX_SELECTION_BYTES = 1 * 1024 * 1024 # 1 MiB (up to 10,000 document UUIDs)
JSON_RECEIVE_SECONDS = 15
RETRY_RECEIVE_SECONDS = 5
def get_voice_settings():
return VoiceSettings()
def get_ingestion_settings():
return IngestionSettings()
def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND',
'DOCUMENT_NOT_FOUND':'NOT_FOUND', 'ADMINISTRATOR_REQUIRED':'FORBIDDEN',
'INVALID_SELECTION':'VALIDATION_ERROR',
'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 = {
'FILE_TOO_LARGE':413, 'PAYLOAD_TOO_LARGE':413, 'UNSUPPORTED_FILE_TYPE':415, 'INVALID_FILE':422,
'VALIDATION_ERROR':422, 'REVISION_CONFLICT':409, 'DOCUMENT_NOT_READY':409,
'DOCUMENT_NOT_RETRYABLE':409, 'EXTRACTION_REVIEW_PENDING':409,
'REVIEW_STALE':409, 'REVIEW_ALREADY_DECIDED':409,
'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,
@@ -39,6 +62,105 @@ def error(code):
return HTTPException(codes.get(code, 503), detail={'code': code, 'message': 'Request could not be completed.'})
async def receive_json(request: Request, model_cls, max_bytes: int, timeout_seconds: float | None = None):
if timeout_seconds is None:
timeout_seconds = JSON_RECEIVE_SECONDS
content_type = request.headers.get('content-type', '')
if content_type:
media_type = content_type.split(';')[0].strip().lower()
if media_type != 'application/json':
raise error('VALIDATION_ERROR')
content_length_header = request.headers.get('content-length')
content_length = None
if content_length_header is not None:
try:
content_length = int(content_length_header)
if content_length < 0:
raise error('VALIDATION_ERROR')
if content_length > max_bytes:
raise error('PAYLOAD_TOO_LARGE')
except ValueError:
raise error('VALIDATION_ERROR')
if not JSON_SLOTS.acquire(blocking=False):
raise error('SERVICE_BUSY')
# One owner covers receive, spool, parsing and result reconstruction. A
# timed-out/cancelled caller cancels it but cannot prematurely free its slot.
task = asyncio.create_task(_receive_json(request, model_cls, max_bytes, content_length))
def completed(owner):
JSON_SLOTS.release()
if not owner.cancelled():
owner.exception() # retrieve orphaned errors after caller cancellation
task.add_done_callback(completed)
try:
return await asyncio.wait_for(asyncio.shield(task), timeout_seconds)
except TimeoutError:
task.cancel()
raise error('DEPENDENCY_UNAVAILABLE') from None
except asyncio.CancelledError:
task.cancel()
raise
except ValueError as exc:
raise error(str(exc)) from None
async def _receive_json(request, model_cls, max_bytes, content_length):
body, size, directory, spool = bytearray(), 0, None, None
try:
async for chunk in request.stream():
if len(chunk) > max_bytes - size:
raise error('PAYLOAD_TOO_LARGE')
size += len(chunk)
if spool is None and size > INLINE_BYTES:
directory = tempfile.TemporaryDirectory(prefix='rag-json-')
path = Path(directory.name) / 'payload'
spool = path.open('wb')
await owned_io(spool.write, body)
body.clear()
# Bound each copy/write, including a transport supplying one large
# message. Yield during cooperative streams that never suspend.
for offset in range(0, len(chunk), INLINE_BYTES):
piece = chunk[offset:offset + INLINE_BYTES]
if spool is None:
body.extend(piece)
else:
await owned_io(spool.write, piece)
await asyncio.sleep(0)
if not size or (content_length is not None and size != content_length):
raise error('VALIDATION_ERROR')
if spool is None:
return validate_json(body, model_cls)
await owned_io(spool.close)
spool = None
return await validate_spool(path, model_cls)
finally:
if spool is not None:
await owned_io(spool.close)
if directory is not None:
await owned_io(directory.cleanup)
async def receive_empty(request: Request, timeout_seconds: float | None = None):
if timeout_seconds is None:
timeout_seconds = RETRY_RECEIVE_SECONDS
content_length_header = request.headers.get('content-length')
if content_length_header is not None:
try:
if int(content_length_header) > 0:
raise error('VALIDATION_ERROR')
except ValueError:
raise error('VALIDATION_ERROR')
try:
async with asyncio.timeout(timeout_seconds):
async for chunk in request.stream():
if chunk:
raise error('VALIDATION_ERROR')
except TimeoutError:
raise error('DEPENDENCY_UNAVAILABLE') from None
def get_engine():
global _ENGINE
if _ENGINE is None:
@@ -71,13 +193,15 @@ 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
voice = VoiceSettings()
path = voice.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
if not voice.voice_transport_testing:
raise error('CALIBRATION_REQUIRED') from None
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
@@ -102,3 +226,9 @@ def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_
require_origin(request, config)
if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token):
raise error('CSRF_TOKEN_INVALID')
def require_admin(user: Annotated[UserContext, Depends(get_current_user)]):
if user.role != 'admin':
raise error('FORBIDDEN')
return user
+190
View File
@@ -0,0 +1,190 @@
"""D01-D04, D06-D07: authenticated adapters around existing ingestion services."""
import asyncio
from threading import BoundedSemaphore
from typing import Annotated, Literal, NamedTuple
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request, Response
from app.api.v1.dependencies import (
get_engine, get_ingestion_settings, require_admin, require_csrf, error,
MAX_DECISION_BYTES, JSON_RECEIVE_SECONDS, RETRY_RECEIVE_SECONDS,
receive_json, receive_empty,
)
from app.api.v1.uploads import receive_upload
from app.infrastructure.intake_repository import SqlIntakeRepository
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.infrastructure.review_repository import SqlReviewRepository
from app.infrastructure.file_store import LocalFileStore
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.infrastructure.blocking import blocking
from app.infrastructure.document_queries import DocumentQueries
from app.modules.documents.intake import import_document
from app.modules.documents.errors import IntakeError
from app.modules.documents.review import AdministratorIdentity, ReviewDecision
router = APIRouter(prefix='/documents', tags=['Documents'])
_DECISION_SLOTS = BoundedSemaphore(2)
class DocumentServices(NamedTuple):
settings: object
store: object
candidates: object
intake: object
worker: object
review: object
queries: object
def get_document_services(engine=Depends(get_engine), settings=Depends(get_ingestion_settings)):
store = LocalFileStore(settings.original_directory)
candidates = LocalExtractionCandidates(settings.extraction_directory, original_directory=settings.original_directory)
return DocumentServices(settings, store, candidates, SqlIntakeRepository(engine), SqlWorkerRepository(engine, settings),
SqlReviewRepository(engine, settings, candidates, store), DocumentQueries(engine, settings, store, candidates))
Services = Annotated[DocumentServices, Depends(get_document_services)]
Admin = Annotated[object, Depends(require_admin)]
Csrf = Annotated[None, Depends(require_csrf)]
Key = Annotated[UUID, Header(alias='Idempotency-Key')]
def replay_header(response, result):
if result.get('replayed'):
response.headers['Idempotency-Replayed'] = 'true'
@router.post('', status_code=202, openapi_extra={'requestBody': {
'required': True, 'content': {'multipart/form-data': {'schema': {
'type': 'object', 'additionalProperties': False, 'required': ['file'],
'properties': {'file': {'type': 'string', 'format': 'binary'},
'title': {'type': 'string', 'maxLength': 200}}
}}}
}})
async def upload(request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
settings, store, _, intake, *_ = services
previous = None
try:
_, previous = await blocking(intake.lookup, settings, user.id, key)
# Known replay is bounded by its accepted length, independent of newer
# deployment admission limits. Intake still compares the exact payload.
admission = (settings.model_copy(update={'max_original_bytes': previous['size_bytes']})
if previous is not None else settings)
async with receive_upload(request, admission) as (path, filename, title):
# Cancellation cannot delete the spool while intake still owns it.
task = asyncio.create_task(asyncio.to_thread(import_document, intake, store, settings,
path=path, filename=filename, title=title, administrator_id=user.id, request_id=key))
try:
result = await asyncio.shield(task)
except asyncio.CancelledError:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
continue
except Exception:
break
# Retrieve a possible intake exception while preserving cancellation.
if not task.cancelled():
task.exception()
raise
replay_header(response, result)
doc = result['document']
return dict(document_id=doc['id'], job_id=doc['job']['id'], status=doc['status'],
is_active=doc['is_active'], searchable=doc['searchable'])
except IntakeError as exc:
raise error('IDEMPOTENCY_CONFLICT' if previous is not None and exc.code == 'FILE_TOO_LARGE'
else exc.code) from None
except ValueError as exc:
raise error(str(exc)) from None
@router.get('')
def documents(user: Admin, services: Services, limit: Annotated[int, Query(ge=1, le=100)] = 20,
cursor: Annotated[str | None, Query(max_length=256)] = None,
status: Literal['queued', 'processing', 'ready', 'failed'] | None = None,
is_active: bool | None = None):
try:
return services.queries.list(user.id, limit=limit, cursor=cursor, status=status, is_active=is_active)
except IntakeError as exc:
raise error(exc.code) from None
@router.get('/{document_id}')
def detail(document_id: UUID, user: Admin, services: Services):
try:
return services.queries.detail(user.id, document_id)
except IntakeError as exc:
raise error(exc.code) from None
@router.post('/{document_id}/retry', status_code=202)
async def retry(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
await receive_empty(request)
try:
result = await asyncio.to_thread(services.worker.retry, administrator_id=user.id, document_id=document_id, request_id=key,
store=services.store, candidates=services.candidates)
replay_header(response, result)
return {k: v for k, v in result.items() if k != 'replayed'}
except IntakeError as exc:
raise error(exc.code) from None
@router.get('/{document_id}/extraction-review')
def review(document_id: UUID, user: Admin, services: Services,
limit: Annotated[int, Query(ge=1, le=20)] = 10,
cursor: Annotated[str | None, Query(pattern='^[0-9a-f]{64}$')] = None):
try:
result = services.review.read(AdministratorIdentity(user.id, user.organization_id), document_id, limit=limit, after=cursor)
for item in result['items']:
item['preview_path'] = (f'/api/v1/documents/{document_id}/extraction-review/{item["evidence_sha256"]}/preview'
if item.pop('preview_available') else None)
return result
except IntakeError as exc:
raise error(exc.code) from None
@router.get('/{document_id}/extraction-review/{evidence_sha256}/preview')
def preview(document_id: UUID, evidence_sha256: str, user: Admin, services: Services):
import re
if not re.fullmatch('[0-9a-f]{64}', evidence_sha256):
raise error('VALIDATION_ERROR')
try:
content, mime = services.review.preview(AdministratorIdentity(user.id, user.organization_id), document_id, evidence_sha256)
return Response(content, media_type=mime, headers={'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
except IntakeError as exc:
raise error(exc.code) from None
@router.post('/{document_id}/extraction-review/decisions', openapi_extra={
'requestBody': {
'required': True,
'content': {'application/json': {'schema': ReviewDecision.model_json_schema()}}
}
})
async def decide(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
payload = await receive_json(request, ReviewDecision, max_bytes=MAX_DECISION_BYTES)
try:
if not _DECISION_SLOTS.acquire(blocking=False):
raise error('SERVICE_BUSY')
try:
pending = asyncio.get_running_loop().run_in_executor(None, _apply_decision,
services.review, AdministratorIdentity(user.id, user.organization_id), document_id, key, payload)
except BaseException:
_DECISION_SLOTS.release()
raise
# Cancellation stops the caller, not a possibly committed transaction.
# The worker owns the normalized DTO and releases admission in its finally.
pending.add_done_callback(lambda future: future.exception() if not future.cancelled() else None)
result = await asyncio.shield(pending)
replay_header(response, result)
return {k: v for k, v in result.items() if k != 'replayed'}
except IntakeError as exc:
raise error(exc.code) from None
def _apply_decision(review, identity, document_id, key, payload):
try:
return review.decide(identity, document_id, request_id=key, payload=payload.model_dump(mode='json'))
finally:
_DECISION_SLOTS.release()
+103
View File
@@ -0,0 +1,103 @@
"""K01/K02 and read-only F01, with backend-owned organization scope."""
from uuid import UUID
from app.infrastructure.blocking import blocking
from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import (get_engine, get_current_user, get_ingestion_settings,
get_voice_settings, require_admin, require_csrf, error,
MAX_SELECTION_BYTES, JSON_RECEIVE_SECONDS, receive_json)
from app.modules.knowledge.service import selection_get, selection_replace, authority, transaction, KnowledgeError
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.infrastructure.database import check_compatibility, CompatibilityError
router = APIRouter(tags=['Knowledge and configuration'])
class SelectionRequest(BaseModel):
model_config = ConfigDict(extra='forbid')
expected_revision: int = Field(ge=1, strict=True)
document_ids: list[UUID] = Field(max_length=10000)
@router.get('/knowledge-selection')
def selection(user=Depends(require_admin), engine=Depends(get_engine)):
try:
return selection_get(engine, user.id)
except KnowledgeError as exc:
raise error(exc.code) from None
@router.patch('/knowledge-selection', openapi_extra={
'requestBody': {
'required': True,
'content': {'application/json': {'schema': SelectionRequest.model_json_schema()}}
}
})
async def replace(request: Request, user=Depends(require_admin), engine=Depends(get_engine), _csrf=Depends(require_csrf)):
payload = await receive_json(request, SelectionRequest, max_bytes=MAX_SELECTION_BYTES)
try:
return await blocking(selection_replace, engine, user.id, payload.expected_revision, payload.document_ids)
except KnowledgeError as exc:
failure = error(exc.code)
if exc.details:
failure.detail['details'] = exc.details
raise failure from None
except TimeoutError:
raise error('DEPENDENCY_UNAVAILABLE') from None
except ValueError as exc:
raise error(str(exc)) from None
@router.get('/configuration')
def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
ingest=Depends(get_ingestion_settings), voice=Depends(get_voice_settings)):
try:
with transaction(engine) as conn:
_, settings = authority(conn, user.id)
except KnowledgeError as exc:
raise error(exc.code) from None
# Configuration is availability evidence, not real-provider quality certification.
available = False
calibration_status = "uncalibrated"
try:
voice.require_voice()
ingest.require_embedding_credentials()
with engine.connect() as conn:
check_compatibility(conn, ingest.embedding_profile, require_worker=True)
if voice.search_calibration_report is not None:
import json
cutoff = load_cutoff(json.loads(voice.search_calibration_report.read_text(encoding='utf-8')))
available = (cutoff.profile == ingest.processing_profile()['embedding']
and cutoff.retrieval_policy == RETRIEVAL_POLICY)
if available:
calibration_status = 'calibrated'
except (ValueError, OSError, KeyError, TypeError, AttributeError, CompatibilityError):
pass
if voice.voice_transport_testing and calibration_status != "calibrated":
try:
voice.require_voice()
ingest.require_embedding_credentials()
with engine.connect() as conn:
check_compatibility(conn, ingest.embedding_profile, require_worker=True)
from app.worker import factories
_, provider_factory = factories(ingest)
provider_factory(ingest.processing_profile()) # validation only; no inference
available = True
except (ValueError, CompatibilityError):
pass
from app.modules.voice.settings import RuntimeSettings
limits = RuntimeSettings()
mime_types = {'.pdf': 'application/pdf', '.md': 'text/markdown',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png'}
return dict(revision=settings['revision'], assistant_name=settings['assistant_name'], instruction=settings['instruction'],
capabilities=dict(text=False, voice=available, captions=available,
calibration_status=calibration_status, voice_transport_testing=voice.voice_transport_testing,
supported_upload_types=list(dict.fromkeys(mime_types[e] for e in ingest.accepted_formats)),
max_upload_bytes=ingest.max_original_bytes, max_pdf_pages=ingest.max_pdf_pages,
ocr_review_required=ingest.ocr_review_required,
supported_structure_notes='Readable Markdown and supported DOCX structures; bounded PDF/image extraction. Factual Q&A requires separate approval.',
input_sample_rate=24000, output_sample_rate=24000, channels=1, audio_encoding='pcm16le',
max_binary_message_bytes=limits.max_binary_message_bytes,
max_client_control_bytes=limits.max_client_control_bytes))
+52 -27
View File
@@ -1,9 +1,9 @@
"""V01-V04 and supervised, cookie-authenticated Gemini stream."""
"""V01-V04 and supervised, cookie-authenticated selected-provider stream."""
import asyncio
from dataclasses import asdict
import json
import logging
from typing import Annotated
from typing import Annotated, Literal
from uuid import UUID
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, ConfigDict
@@ -17,7 +17,8 @@ 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.infrastructure.voice_provider import create_adapter
from app.modules.voice.authority import authority_failure_code
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.modules.documents.settings import IngestionSettings
@@ -42,6 +43,7 @@ class LiveSessionResponse(BaseModel):
stream_path: str | None
expires_at: str
poll_url: str
calibration_status: Literal["calibrated", "uncalibrated", "unknown"] = "unknown"
class CloseLiveSessionResponse(BaseModel):
session_id: str
@@ -59,14 +61,25 @@ def capability(config):
or cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise ValueError('CALIBRATION_REQUIRED')
except (OSError, ValueError, KeyError, TypeError, AttributeError):
if config.voice_transport_testing:
return None
raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff
def search_profile(cutoff, settings=None):
if cutoff is None:
return dict(embedding=asdict((settings or IngestionSettings()).embedding_profile),
calibration_status='uncalibrated', mode='transport_testing',
retrieval_policy=RETRIEVAL_POLICY)
return dict(embedding=cutoff.profile, calibration_id=cutoff.calibration_id,
retrieval_policy=cutoff.retrieval_policy, distance=cutoff.distance)
@router.post('', response_model=LiveSessionResponse, status_code=201)
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
engine: Annotated[object, Depends(get_engine)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
# Recover replay before capability checks: a configuration change cannot alter identity.
@@ -84,10 +97,12 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
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}
# Construct configured embedding transport only after replay recovery.
# Construction validates identity/limits/credentials without inference.
search_settings = get_search_service(engine).settings if cutoff is None else None
profile["search"] = search_profile(cutoff, search_settings)
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.gemini_model, execution_profile=profile)
provider=config.provider, model=config.selected_model, execution_profile=profile)
except ValueError as exc:
raise error(str(exc)) from None
if result['replayed']:
@@ -131,13 +146,11 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
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:
if search_service.cutoff is None and not config.voice_transport_testing:
raise ValueError('CALIBRATION_REQUIRED')
if (info['provider'] != 'gemini' or info['model'] != config.gemini_model
if (info['provider'] != config.provider or info['model'] != config.selected_model
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != {
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
or info['execution_profile'].get('search') != search_profile(search_service.cutoff, search_service.settings)):
raise ValueError('LIVE_SESSION_UNUSABLE')
except Exception as exc:
logger.info('Stream admission rejected: %s', type(exc).__name__)
@@ -164,17 +177,10 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
# 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)
adapter = await create_adapter(config, 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
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
return True
store = DurableTools(lifecycle_service, user, session_id)
async def emit(event):
@@ -198,8 +204,20 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
await runtime.start()
async def browser():
while runtime.usable:
# Keep the delivered binary message in the transport budget until
# its provider send completes. Don't add a second runtime backlog
# on top of the parser's eight queued + one assembling messages.
while runtime.usable and runtime.input_transport_count:
await asyncio.sleep(.001)
if not runtime.usable:
return
message = await websocket.receive()
if message['type'] == 'websocket.disconnect':
code = {1009: 'LIVE_FRAME_TOO_LARGE', 1002: 'LIVE_PROTOCOL_ERROR',
1007: 'LIVE_PROTOCOL_ERROR'}.get(message.get('code'))
if code:
async with runtime.lock:
runtime.fail(code, writable=False)
return
if not runtime.ready and ready_sent.is_set():
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds)
@@ -208,15 +226,13 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
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)
except Exception as exc:
async with runtime.lock:
runtime.fail('CONTEXT_REVOKED')
runtime.fail(authority_failure_code(exc))
return
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
@@ -232,7 +248,7 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
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
outcome = runtime.failure
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED'
@@ -257,7 +273,16 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
except Exception:
logger.warning('Bounded provider cleanup incomplete')
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
# Saturation must not strand the durable terminal outcome once admission frees.
deadline = asyncio.get_running_loop().time() + 6
while True:
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
break
except ValueError as exc:
if str(exc) != 'SERVICE_BUSY' or asyncio.get_running_loop().time() >= deadline:
raise
await asyncio.sleep(.025)
except Exception:
logger.warning('Live terminal persistence unavailable')
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
+149
View File
@@ -0,0 +1,149 @@
"""Streaming multipart admission with bounded headers, metadata and disk spooling."""
from contextlib import asynccontextmanager
import asyncio
from pathlib import Path
import re
from tempfile import TemporaryDirectory
from threading import BoundedSemaphore
from typing import NamedTuple
from python_multipart.multipart import MultipartParser, parse_options_header
from python_multipart.exceptions import MultipartParseError
from app.modules.documents.errors import IntakeError
# A finite per-process spool budget: four requests, each at most one configured file.
_UPLOAD_SLOTS = BoundedSemaphore(4)
MULTIPART_OVERHEAD = 16 * 1024
MAX_TITLE_BYTES = 800
MAX_HEADER_BYTES = 4096
UPLOAD_RECEIVE_SECONDS = 60
class UploadSpool(NamedTuple):
path: Path
filename: str
title: str | None
@asynccontextmanager
async def receive_upload(request, settings):
if not _UPLOAD_SLOTS.acquire(blocking=False):
raise IntakeError('RATE_LIMITED', 'Upload capacity unavailable')
try:
with TemporaryDirectory(prefix='rag-upload-') as directory:
spool_path = Path(directory) / 'payload'
with spool_path.open('wb') as stream:
upload = _MultipartUpload(request.headers.get('content-type', ''), stream, settings)
total = 0
try:
async with asyncio.timeout(UPLOAD_RECEIVE_SECONDS):
async for data in request.stream():
total += len(data)
if total > settings.max_original_bytes + MULTIPART_OVERHEAD:
raise IntakeError('FILE_TOO_LARGE', 'Request exceeds upload limit')
# Feed bounded pieces even if ASGI supplies a large chunk.
for offset in range(0, len(data), 65536):
try:
upload.parser.write(data[offset:offset + 65536])
except MultipartParseError:
raise IntakeError('INVALID_FILE', 'Malformed multipart upload') from None
except TimeoutError:
raise IntakeError('DEPENDENCY_UNAVAILABLE', 'Upload receive deadline exceeded') from None
upload.parser.finalize()
if not upload.ended or 'file' not in upload.names:
raise IntakeError('INVALID_FILE', 'Incomplete multipart upload')
yield UploadSpool(spool_path, upload.filename, upload.title)
finally:
_UPLOAD_SLOTS.release()
class _MultipartUpload:
def __init__(self, content_type, stream, settings):
if len(content_type) > 512:
raise IntakeError('INVALID_FILE', 'Invalid multipart header')
try:
kind, options = parse_options_header(content_type)
except (ValueError, UnicodeError):
raise IntakeError('INVALID_FILE', 'Invalid multipart header') from None
boundary = options.get(b'boundary', b'')
if kind != b'multipart/form-data' or not re.fullmatch(rb"[A-Za-z0-9'()+_,./:=?-]{1,70}", boundary):
raise IntakeError('INVALID_FILE', 'Multipart boundary required')
self.stream, self.settings = stream, settings
self.names, self.filename, self.title, self.ended = set(), None, None, False
self.file_bytes = 0
self.parser = MultipartParser(boundary, {
'on_part_begin': self.part_begin, 'on_header_field': self.header_field,
'on_header_value': self.header_value, 'on_header_end': self.header_end,
'on_headers_finished': self.headers_finished, 'on_part_data': self.part_data,
'on_part_end': self.part_end, 'on_end': self.end,
})
def part_begin(self):
if len(self.names) >= 2:
raise IntakeError('INVALID_FILE', 'Too many multipart parts')
self.headers, self.field, self.value = {}, bytearray(), bytearray()
self.header_bytes, self.header_count = 0, 0
self.name, self.metadata = None, bytearray()
def header_data(self, target, data, start, end):
self.header_bytes += end - start
if self.header_bytes > MAX_HEADER_BYTES:
raise IntakeError('INVALID_FILE', 'Multipart headers too large')
target.extend(data[start:end])
def header_field(self, data, start, end):
self.header_data(self.field, data, start, end)
def header_value(self, data, start, end):
self.header_data(self.value, data, start, end)
def header_end(self):
key = bytes(self.field).lower()
self.header_count += 1
if self.header_count > 4 or key in self.headers or key not in (b'content-disposition', b'content-type'):
raise IntakeError('INVALID_FILE', 'Invalid multipart headers')
self.headers[key] = bytes(self.value)
self.field.clear(); self.value.clear()
def headers_finished(self):
disposition = self.headers.get(b'content-disposition', b'')
try:
kind, options = parse_options_header(disposition)
self.name = options.get(b'name', b'').decode('utf-8')
if kind != b'form-data' or self.name not in ('file', 'title') or self.name in self.names:
raise ValueError()
if self.name == 'file':
filename = options[b'filename'].decode('utf-8')
# Validate before using any caller text as a temporary pathname.
from app.modules.documents.intake import unsafe_display_character
if (not filename or len(filename) > 255 or filename in ('.', '..')
or any(c in '<>:"/\\|?*' or unsafe_display_character(c) for c in filename)
or b'\\' in disposition or filename.rstrip(' .') != filename):
raise ValueError()
self.filename = filename
elif b'filename' in options:
raise ValueError()
except (ValueError, KeyError, UnicodeError):
raise IntakeError('INVALID_FILE', 'Invalid upload part') from None
self.names.add(self.name)
def part_data(self, data, start, end):
if self.name == 'file':
self.file_bytes += end - start
if self.file_bytes > self.settings.max_original_bytes:
raise IntakeError('FILE_TOO_LARGE', 'File exceeds upload limit')
self.stream.write(data[start:end])
else:
if len(self.metadata) + end - start > MAX_TITLE_BYTES:
raise IntakeError('INVALID_FILE', 'Title exceeds metadata limit')
self.metadata.extend(data[start:end])
def part_end(self):
if self.name == 'title':
try:
self.title = self.metadata.decode('utf-8')
except UnicodeError:
raise IntakeError('INVALID_FILE', 'Invalid title encoding') from None
def end(self):
self.ended = True