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
+105
View File
@@ -0,0 +1,105 @@
"""Safe document polling projections and scoped pagination over existing repositories."""
import base64
from datetime import datetime
import json
from uuid import UUID
from sqlalchemy import text
from app.infrastructure.intake_repository import administrator, document_status
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.modules.documents.errors import IntakeError
from app.modules.documents.review import pending_review, reviews_approved
from app.modules.documents.extraction_artifacts import ocr_review_required
def encode_cursor(document):
return base64.urlsafe_b64encode(json.dumps([document['created_at'].isoformat(), str(document['id'])]).encode()).decode()
def decode_cursor(cursor):
try:
if len(cursor) > 256:
raise ValueError()
stamp, identifier = json.loads(base64.b64decode(cursor, altchars=b'-_', validate=True))
stamp = datetime.fromisoformat(stamp)
if stamp.tzinfo is None:
raise ValueError()
return stamp, UUID(identifier)
except (ValueError, TypeError, UnicodeError):
raise IntakeError('VALIDATION_ERROR', 'Invalid document cursor') from None
class DocumentQueries:
def __init__(self, engine, settings, store, candidates):
self.engine, self.settings, self.store, self.candidates = engine, settings, store, candidates
self.worker = SqlWorkerRepository(engine, settings)
def project(self, row):
job, state = row['job'], row['extraction_state']
can_retry = False
if row['status'] == 'failed' and job['status'] == 'failed':
try:
self.worker.validate_retry_snapshot(row, self.store, self.candidates)
can_retry = (job['error_code'] not in ('EXTRACTION_REVIEW_REQUIRED', 'EXTRACTION_REVIEW_REJECTED')
or reviews_approved(state))
except (IntakeError, OSError, ValueError):
pass
rejected = any((p.get('decision') or {}).get('decision') == 'reject' for p in state.get('candidates', ()))
review_state = ('rejected' if rejected else 'pending' if pending_review(state)
else 'approved' if reviews_approved(state)
else 'not_required' if state.get('complete_artifact') else 'not_evaluated')
quality = None
if state.get('complete_artifact'):
quality = self.candidates.inspect_pointer(state['complete_artifact'], document=row).quality_decision
return dict(id=row['id'], title=row['title'], filename=row['original_filename'],
status=row['status'], is_active=row['is_active'], searchable=row['searchable'],
created_at=row['created_at'], chunk_count=row['chunk_count'],
review_required=pending_review(state), review_state=review_state,
extraction_quality_decision=quality,
ocr_review_required=ocr_review_required(row['processing_profile']),
job=dict(id=job['id'], status=job['status'], stage=job['stage'],
attempt_count=job['attempt_count'], retry_generation=job['retry_generation'],
can_retry=can_retry, error=(dict(code=job['error_code'],
message='Ingestion could not complete; use the error code and review state.',
retryable=job['error_retryable']) if job['error_code'] else None)))
def detail(self, actor, identifier):
with self.engine.begin() as conn:
org = administrator(conn, actor)
row = document_status(conn, org, identifier)
self.visible(row)
return self.project(row)
@staticmethod
def visible(row):
if row['deleted_at'] is not None or row['content_purged_at'] is not None:
raise IntakeError('DOCUMENT_NOT_FOUND', 'Document unavailable')
def list(self, actor, *, limit=20, cursor=None, status=None, is_active=None):
params = dict(limit=limit + 1, status=status, active=is_active)
condition = ''
if cursor is not None:
stamp, identifier = decode_cursor(cursor)
params.update(stamp=stamp, identifier=identifier)
condition = ' AND (d.created_at,d.id)<(:stamp,:identifier)'
with self.engine.begin() as conn:
params['org'] = administrator(conn, actor)
revision = conn.execute(text('SELECT knowledge_revision FROM organization_settings WHERE organization_id=:org'), params).scalar_one()
if cursor is not None:
known = conn.execute(text('SELECT 1 FROM documents WHERE organization_id=:org AND id=:identifier AND created_at=:stamp AND deleted_at IS NULL AND content_purged_at IS NULL'), params).scalar_one_or_none()
if known is None:
raise IntakeError('VALIDATION_ERROR', 'Unknown document cursor')
rows = conn.execute(text('''
SELECT d.*, row_to_json(j) AS job FROM documents d JOIN ingestion_jobs j
ON j.document_id=d.id AND j.organization_id=d.organization_id
WHERE d.organization_id=:org AND d.deleted_at IS NULL AND d.content_purged_at IS NULL
AND (CAST(:status AS text) IS NULL OR d.status=:status)
AND (CAST(:active AS boolean) IS NULL OR d.is_active=:active)
''' + condition + ' ORDER BY d.created_at DESC,d.id DESC LIMIT :limit'), params).mappings().all()
items = []
for row in rows[:limit]:
row = dict(row)
row['searchable'] = row['status'] == 'ready' and row['is_active']
items.append(self.project(row))
return dict(items=items, next_cursor=encode_cursor(rows[limit - 1]) if len(rows) > limit else None,
knowledge_revision=revision)
+7 -3
View File
@@ -165,8 +165,8 @@ class GeminiVision:
if any("text" not in p for p in parts):
raise ExtractionError("Unexpected vision response parts")
transcript = Transcription.model_validate_json("".join(p["text"] for p in parts))
if not transcript.complete or transcript.warnings or not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain")
if not transcript.blocks:
raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = []
@@ -174,10 +174,14 @@ class GeminiVision:
if (block.ordinal != index or block.method != "vision" or block.actual_model != self.model or block.page != page
or not block.source_locator.startswith(section + "/")):
raise ExtractionError("Vision returned incompatible evidence provenance")
if unreadable(block.text) or any("unreadable" in w.lower() or "ناخوانا" in w for w in block.warnings):
if unreadable(block.text):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={"search_text":
normalize_search_text(block.text, processing_profile["normalizer"])}))
# Recognition diagnostics belong to the exact review candidate.
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+143
View File
@@ -0,0 +1,143 @@
"""Two admitted JSON requests; large decoding/validation has a separate GIL.
Only backend-chosen DTO classes enter the child. Its bounded pickle frames are
trusted local results, never client pickle input. Admission outlives cancellation
until the owner has joined disk I/O, reaped its child and removed its spool.
"""
import asyncio
import importlib
import json
import pickle
from pathlib import Path
import struct
import sys
from threading import BoundedSemaphore
JSON_SLOTS = BoundedSemaphore(2)
INLINE_BYTES = 64 * 1024
FRAME_BYTES = 256 * 1024
async def owned_io(function, *args):
"""A cancelled owner must join a write before closing/deleting its file."""
task = asyncio.get_running_loop().run_in_executor(None, function, *args)
try:
return await asyncio.shield(task)
except asyncio.CancelledError:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
continue
task.result()
raise
def validate_json(body, model_cls):
try:
return model_cls.model_validate(json.loads(body.decode('utf-8')))
except (ValueError, UnicodeError, RecursionError):
raise ValueError('VALIDATION_ERROR') from None
async def validate_spool(path, model_cls):
# No large process-pool argument/result pickling in the API process: input is
# spooled, and validated flat DTO fields return in bounded batches.
spawning = asyncio.create_task(asyncio.create_subprocess_exec(
sys.executable, '-m', 'app.infrastructure.json_processing',
model_cls.__module__, model_cls.__name__, str(path),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
limit=FRAME_BYTES,
))
try:
child = await asyncio.shield(spawning)
except OSError:
raise ValueError('DEPENDENCY_UNAVAILABLE') from None
except asyncio.CancelledError:
# Cancellation during process creation still owns the eventual child.
while not spawning.done():
try:
await asyncio.shield(spawning)
except asyncio.CancelledError:
continue
child = spawning.result()
if child.returncode is None:
child.kill()
reap = asyncio.create_task(child.wait())
while not reap.done():
try:
await asyncio.shield(reap)
except asyncio.CancelledError:
continue
reap.result()
raise
values, kinds, fields_set = {}, {}, None
try:
while True:
length = struct.unpack('!I', await child.stdout.readexactly(4))[0]
if length > FRAME_BYTES:
raise ValueError('DEPENDENCY_UNAVAILABLE')
name, kind, value = pickle.loads(await child.stdout.readexactly(length))
if name is None:
if value is None:
raise ValueError('VALIDATION_ERROR')
fields_set = value
break
if kind == 0:
values[name] = value
else:
values.setdefault(name, []).extend(value)
kinds[name] = kind
await asyncio.sleep(0)
if await child.wait() != 0:
raise ValueError('DEPENDENCY_UNAVAILABLE')
for name, kind in kinds.items():
if kind == 2:
values[name] = tuple(values[name])
# These exact values and fields_set were validated in our child. Repeating
# validation here would put the expensive work back on the API's loop.
return model_cls.model_construct(_fields_set=fields_set, **values)
except (asyncio.IncompleteReadError, OSError, pickle.UnpicklingError):
raise ValueError('DEPENDENCY_UNAVAILABLE') from None
finally:
if child.returncode is None:
child.kill()
reap = asyncio.create_task(child.wait())
while not reap.done():
try:
await asyncio.shield(reap)
except asyncio.CancelledError:
continue
reap.result()
def _send(record):
payload = pickle.dumps(record, protocol=5)
if len(payload) > FRAME_BYTES:
raise ValueError('Validated DTO field exceeds internal frame bound')
sys.stdout.buffer.write(struct.pack('!I', len(payload)))
sys.stdout.buffer.write(payload)
def _worker(module, name, path):
model_cls = getattr(importlib.import_module(module), name)
try:
model = validate_json(Path(path).read_bytes(), model_cls)
except ValueError:
_send((None, 0, None))
return
for field in model_cls.model_fields:
value = getattr(model, field)
if isinstance(value, (tuple, list)):
kind = 2 if isinstance(value, tuple) else 1
# 64 supported 500-character identifiers fit well below FRAME_BYTES,
# even as raw four-byte UTF-8 scalars. Empty arrays still carry type.
for offset in range(0, max(1, len(value)), 64):
_send((field, kind, value[offset:offset + 64]))
else:
_send((field, 0, value))
_send((None, 0, model.model_fields_set))
if __name__ == '__main__':
_worker(*sys.argv[1:])
+10 -4
View File
@@ -149,7 +149,9 @@ class OpenRouterVision:
try:
native = json.loads(content)
choices = native.get("choices")
if not choices or not isinstance(choices, list):
if not isinstance(choices, list) or len(choices) != 1:
raise ExtractionError("Vision transcription incomplete or blocked")
if choices[0].get("finish_reason") not in (None, "stop"):
raise ExtractionError("Vision transcription incomplete or blocked")
message = choices[0].get("message", {})
raw_text = message.get("content", "")
@@ -168,14 +170,14 @@ class OpenRouterVision:
if "ordinal" not in b or type(b["ordinal"]) is not int:
b["ordinal"] = i
transcript = Transcription.model_validate(raw_dict)
if not transcript.complete or transcript.warnings or not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain")
if not transcript.blocks:
raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = []
for index, block in enumerate(transcript.blocks):
locator = block.source_locator if block.source_locator and block.source_locator.startswith(section + "/") else f"{section}/block/{index + 1}"
if unreadable(block.text) or any("unreadable" in w.lower() or "ناخوانا" in w for w in block.warnings):
if unreadable(block.text):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={
"ordinal": index,
@@ -185,6 +187,10 @@ class OpenRouterVision:
"source_locator": locator,
"search_text": normalize_search_text(block.text, processing_profile["normalizer"])
}))
# Recognition diagnostics belong to the exact review candidate.
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+2 -2
View File
@@ -1,4 +1,4 @@
"""Trusted admin review services; HTTP authentication/Origin/CSRF is not implemented."""
"""Trusted admin review services; HTTP identity/Origin/CSRF is enforced by the API."""
import base64
import json
from uuid import UUID, uuid4
@@ -92,7 +92,7 @@ class SqlReviewRepository:
if after is not None:
matches = [i for i, p in enumerate(pointers) if p["evidence_sha256"] == after]
if not matches:
raise IntakeError("REVIEW_STALE", "Review cursor no longer available")
raise IntakeError("VALIDATION_ERROR", "Review cursor no longer available")
start = matches[0] + 1
from app.modules.documents.extraction_artifacts import bounded_json_size
remaining = document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"]
+17
View File
@@ -0,0 +1,17 @@
"""Selected voice transport construction shared by the API and operator smoke."""
import asyncio
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
async def create_adapter(config, limits):
config.require_voice()
connect = connect_gemini if config.provider == 'gemini' else connect_openai
transport = await asyncio.wait_for(connect(config.selected_key.get_secret_value(),
config.selected_model, config.selected_proxy, limits), limits.connect_timeout_seconds)
try:
adapter = GeminiLiveAdapter if config.provider == 'gemini' else RealtimeAdapter
return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits)
except BaseException:
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
raise
+214
View File
@@ -0,0 +1,214 @@
"""Pre-payload limits and bounded reassembly for Uvicorn legacy WebSocket backend.
Eight queued messages plus one assembling and one delivered message fit the
96,000-byte application receive budget even for maximum-size binary messages.
Validated LIVE_* settings lower binary/control limits and queue/audio capacity.
"""
import asyncio
import codecs
from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
from websockets.exceptions import ProtocolError
from websockets.legacy.framing import Frame
from app.modules.voice.settings import RuntimeSettings
class BoundedWebSocketProtocol(WebSocketProtocol):
def __init__(self, config, server_state, app_state, _loop=None):
settings = getattr(config, 'ws_settings', None) or RuntimeSettings()
self.settings = settings
self.max_binary_message_bytes = settings.max_binary_message_bytes
self.max_client_control_bytes = settings.max_client_control_bytes
self.max_queued_audio_bytes = settings.max_queued_audio_bytes
self.max_queued_audio_messages = settings.max_queued_audio_messages
max_size = max(self.max_binary_message_bytes, self.max_client_control_bytes)
config.ws_max_size = max_size
config.ws_per_message_deflate = False
audio_budget = min(
self.max_queued_audio_messages,
max(1, self.max_queued_audio_bytes // self.max_binary_message_bytes)
)
queue_cap = max(1, audio_budget - 2) if audio_budget > 2 else 1
config.ws_max_queue = queue_cap
self.max_audio_messages = audio_budget
super().__init__(config, server_state, app_state, _loop)
self.message_remaining = None
self.assembling_scratch = None
self.assembling_type = None
self.in_flight_message = None
self.capacity_available = asyncio.Event()
self.capacity_available.set()
self.rejection_code = None
@property
def total_message_count(self):
count = 1 if self.assembling_type is not None else 0
count += len(self.messages)
if self.in_flight_message is not None:
count += 1
return count
@property
def current_audio_bytes(self):
total = len(self.assembling_scratch) if (self.assembling_scratch is not None and self.assembling_type == 2) else 0
total += sum(len(m) for m in self.messages if isinstance(m, (bytes, bytearray)))
if self.in_flight_message is not None and isinstance(self.in_flight_message, (bytes, bytearray)):
total += len(self.in_flight_message)
return total
def has_capacity(self):
if self.closed_event.is_set():
return True
if self.total_message_count >= self.max_audio_messages:
return False
if self.current_audio_bytes + self.max_binary_message_bytes > self.max_queued_audio_bytes:
return False
return True
async def wait_for_capacity(self):
while not self.closed_event.is_set():
if self.has_capacity():
return
self.capacity_available.clear()
await self.capacity_available.wait()
async def read_frame(self, max_size):
header = await self.reader.readexactly(2)
# Reject compressed/reserved bits before reading lengths, masks or payloads.
if header[0] & 0x70:
raise ProtocolError('Reserved bits are unsupported')
opcode = header[0] & 0x0f
if opcode in (1, 2):
if self.message_remaining is not None:
raise ProtocolError('Interleaved data message')
limit = self.max_client_control_bytes if opcode == 1 else self.max_binary_message_bytes
self.message_remaining = limit
elif opcode == 0:
if self.message_remaining is None:
raise ProtocolError('Unexpected continuation')
elif opcode not in (8, 9, 10):
raise ProtocolError('Invalid opcode')
bound = self.message_remaining if opcode in (0, 1, 2) else 125
if max_size is not None and opcode in (0, 1, 2):
bound = min(bound, max_size)
first = True
async def read(size):
nonlocal first
if first:
first = False
return header
return await self.reader.readexactly(size)
try:
frame = await Frame.read(read, mask=True, max_size=bound, extensions=[])
except Exception:
if opcode in (0, 1, 2):
self.message_remaining = None
raise
if opcode in (0, 1, 2):
self.message_remaining -= len(frame.data)
if frame.fin:
self.message_remaining = None
return frame
async def read_message(self):
await self.wait_for_capacity()
if self.closed_event.is_set():
return None
frame = await self.read_data_frame(max_size=self.max_size)
if frame is None:
return None
if frame.opcode == 1:
text = True
elif frame.opcode == 2:
text = False
else:
raise ProtocolError('unexpected opcode')
if frame.fin:
if text:
return frame.data.decode('utf-8')
return bytes(frame.data)
# Fragmentation with finite retained metadata and scratch storage
scratch = bytearray()
self.assembling_scratch = scratch
self.assembling_type = 1 if text else 2
try:
if text:
decoder = codecs.getincrementaldecoder('utf-8')(errors='strict')
decoder.decode(frame.data, frame.fin)
if frame.data:
scratch.extend(frame.data)
while not frame.fin:
frame = await self.read_data_frame(max_size=self.message_remaining)
if frame is None:
raise ProtocolError('incomplete fragmented message')
if frame.opcode != 0:
raise ProtocolError('expected continuation frame')
if text:
decoder.decode(frame.data, frame.fin)
if frame.data:
scratch.extend(frame.data)
if text:
return scratch.decode('utf-8')
return bytes(scratch)
finally:
self.assembling_scratch = None
self.assembling_type = None
self.message_remaining = None
self.capacity_available.set()
async def recv(self):
self._release_in_flight()
msg = await super().recv()
self._record_in_flight(msg)
return msg
def _release_in_flight(self):
if self.in_flight_message is not None:
self.in_flight_message = None
self.capacity_available.set()
def _record_in_flight(self, msg):
self.in_flight_message = msg
def _cleanup_resources(self):
self.assembling_scratch = None
self.assembling_type = None
self.message_remaining = None
self.in_flight_message = None
self.capacity_available.set()
def connection_lost(self, exc):
self._cleanup_resources()
super().connection_lost(exc)
def fail_connection(self, code=1006, reason=''):
if code in (1002, 1007, 1009):
self.rejection_code = code
self._cleanup_resources()
super().fail_connection(code, reason)
async def asgi_receive(self):
message = await super().asgi_receive()
if message['type'] == 'websocket.disconnect' and self.rejection_code is not None:
# A failed parser stops reading, so close_code can be 1006 even after
# sending a standards-compliant 1007. Preserve the actual rejection.
message = dict(message, code=self.rejection_code)
return message
async def close(self, code=1000, reason=''):
self._cleanup_resources()
return await super().close(code, reason)
+27 -17
View File
@@ -237,23 +237,7 @@ class SqlWorkerRepository:
"""), dict(org=org, actor=administrator_id, document=document_id, request=request_id)).scalar_one_or_none()
if previous is not None:
return dict(replayed=True, **previous)
try:
read_original(store, snapshot)
except (OSError, ValueError, KeyError):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Retained original is unavailable or incompatible") from None
review_state = snapshot.get("extraction_state", {})
if review_state.get("candidates"):
if any((p.get("decision") or {}).get("decision") == "reject" for p in review_state["candidates"]):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Rejected evidence cannot be retried")
if not reviews_approved(review_state):
raise IntakeError("EXTRACTION_REVIEW_PENDING", "All current evidence must be approved before retry")
if candidates is None:
from .extraction_candidates import LocalExtractionCandidates
candidates = LocalExtractionCandidates(self.settings.extraction_directory, original_directory=store.directory)
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)
for pointer in review_state["candidates"]:
service._body(pointer, snapshot)
self.validate_retry_snapshot(snapshot, store, candidates)
with self.engine.begin() as connection:
check_compatibility(connection, self.settings.embedding_profile)
org = administrator(connection, administrator_id)
@@ -300,6 +284,32 @@ class SqlWorkerRepository:
request=request_id, response=json.dumps(response)))
return dict(replayed=False, **response)
def validate_retry_snapshot(self, snapshot, store, candidates=None):
"""Shared eligibility for polling and retry; frozen policy cannot waive retained reviews."""
if (snapshot["status"] != "failed" or snapshot["deleted_at"] is not None
or snapshot["content_purged_at"] is not None or snapshot["is_active"]
or snapshot["chunk_count"] != 0):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Only eligible failed documents can be retried")
try:
from app.modules.documents.extraction_artifacts import ocr_review_required
ocr_review_required(snapshot["processing_profile"])
read_original(store, snapshot)
except (OSError, ValueError, KeyError):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Retained original is unavailable or incompatible") from None
review_state = snapshot.get("extraction_state", {})
if review_state.get("candidates"):
if any((p.get("decision") or {}).get("decision") == "reject" for p in review_state["candidates"]):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Rejected evidence cannot be retried")
if not reviews_approved(review_state):
raise IntakeError("EXTRACTION_REVIEW_PENDING", "All current evidence must be approved before retry")
if candidates is None:
from .extraction_candidates import LocalExtractionCandidates
candidates = LocalExtractionCandidates(self.settings.extraction_directory, original_directory=store.directory)
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)
for pointer in review_state["candidates"]:
service._body(pointer, snapshot)
def review_resume(self, claim, candidates, store):
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)
+9 -5
View File
@@ -10,6 +10,8 @@ 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.documents import router as documents_router
from app.api.v1.knowledge import router as knowledge_router
from app.api.v1 import dependencies
from app.infrastructure.blocking import blocking, shutdown_pool
from app.modules.voice.configuration import VoiceSettings
@@ -23,6 +25,7 @@ async def lifespan(app):
try:
engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(dependencies.prepare_search_tools)
await blocking(lifecycle.reconcile_startup)
app.state.ready = True
yield
@@ -67,7 +70,8 @@ app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan)
app.state.ready = False
config = VoiceSettings()
app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True,
allow_methods=['GET','POST'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID'])
allow_methods=['GET','POST','PATCH'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID','Idempotency-Key'],
expose_headers=['X-Request-ID','Idempotency-Replayed'])
@app.middleware('http')
async def transport(request, call_next):
@@ -85,16 +89,16 @@ async def transport(request, call_next):
result.headers['X-Request-ID'] = request_id
return result
def envelope(request, code, status):
def envelope(request, code, status, details=None):
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)}})
'retryable': status in (429,503), **({'details':details} if details else {})}})
@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)
return envelope(request, detail.get('code', 'NOT_FOUND' if exc.status_code == 404 else 'REQUEST_FAILED'), exc.status_code, detail.get('details'))
@app.exception_handler(RequestValidationError)
async def dto_error(request, exc):
@@ -104,7 +108,7 @@ async def dto_error(request, exc):
async def unexpected_error(request, exc):
return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503)
for router in (auth_router, identity_router, conversations_router, voice_router):
for router in (auth_router, identity_router, conversations_router, voice_router, documents_router, knowledge_router):
app.include_router(router, prefix='/api/v1')
@app.get('/health/live')
+6 -3
View File
@@ -250,7 +250,7 @@ def factual_context_units(blocks):
source_units.append([block.group_id, [block], True])
else:
source_units.append([None, [block], False])
scopes, resolved = [], []
scopes, resolved, preamble = [], [], []
def close_scope():
scope = scopes.pop()
@@ -263,7 +263,7 @@ def factual_context_units(blocks):
raise ExtractionError("Unresolved non-FAQ source group")
# Validate every group, including excluded groups, before selection.
associate_dependencies([(group, unit, True)])
context = [b for scope in scopes for b in scope["blocks"]]
context = preamble + [b for scope in scopes for b in scope["blocks"]]
for scope in scopes:
scope["used"] = True
resolved.append([group, context + unit, True])
@@ -278,10 +278,13 @@ def factual_context_units(blocks):
while scopes and scopes[-1]["level"] >= level:
close_scope()
scopes.append(dict(level=level, blocks=[block], used=False))
elif not scopes and not resolved and block.parent_block_id is None:
# Initial source prose is document-wide context, never pair-local.
preamble.append(block)
elif scopes and not scopes[-1]["used"] and block.parent_block_id is None:
scopes[-1]["blocks"].append(block)
else:
# Unheaded preambles and prose between pairs have no reliable scope.
# Prose after pairs still has no reliable association.
raise ExtractionError("Ambiguous governing context for factual FAQ")
while scopes:
close_scope()
+9 -5
View File
@@ -11,7 +11,7 @@ import unicodedata
from uuid import UUID
from zipfile import ZipFile
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact, ocr_review_required
from .formats import DOCX_MIME, validate_docx, validate_image
from .normalization import normalize_search_text, normalized_inputs
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
@@ -230,6 +230,7 @@ class PageBlockExtractor:
self.owned()
self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider
self.original_hash, self.profile, self.reviewed = original_hash, profile, False
self.automatic_ocr = False
self.document_id, self.title = document_id, title
self.annotations = []
extraction = profile["extraction"]
@@ -273,7 +274,8 @@ class PageBlockExtractor:
blocks = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate(blocks))
envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"],
complete=True, quality_decision="reviewed" if self.reviewed else "passed",
complete=True, quality_decision=("partially_reviewed" if self.reviewed and self.automatic_ocr
else "reviewed" if self.reviewed else "passed"),
review_annotations=tuple(self.annotations), blocks=blocks)
normalized_inputs(envelope, profile)
payload = serialize_artifact(envelope, profile)
@@ -795,7 +797,8 @@ class PageBlockExtractor:
data = {"artifact_schema": 1, "document_id": str(self.document_id), "title": self.title,
"original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest,
"normalization_policy": self.profile["normalizer"], "complete": True,
"quality_decision": "reviewed" if self.reviewed else "passed", "warnings": [],
"quality_decision": ("partially_reviewed" if self.reviewed and getattr(self, "automatic_ocr", False)
else "reviewed" if self.reviewed else "passed"), "warnings": [],
"review_annotations": [a.model_dump(mode="json") for a in self.annotations],
"blocks": [dict(b.model_dump(mode="json"), ordinal=i) for i, b in enumerate(blocks)]}
bounded_json_size(data, self.profile["extraction"]["max_extraction_artifact_bytes"])
@@ -824,11 +827,12 @@ class PageBlockExtractor:
or b.page != page or not b.source_locator.startswith(locator + "/")
or unreadable(b.text)):
raise ExtractionError("Vision evidence identity, location or readability mismatch")
if any("unreadable" in w.lower() or "ناخوانا" in w for w in b.warnings):
raise ExtractionError("Vision reports unreadable source regions")
# Validate local source relationships before manually attesting to the result.
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
complete=True, quality_decision="passed",
blocks=tuple(blocks))
if not ocr_review_required(self.profile) and not any(b.warnings for b in blocks):
self.automatic_ocr = True
return blocks
return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))
@@ -11,6 +11,14 @@ class LegacyProcessingProfile(ValueError):
pass
def ocr_review_required(profile: Mapping) -> bool:
"""Fail closed for legacy snapshots; deployment defaults never reinterpret jobs."""
value = profile.get("extraction", {}).get("ocr_review_required", True)
if type(value) is not bool:
raise ValueError("Invalid frozen OCR review policy")
return value
def processing_profile_kind(profile: Mapping) -> str:
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
return "legacy-v1"
@@ -20,6 +28,7 @@ def processing_profile_kind(profile: Mapping) -> str:
def extraction_profile_digest(profile: Mapping) -> str:
ocr_review_required(profile)
if processing_profile_kind(profile) == "legacy-v1":
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
# Faithful extraction is reusable across chunk/embedding/normalization changes.
+13 -11
View File
@@ -22,9 +22,10 @@ def unsafe_display_character(character: str) -> bool:
{"RLO", "LRO", "RLE", "LRE", "PDF", "LRI", "RLI", "FSI", "PDI"})
def normalized_title(path: Path, title: str | None) -> str:
filename = unicodedata.normalize("NFC", Path(path).name)
value = unicodedata.normalize("NFC", title if title is not None else Path(filename).stem)
def normalized_title(path: Path, title: str | None, *, filename: str | None = None) -> str:
name = filename if filename is not None else Path(path).name
nfc_name = unicodedata.normalize("NFC", name)
value = unicodedata.normalize("NFC", title if title is not None else Path(nfc_name).stem)
return " ".join(value.split())
@@ -34,7 +35,7 @@ def payload_hash(sha: str, title: str) -> str:
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
def replay_payload_hash(path: Path, title: str | None, size_bytes: int, *, filename: str | None = None) -> str:
"""Stream at most the accepted length plus one byte, with constant memory."""
path = Path(path)
digest, total = hashlib.sha256(), 0
@@ -54,12 +55,13 @@ def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
raise IntakeError("INVALID_FILE", "Cannot read input file") from None
if total != size_bytes:
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
return payload_hash(digest.hexdigest(), normalized_title(path, title))
return payload_hash(digest.hexdigest(), normalized_title(path, title, filename=filename))
def prepare_file(path: Path, title: str | None, settings) -> dict:
def prepare_file(path: Path, title: str | None, settings, *, filename: str | None = None) -> dict:
path = Path(path)
filename = unicodedata.normalize("NFC", path.name)
display_name = filename if filename is not None else path.name
filename = unicodedata.normalize("NFC", display_name)
# Display names are portable and reject path delimiters, controls and bidi marks.
if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename
or any(c in '<>:"/\\|?*' or unsafe_display_character(c)
@@ -69,7 +71,7 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
extension = Path(filename).suffix.lower()
if extension not in settings.accepted_formats:
raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
canonical_title = normalized_title(path, title)
canonical_title = normalized_title(path, title, filename=filename)
if (not canonical_title or len(canonical_title) > 200
or any(unsafe_display_character(c) for c in canonical_title)):
raise IntakeError("INVALID_FILE", "Title must contain 1-200 display characters")
@@ -96,16 +98,16 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
def import_document(repository: IntakeRepository, store: FileStore, settings, *, path,
administrator_id, request_id, title=None):
administrator_id, request_id, title=None, filename=None):
administrator_id, request_id = UUID(str(administrator_id)), UUID(str(request_id))
org, previous = repository.lookup(settings, administrator_id, request_id)
if previous is not None:
# Existing requests compare payloads independently of current acceptance policy.
# File I/O is outside database transactions and creates no candidate.
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"])
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"], filename=filename)
result = repository.replay(org, administrator_id, previous, submitted_hash)
return {"replayed": True, "document": result}
prepared = prepare_file(path, title, settings)
prepared = prepare_file(path, title, settings, filename=filename)
key = store.put(prepared["content"])
replayed, conflict, result = repository.create(
settings, prepared, key, administrator_id, request_id, org)
+2
View File
@@ -58,6 +58,7 @@ class IngestionSettings(BaseSettings):
vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
ocr_review_required: bool = True
normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
chunking_policy: str = Field(default="paragraph-v1", min_length=1)
render_dpi: int = Field(default=144, gt=0, le=600)
@@ -211,6 +212,7 @@ class IngestionSettings(BaseSettings):
"vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
"ocr_review_required": self.ocr_review_required,
"render_dpi": self.render_dpi,
"max_rendered_page_pixels": self.max_rendered_page_pixels,
"max_pdf_pages": self.max_pdf_pages,
+1 -1
View File
@@ -67,7 +67,7 @@ class ExtractionEnvelope(BaseModel):
extraction_profile_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
normalization_policy: str = Field(min_length=1)
complete: Literal[True]
quality_decision: Literal["passed", "reviewed"]
quality_decision: Literal["passed", "reviewed", "partially_reviewed"]
warnings: tuple[str, ...] = ()
review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1)
+21 -6
View File
@@ -10,7 +10,7 @@ from threading import Event, Thread
from .chunking import chunk_extraction
from .embeddings import EmbeddingError, stage_document
from .extraction import ExtractionError, ReviewRequired
from .extraction_artifacts import extraction_profile_digest
from .extraction_artifacts import extraction_profile_digest, ocr_review_required
from .review import FactualReviewRequired, prepare_chunks
from .operational_limits import validate_worker_durations
@@ -63,21 +63,36 @@ def validate_source(envelope, document, content):
if envelope.title != document["title"]:
raise ExtractionError("Extraction title differs from immutable source")
warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings))
if warnings and envelope.quality_decision != "reviewed":
from .extraction import unreadable, PLACEHOLDER
from .review import factual_groups
groups = factual_groups(envelope)
if any(unreadable(b.text) or (PLACEHOLDER.search(b.text) and b.group_id not in groups)
for b in envelope.blocks):
raise ExtractionError("Unreadable or placeholder extracted evidence")
if warnings and envelope.quality_decision not in ("reviewed", "partially_reviewed"):
raise ExtractionError("Unreviewed extraction warnings")
if any("unreadable" in w.lower() or "\u0646\u0627\u062e\u0648\u0627\u0646\u0627" in w for w in warnings):
raise ExtractionError("Unreadable retained evidence")
mime = document["mime_type"]
if envelope.quality_decision == "partially_reviewed":
inspected = {annotation.locator for annotation in envelope.review_annotations}
automatic = [b for b in envelope.blocks if not any(
b.source_locator.startswith(locator + "/") for locator in inspected)]
if (mime != "application/pdf" or ocr_review_required(document["processing_profile"])
or not inspected or not automatic or envelope.warnings
or any(b.method not in ("vision", "ocr") or b.warnings for b in automatic)):
raise ExtractionError("Mixed extraction requires exact inspected non-automatic evidence")
automatic_ocr = (not ocr_review_required(document["processing_profile"])
and envelope.quality_decision == "passed" and not warnings
and all(b.method in ("vision", "ocr") for b in envelope.blocks))
if mime == "application/pdf":
import pymupdf
with pymupdf.open(stream=content, filetype="pdf") as source:
if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"]
or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))):
raise ExtractionError("Incomplete PDF source coverage")
if envelope.quality_decision != "reviewed":
if envelope.quality_decision not in ("reviewed", "partially_reviewed") and not automatic_ocr:
raise ExtractionError("PDF extraction requires inspection")
elif mime in ("image/jpeg", "image/png"):
if envelope.quality_decision != "reviewed" or any(
if (envelope.quality_decision != "reviewed" and not automatic_ocr) or any(
b.page is not None or b.method not in ("vision", "ocr") for b in envelope.blocks):
raise ExtractionError("Image extraction requires inspected complete evidence")
elif mime in ("text/markdown", "text/plain",
+16 -1
View File
@@ -183,9 +183,24 @@ class SearchToolRunner:
self._lock.wait_for(lambda: self._admitted == 0)
def prepare_search_tools():
"""Resolve the optional framework before voice admission/tool deadlines."""
try:
from langchain_core.tools import StructuredTool
except ModuleNotFoundError as exc:
# Document-only API installations keep the existing optional boundary.
if exc.name != 'langchain_core':
raise
return None
# Importing StructuredTool resolves its callback/configuration dependencies.
return StructuredTool
def create_search_tool(service, context, runner):
"""Build only on explicit opt-in; core imports do not require LangChain."""
from langchain_core.tools import StructuredTool
StructuredTool = prepare_search_tools()
if StructuredTool is None:
raise ModuleNotFoundError('Install the existing search/voice extra for LangChain tools')
trusted = context
+21
View File
@@ -0,0 +1,21 @@
"""Fail closed without labelling unavailable authority as verified revocation."""
from sqlalchemy.exc import SQLAlchemyError
from app.modules.knowledge.service import KnowledgeError
def authority_failure_code(exc):
if isinstance(exc, KnowledgeError) and exc.code in {'ACTOR_UNAVAILABLE', 'CONTEXT_REVOKED'}:
return 'CONTEXT_REVOKED'
if isinstance(exc, TimeoutError):
return 'SEARCH_TIMEOUT'
if isinstance(exc, SQLAlchemyError):
return 'DEPENDENCY_UNAVAILABLE'
if isinstance(exc, ValueError):
if str(exc) == 'SERVICE_BUSY':
return 'SEARCH_SATURATED'
if str(exc) in {'AUTH_REQUIRED', 'USER_DISABLED', 'ACCOUNT_DISABLED', 'SESSION_REVOKED', 'SESSION_EXPIRED',
'CONTEXT_REVOKED', 'CONVERSATION_STALE', 'CONVERSATION_CLOSED',
'CONVERSATION_NOT_FOUND', 'SESSION_NOT_FOUND', 'LIVE_SESSION_EXPIRED',
'LIVE_SESSION_UNUSABLE'}:
return 'CONTEXT_REVOKED'
return 'DEPENDENCY_UNAVAILABLE'
+61 -11
View File
@@ -2,39 +2,51 @@
from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
from pydantic import Field, SecretStr, field_validator, model_validator
from pydantic import AliasChoices, 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'
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
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
openai_realtime_api_key: SecretStr = SecretStr('')
openai_realtime_model: str = Field(default='gpt-realtime-mini', min_length=1, max_length=200)
openai_realtime_voice: str = Field(default='shimmer', min_length=1, max_length=80)
openai_realtime_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
voice_transport_testing: bool = False
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')
def __init__(self, **values):
# Settings sources normalize aliases and would otherwise discard conflicting init keys.
aliases = [key for key in values if key.lower() in ('voice_provider', 'provider')]
if len({values[key] for key in aliases}) > 1:
raise ValueError('Conflicting voice provider aliases')
super().__init__(**values)
@field_validator('gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_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')
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy', 'openai_realtime_proxy')
@classmethod
def urls(cls, value, info):
if info.field_name == 'gemini_proxy' and value is None:
if info.field_name.endswith('_proxy') and value is None:
return value
values = (value,) if info.field_name == 'gemini_proxy' else value
values = (value,) if info.field_name.endswith('_proxy') else value
if not values or len(values) > 20:
raise ValueError('Explicit bounded trusted endpoints required')
for entry in values:
@@ -43,7 +55,7 @@ class VoiceSettings(BaseSettings):
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')
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name.endswith('_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')
@@ -55,11 +67,49 @@ class VoiceSettings(BaseSettings):
raise ValueError('Insecure cookies require loopback-only development origins')
return self
@classmethod
def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings):
# Normalize aliases before source merging; ordinary init > env > dotenv priority remains.
deployed = {**dotenv_settings.env_vars, **env_settings.env_vars}
if ('voice_provider' in deployed and 'provider' in deployed
and deployed['voice_provider'] != deployed['provider']):
raise ValueError('Conflicting VOICE_PROVIDER and PROVIDER')
def normalized(source):
def read():
values = source()
aliases = [key for key in ('VOICE_PROVIDER', 'PROVIDER', 'provider') if key in values]
if len({values[key] for key in aliases}) > 1:
raise ValueError('Conflicting voice provider aliases')
if aliases:
selected = values[aliases[0]]
for key in aliases:
del values[key]
values['VOICE_PROVIDER'] = selected
return values
return read
return tuple(normalized(source) for source in (init_settings, env_settings, dotenv_settings, file_secret_settings))
@property
def selected_model(self):
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
@property
def selected_voice(self):
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
@property
def selected_proxy(self):
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
@property
def selected_key(self):
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
def require_voice(self):
key = self.gemini_api_key.get_secret_value()
key = self.selected_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)
return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
+9 -2
View File
@@ -78,12 +78,18 @@ class LiveLifecycleService:
raise ValueError('LIVE_SESSION_UNUSABLE')
return row
@staticmethod
def _calibration_status(row):
search = (row["execution_profile"] or {}).get("search", {})
return "calibrated" if search.get("calibration_id") else search.get("calibration_status", "unknown")
@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)
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed,
calibration_status=LiveLifecycleService._calibration_status(row))
@staticmethod
def _terminal(conn, sid, reason, *, failed=False):
@@ -250,7 +256,8 @@ class LiveLifecycleService:
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)
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results,
calibration_status=self._calibration_status(row))
def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
arguments = SearchInput.model_validate(arguments).model_dump()
+3 -1
View File
@@ -1,4 +1,5 @@
"""Bounded, session-local voice state machine. HTTP identity/persistence is Phase 2."""
from app.modules.voice.authority import authority_failure_code
import asyncio
import base64
from collections import deque
@@ -235,7 +236,8 @@ class VoiceRuntime:
try:
valid = await asyncio.wait_for(self.authority_check(
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds)
except Exception:
except Exception as exc:
self.fail(authority_failure_code(exc))
valid = False
return valid
+34
View File
@@ -0,0 +1,34 @@
"""Supported single-process API entrypoint: python -m app.server."""
import argparse
import uvicorn
from app.infrastructure.voice_websocket import BoundedWebSocketProtocol
from app.modules.voice.settings import RuntimeSettings
def server_config(app='app.main:app', *, host='127.0.0.1', port=8000, settings=None, **kwargs):
if settings is None:
settings = RuntimeSettings()
max_binary = settings.max_binary_message_bytes
max_control = settings.max_client_control_bytes
max_size = max(max_binary, max_control)
audio_budget = min(settings.max_queued_audio_messages, max(1, settings.max_queued_audio_bytes // max_binary))
queue = max(1, audio_budget - 2) if audio_budget > 2 else 1
config = uvicorn.Config(app, host=host, port=port, workers=1,
ws=BoundedWebSocketProtocol, ws_max_size=max_size, ws_max_queue=queue,
ws_per_message_deflate=False, **kwargs)
config.ws_settings = settings
return config
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', type=int, default=8000)
args = parser.parse_args()
uvicorn.Server(server_config(host=args.host, port=args.port)).run()
if __name__ == '__main__':
main()
+3 -9
View File
@@ -1,4 +1,4 @@
"""Operator-only diagnostic Gemini/search smoke; no HTTP/text-chat route."""
"""Operator-only diagnostic selected-provider/search smoke; no HTTP/text-chat route."""
import argparse
import asyncio
from dataclasses import asdict
@@ -19,6 +19,7 @@ from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
from app.modules.voice.configuration import VoiceSettings
from app.infrastructure.voice_provider import create_adapter
def preflight(engine, settings, actor, cutoff):
if cutoff.profile != asdict(settings.embedding_profile):
@@ -50,13 +51,6 @@ async def run(service, runner, actor, config, query, seconds, max_calls):
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
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):
adapter = await create_adapter(config, limits)
async def emit(event):
@@ -129,7 +123,7 @@ def main(argv=None):
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize Gemini Live plus up to --max-tool-calls query embeddings")
help="Authorize the selected voice provider 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("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
args = parser.parse_args(argv)