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
+15 -2
View File
@@ -78,12 +78,18 @@ INGEST_MAX_EXTRACTED_BLOCKS=10000
INGEST_EMBEDDING_SEND_DIMENSIONS=false INGEST_EMBEDDING_SEND_DIMENSIONS=false
INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216 INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216
# Temporary sole voice provider; independent of extraction and embedding credentials. # Backend voice selection; Gemini is the temporary default. No automatic fallback.
PROVIDER=gemini # Legacy PROVIDER is accepted; do not set it differently from VOICE_PROVIDER.
VOICE_PROVIDER=gemini
GEMINI_API_KEY= GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.0-flash-exp GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede GEMINI_VOICE=Aoede
# GEMINI_PROXY=https://trusted-proxy.example:443 # GEMINI_PROXY=https://trusted-proxy.example:443
# Required only when VOICE_PROVIDER=openai. Independent of embedding/LLM OPENAI_API_KEY.
OPENAI_REALTIME_API_KEY=
OPENAI_REALTIME_MODEL=gpt-realtime-mini
OPENAI_REALTIME_VOICE=shimmer
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
TRUSTED_ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"] TRUSTED_ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"]
TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"] TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"]
# Explicit local development only. Production requires HTTPS and true. # Explicit local development only. Production requires HTTPS and true.
@@ -92,3 +98,10 @@ AUTH_SESSION_SECONDS=28800
LIVE_SESSION_SECONDS=600 LIVE_SESSION_SECONDS=600
# Path to a measured, profile-compatible calibrated report; never a status placeholder. # Path to a measured, profile-compatible calibrated report; never a status placeholder.
# SEARCH_CALIBRATION_REPORT=/absolute/path/measured-report.json # SEARCH_CALIBRATION_REPORT=/absolute/path/measured-report.json
# Explicit connectivity testing only; no uncalibrated document evidence is admitted.
# Sessions expose calibration_status=uncalibrated. Production default remains false.
VOICE_TRANSPORT_TESTING=false
# OCR supervisor gate for NEW jobs only; false admits only automatically validated OCR.
# Existing/legacy jobs keep their frozen policy. Factual/non-OCR review remains required.
INGEST_OCR_REVIEW_REQUIRED=true
+133 -3
View File
@@ -1,6 +1,10 @@
"""Cookie-only identity and shared backend services, lazily constructed.""" """Cookie-only identity and shared backend services, lazily constructed."""
import asyncio
from datetime import timedelta from datetime import timedelta
import json 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 typing import Annotated
from fastapi import Depends, Header, HTTPException, Request from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.engine import Engine 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.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings from app.modules.voice.configuration import VoiceSettings
from app.modules.knowledge.service import SearchService 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 from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None _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(): def get_voice_settings():
return VoiceSettings() return VoiceSettings()
def get_ingestion_settings():
return IngestionSettings()
def error(code): def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND', 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', 'SESSION_REVOKED':'AUTH_REQUIRED','SESSION_EXPIRED':'AUTH_REQUIRED','ACCOUNT_DISABLED':'AUTH_REQUIRED',
'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED', 'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED',
'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code) 'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code)
codes = { 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, 'AUTH_REQUIRED': 401, 'INVALID_CREDENTIALS': 401, 'ACCOUNT_DISABLED': 401,
'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403, 'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403,
'FORBIDDEN_ORIGIN': 403, 'CONVERSATION_NOT_FOUND': 404, 'SESSION_NOT_FOUND': 404, '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.'}) 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(): def get_engine():
global _ENGINE global _ENGINE
if _ENGINE is None: if _ENGINE is None:
@@ -71,13 +193,15 @@ def get_search_service(engine: Annotated[Engine, Depends(get_engine)]):
global _SEARCH_SERVICE global _SEARCH_SERVICE
if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine: if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine:
settings = IngestionSettings() settings = IngestionSettings()
path = VoiceSettings().search_calibration_report voice = VoiceSettings()
path = voice.search_calibration_report
cutoff = None cutoff = None
if path is not None: if path is not None:
try: try:
cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8'))) cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8')))
except (ValueError, OSError, KeyError, TypeError, AttributeError): 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 from app.worker import factories
_, provider_factory = factories(settings) _, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile()) 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) require_origin(request, config)
if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token): if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token):
raise error('CSRF_TOKEN_INVALID') 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 import asyncio
from dataclasses import asdict from dataclasses import asdict
import json import json
import logging import logging
from typing import Annotated from typing import Annotated, Literal
from uuid import UUID from uuid import UUID
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, ConfigDict 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.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools from app.modules.voice.durable_tools import DurableTools
from app.modules.voice import registry 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.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.modules.documents.settings import IngestionSettings from app.modules.documents.settings import IngestionSettings
@@ -42,6 +43,7 @@ class LiveSessionResponse(BaseModel):
stream_path: str | None stream_path: str | None
expires_at: str expires_at: str
poll_url: str poll_url: str
calibration_status: Literal["calibrated", "uncalibrated", "unknown"] = "unknown"
class CloseLiveSessionResponse(BaseModel): class CloseLiveSessionResponse(BaseModel):
session_id: str session_id: str
@@ -59,14 +61,25 @@ def capability(config):
or cutoff.retrieval_policy != RETRIEVAL_POLICY): or cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise ValueError('CALIBRATION_REQUIRED') raise ValueError('CALIBRATION_REQUIRED')
except (OSError, ValueError, KeyError, TypeError, AttributeError): except (OSError, ValueError, KeyError, TypeError, AttributeError):
if config.voice_transport_testing:
return None
raise ValueError('CALIBRATION_REQUIRED') from None raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff 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) @router.post('', response_model=LiveSessionResponse, status_code=201)
def create_voice_session(req: CreateLiveSessionRequest, response: Response, def create_voice_session(req: CreateLiveSessionRequest, response: Response,
user: Annotated[UserContext, Depends(get_current_user)], user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)], lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)], config: Annotated[VoiceSettings, Depends(get_voice_settings)],
engine: Annotated[object, Depends(get_engine)],
_csrf: Annotated[None, Depends(require_csrf)] = None): _csrf: Annotated[None, Depends(require_csrf)] = None):
try: try:
# Recover replay before capability checks: a configuration change cannot alter identity. # 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 return result
cutoff = capability(config) cutoff = capability(config)
profile = config.profile() profile = config.profile()
profile["search"] = {"embedding": cutoff.profile, "calibration_id": cutoff.calibration_id, # Construct configured embedding transport only after replay recovery.
"retrieval_policy": cutoff.retrieval_policy, "distance": cutoff.distance} # 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, 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: except ValueError as exc:
raise error(str(exc)) from None raise error(str(exc)) from None
if result['replayed']: 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)) 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) info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
config.require_voice() 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') 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 any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != { or info['execution_profile'].get('search') != search_profile(search_service.cutoff, search_service.settings)):
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
raise ValueError('LIVE_SESSION_UNUSABLE') raise ValueError('LIVE_SESSION_UNUSABLE')
except Exception as exc: except Exception as exc:
logger.info('Stream admission rejected: %s', type(exc).__name__) 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. # Guard is released even if accept fails.
await websocket.accept() await websocket.accept()
limits = RuntimeSettings() limits = RuntimeSettings()
transport = await asyncio.wait_for(connect_gemini(config.gemini_api_key.get_secret_value(), adapter = await create_adapter(config, limits)
config.gemini_model, config.gemini_proxy, limits), limits.connect_timeout_seconds)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
async def authority_check(execution): async def authority_check(execution):
nonlocal outcome await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
try: await blocking(lifecycle_service.validate_stream, user, session_id, execution)
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
except ValueError as exc:
outcome = str(exc)
raise
return True return True
store = DurableTools(lifecycle_service, user, session_id) store = DurableTools(lifecycle_service, user, session_id)
async def emit(event): async def emit(event):
@@ -198,8 +204,20 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
await runtime.start() await runtime.start()
async def browser(): async def browser():
while runtime.usable: 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() message = await websocket.receive()
if message['type'] == 'websocket.disconnect': 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 return
if not runtime.ready and ready_sent.is_set(): if not runtime.ready and ready_sent.is_set():
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds) 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: elif message.get('text') is not None:
await runtime.client_control(message['text'].encode('utf-8')) await runtime.client_control(message['text'].encode('utf-8'))
async def monitor(): async def monitor():
nonlocal outcome
while runtime.usable: while runtime.usable:
await asyncio.sleep(.25) await asyncio.sleep(.25)
try: try:
await blocking(lifecycle_service.validate_stream, user, session_id) await blocking(lifecycle_service.validate_stream, user, session_id)
except ValueError as exc: except Exception as exc:
outcome = str(exc)
async with runtime.lock: async with runtime.lock:
runtime.fail('CONTEXT_REVOKED') runtime.fail(authority_failure_code(exc))
return return
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()), children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())] 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) await asyncio.wait_for(runtime.error_delivered.wait(), limits.send_timeout_seconds)
except TimeoutError: except TimeoutError:
pass 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') failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
except WebSocketDisconnect: except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED' outcome = 'LIVE_TRANSPORT_FAILED'
@@ -257,7 +273,16 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
except Exception: except Exception:
logger.warning('Bounded provider cleanup incomplete') logger.warning('Bounded provider cleanup incomplete')
try: 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: except Exception:
logger.warning('Live terminal persistence unavailable') logger.warning('Live terminal persistence unavailable')
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5) 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): if any("text" not in p for p in parts):
raise ExtractionError("Unexpected vision response parts") raise ExtractionError("Unexpected vision response parts")
transcript = Transcription.model_validate_json("".join(p["text"] for p in parts)) transcript = Transcription.model_validate_json("".join(p["text"] for p in parts))
if not transcript.complete or transcript.warnings or not transcript.blocks: if not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain") raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]: if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded") raise ExtractionError("Vision block limit exceeded")
blocks = [] 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 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 + "/")): or not block.source_locator.startswith(section + "/")):
raise ExtractionError("Vision returned incompatible evidence provenance") 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") raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={"search_text": blocks.append(block.model_copy(update={"search_text":
normalize_search_text(block.text, processing_profile["normalizer"])})) 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) return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc: except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError): 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: try:
native = json.loads(content) native = json.loads(content)
choices = native.get("choices") 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") raise ExtractionError("Vision transcription incomplete or blocked")
message = choices[0].get("message", {}) message = choices[0].get("message", {})
raw_text = message.get("content", "") raw_text = message.get("content", "")
@@ -168,14 +170,14 @@ class OpenRouterVision:
if "ordinal" not in b or type(b["ordinal"]) is not int: if "ordinal" not in b or type(b["ordinal"]) is not int:
b["ordinal"] = i b["ordinal"] = i
transcript = Transcription.model_validate(raw_dict) transcript = Transcription.model_validate(raw_dict)
if not transcript.complete or transcript.warnings or not transcript.blocks: if not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain") raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]: if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded") raise ExtractionError("Vision block limit exceeded")
blocks = [] blocks = []
for index, block in enumerate(transcript.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}" 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") raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={ blocks.append(block.model_copy(update={
"ordinal": index, "ordinal": index,
@@ -185,6 +187,10 @@ class OpenRouterVision:
"source_locator": locator, "source_locator": locator,
"search_text": normalize_search_text(block.text, processing_profile["normalizer"]) "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) return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc: except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError): 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 base64
import json import json
from uuid import UUID, uuid4 from uuid import UUID, uuid4
@@ -92,7 +92,7 @@ class SqlReviewRepository:
if after is not None: if after is not None:
matches = [i for i, p in enumerate(pointers) if p["evidence_sha256"] == after] matches = [i for i, p in enumerate(pointers) if p["evidence_sha256"] == after]
if not matches: 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 start = matches[0] + 1
from app.modules.documents.extraction_artifacts import bounded_json_size from app.modules.documents.extraction_artifacts import bounded_json_size
remaining = document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"] 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() """), dict(org=org, actor=administrator_id, document=document_id, request=request_id)).scalar_one_or_none()
if previous is not None: if previous is not None:
return dict(replayed=True, **previous) return dict(replayed=True, **previous)
try: self.validate_retry_snapshot(snapshot, store, candidates)
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)
with self.engine.begin() as connection: with self.engine.begin() as connection:
check_compatibility(connection, self.settings.embedding_profile) check_compatibility(connection, self.settings.embedding_profile)
org = administrator(connection, administrator_id) org = administrator(connection, administrator_id)
@@ -300,6 +284,32 @@ class SqlWorkerRepository:
request=request_id, response=json.dumps(response))) request=request_id, response=json.dumps(response)))
return dict(replayed=False, **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): def review_resume(self, claim, candidates, store):
from .review_repository import SqlReviewRepository from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store) 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.auth import router as auth_router, identity_router
from app.api.v1.conversations import router as conversations_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.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.api.v1 import dependencies
from app.infrastructure.blocking import blocking, shutdown_pool from app.infrastructure.blocking import blocking, shutdown_pool
from app.modules.voice.configuration import VoiceSettings from app.modules.voice.configuration import VoiceSettings
@@ -23,6 +25,7 @@ async def lifespan(app):
try: try:
engine = dependencies.get_engine() engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine) lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(dependencies.prepare_search_tools)
await blocking(lifecycle.reconcile_startup) await blocking(lifecycle.reconcile_startup)
app.state.ready = True app.state.ready = True
yield yield
@@ -67,7 +70,8 @@ app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan)
app.state.ready = False app.state.ready = False
config = VoiceSettings() config = VoiceSettings()
app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True, 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') @app.middleware('http')
async def transport(request, call_next): async def transport(request, call_next):
@@ -85,16 +89,16 @@ async def transport(request, call_next):
result.headers['X-Request-ID'] = request_id result.headers['X-Request-ID'] = request_id
return result 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, 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())), '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(StarletteHTTPException)
@app.exception_handler(HTTPException) @app.exception_handler(HTTPException)
async def http_error(request, exc): async def http_error(request, exc):
detail = exc.detail if isinstance(exc.detail, dict) else {} 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) @app.exception_handler(RequestValidationError)
async def dto_error(request, exc): async def dto_error(request, exc):
@@ -104,7 +108,7 @@ async def dto_error(request, exc):
async def unexpected_error(request, exc): async def unexpected_error(request, exc):
return envelope(request, 'DEPENDENCY_UNAVAILABLE', 503) 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.include_router(router, prefix='/api/v1')
@app.get('/health/live') @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]) source_units.append([block.group_id, [block], True])
else: else:
source_units.append([None, [block], False]) source_units.append([None, [block], False])
scopes, resolved = [], [] scopes, resolved, preamble = [], [], []
def close_scope(): def close_scope():
scope = scopes.pop() scope = scopes.pop()
@@ -263,7 +263,7 @@ def factual_context_units(blocks):
raise ExtractionError("Unresolved non-FAQ source group") raise ExtractionError("Unresolved non-FAQ source group")
# Validate every group, including excluded groups, before selection. # Validate every group, including excluded groups, before selection.
associate_dependencies([(group, unit, True)]) 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: for scope in scopes:
scope["used"] = True scope["used"] = True
resolved.append([group, context + unit, True]) resolved.append([group, context + unit, True])
@@ -278,10 +278,13 @@ def factual_context_units(blocks):
while scopes and scopes[-1]["level"] >= level: while scopes and scopes[-1]["level"] >= level:
close_scope() close_scope()
scopes.append(dict(level=level, blocks=[block], used=False)) 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: elif scopes and not scopes[-1]["used"] and block.parent_block_id is None:
scopes[-1]["blocks"].append(block) scopes[-1]["blocks"].append(block)
else: 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") raise ExtractionError("Ambiguous governing context for factual FAQ")
while scopes: while scopes:
close_scope() close_scope()
+9 -5
View File
@@ -11,7 +11,7 @@ import unicodedata
from uuid import UUID from uuid import UUID
from zipfile import ZipFile 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 .formats import DOCX_MIME, validate_docx, validate_image
from .normalization import normalize_search_text, normalized_inputs from .normalization import normalize_search_text, normalized_inputs
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
@@ -230,6 +230,7 @@ class PageBlockExtractor:
self.owned() self.owned()
self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider
self.original_hash, self.profile, self.reviewed = original_hash, profile, False self.original_hash, self.profile, self.reviewed = original_hash, profile, False
self.automatic_ocr = False
self.document_id, self.title = document_id, title self.document_id, self.title = document_id, title
self.annotations = [] self.annotations = []
extraction = profile["extraction"] extraction = profile["extraction"]
@@ -273,7 +274,8 @@ class PageBlockExtractor:
blocks = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate(blocks)) 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, envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"], 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) review_annotations=tuple(self.annotations), blocks=blocks)
normalized_inputs(envelope, profile) normalized_inputs(envelope, profile)
payload = serialize_artifact(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, data = {"artifact_schema": 1, "document_id": str(self.document_id), "title": self.title,
"original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest, "original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest,
"normalization_policy": self.profile["normalizer"], "complete": True, "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], "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)]} "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"]) 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 b.page != page or not b.source_locator.startswith(locator + "/")
or unreadable(b.text)): or unreadable(b.text)):
raise ExtractionError("Vision evidence identity, location or readability mismatch") 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. # Validate local source relationships before manually attesting to the result.
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash, ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"], extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
complete=True, quality_decision="passed", complete=True, quality_decision="passed",
blocks=tuple(blocks)) 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",)) return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))
@@ -11,6 +11,14 @@ class LegacyProcessingProfile(ValueError):
pass 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: def processing_profile_kind(profile: Mapping) -> str:
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1": if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
return "legacy-v1" return "legacy-v1"
@@ -20,6 +28,7 @@ def processing_profile_kind(profile: Mapping) -> str:
def extraction_profile_digest(profile: Mapping) -> str: def extraction_profile_digest(profile: Mapping) -> str:
ocr_review_required(profile)
if processing_profile_kind(profile) == "legacy-v1": if processing_profile_kind(profile) == "legacy-v1":
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden") raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
# Faithful extraction is reusable across chunk/embedding/normalization changes. # 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"}) {"RLO", "LRO", "RLE", "LRE", "PDF", "LRI", "RLI", "FSI", "PDI"})
def normalized_title(path: Path, title: str | None) -> str: def normalized_title(path: Path, title: str | None, *, filename: str | None = None) -> str:
filename = unicodedata.normalize("NFC", Path(path).name) name = filename if filename is not None else Path(path).name
value = unicodedata.normalize("NFC", title if title is not None else Path(filename).stem) 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()) return " ".join(value.split())
@@ -34,7 +35,7 @@ def payload_hash(sha: str, title: str) -> str:
return hashlib.sha256(payload.encode("utf-8")).hexdigest() 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.""" """Stream at most the accepted length plus one byte, with constant memory."""
path = Path(path) path = Path(path)
digest, total = hashlib.sha256(), 0 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 raise IntakeError("INVALID_FILE", "Cannot read input file") from None
if total != size_bytes: if total != size_bytes:
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload") 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) 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. # Display names are portable and reject path delimiters, controls and bidi marks.
if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename
or any(c in '<>:"/\\|?*' or unsafe_display_character(c) 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() extension = Path(filename).suffix.lower()
if extension not in settings.accepted_formats: if extension not in settings.accepted_formats:
raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format") 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 if (not canonical_title or len(canonical_title) > 200
or any(unsafe_display_character(c) for c in canonical_title)): or any(unsafe_display_character(c) for c in canonical_title)):
raise IntakeError("INVALID_FILE", "Title must contain 1-200 display characters") 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, 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)) administrator_id, request_id = UUID(str(administrator_id)), UUID(str(request_id))
org, previous = repository.lookup(settings, administrator_id, request_id) org, previous = repository.lookup(settings, administrator_id, request_id)
if previous is not None: if previous is not None:
# Existing requests compare payloads independently of current acceptance policy. # Existing requests compare payloads independently of current acceptance policy.
# File I/O is outside database transactions and creates no candidate. # 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) result = repository.replay(org, administrator_id, previous, submitted_hash)
return {"replayed": True, "document": result} return {"replayed": True, "document": result}
prepared = prepare_file(path, title, settings) prepared = prepare_file(path, title, settings, filename=filename)
key = store.put(prepared["content"]) key = store.put(prepared["content"])
replayed, conflict, result = repository.create( replayed, conflict, result = repository.create(
settings, prepared, key, administrator_id, request_id, org) 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) vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
fallback_policy: str = Field(default="affected-pages-v1", min_length=1) fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
quality_policy: str = Field(default="bounded-checks-manual-review-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) normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
chunking_policy: str = Field(default="paragraph-v1", min_length=1) chunking_policy: str = Field(default="paragraph-v1", min_length=1)
render_dpi: int = Field(default=144, gt=0, le=600) 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, "vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds}, "model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy, "fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
"ocr_review_required": self.ocr_review_required,
"render_dpi": self.render_dpi, "render_dpi": self.render_dpi,
"max_rendered_page_pixels": self.max_rendered_page_pixels, "max_rendered_page_pixels": self.max_rendered_page_pixels,
"max_pdf_pages": self.max_pdf_pages, "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}$") extraction_profile_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
normalization_policy: str = Field(min_length=1) normalization_policy: str = Field(min_length=1)
complete: Literal[True] complete: Literal[True]
quality_decision: Literal["passed", "reviewed"] quality_decision: Literal["passed", "reviewed", "partially_reviewed"]
warnings: tuple[str, ...] = () warnings: tuple[str, ...] = ()
review_annotations: tuple[ExtractionReviewAnnotation, ...] = () review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1) 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 .chunking import chunk_extraction
from .embeddings import EmbeddingError, stage_document from .embeddings import EmbeddingError, stage_document
from .extraction import ExtractionError, ReviewRequired 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 .review import FactualReviewRequired, prepare_chunks
from .operational_limits import validate_worker_durations from .operational_limits import validate_worker_durations
@@ -63,21 +63,36 @@ def validate_source(envelope, document, content):
if envelope.title != document["title"]: if envelope.title != document["title"]:
raise ExtractionError("Extraction title differs from immutable source") raise ExtractionError("Extraction title differs from immutable source")
warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings)) 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") 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"] 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": if mime == "application/pdf":
import pymupdf import pymupdf
with pymupdf.open(stream=content, filetype="pdf") as source: with pymupdf.open(stream=content, filetype="pdf") as source:
if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"] 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))): or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))):
raise ExtractionError("Incomplete PDF source coverage") 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") raise ExtractionError("PDF extraction requires inspection")
elif mime in ("image/jpeg", "image/png"): 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): 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") raise ExtractionError("Image extraction requires inspected complete evidence")
elif mime in ("text/markdown", "text/plain", 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) 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): def create_search_tool(service, context, runner):
"""Build only on explicit opt-in; core imports do not require LangChain.""" """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 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 pathlib import Path
from typing import Literal from typing import Literal
from urllib.parse import urlsplit 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 from pydantic_settings import BaseSettings, SettingsConfigDict
class VoiceSettings(BaseSettings): class VoiceSettings(BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True) model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
provider: Literal['gemini'] = 'gemini' provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
gemini_api_key: SecretStr = SecretStr('') gemini_api_key: SecretStr = SecretStr('')
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200) 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_voice: str = Field(default='Aoede', min_length=1, max_length=80)
gemini_proxy: str | None = None 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_origins: tuple[str, ...] = ('http://localhost:8000', 'http://127.0.0.1:8000')
trusted_hosts: tuple[str, ...] = ('localhost:8000', '127.0.0.1:8000') trusted_hosts: tuple[str, ...] = ('localhost:8000', '127.0.0.1:8000')
cookie_secure: bool = True cookie_secure: bool = True
auth_session_seconds: int = Field(default=28800, ge=60, le=604800) auth_session_seconds: int = Field(default=28800, ge=60, le=604800)
live_session_seconds: int = Field(default=600, ge=10, le=3600) live_session_seconds: int = Field(default=600, ge=10, le=3600)
search_calibration_report: Path | None = None search_calibration_report: Path | None = None
voice_transport_testing: bool = False
max_provider_sessions: int = Field(default=4, ge=1, le=32) max_provider_sessions: int = Field(default=4, ge=1, le=32)
login_attempts_per_minute: int = Field(default=12, ge=1, le=120) 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 @classmethod
def identifier(cls, value): def identifier(cls, value):
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value): if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
raise ValueError('Invalid voice profile identifier') raise ValueError('Invalid voice profile identifier')
return value return value
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy') @field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy', 'openai_realtime_proxy')
@classmethod @classmethod
def urls(cls, value, info): 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 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: if not values or len(values) > 20:
raise ValueError('Explicit bounded trusted endpoints required') raise ValueError('Explicit bounded trusted endpoints required')
for entry in values: for entry in values:
@@ -43,7 +55,7 @@ class VoiceSettings(BaseSettings):
port = p.port port = p.port
except ValueError: except ValueError:
raise ValueError('Invalid endpoint configuration') from None 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 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): or p.password or p.path or p.query or p.fragment or '*' in entry):
raise ValueError('Invalid endpoint configuration') raise ValueError('Invalid endpoint configuration')
@@ -55,11 +67,49 @@ class VoiceSettings(BaseSettings):
raise ValueError('Insecure cookies require loopback-only development origins') raise ValueError('Insecure cookies require loopback-only development origins')
return self 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): 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): if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE') raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
def profile(self): def profile(self):
return dict(provider=self.provider, model=self.gemini_model, voice=self.gemini_voice, return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
input_sample_rate=16000, output_sample_rate=24000) 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') raise ValueError('LIVE_SESSION_UNUSABLE')
return row 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 @staticmethod
def _shape(row, *, replayed=False, eligible=True): def _shape(row, *, replayed=False, eligible=True):
sid = str(row['id']) sid = str(row['id'])
return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'], 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, 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 @staticmethod
def _terminal(conn, sid, reason, *, failed=False): 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', []))) error_code=c['error_code'], sources=self._sources(conn, user.organization_id, (c['result_json'] or {}).get('sources', [])))
for c in reversed(calls)] for c in reversed(calls)]
return dict(session_id=str(row['id']), status=row['status'], close_reason=row['close_reason'], 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): def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
arguments = SearchInput.model_validate(arguments).model_dump() 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.""" """Bounded, session-local voice state machine. HTTP identity/persistence is Phase 2."""
from app.modules.voice.authority import authority_failure_code
import asyncio import asyncio
import base64 import base64
from collections import deque from collections import deque
@@ -235,7 +236,8 @@ class VoiceRuntime:
try: try:
valid = await asyncio.wait_for(self.authority_check( valid = await asyncio.wait_for(self.authority_check(
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds) 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 valid = False
return valid 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 argparse
import asyncio import asyncio
from dataclasses import asdict 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.serialization import bounded_json
from app.modules.voice.configuration import VoiceSettings from app.modules.voice.configuration import VoiceSettings
from app.infrastructure.voice_provider import create_adapter
def preflight(engine, settings, actor, cutoff): def preflight(engine, settings, actor, cutoff):
if cutoff.profile != asdict(settings.embedding_profile): if cutoff.profile != asdict(settings.embedding_profile):
@@ -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) print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
return 1 return 1
async def create_adapter(config, limits):
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
config.require_voice()
transport = await connect_gemini(config.gemini_api_key.get_secret_value(), config.gemini_model, config.gemini_proxy, limits)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
return adapter
async def _run(service, runner, actor, config, query, max_calls, limits): async def _run(service, runner, actor, config, query, max_calls, limits):
adapter = await create_adapter(config, limits) adapter = await create_adapter(config, limits)
async def emit(event): async def emit(event):
@@ -129,7 +123,7 @@ def main(argv=None):
parser.add_argument("--user-id", type=UUID, required=True) parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True) parser.add_argument("--query", required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True, parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize 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("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600")
parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10") parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
args = parser.parse_args(argv) args = parser.parse_args(argv)
@@ -0,0 +1,483 @@
# راهنمای اتصال UI به backend دستیار اسناد و مکالمهٔ صوتی
تاریخ تهیه: ۲۰۲۶-۱۰-۰۹
این فایل برای توسعه‌دهندهٔ frontend تهیه شده است تا UI موجود را به backend فعلی وصل کند. قرارداد مرورگر برای Gemini Live و OpenAI Realtime یکسان است؛ انتخاب provider و کلیدهای آن فقط سمت backend قرار دارند. فعلاً Gemini پیش‌فرض موقت است.
این راهنما دستور اتصال است و به معنی پذیرش اجراشدهٔ UI، کیفیت گفتار فارسی یا سخت‌افزار مرورگر نیست. نمونه‌های JSON شکل داده را نشان می‌دهند؛ شناسه، digest، revision و مسیر نشست باید از پاسخ واقعی سرور گرفته شوند.
## ۱. اطلاعاتی که تیم backend باید تحویل دهد
پیش از تست مشترک، جدول زیر با اطلاعات محیط واقعی تکمیل شود. جای‌خالی‌ها نباید به تنظیمات اجرایی تبدیل شوند.
| مورد | مقدار مورد توافق |
| --- | --- |
| آدرس backend قابل‌دسترسی از ماشین اجرای پراکسی | `TO_BE_PROVIDED`؛ پیش‌فرض محلی Compose: `http://localhost:8080` |
| آدرس و Origin دقیق UI | `TO_BE_PROVIDED`؛ نمونهٔ محلی: `http://localhost:5173` |
| نسخهٔ مشترک backend و فایل‌های نمونه | commit یا snapshot مورد توافق: `TO_BE_PROVIDED` |
| حساب تست administrator | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| حساب تست user | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| فایل نمونه برای آپلود و بازبینی انسانی | `TO_BE_PROVIDED` |
| سند آماده و انتخاب‌شده برای تست مکالمه | شناسهٔ واقعی و سؤال دارای پاسخ در همان سند: `TO_BE_PROVIDED` |
| آمادگی صوت و calibration | تیم backend وضعیت واقعی را اعلام کند؛ UI نیز F01 را بخواند |
| زمان تست مشترک مرورگر، میکروفن و بلندگو | `TO_BE_PROVIDED` |
اگر frontend و backend روی دو ماشین جدا اجرا می‌شوند، `localhost` در target پراکسی به ماشین frontend اشاره می‌کند. آدرس قابل‌دسترسی backend را جایگزین کنید.
کلید provider، رمز دیتابیس و فایل `.env` حاوی اسرار وارد کد، build، تنظیمات عمومی یا storage مرورگر نشوند. UI برای ورود فقط اطلاعات حساب کاربردی دریافت می‌کند.
## ۲. فایل‌های همراه و مرجع قرارداد
این فایل Markdown همراه با فایل‌های زیر تحویل شود. لینک‌ها نسبت به محل این فایل در repository هستند؛ برای تحویل خارج از repository، فایل‌های اشاره‌شده را نیز ارسال کنید.
| فایل | کاربرد |
| --- | --- |
| [راهنمای backend فاز ۳](realtime-agent-phase3-handoff.md) | قرارداد اسناد، review، retry، selection و تنظیمات توسعه |
| [راهنمای صوت](frontend-voice-integration-example.md) | جریان صوت، کنترل‌ها، رویدادها و recovery |
| [API catalog](../specifications/RAG-Phase1-API-Catalog.md) | قرارداد مرجع API؛ فقط endpointهای MVP در این تحویل استفاده شوند |
| [document-client.js](../../examples/document-client.js) | helper عملیات اسناد و configuration |
| [voice-client.js](../../examples/voice-client.js) | helper ورود، ساخت نشست، صوت و cleanup |
| [voice-audio-worklet.js](../../examples/voice-audio-worklet.js) | capture و playback و گزارش نمونه‌های واقعاً پخش‌شده |
| [vite-proxy.config.js](../../examples/vite-proxy.config.js) | پراکسی توسعهٔ HTTP و WebSocket |
helperها نمونهٔ توسعه‌اند؛ مدیریت صفحات، وضعیت UI، خطا، درخواست‌های لغوشده و ذخیرهٔ تلاش‌های نامطمئن بر عهدهٔ frontend است. در صورت اختلاف با یک پاسخ واقعی، کد خطا و request ID را به تیم backend بدهید؛ پاسخ یا قرارداد را خودسرانه بازتعریف نکنید.
## ۳. محدودهٔ UI و مسئولیت طرفین
| قابلیت | مسئولیت UI | مسئولیت backend |
| --- | --- | --- |
| ورود و نقش | فرم ورود، نگهداری وضعیت کاربر، نمایش قابلیت‌های مجاز | cookie، اعتبارسنجی حساب و مجوز هر درخواست |
| اسناد | آپلود، نمایش وضعیت، مرور شواهد، approve/reject، retry و selection | ذخیرهٔ immutable، پردازش worker، کنترل review و انتشار |
| صوت | میکروفن، playback، transcript، منابع، توقف و recovery | اتصال provider، ابزار جست‌وجو، lifecycle و کنترل دسترسی |
| خطا | پیام قابل‌فهم و اقدام مناسب، نگهداری شناسهٔ خطا | error envelope امن و correlation |
`admin` به اسناد، review، retry و selection دسترسی دارد. `admin` و `user` می‌توانند configuration را بخوانند و مکالمهٔ صوتی متعلق به خودشان را بسازند. پنهان‌کردن دکمه در UI جای کنترل مجوز سرور را نمی‌گیرد.
در MVP فعلی UI برای ثبت‌نام عمومی، مدیریت حساب، حذف سند، ویرایش configuration، انتخاب مدل/provider، public text chat یا تاریخچهٔ کامل و پایدار transcript ساخته نشود. routeهای deferred در API catalog به معنی route قابل‌استفاده نیستند.
## ۴. تنظیم اتصال محلی
### پراکسی same-origin
در مثال فعلی UI روی `http://localhost:5173` است و API از میزبان روی `8080` در دسترس خواهد بود. مرورگر تمام HTTPها را به `/api/v1/...` روی Origin خود UI می‌فرستد. پراکسی همان مسیر `/api` را بدون حذف prefix به backend منتقل می‌کند.
نمونهٔ Vite را در configuration موجود ادغام کنید؛ تنظیمات دیگر پروژه را جایگزین نکنید:
```js
export default {
server: {
host: 'localhost',
port: 5173,
strictPort: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
ws: true,
changeOrigin: false
}
}
}
};
```
`changeOrigin: false`، Host مرورگر را حفظ می‌کند. تیم backend برای این مثال محلی تنظیم کند:
```dotenv
TRUSTED_HOSTS=["localhost:5173","localhost:8080"]
TRUSTED_ORIGINS=["http://localhost:5173"]
COOKIE_SECURE=false
```
Host دوم برای دسترسی مستقیم محلی به health و schema است؛ اجرای mutation از Origin دیگری نیازمند تنظیم صریح همان Origin است. در محیط HTTPS، cookie باید Secure باشد و اتصال صوت WSS باشد. از wildcard برای CORS همراه credentials استفاده نشود. مرورگر برای میکروفن و AudioWorklet به secure context، مثل HTTPS یا localhost، نیاز دارد.
پیش‌فرض Docker Compose: API داخل container روی `8000` و روی میزبان با `${API_PORT:-8080}` منتشر می‌شود. اگر `API_PORT` عوض شد، target پراکسی را هماهنگ کنید. برای اجرای مستقیم مطابق این مثال، تیم backend از یک API process روی `8080` و worker جداگانه استفاده کند:
```sh
python -m app.server --host 0.0.0.0 --port 8080
python -m app.worker
```
آماده‌سازی دیتابیس، migration، حساب‌ها، storage، credentials و calibration وظیفهٔ تیم backend است. شروع worker می‌تواند provider call ایجاد کند و باید مطابق مجوز محیط انجام شود. frontend چند API worker یا reload برای محیط تست صوت درخواست نکند.
### تشخیص اتصال
با Host مجاز و backend آماده:
- `GET http://localhost:8080/health/live`: پاسخ `200` و `{"status":"ok"}`.
- `GET http://localhost:8080/health/ready`: پاسخ `200` هنگام readiness و `503` هنگام آماده‌نبودن.
- `GET http://localhost:8080/openapi.json`: schema محیط جاری.
- `http://localhost:8080/docs`: نمایش schema؛ اجرای درخواست‌های تعاملی نیز باید الزامات Origin/CSRF را رعایت کند.
پراکسی نمونه فقط `/api` را منتقل می‌کند؛ برای health از آدرس مستقیم مجاز استفاده کنید، یا مسیر health را صریحاً در پراکسی خود اضافه کنید. هیچ‌کدام از healthها گواه کیفیت provider نیستند.
## ۵. احراز هویت و قرارداد HTTP
تمام routeهای جدول‌های بعدی زیر `/api/v1` هستند.
| عملیات | درخواست | نتیجه |
| --- | --- | --- |
| ورود | `POST /auth/login` با `username` و `password` | `200`، cookie و user/CSRF/expiry |
| خواندن یا refresh هویت | `GET /me` | `200` با همان شکل هویت؛ یا `401` |
| خروج | `POST /auth/logout` بدون body | `204` بدون JSON |
| خواندن قابلیت‌ها | `GET /configuration` | `200` برای هر دو نقش |
نمونهٔ ورود:
```json
{"username":"<test-account>","password":"<password-from-login-form>"}
```
شکل پاسخ ورود و `/me`:
```json
{
"user": {
"id": "<server-user-id>",
"username": "<actual-username>",
"role": "admin",
"organization_id": "<server-organization-id>"
},
"csrf_token": "<server-csrf-token>",
"expires_at": "<server-ISO-timestamp>"
}
```
- cookie به نام `rag_session`، HttpOnly است؛ آن را از JavaScript نخوانید و token جایگزین نسازید.
- در معماری same-origin از `credentials: 'same-origin'` استفاده کنید.
- mutationهای authenticated، شامل upload و ساخت نشست، `X-CSRF-Token` می‌خواهند. CSRF از login یا `/me` گرفته شود. login خودش trusted Origin می‌خواهد.
- پس از reload ابتدا `/me` را بخوانید. روی `401` وضعیت authenticated را پاک و ورود مجدد را نمایش دهید.
- برای `FormData`، Content-Type را دستی ننویسید؛ browser باید boundary را بسازد. برای JSON از `application/json` استفاده کنید.
- پاسخ `204` را با `response.json()` نخوانید.
- `organization_id`، actor، reviewer یا مدل را برای تحمیل scope در درخواست‌ها اضافه نکنید.
configuration شامل `revision`، `assistant_name`، `instruction` و `capabilities` است. UI از مقادیر واقعی `text`، `voice`، `captions`، `supported_upload_types`، `max_upload_bytes`، `max_pdf_pages` و مشخصات audio استفاده کند. در صورت `voice=false`، شروع صوت غیرفعال و پیش‌نیاز به تیم backend اعلام شود؛ این flag گواه کیفیت گفتار نیست. `ocr_review_required` در configuration سیاست فعلی deployment است، نه سیاست همهٔ اسناد قبلی.
## ۶. جریان اسناد برای administrator
| عملیات | route | موفقیت و نکته |
| --- | --- | --- |
| آپلود | `POST /documents` | `202`؛ multipart؛ required `Idempotency-Key` |
| فهرست | `GET /documents` | `200`؛ pagination و فیلتر |
| polling جزئیات | `GET /documents/{document_id}` | `200`؛ وضعیت واقعی processing/review/retry |
| شواهد pending | `GET /documents/{document_id}/extraction-review` | `200`؛ paginated |
| preview | مسیر `preview_path` در پاسخ شواهد | تصویر authenticated؛ بدون path ساخته‌شده توسط UI |
| تصمیم انسانی | `POST /documents/{document_id}/extraction-review/decisions` | `200`؛ JSON و required `Idempotency-Key` |
| retry همان job | `POST /documents/{document_id}/retry` | `202`؛ بدون body و required `Idempotency-Key` |
| خواندن selection | `GET /knowledge-selection` | `200` |
| جایگزینی selection | `PATCH /knowledge-selection` | `200`؛ کل مجموعه با expected revision |
### آپلود و وضعیت
body فقط یک `file` و `title` اختیاری دارد. title حداکثر ۲۰۰ کاراکتر است؛ محدودیت فایل را از configuration بخوانید. UI اعتبارسنجی اولیه انجام دهد، ولی format و محتوا را سرور تصمیم می‌گیرد.
```js
const uploadKey = crypto.randomUUID();
const uploaded = await documents.upload(file, title, uploadKey);
// uploaded.document_id و uploaded.job_id را از پاسخ واقعی نگه دارید.
```
هر upload با کلید تازه یک سند مستقل می‌سازد. برای نتیجهٔ نامطمئن همان File، title و کلید را نگه دارید و همان درخواست را replay کنید؛ تولید کلید جدید می‌تواند سند دیگری بسازد. کلید در header `Idempotency-Key` ارسال می‌شود. replay موفق header `Idempotency-Replayed: true` دارد؛ تغییر payload زیر همان کلید، `409 IDEMPOTENCY_CONFLICT` می‌دهد.
تا زمانی که document وضعیت `queued` یا `processing` دارد polling کنید؛ فاصلهٔ پیشنهادی دو ثانیه است، در tab پنهان آهسته‌تر شود. polling با خروج از صفحه لغو شود و پاسخ دیررس نتواند سند جدیدِ انتخاب‌شده در UI را بازنویسی کند. درصد پیشرفت ساختگی نمایش ندهید؛ از `job.stage` و وضعیت واقعی استفاده کنید.
| وضعیت یا فیلد پاسخ | رفتار UI |
| --- | --- |
| `queued` / `processing` | نمایش انتظار و مرحله، ادامهٔ polling |
| `failed` و `review_required=true` | دریافت و نمایش شواهد pending |
| `failed` و `job.can_retry=true` | امکان retry صریح؛ علت خطا نیز نمایش داده شود |
| `failed` و `review_state=rejected` | نمایش رد؛ retry خودکار انجام نشود |
| `ready` و `is_active=false` | آمادهٔ انتخاب؛ هنوز وارد جست‌وجو نشده است |
| `searchable=true` | سند طبق پاسخ فعلی سرور قابل جست‌وجو است |
`job.error` ممکن است null یا شامل `code`، `message` و `retryable` باشد. امکان retry را از `job.can_retry` بگیرید؛ صرف `retryable=true` مجوز retry خودکار نیست.
فهرست اسناد `limit` پیش‌فرض ۲۰ و حداکثر ۱۰۰ دارد؛ فیلترهای `status` و `is_active` پشتیبانی می‌شوند. پاسخ شامل `items`، `next_cursor` و `knowledge_revision` است. cursor opaque است؛ آن را تغییر ندهید و در query URL encode کنید.
### review و سیاست OCR
شواهد review پیش‌فرض ۱۰ و حداکثر ۲۰ item در هر صفحه دارد. از `next_cursor` برای ادامه استفاده کنید. اگر مجموعه پس از تصمیم‌ها تغییر کرد و cursor نامعتبر شد، pendingها را دوباره از ابتدای مجموعه بخوانید. item شامل digest واقعی، `review_kind`، blocks، `required_checks` و preview احتمالی است.
UI برای انسان، متن دقیق، گروه‌های Q&A و تصویر موجود را نمایش دهد. تصمیم approve/reject و یادداشت از انسان گرفته شود؛ روی دکمهٔ approve تمام چک‌ها به‌طور خودکار تأیید نشوند.
```json
{
"evidence_sha256": "<digest-from-current-review-item>",
"decision": "approve",
"checked": ["<actual-required-check-names-confirmed-by-human>"],
"note": "<nonblank-human-review-note>",
"excluded_group_ids": []
}
```
برای approval، مجموعهٔ `checked` باید دقیقاً با چک‌های موردنیاز item تطبیق کند. note غیرخالی و حداکثر ۲۰۰۰ کاراکتر است. برای rejection نیز note لازم است؛ چک‌های تکمیل‌نشده را تأییدشده وانمود نکنید.
در review استخراج، `excluded_group_ids` باید خالی باشد. در `factual_corpus` فقط گروه‌های کامل موجود را می‌توان exclude کرد؛ دست‌کاری متن اصلی یا حذف نیمهٔ سؤال/پاسخ مجاز نیست. approval باید دست‌کم یک گروه factual واجد شرایط باقی بگذارد و placeholderهای نامعتبر را وارد corpus نکند. `preview_path` برای factual ممکن است null باشد.
سیاست `INGEST_OCR_REVIEW_REQUIRED` فقط تنظیم backend است، default آن true است و در هر job ثابت می‌ماند. UI از فیلدهای همان document استفاده کند:
- `ocr_review_required`: سیاست frozen آن سند.
- `review_required`: وجود تصمیم pending.
- `review_state`: `not_evaluated`، `not_required`، `pending`، `approved` یا `rejected`.
- `extraction_quality_decision`: null، `passed`، `reviewed` یا `partially_reviewed`؛ بدون ساختن ادعای تأیید انسانی.
false بودن سیاست OCR، review factual یا reviewهای دیگر را حذف نمی‌کند. UI toggle برای تغییر این سیاست ندارد. در preview از URL سرور با cookie استفاده کنید؛ path ذخیره‌سازی یا URL provider ساخته نشود.
approve به‌تنهایی retry، انتشار یا activation نمی‌کند. پس از تکمیل pendingها، detail را بخوانید و در صورت `job.can_retry=true`، retry صریح با کلید مستقل ارسال کنید. صفحات بعدی استخراج نیز ممکن است review تازه بخواهند. retry همان سند و همان job را ادامه می‌دهد. retry با body غیرخالی، `422 VALIDATION_ERROR` است.
### selection
برای اضافه یا حذف یک سند، ابتدا K01 را بخوانید، مجموعهٔ کامل جدید را بسازید و K02 را ارسال کنید:
```json
{
"expected_revision": 3,
"document_ids": ["<all-selected-document-ids-in-the-desired-new-set>"]
}
```
`expected_revision` در مثال فرضی است و باید از آخرین K01 بیاید. PATCH یک delta نیست؛ ارسال فقط یک ID می‌تواند بقیهٔ اسناد را حذف کند. شناسه‌ها unique و سندها ready باشند.
بعد از timeout یا `REVISION_CONFLICT` ابتدا K01 را دوباره بخوانید. درخواست قبلی ممکن است commit شده باشد؛ آن را کورکورانه تکرار نکنید. حذف سند فعال می‌تواند epoch را تغییر دهد و نشست‌های صوت قبلی را ببندد. UI منابع قدیمی را معتبر نمایش ندهد و ساخت مکالمهٔ تازه را پیشنهاد کند.
## ۷. ساخت و کنترل نشست صوت
| عملیات | route | کاربرد |
| --- | --- | --- |
| C01 | `POST /conversations` | ساخت owned conversation با `mode=voice`؛ `201` |
| V01 | `POST /voice/sessions` | رزرو session؛ `201` یا replay با `201/202` |
| V02 | `GET /voice/sessions/{session_id}` | وضعیت، diagnostics امن و toolهای اخیر |
| V03 | `GET /voice/sessions/by-request/{client_request_id}` | بازیابی رزرو بدون اتصال provider |
| V04 | `POST /voice/sessions/{session_id}/close` | بستن صریح بدون body؛ `200` |
| media | WebSocket روی `stream_path` دریافتی | یک اتصال فعال؛ cookie و Origin |
ابتدا C01 و سپس V01:
```json
{"client_request_id":"<conversation-request-uuid>","mode":"voice"}
```
```json
{"conversation_id":"<id-from-C01>","client_request_id":"<session-request-uuid>"}
```
این دو request ID جدا هستند و در JSON می‌آیند؛ با header کلید عملیات سند اشتباه نشوند. پاسخ V01 شامل `session_id`، `conversation_id`، `status`، `stream_path`، `expires_at` و `poll_url` است. مسیر اتصال را از `stream_path` بگیرید؛ route provider یا path ثابت اختراع نکنید.
برای نتیجهٔ نامطمئن، payload و IDهای همان تلاش حفظ و replay شوند. V03 برای reconciliation است و provider جدید باز نمی‌کند. نشست connected یا terminal اتصال media را از نو احیا نمی‌کند؛ recovery به معنی seamless reconnect نیست.
دو WebSocket هم‌زمان برای یک session ساخته نشود. پس از loss، وضعیت را از V02/V03 بگیرید، رزرو قدیمی را ببندید و با اقدام صریح کاربر مکالمه و نشست تازه بسازید. هنگام refresh صفحه، helper فعلی تلاش ایجاد را فقط در حافظهٔ همان instance نگه می‌دارد؛ اگر recovery بین reload لازم است، UI باید IDها و payload همان تلاش را بدون provider secret نگه دارد و ابتدا با سرور reconcile کند.
## ۸. راه‌اندازی helper و فایل صوت
در پروژهٔ UI، دو client module را در مسیر source قرار دهید و worklet را به‌عنوان asset مستقل از همان Origin سرو کنید. برای Vite می‌توان worklet را در `public/voice-audio-worklet.js` گذاشت و URL زیر را به constructor داد. متن worklet باید JavaScript باشد؛ fallback HTML مربوط به SPA برای این URL برنگردد.
```js
import {VoiceClient} from './integrations/voice-client.js';
import {DocumentClient} from './integrations/document-client.js';
// handleVoiceEvent و showFailure توابع UI خودتان هستند.
const voice = new VoiceClient(handleVoiceEvent, '/voice-audio-worklet.js');
const documents = new DocumentClient(voice);
async function signIn(username, password) {
const identity = await voice.login(username, password);
const configuration = await documents.configuration();
return {identity, configuration};
}
async function prepareVoice() {
const configuration = await documents.configuration();
if (!configuration.capabilities.voice) throw new Error('VOICE_UNAVAILABLE');
voice.newCreationAttempt(); // فقط برای یک تلاش واقعاً تازه
return voice.reserve();
}
// ابتدا prepareVoice موفق شود؛ سپس دکمهٔ شروع برای کاربر فعال شود.
// connect مستقیماً از gesture کاربر فراخوانی شود تا AudioContext مجاز باشد.
startButton.addEventListener('click', () => {
void voice.connect().catch(showFailure);
});
stopButton.addEventListener('click', () => {
void voice.close().catch(showFailure);
});
// logoutButton در handler خود voice.logout() را فراخوانی کند.
// route/component هنگام خروج باید voice.close() را await کند و خطا را مدیریت کند.
```
`prepareVoice` را با نشست فعال دوباره اجرا نکنید. پس از timeout ایجاد، به‌جای `newCreationAttempt` از `retryCreation()` همان تلاش استفاده کنید. شروع و cleanup باید برای هر connection مالکیت مشخص داشته باشند؛ جواب دیررس permission یا callback نشست قدیمی نباید نشست جدید را ببندد.
متدهای اصلی نمونه:
| client | متدها |
| --- | --- |
| VoiceClient | `login`، `refreshIdentity`، `newCreationAttempt`، `reserve`، `retryCreation`، `recover`، `poll`، `connect`، `close`، `logout`، `freshSession` |
| DocumentClient | `configuration`، `upload`، `list`، `poll`، `review`، `decide`، `retry`، `selection`، `replace` |
برای recovery صوت، اگر از `freshSession()` استفاده می‌کنید آن را با gesture مناسب کاربر اجرا کنید و روی browser واقعی مجازبودن AudioContext را تست کنید. UI نباید پس از refresh یا قطع شبکه خودکار میکروفن را باز کند.
## ۹. قرارداد صوت و رویدادها
صوت در هر دو جهت raw mono signed PCM16 little-endian با نرخ **۲۴۰۰۰ Hz**، یک channel و بدون WAV header است؛ معادل ۴۸۰۰۰ byte در ثانیه. WebM، Opus یا blob خروجی MediaRecorder را روی این stream نفرستید. capture دستگاه باید به نرخ قرارداد تبدیل شود. helper و worklet این مسیر را پیاده می‌کنند و AudioContext با نرخ نامعتبر را رد می‌کنند.
میکروفن فقط پس از `session_ready` شروع به ارسال کند. سقف هر پیام binary در نمونهٔ فعلی ۹۶۰۰ byte است و طول باید sample-aligned باشد. capture و playback نمونه دارای دو سقف مستقل ۹۶۰۰۰ byte و ۱۰۰ پیام هستند. در adaptation، هر دو کنترل و cleanup آن‌ها حفظ شوند؛ ظرفیت پرشده باید با failure امن پایان یابد، نه با حذف بی‌صدای PCM و ادامهٔ همان context.
| رویداد سرور | رفتار UI |
| --- | --- |
| `session_ready` | session ID و audio format را تطبیق دهید؛ آماده‌شدن واقعی را نمایش دهید |
| `user_speech_started` | turn جدید را با `turn_ref` ثبت کنید |
| `transcript` | برحسب turn و role، partial را به‌روز و completed را نهایی کنید |
| `sources` | منابع را به همان turn/tool call مرتبط کنید؛ منابع turnهای دیگر مخلوط نشوند |
| `audio_started` | `audio_ref` فعلی را برای binaryهای بعدی تعیین کنید |
| `audio_ended` | پایان generation همان audio ref؛ به معنی شنیده‌شدن نیست |
| `turn_interrupted` | صوت صف‌شده را flush و progress نهایی مصرف‌شده را گزارش کنید |
| `error` | خطای turn یا session را با قواعد راهنمای صوت مدیریت کنید |
شکل readiness:
```json
{
"type": "session_ready",
"session_id": "<reserved-session-id>",
"input_audio": {"encoding":"pcm_s16le","sample_rate":24000,"channels":1},
"output_audio": {"encoding":"pcm_s16le","sample_rate":24000,"channels":1}
}
```
شکل transcript:
```json
{"type":"transcript","turn_ref":"<server-turn-ref>","role":"assistant","text":"<actual-transcript>","status":"completed"}
```
تنها کنترل JSON از سمت client:
```json
{"type":"playback_progress","audio_ref":"<server-audio-ref>","played_ms":120}
```
`played_ms` مقدار تجمعی واقعی است؛ از sampleهای مصرف‌شدهٔ worklet محاسبه می‌شود، نه elapsed timer، دریافت شبکه یا طول کل فایل. flush یا admission به معنی شنیدن نیست. مقدار را برای هر `audio_ref` جدا نگه دارید و گزارش نهایی interruption را بفرستید. helper این کار را انجام می‌دهد؛ UI کانال progress موازی با شمارش حدسی اضافه نکند.
برای sources از `source_ref`، title و location دریافتی استفاده کنید. location می‌تواند page یا section خالی داشته باشد. منبع، excerpt، لینک دانلود یا مسیر اصل سند را از خودتان نسازید؛ API دانلود اصل سند در این تحویل وجود ندارد. در polling، `available=false` یعنی excerpt قبلی معتبر نیست و نباید همچنان نمایش داده شود.
خطای canonical search برای turn واجد شرایط می‌تواند با توضیح صوتی امن ادامه یابد. خطای setup، transport، overflow، authority یا context sync نشست را متوقف می‌کند. fatal بودن را فقط از `retryable` استنتاج نکنید؛ رفتار helper و قرارداد guide را حفظ کنید. UI ابزار backend را خودش دوباره اجرا نمی‌کند.
### محدودیت‌های فعلی که در UX رعایت شوند
- Gemini فعلاً truncation نمونه‌دقیقِ تأییدشده برای context ندارد؛ interruption می‌تواند نشست را ببندد و نیازمند مکالمهٔ تازه باشد. seamless barge-in وعده داده نشود.
- ورودی commitنشده، شامل سکوت، سقف ده ثانیه دارد. UI ack یا مرز گفتار ساختگی برای دورزدن این محدودیت نفرستد؛ شکست و recovery را مطابق سرور مدیریت کند.
- transcript و منابع متعلق به نشست فعلی‌اند؛ history کامل و ماندگار وعده داده نشود.
- logout، خروج از صفحه و توقف باید trackهای میکروفن، worklet، AudioContext و WebSocket را آزاد کنند. در توقف عمدی، progress نهایی و V04 پیش از بسته‌شدن transport انجام شوند؛ `voice.close()` این ترتیب را اجرا می‌کند.
## ۱۰. خطا و بازیابی
شکل HTTP error:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Request could not be completed.",
"request_id": "<correlation-uuid>",
"retryable": false
}
}
```
header `X-Request-ID` همان correlation را فراهم می‌کند؛ بعضی خطاها `details` دارند. متن خام error را به‌عنوان تنها UX استفاده نکنید؛ برحسب code پیام فارسی مناسب نمایش دهید. لایهٔ request در UI، status، code و request ID را حفظ کند. DocumentClient این فیلدها را ارائه می‌کند؛ VoiceClient.request نمونه فقط code/status را در exception نگه می‌دارد و برای diagnostics کامل باید metadata امن response را در adaptation حفظ کنید.
| کد یا وضعیت | اقدام |
| --- | --- |
| `401 AUTH_REQUIRED` | cleanup رسانه و ورود مجدد؛ `/me` برای وضعیت هویت |
| `403 CSRF_INVALID` | در صورت باقی‌بودن هویت، refresh از `/me`؛ replay فقط با همان کلید/payload و پس از رفع علت |
| `403 FORBIDDEN` | بررسی نقش یا Host/Origin؛ درخواست تکراری بدون تغییر علت مفید نیست |
| `404 NOT_FOUND` | ID مخفی/حذف‌شده یا رزرو پیدا نشده؛ ابتدا نوع عملیات و تلاش ایجاد را بررسی کنید |
| `409 IDEMPOTENCY_CONFLICT` | payload زیر کلید تغییر کرده؛ تلاش اصلی را reconcile کنید |
| `409 REVISION_CONFLICT` | K01 جدید و اقدام کاربر بر اساس state تازه |
| `409 DOCUMENT_NOT_READY` | موارد rejected در details را نمایش دهید؛ selection ناقص نفرستید |
| `409 EXTRACTION_REVIEW_PENDING` | pendingها را بخوانید و review انسانی را تکمیل کنید |
| `409 DOCUMENT_NOT_RETRYABLE` | detail تازه و شرایط retry؛ دکمه بر اساس can_retry |
| `409 REVIEW_STALE` / `REVIEW_ALREADY_DECIDED` | شواهد و وضعیت تازه؛ approval قدیمی را روی output جدید کپی نکنید |
| `409 LIVE_SESSION_BUSY` | نشست موجود را reconcile کنید؛ اتصال دوم نسازید |
| `CONTEXT_REVOKED` / `CONVERSATION_STALE` | context و خروجی قدیمی را کنار بگذارید؛ نشست تازه، بدون کپی context revoked |
| `413 FILE_TOO_LARGE` / `PAYLOAD_TOO_LARGE` | محدودیت فایل یا envelope درخواست؛ تغییر اندازه به معنی تغییر payload است |
| `415 UNSUPPORTED_FILE_TYPE` | فایل مجاز طبق configuration انتخاب شود |
| `422 INVALID_FILE` / `VALIDATION_ERROR` | مشکل file یا شکل درخواست را اصلاح کنید |
| `429 RATE_LIMITED` | `Retry-After` را رعایت کنید؛ از retry burst جلوگیری کنید |
| `503 DEPENDENCY_UNAVAILABLE` / `CALIBRATION_REQUIRED` | آمادگی backend بررسی شود؛ نتیجهٔ mutation ممکن است نامطمئن باشد |
| قطع WebSocket یا API restart | cleanup، polling/reconciliation و تلاش تازهٔ صریح؛ ادامهٔ context فرضی ممنوع |
انتظار برای دریافت JSON در backend ۱۵ ثانیه و برای body خالی retry پنج ثانیه است؛ محدودیت envelope تصمیم ۶۰٬۱۵۱٬۰۷۲ byte و selection یک MiB است. این‌ها تضمین مدت تکمیل processing نیستند. تایم‌اوت کوتاه client به معنی rollback نیست. helper صوت HTTP deadline پنج ثانیه دارد؛ helper اسناد deadline اختصاصی ندارد و UI باید سیاست timeout و لغو خود را با حفظ semantics عملیات اضافه کند.
هیچ retry خودکار نباید کلید تازهٔ upload/decision/retry بسازد. K02 کلید عملیات سند ندارد و با revision کنترل می‌شود. پس از timeout آن K01 بخوانید. در logout حتی اگر V04 شکست خورد، تلاش برای A02 و پاک‌سازی محلی انجام شود؛ helper فعلی این کار را می‌کند.
در diagnostics فقط زمان، نوع عملیات، status، code، request/session/turn/audio refs لازم ثبت شوند؛ رمز، cookie، CSRF، audio، متن سند و متن خصوصی transcript در log ثبت نشوند.
## ۱۱. معیارهای تست مشترک UI و backend
| سناریو | نتیجهٔ مورد انتظار |
| --- | --- |
| ورود admin و user، reload و `/me` | هویت واقعی و مجوز صحیح؛ CSRF تازه |
| logout هنگام صوت | توقف میکروفن و پخش، revoke حساب session و UI خارج‌شده |
| user روی عملیات اسناد | دسترسی UI محدود و رد واقعی سرور |
| آپلود فایل تازه | document/job واقعی و مستقل، ابتدا inactive |
| timeout یا double-click آپلود | replay با همان کلید؛ سند تکراری ناخواسته ساخته نشود |
| فایل نامعتبر یا بیش‌ازحد | پیام برحسب code و حفظ امکان انتخاب فایل جدید |
| processing و تغییر صفحه | وضعیت واقعی، polling قابل‌لغو و عدم نمایش پاسخ دیررس برای سند دیگر |
| review چندصفحه‌ای و preview | شواهد واقعی، cookie، چک انسانی و تصمیم evidence-bound |
| approve/reject و retry | approve خودکار منتشر نکند؛ rejected ادامه نگیرد؛ retry همان job باشد |
| OCR اختیاری و factual | UI سیاست frozen سند و نیاز مستقل factual را رعایت کند |
| selection و revision conflict | ready-only، کل مجموعه، re-read پس از conflict یا timeout |
| قطع پاسخ C01/V01 | همان تلاش با UUID و payload قبلی replay/reconcile شود |
| شروع صوت با کلیک و permission ردشده | صدای واقعی یا پیام قابل‌فهم، بدون میکروفن یا context رهاشده |
| سؤال فارسی و پیگیری | transcript و sourceها به turn صحیح متصل باشند؛ شنیده‌شدن انسانی بررسی شود |
| پاسخ بی‌مدرک یا خطای جست‌وجو | منبع ساختگی نشان داده نشود؛ خطای turn با fatal session اشتباه نشود |
| interruption هنگام جست‌وجو و playback | صوت قدیمی متوقف، progress واقعی، recovery مطابق provider منتخب |
| قطع provider، شبکه و API restart | cleanup و state سرور روشن؛ اتصال خودکار به همان نشست فرض نشود |
| حذف سند از selection هنگام صوت | نشست قدیمی بی‌اعتبار و excerpt revoked پنهان شود |
| مرورگر یا tab دوم | نشست دیگر مجوز مالکیت ایجاد نکند؛ دو اتصال یک session رد شوند |
برای هر نتیجه، نوع محیط/browser، نسخهٔ مشترک، حساب/نقش بدون رمز، سناریو، زمان و request IDهای امن ثبت شود. provider و hardware واقعی جدا از mock بررسی شوند. هیچ خانهٔ اجرا‌نشده به‌عنوان pass ثبت نشود.
## ۱۲. متن آماده برای واگذاری به عامل frontend
```text
Integrate the existing UI with the supplied backend handoff and client examples.
Read frontend-backend-connection-handoff.md and its linked current contracts.
Use a same-origin /api proxy supporting HTTP and WebSocket. Wire login/logout,
identity refresh, role-aware documents, upload and polling, human evidence review,
same-job retry, full-set knowledge selection, and owned voice-session lifecycle.
Serve the worklet from the UI origin with the correct asset URL. Preserve the
24 kHz mono PCM16LE contract, bounded audio queues, actual playback progress,
interruption behavior, generation ownership, and complete resource cleanup.
Preserve cookie/CSRF authentication, server-returned capabilities and permissions,
idempotency keys and immutable payloads across ambiguous failures, selection
revision recovery, and fresh-session reconciliation after media/context loss.
Gemini interruption can require ending the old session and starting a fresh one.
Provider selection and secrets remain on the backend. Implement only MVP routes.
Do not invent endpoints, approvals, sources, processing percentages or transcript
history. Adapt the examples to the existing UI framework without changing the
backend contract. Preserve unrelated UI work.
Use the supplied accounts and approved files. Execute the shared test matrix on
the running backend and actual browser, within the approved provider-call budget.
Report changed files, actual checks, safe correlation evidence and unrun cases.
If a prerequisite is missing, name it and continue independent integration work.
Do not claim real voice or browser acceptance from mocked responses.
```
Explicit uncalibrated connectivity testing: set `VOICE_TRANSPORT_TESTING=true`
and restart the API. Configure a compatible embedding adapter, credentials and
bounded request limits first. Pending/missing calibration then permits voice
reservation and provider streaming; create/recovery/poll report
`calibration_status: "uncalibrated"`. F01 also reports the policy and calibration
status. Treat this as connectivity testing: shared search still returns
`CALIBRATION_REQUIRED` with no sources. Disable the policy for strict admission;
existing reservations remain pinned and may require a new session after policy or
calibration changes. No automatic provider switch, calibration or paid call occurs
when enabling the policy. Existing client examples tolerate the additive metadata;
the actual developer UI should display the status.
@@ -1,7 +1,7 @@
# Authenticated Gemini voice integration # Authenticated voice integration
Gemini Live is temporarily the sole voice provider because an OpenAI Realtime The backend selects Gemini Live or OpenAI Realtime with `VOICE_PROVIDER`. Gemini
voice key is unavailable. Extraction, embeddings, calibration and canonical is the temporary default while an OpenAI Realtime voice key is unavailable. Extraction, embeddings, calibration and canonical
search retain their existing providers and frozen profiles. The browser never search retain their existing providers and frozen profiles. The browser never
receives a provider credential, event, model selector or private call ID. receives a provider credential, event, model selector or private call ID.
@@ -13,7 +13,8 @@ same origin. This is a developer example, not a production interface.
import {VoiceClient} from './voice-client.js'; import {VoiceClient} from './voice-client.js';
const client = new VoiceClient(event => console.log(event.type)); const client = new VoiceClient(event => console.log(event.type));
await client.login(username, password); // supply credentials from your local form await client.login(username, password); // supply credentials from your local form
await client.reserve(); // retain request IDs for identical retries/recovery client.newCreationAttempt(); // exposes IDs before C01 and retains immutable payloads
await client.reserve(); // after an ambiguous response: await client.retryCreation()
await client.connect(); // call from a user gesture permitting AudioContext await client.connect(); // call from a user gesture permitting AudioContext
// On explicit stop: await client.close(); await client.poll(); // On explicit stop: await client.close(); await client.poll();
// On media loss: await client.recover(); await client.freshSession(); // On media loss: await client.recover(); await client.freshSession();
@@ -23,7 +24,7 @@ await client.connect(); // call from a user gesture permitting AudioContext
`GET /api/v1/me` refreshes actual expiry and CSRF. HTTP mutations use the opaque `GET /api/v1/me` refreshes actual expiry and CSRF. HTTP mutations use the opaque
cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin. cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin.
The API accepts no bearer or query token. Preserve the same normalized payload The API accepts no bearer or query token. Preserve the same normalized payload
and request ID after ambiguous creation; V03 recovers without opening Gemini. and request ID after ambiguous creation; V03 recovers without opening a provider connection.
Connected/terminal recovery does not restore media/provider context. Close the Connected/terminal recovery does not restore media/provider context. Close the
old reservation before requesting a fresh conversation and session. old reservation before requesting a fresh conversation and session.
@@ -36,9 +37,20 @@ and sources are retrieved/current-session information, not durable full history.
The client waits for `session_ready` before opening the microphone. It verifies The client waits for `session_ready` before opening the microphone. It verifies
an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes
channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context
rates fail explicitly. Sending is bounded by WebSocket buffered bytes. Ordered rates fail explicitly. Capture enforces dual capacity bounds of 96000 raw PCM bytes
AND 100 messages across capture handoff and outgoing WebSocket buffering. The worklet
tracks both pending messages and pending bytes (rejecting with overflow if either limit
would be exceeded). Capture handoff does not falsely imply network completion: the client
polls socket.bufferedAmount and delivers `{type: 'accepted', bytes}` to the worklet only
upon verified conservative buffer drain (`captureBytes - bufferedAmount >= packetBytes`).
Capacity is released exactly once on verified drain or terminal cleanup. Ordered
binary playback belongs to the last audio_started reference and is sealed by binary playback belongs to the last audio_started reference and is sealed by
audio_ended. The playback worklet bounds samples and reports the floor of actual audio_ended. The client reserves playback capacity before PCM conversion and counts pending
MessagePort handoffs. The worklet independently enforces 96000 raw PCM bytes AND
100 messages across references, retaining a partially consumed packet in the
message count. Consumed-sample acknowledgements release byte reservations; only
completed/discarded packets release message reservations, exactly once. Admission
and flush acknowledgements never imply heard audio. The worklet reports the floor of actual
consumed samples / 24, never estimated elapsed time or generated samples. consumed samples / 24, never estimated elapsed time or generated samples.
Interruption flushes queued audio and reports each reference's final consumed Interruption flushes queued audio and reports each reference's final consumed
position. Explicit close stops capture and tracks, flushes actual final playback progress position. Explicit close stops capture and tracks, flushes actual final playback progress
@@ -71,3 +83,122 @@ Technical fake-wire/worklet checks, retrieval quality and real-browser speech
acceptance are separate. Real microphone/Persian audio/network behavior remains acceptance are separate. Real microphone/Persian audio/network behavior remains
unverified until explicit provider opt-in, approved corpus, measured compatible unverified until explicit provider opt-in, approved corpus, measured compatible
calibration and budgets are supplied. See the [repair report](realtime-agent-phase2-repair.md). calibration and budgets are supplied. See the [repair report](realtime-agent-phase2-repair.md).
## Creation attempts and recovery
`newCreationAttempt()` explicitly selects new C01 and V01 request IDs and retains
C01's immutable payload before either request. `creationAttempt`,
`conversationRequestID` and `requestID` are inspectable after failure. Once C01's
response supplies the owned conversation ID, V01's immutable payload is stored
before sending V01. `retryCreation()` (or `reserve()` with the existing attempt)
replays identical payloads and IDs after a committed response is lost. Calls with
changed IDs require an explicit new attempt; payload mutation is rejected locally,
and changed payloads at the backend retain IDEMPOTENCY_CONFLICT behavior.
`recover()` uses V03 and never connects automatically; a lost C01 response may
precede V01, so recovery can return SESSION_NOT_FOUND until identical C01/V01 retry.
`freshSession()` explicitly closes/reconciles the old reservation, creates a new
attempt and connects. Retain the attempt in application storage if page reload
recovery is required; this example retains it only in the current JS instance.
## Backend configuration and supported startup
Gemini deployment (no OpenAI voice key required):
```dotenv
VOICE_PROVIDER=gemini
GEMINI_API_KEY=<server-only-key>
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede
# GEMINI_PROXY=https://trusted-proxy.example:443
```
OpenAI deployment (no Gemini key required):
```dotenv
VOICE_PROVIDER=openai
OPENAI_REALTIME_API_KEY=<server-only-voice-key>
OPENAI_REALTIME_MODEL=gpt-realtime-mini
OPENAI_REALTIME_VOICE=shimmer
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
```
Existing `GEMINI_*` names and legacy `PROVIDER` remain valid. Matching provider
aliases are accepted; conflicting `VOICE_PROVIDER`/`PROVIDER` across environment
and dotenv configuration fail. Explicit constructor settings otherwise take
priority over environment, then dotenv. `OPENAI_API_KEY` is not a voice alias:
embedding and other provider configuration remain independent. A compatible
measured `SEARCH_CALIBRATION_REPORT` and the existing origin/host/cookie settings
are still required. Do not put secrets in browser configuration. Model defaults
are compatibility defaults, not claims of current live service availability.
Reservation snapshots pin selected provider/model/voice/native rates plus search
profile; stream admission rejects a changed configuration. Durable V01 replay
still returns the original reservation without reinterpreting it.
```sh
.venv/bin/python -m app.server --host 0.0.0.0 --port 8000
# Separate ingestion process:
.venv/bin/python -m app.worker
```
Docker Compose uses the same API entrypoint. Run exactly one API process and no
API reload/multiple workers: media admission and runtime registry are process-local,
not distributed ownership. The ingestion worker is a separate process. For
production use trusted same-origin HTTPS/cookie settings and bounded reverse proxy
configuration; a proxy cannot substitute for backend message reassembly limits.
The supported entrypoint explicitly selects `BoundedWebSocketProtocol` over the
installed Uvicorn legacy WebSocket implementation, configured with validated
`LIVE_*` `RuntimeSettings`. It performs bounded reassembly using finite scratch
storage (`bytearray`) and an incremental UTF-8 decoder without retaining an unbounded
list of continuation metadata (preventing long empty-continuation memory retention).
Cancellation and connection termination release all scratch and assembly resources.
The parser rejects binary messages above `max_binary_message_bytes` (default 9600 bytes)
and UTF-8 text above `max_client_control_bytes` (default 4096 bytes), including aggregate
fragments, from declared frame lengths before reading payload/decoding. Compression is not
negotiated; any RSV/compression bit is rejected from the first two header bytes.
Total receive capacity strictly accounts for assembling, queued, and delivered/in-flight
messages against `max_queued_audio_messages` and `max_queued_audio_bytes`. Delivering a
message to the ASGI application retains its reservation until the next `recv()` call,
preventing an unmonitored runtime audio backlog. Queue depth is configured as
`max(1, max_queued_audio_messages - 2)` when the budget exceeds two, or one for small
budgets, preventing zero-capacity deadlocks on message budgets of one and two while
retaining deterministic wire backpressure. TCP/StreamReader scratch and kernel
buffers are separate finite transport buffers, not playback or commitment evidence.
Application checks remain defense in depth. Generic `uvicorn app.main:app`, `ws=auto`
and alternate/sansio backends are outside this supported policy. The selected legacy
backend is deprecated upstream: rerun real loopback tests on dependency upgrades;
replacement needs equivalent pre-payload enforcement, not renamed flags alone.
Authority-check saturation, timeout and SQL failure stop the session with
SEARCH_SATURATED, SEARCH_TIMEOUT and DEPENDENCY_UNAVAILABLE respectively; unverified
content/continuation is withheld. Verified revocation uses CONTEXT_REVOKED. Technical
failures persist `failed` with matching close reason/error code; committed terminal
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
saturation, but a database outage can still prevent a durable write and is logged.
## Continuous idle input limitation
The example continuously sends microphone PCM after readiness, including silence.
The frozen input-since-commit budget is 480000 bytes (10 seconds at 24 kHz PCM16LE).
Without verified native commitment, exactly 480000 bytes are accepted; the next
sample fails LIVE_BUFFER_OVERFLOW and closes. Native input consumption/transport
send is not commitment. This behavior is deterministic for an idle Gemini fake
with no activity boundary and applies to uncommitted admission for either adapter.
Longer continuous idle operation remains a product/provider-contract decision.
This example does not gate silence, fabricate commitment or add browser activity
controls. Use explicit stop/close and a fresh eligible session after overflow;
do not assume uninterrupted idle capture or seamless Gemini barge-in is supported.
Automated fake-provider/loopback/worklet results prove technical boundaries only.
Real provider access, measured retrieval quality, Persian speech, microphone,
heard audio and browser/hardware acceptance require their separate explicit opt-ins
and prerequisites; frontend readiness is not certified.
## Document workflow integration
Use the [Phase 3 HTTP handoff](realtime-agent-phase3-handoff.md) and delivered
DocumentClient with this VoiceClient. F01 exposes current OCR policy; document
polling exposes its frozen policy and actual review state. Automatic OCR admission
does not imply human review, factual authority, readiness or activation. Read K01
before replacing selection; removal revokes active voice context.
@@ -0,0 +1,172 @@
# Ingestion and voice admission repair — 2026-10-09
This scoped implementation supersedes the relevant ingestion/admission blockers
in the [Phase 4 operational report](realtime-agent-phase4-acceptance.md).
It does not certify real provider quality, browser audio or public HTTPS/WSS,
and does not complete Phase 4. No paid calls were made during this repair.
## Observable behavior
Initial unstyled FAQ titles and introductory paragraphs are document-wide context.
Every included pair retains that context, its text and original locators, including
pairs under later formal headings. Explicit heading ancestry and exclusive pair
context remain; detached prose after pairs and unresolved relationships still fail.
Factual authority approval is independent of extraction and remains mandatory.
The original extraction is never shortened or rewritten to make ingestion pass.
Gemini/OpenRouter recognition complete=false or warnings preserve nonempty legible
blocks. Global diagnostics and an explicit incomplete-recognition marker are retained
as block metadata, never injected into source text. These force the existing exact
extraction review even if the job's frozen OCR supervisor policy is false. Pending
review publishes no chunks. Approval/rejection uses existing D06/D07, source/profile/
evidence digests, backend reviewer identity, checks and deduplication. Approved retry
resumes the same job/candidate without repeating vision. Human completeness approval
must be genuine: missing content is a reason to reject, not an invitation to guess.
Malformed/empty responses, native truncation/blocking, model/provenance/relationship
violations, unreadable source text and resource limits remain fatal. OpenRouter now
also rejects multiple choices and explicit non-stop finish reasons. Warning wording
alone, including uncertainty about a margin, is a review diagnostic. Source text
containing replacement characters or unresolved PDF font identifiers is still invalid.
`VOICE_TRANSPORT_TESTING=false` remains the deployment default. Explicit true permits
transport testing without finalized offline calibration. V01 constructs configured
embedding transport after replay recovery, validating identity, credentials and
request limits without inference. The existing session execution-profile JSON pins
embedding identity and `mode: transport_testing`, with no distance or calibration ID.
Create/recovery/poll expose `calibration_status: uncalibrated`; calibrated reservations
report calibrated, and legacy reservations without search metadata report unknown.
F01 exposes the status and testing policy, and does not advertise testing availability
with an invalid embedding request policy. The delivered example client accepts these
additive fields; actual developer UI integration remains pending.
Authenticated WebSocket admission still checks Origin, owner/auth session, expiry,
access epoch, provider/model/voice and exact frozen search profile before opening a
provider connection. Disabling testing rejects an uncalibrated stream before provider
invocation. Replays keep their original identity and diagnostic status. Calibration
or policy changes cannot silently turn an existing reservation into another mode.
Shared canonical search still returns error/CALIBRATION_REQUIRED with no sources;
no invented fallback threshold, calibration report or alternate retrieval is created.
Operators can test streaming and greetings without claiming document-grounded answers.
## Acceptance and reproduction
Regression sources:
- `tests/unit/test_ingestion_admission_repairs.py`: 100-pair title/condition retention,
independent factual approval, unstyled Word introduction, both native vision
adapters' incomplete/global/block diagnostics, fatal OpenRouter output, pending
cutoff policy and search-service construction without uncalibrated evidence.
- `tests/integration/test_ingestion_admission_repairs.py`: real isolated database,
zero publication before review, D07 replay, same-job D04 resume without a second
vision call, inactive ready publication, Word/text factual review, authenticated
Gemini/OpenAI synthetic streaming, reservation replay and policy-disable rejection,
safe F01 diagnostics and configured embedding availability.
- Existing vision/OCR/source tests were updated only where the requested contract
changes their expected behavior. Genuine corrupt source text remains terminal;
detached FAQ prose and all worker/tenant/replay/fencing coverage remain.
Commands from the repository root (synthetic provider tests, no paid work):
```sh
.venv/bin/python -m pytest tests/unit/test_ingestion_admission_repairs.py tests/unit/test_phase5_repairs.py tests/unit/test_gemini_vision.py tests/unit/test_ocr_policy.py tests/unit/test_phase3_repairs.py -q -p no:cacheprovider --tb=short
.venv/bin/python -m pytest -m 'not postgres' -q -p no:cacheprovider --tb=short
docker run --rm -d --name rag-admission-regression-test --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=fixture -e POSTGRES_DB=rag_admission_test -p 127.0.0.1:55469:5432 pgvector/pgvector:pg16
export TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55469/rag_admission_test
.venv/bin/python -m pytest tests/integration/test_ingestion_admission_repairs.py --require-postgres -q -p no:cacheprovider --tb=short
.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Final regression run reuses the two unchanged large-review cases that passed above.
.venv/bin/python -m pytest -m postgres --require-postgres -q -k 'not test_large_eligible_review_persists_and_replays' -p no:cacheprovider --tb=short --junitxml=/tmp/admission-postgres-final.xml
docker stop rag-admission-regression-test
git diff --check
```
The approved original DOCX also passed an offline `PageBlockExtractor.extract_for_review`
and `factual_context_units` diagnostic: **201 blocks, 100 pairs, all 201 review blocks**,
and the initial block appears in every pair context. Original SHA-256:
`6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23`.
No database connection, human approval, publication or provider invocation was made.
The diagnostic used an inert explicit database URL because the real `.env` lacks a
host-run database URL. This is structural repair evidence, not factual acceptance.
Initial provider-free regression attempts failed settings validation inside the
socket-restricted sandbox; permitted execution outside it resolved that prerequisite.
The first complete run then found old warning-only terminal assertions (including
its nested isolation-suite run). Two PostgreSQL warning-only assertions also described
the superseded contract. Revised tests require review for diagnostics and terminal
failure for genuinely corrupt text. Final results are recorded below.
## Remaining runtime acceptance
Real Gemini Live and OpenAI audio quality were not run. Neither adapter was switched
or removed; Gemini remains the temporary default. OpenAI still requires its dedicated
key. Recognition changes were tested with deterministic native response fixtures;
the prior paid infographic attempt was not repeated to spend credits. The developer's
actual frontend remains under development, and browser/hardware/public deployment
acceptance remains not_run. Pending real calibration, human decisions and unseen labels
remain explicit quality prerequisites even when transport testing is enabled.
The real `.env` still needs its compatible database/request-limit configuration before
its backend transport can operate; changing admission does not repair or fabricate
those settings. Set the explicit testing flag and restart only after configuring them.
Health routes never construct or invoke providers. Applied migrations 0001–0005,
original inputs, stored profiles, tenant isolation, atomic publication, request keys
and lease fencing are preserved; no database schema changes or dependencies added.
## Executed results
- Focused final unit command above: **124 passed**, 4.36 s. New repair source:
**16 passed**, 1.56 s; broader extraction plus new source: **56 passed**, 3.99 s.
- Final complete provider-free suite: **1767 passed**, two existing Windows-path
skips, 403 PostgreSQL cases deselected at collection, 25 existing warnings,
**168.38 s**. Its nested ambient-configuration isolation suite also passed.
- New final database repair source: **7 passed**, 16.72 s. Earlier six-scenario
version passed in 12.60 s; final six plus existing F01 checks passed **8**, 19.37 s.
Strengthened corrupt-text database regressions: **2 passed**, 1.94 s.
- Complete initial database run: **401 passed / 2 obsolete assertion failures**,
zero skips, 1763 deselected, four warnings, **680.43 s**. Both existing
`test_large_eligible_review_persists_and_replays[False/True]` cases passed in
this run. Final recheck excludes only those two already executed unchanged
cases, includes the updated terminal-text assertions and newly added F01 case,
and produces per-case durations in `/tmp/admission-postgres-final.xml`. This
reuse is explicit, not a claim of a single final all-cases green invocation.
Database prerequisites: PostgreSQL **16.15**, pgvector **0.8.7**, dedicated
`rag_admission_test` on task-owned tmpfs container, never the existing database.
AST parsing, local repair/handoff links and `git diff --check` passed. All ten
protected input/migration files match the prior SHA-256 baseline, including every
applied migration 0001–0005 and all four supplied originals. The 55-case restored
`tests/unit/test_phase3_repairs.py` remains byte-identical.
Affected runtime files: `app/modules/documents/chunking.py`,
`app/infrastructure/gemini_vision.py`, `app/infrastructure/openrouter_vision.py`,
`app/modules/documents/extraction.py`, `app/modules/documents/worker.py`,
`app/modules/voice/configuration.py`, `app/modules/voice/lifecycle.py`,
`app/api/v1/live.py`, `app/api/v1/dependencies.py`, `app/api/v1/knowledge.py`.
Configuration/docs: `.env.example`, API catalog, implementation guide, reference
map, frontend backend handoff, operations guide, Phase 4 report and this repair
report. Existing test changes are limited to `test_gemini_vision.py`,
`test_phase5_repairs.py`, `test_phase3.py`, `test_ocr_policy.py` and integration
`test_phase5.py`; the two new repair test sources are listed above. Unrelated
working-tree changes were retained.
Final database recheck: **402 passed**, **zero skips**, 1771 deselected (1769
non-PostgreSQL cases plus the two previously passed large-review cases), four
existing warnings, **357.63 s**. Combined with those two actual earlier passes,
all **404 current PostgreSQL scenarios** have executed passing evidence. The
complete initial run with two superseded assertions is retained above; this is
coverage across executions, not a claim that its exit status was successful.
Temporary logs: `/tmp/admission-provider-free-final.log`,
`/tmp/admission-targeted-unit-final.log`, `/tmp/admission-targeted-complete.log`,
`/tmp/admission-postgres.log`, `/tmp/admission-postgres-final.log`.
Cleanup inspection found zero remaining application test schemas, zero public
tables and zero additional test databases. The task-owned tmpfs database container
was then stopped/removed. Existing containers and prior acceptance volumes were
not modified. For container deployment, rebuild the application image to include
this source change before restarting the API with the explicit testing policy;
worker startup still requires an approved queue and spending bounds. The operator
`app.voice_smoke` remains a calibrated search/voice-quality diagnostic; this policy
amendment applies to authenticated V01/WebSocket connectivity testing.
+230 -5
View File
@@ -1,10 +1,11 @@
# Phase 2 repair and acceptance record # Phase 2 repair and acceptance record
Initial repair checkpoint: 2026-10-09. The [remaining-defect repair](#remaining-defect-repair-2026-10-09) Current checkpoint: [transport defect repairs](#transport-defect-repairs-2026-10-09).
below supersedes affected behavior and validation totals. Gemini Live is the temporary sole voice provider Gemini is the temporary default; backend configuration can select the preserved
because an OpenAI Realtime voice key is unavailable. This decision changes voice OpenAI adapter. Earlier initial and remaining-defect records below retain their
only. Extraction, embeddings, frozen profiles, calibration inputs, the canonical historical results. The latest checkpoint supersedes their Gemini-only restriction
search pipeline and the shared bounded SearchToolRunner are preserved. and affected behavior; extraction, embeddings, frozen profiles, calibration inputs
and canonical search remain preserved.
The implementation and technical acceptance below are distinct from real Gemini The implementation and technical acceptance below are distinct from real Gemini
access, retrieval quality and browser/Persian voice acceptance. This report does access, retrieval quality and browser/Persian voice acceptance. This report does
@@ -315,3 +316,227 @@ interrupted fixture run and zero public application tables**. That residue was
confined to this disposable container and was removed with it; it is not claimed confined to this disposable container and was removed with it; it is not claimed
as clean fixture teardown. Preexisting containers and shared databases were as clean fixture teardown. Preexisting containers and shared databases were
untouched. Executed logs and preservation inventories remain under /tmp. untouched. Executed logs and preservation inventories remain under /tmp.
## Provider selection and transport repair (2026-10-09)
This checkpoint supersedes the Gemini-only restriction and affected behavior in
both earlier checkpoints. Gemini remains the temporary operational default;
`VOICE_PROVIDER=gemini|openai` selects the backend adapter. Both authenticated
Live and operator smoke now use the small [shared factory](../../app/infrastructure/voice_provider.py).
The existing OpenAI adapter and Gemini adapter remain byte-identical to the
preservation baseline. No real provider calls were made.
### Findings → fixes → executable evidence
| Reproduced finding | Repair | Regression evidence |
| --- | --- | --- |
| `VoiceSettings(provider='openai')` raised ValidationError; API and smoke constructed Gemini directly. | Backend selection, selected-only credentials, dedicated OPENAI_REALTIME_* settings, legacy PROVIDER/GEMINI_* compatibility with conflicting aliases rejected. Factory reuses the existing adapters/connections. V01/stream pin selected provider/model/voice/native audio/search profile; replay returns original identity. | `test_phase2_provider_selection.py`: both factory profiles, selected credentials/aliases, actual OpenAI runtime tool/audio/continuation/cancel/truncate. Existing native Gemini runtime tests. Both providers execute actual smoke construction; PostgreSQL API tests exercise readiness, native input, canonical ok/no_evidence/error tool dispatch and matching durable results/public refs. Changed-provider admission opens zero transports; replay retains reservation. |
| Installed Uvicorn defaults were 16777216-byte messages, 32 queued messages, compression enabled. | [Supported entrypoint](../../app/server.py) selects [BoundedWebSocketProtocol](../../app/infrastructure/voice_websocket.py). Pre-payload binary 9600 / text 4096 limits apply across fragments; RSV rejected before payload, compression disabled, queue eight. API retains delivered input capacity until native send completes, avoiding a second backlog. | `test_voice_websocket_transport.py`: ten real loopback cases for exact binary/UTF-8 boundaries, fragments, oversized messages, header-only rejection without mask/payload, compressed-bit rejection, negotiation and queue backpressure. Application validation remains active. |
| Authority helper returned False after SERVICE_BUSY; monitor treated infrastructure exceptions as revocation with inconsistent durable state. | Shared authority classification: SEARCH_SATURATED / SEARCH_TIMEOUT / DEPENDENCY_UNAVAILABLE for infrastructure; CONTEXT_REVOKED only for verified authority loss. Fail closed before release/delivery; first terminal code retained. Durable finish retries bounded pool admission; prior committed terminal outcomes remain immutable. | Unit startup/release/output cases and actual authority deadline. PostgreSQL monitor cases occupy all eight real blocking slots, raise a real SQL failure, exercise timeout classification and change actual DB authority; client errors match status/reason/error_code. Existing logout/disable/expiry/epoch/V04 race tests preserve committed terminal outcomes. |
| Executed delivered worklet admitted 101 tiny packets without overflow. | Both client and worklet enforce 96000 bytes AND 100 messages across refs, including partial packets and pending handoffs. Capacity reserved before PCM conversion. Cumulative consumed counters and completion/discard IDs make release idempotent; admission never advances played_ms. | `voice_phase2_repairs.mjs` executes delivered code: 100/101 tiny packets, exact byte capacity, multiple refs, partial consumption, duplicate consumption ack, interruption flush and cleanup. Existing worklet capture/progress and ASGI active-playback bridge remain exercised. |
| Committed/lost C01 response left creationAttempt and conversationRequestID undefined. | Expose attempt and both IDs before C01; retain frozen C01 and, before V01, frozen V01 payload. retryCreation/ordinary reserve replay identical attempt; newCreationAttempt/freshSession explicitly create new identity. V03 recovery does not connect. | Delivered JS simulates committed/lost C01 and V01 responses, checks identical retry payloads, immutable payload/conflicting IDs, V03 recovery, intentional freshSession ordering. Existing PostgreSQL identical/changed C01/V01 concurrency tests retain backend conflict guarantees. |
| Continuous uncommitted silence reaches the 10-second input cap. | Bound preserved; no commitment or transcript/activity binding invented. Frontend handoff now states the limitation and isolates longer idle operation as a product/provider-contract decision. | Actual Gemini adapter/runtime accepts exactly 480000 bytes of silent PCM without native activity commitment, then rejects the next sample with LIVE_BUFFER_OVERFLOW. No fake tool output/commitment. |
### Deployment and limits
The [frontend handoff](frontend-voice-integration-example.md#backend-configuration-and-supported-startup)
contains both backend configuration examples, aliases, selected-only secrets,
24 kHz browser/native audio behavior, reservation compatibility, explicit retry
and fresh-session APIs, and idle-input limitations. `.env.example` supplies both
provider-specific configurations. Embedding OPENAI_API_KEY/INGEST_* settings are
not voice aliases and were not changed.
Run `.venv/bin/python -m app.server --host 0.0.0.0 --port 8000`; Docker Compose uses
this same supported configuration. Run ingestion separately with
`.venv/bin/python -m app.worker`. Exactly one API process owns process-local
media guards and registry; multiple workers/reload/distributed ownership are not
supported. Browser controls and HTTP schemas remain frozen. Gemini safe-close
interruption does not alter OpenAI cancellation/truncation.
Inspected installed versions: Uvicorn 0.54.0 and websockets 16.1.1. The selected
legacy parser is explicitly named, rather than relying on `ws=auto`. Upstream
legacy deprecation warnings are expected and retained in test output; upgrades
require these loopback checks before changing parser/backend. The upstream
[legacy server reference](https://websockets.readthedocs.io/en/stable/reference/legacy/server.html)
describes compression disabling and message-queue backpressure; local installed
source inspection and executable tests prove the chosen implementation here.
TCP/read scratch and kernel buffers remain separate from admitted-message
budgets. Fake native acknowledgements/input consumption/context sync were not added.
### Executed checks and preservation
Commands run from the repository root using Linux `.venv/bin/python`.
PostgreSQL acceptance uses only the task-created `rag_phase2_selection_test`
database at loopback port 55439 and disposable application schemas, with pgvector
in `test_vector`. No existing application database was reused. Repeated schema
migration writes were unusually slow; only the disposable container was changed
to fsync=off and synchronous_commit=off for functional acceptance. These results
do not prove database crash durability or production throughput.
Executed command results (logs retained under `/tmp/phase2-selection-*.log`):
- Initial focused existing cases:
`.venv/bin/python -m pytest tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py tests/unit/test_voice_client_example.py tests/unit/test_phase2_remaining.py -q`
— **65 passed**, 22.09 seconds.
- Provider/factory/native cancellation/smoke/browser/loopback focus:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py::test_operator_harness_actual_fake_transport_tool_correlation -q`
— **35 passed**, 8.43 seconds. Later three-file focus with `-p no:cacheprovider --tb=short`
— **33 passed**, 7.36 seconds. After explicit expiry/disablement cases,
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **25 passed**, 5.28 seconds.
- Affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— first **58 passed**, 483.11 seconds; expanded both-provider tool/result and real
authority coverage **61 passed**, zero skips, 331.67 seconds.
- Final full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1679 passed**, two existing Windows path-alias skips, 372 PostgreSQL cases
deselected, 12 expected legacy-backend warnings; 142.03 seconds. A preceding
complete run passed 1677 cases before two additional authority regressions;
its results are superseded by this final run.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **372 passed**, zero skips, 1681 provider-free cases deselected, two expected
legacy-backend warnings; 394.30 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**, zero database passes/skips.
- `node tests/support/voice_phase2_repairs.mjs` and
`node tests/support/voice_client_harness.mjs unit` — passed. Delivered worklet,
module/client and harness syntax passed (`node --check`, client via
`node --input-type=module --check < examples/voice-client.js`). Python compileall
for app and affected tests, scoped AST/UTF-8, unchanged pyproject TOML parsing,
CLI help for `app.server`/`app.voice_smoke`, and `git diff --check` passed.
- New local documentation links resolve. The initial whole-modified-doc link check
found two unchanged README links to an absent LICENSE, confirmed present in HEAD;
this unrelated existing defect was preserved and excluded from the added-link check.
Failed/interrupted checks are separate from acceptance. The first new focus had
19 passes and two failures: conflicting constructor aliases were silently dropped
by the settings source, and a new timeout fixture incorrectly used dataclasses.replace
on Pydantic settings. Alias validation and the fixture were corrected. A later
focus had 34 passes and one timeout because its fake cancellation omitted the
required native terminal acknowledgement before truncation; the fixture was
corrected, preserving the OpenAI adapter and its acknowledgement gate. The earlier
full provider-free attempt and tool/container launch inspection were interrupted
by the user; completion was not recovered as suite acceptance. The disposable
container was subsequently verified running and full checks rerun. No failed,
interrupted, missing-database or skipped run is counted as PostgreSQL acceptance.
Preparation captured a clean working tree at HEAD `9be4719` and SHA-256 hashes of
213 existing repository files before editing, retained in
`/tmp/phase2-provider-selection-baseline.json`. The changes are limited to voice
configuration/factory/runtime authority/Live transport, supported startup,
browser examples, related tests and handoff/contracts. Protected migrations
0001–0005, both existing voice adapters, extraction/embedding configuration and
modules, shared SearchService/StructuredTool/SearchToolRunner, calibration inputs,
proof scripts and original-document paths were not edited. No migration was
required or added. Unrelated changes were absent at the initial baseline. A final
hash comparison matched exactly the 21 scoped modified existing paths; 42 protected
baseline entries remained unchanged. OpenAI adapter SHA-256:
`c5906daa1fb619baca6bb35a676b7cfdee720be4a4d52331278039c6efe01206`;
Gemini adapter SHA-256:
`607cf142801b8bede48482b42bc997462f2010b555eaf051a707242f09b575ae`.
Added paths are the shared factory, authority classifier, server/parser and their
regression/harness files; no unrelated existing paths changed.
Remaining external acceptance: separately authorized Gemini/OpenAI service
access with valid selected voice key/model/voice; compatible measured retrieval
calibration and approved corpus; budgets; Persian speech; real browser microphone,
AudioContext/hardware and heard-audio testing. Fake-provider tests establish
technical behavior only. Frontend readiness, seamless Gemini interruption and
longer continuous uncommitted idle capture remain uncertified.
## Transport defect repairs (2026-10-09)
This checkpoint repairs three verified Phase 2 transport defects across backend
WebSocket protocol reassembly, browser capture buffering, and trusted wire limits.
Both Gemini and OpenAI adapters, credentials, pinned profiles, migrations 0001–0005,
frozen payload/queue/playback limits, and canonical retrieval remain preserved.
### Verified defects, repairs, and observable regressions
| Transport defect | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| 1. Bound fragmented-message reassembly (`app/infrastructure/voice_websocket.py`, `app/server.py`) | Reassembly uses finite scratch storage (`bytearray`), incremental UTF-8 decoding, and bounded retained metadata. Empty continuations do not allocate or grow fragment lists (preventing probe memory growth across 20,001 empty frames). Aggregate byte limits (`max_binary_message_bytes`, `max_client_control_bytes`), pre-payload frame header checks (`Frame.read(max_size=bound)`), and compression rejection are enforced. Connection close, failure, and cancellation release assembly resources. Interleaved control frames (ping/pong) remain supported during fragmentation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_bounded_fragment_reassembly_long_empty_and_tiny_sequences` (20,001 empty continuation frames, exact 9600-byte binary and 4096-byte UTF-8 boundaries), `test_interleaved_protocol_controls_during_fragmentation` (ping/pong interleaved during reassembly), and `test_malformed_fragmentation_sequences_and_resource_cleanup` (opcode 0 without start rejected with 1002, interleaved data frame rejected with 1002, unfinished message cleaned up on disconnect). |
| 2. Bound outgoing microphone messages through completion (`examples/voice-client.js`, `examples/voice-audio-worklet.js`) | Capture handoff and outgoing socket buffering enforce both byte (96000) and message (100) capacity bounds. Worklet tracks `pending` messages and `pendingBytes`, rejecting with `overflow` when either bound would be exceeded. Conservative browser `socket.bufferedAmount` accounting delivers `{type: 'accepted', bytes}` to the worklet only after verified drain across the socket (`captureBytes - bufferedAmount >= packetBytes`). Worklet acceptance does not falsely imply network completion. Capacity is released exactly once on verified drain or terminal cleanup. | Regressions in `tests/support/voice_phase2_repairs.mjs` (executed by `tests/unit/test_voice_client_example.py`): standalone worklet 100/101 boundary, client+worklet stalled socket 100/101 boundary (48,000 bytes admitted, 101st overflows), partial drain conservative accounting (partial packet bytes do not trigger acceptance), delayed handoffs, terminal cleanup, and stale callbacks. |
| 3. Honor lower trusted runtime limits at the wire boundary (`app/server.py`, `app/infrastructure/voice_websocket.py`) | Validated `LIVE_*` `RuntimeSettings` are injected into `server_config()` and `BoundedWebSocketProtocol`. Pre-allocation message admission accounts for assembling, queued, and in-flight messages (`recv()` entry release). Queue depth is set to `max(1, max_queued_audio_messages - 2)` when $> 2$ or 1, avoiding zero-capacity deadlocks for message budgets of one and two while strictly bounding total capacity. Oversized declarations are rejected before mask/payload allocation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_lower_trusted_runtime_limits_and_prepayload_rejection` (1201 binary and 501 text rejected with 1009 before reading mask/payload; legal 1200 binary and 500 text accepted), `test_small_message_budgets_one_and_two_deadlock_free` (budget of 1 functions with in-flight backpressure and sequential drain without deadlock; budget of 2 bounds total capacity to 2). |
### Exact checks and outcomes
Commands run from repository root using `.venv/bin/python` (Python 3.13.7) and `node` (v22.23.1):
- Transport loopback regressions and voice client example tests:
`.venv/bin/python -m pytest tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **18 passed**, 22 expected legacy-backend warnings in 7.60s.
- Node worklet and client repair regressions:
`node tests/support/voice_phase2_repairs.mjs`
— **passed**: playback bounds, consumed capacity, flush, cleanup, capture bounds, 100/101 stalled socket, drain, delayed handoffs.
- Node client harness unit test:
`node tests/support/voice_client_harness.mjs unit`
— **passed**: VoiceClient ownership, errors, logout, and close.
- Provider selection, lifecycle, and Gemini Live regressions:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short`
— **44 passed** in 4.46s.
- Full provider-free test suite:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1684 passed**, 2 skipped (Windows path alias), 372 deselected, 22 expected warnings in 150.64s.
- Missing-configuration gate:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**: `TEST_DATABASE_URL is required for PostgreSQL acceptance`.
- PostgreSQL acceptance status:
No active PostgreSQL container or TEST_DATABASE_URL is configured in this Linux test environment. Prerequisite gate verified; full PostgreSQL acceptance is reported as unavailable pending environment setup.
- JavaScript syntax and formatting:
`node --check examples/voice-audio-worklet.js` and `node --input-type=module --check < examples/voice-client.js`
— **passed**.
- Code integrity and git checks:
`git diff --check`
— **passed** with zero whitespace/formatting defects.
### Material limitations and scope preservation
All repairs preserve:
- `VOICE_PROVIDER=gemini|openai`, Gemini default, OpenAI adapter, shared adapter factory, and credentials.
- Applied migrations 0001–0005, protected inputs, canonical retrieval, and ownership/replay/revocation rules.
- Frozen payload (9600 binary / 4096 control), queue (96000 bytes / 100 messages), playback, and 10-second uncommitted input limits. No limits were widened.
- No provider fallback, frontend provider selector, new browser control types, or deferred history features were introduced.
Automated simulations, Node worklet tests, and transport loopback tests establish technical wire boundaries only. They do not certify real-provider availability, live microphone hardware, heard-audio acoustics, or real-browser production readiness.
## Phase 3 integration: final two Phase 2 transport findings (2026-10-09)
Both requested findings are repaired without changing selected Gemini/OpenAI
adapters, voice/model configuration, browser mono PCM16LE 24 kHz, playback limits,
canonical retrieval or migrations 0001–0005.
- Receive-capacity cancellation: wait_for_capacity now propagates CancelledError.
The real installed-parser regression fills a valid one-message capacity budget,
fails the protocol with a nonresponsive peer, shields the termination assertions
from issuing another cancellation and verifies bounded transport teardown.
Existing one/two-message, fragmentation, compression and header-only limits remain.
- Invalid UTF-8 classification: the parser retains its 1007 rejection for ASGI;
Uvicorn otherwise can expose 1006 because a failed parser no longer reads the
peer close. Live maps 1007 to LIVE_PROTOCOL_ERROR. Complete and fragmented raw
invalid UTF-8 produce wire close 1007 and real PostgreSQL terminal polling reports
the protocol error. Ordinary loss remains LIVE_TRANSPORT_FAILED; existing loss
regressions remain in the affected/full acceptance suites.
Finding-to-test mapping:
`tests/unit/test_voice_websocket_transport.py::test_capacity_failure_terminates_receive_with_nonresponsive_peer`,
`test_invalid_utf8_retains_standard_1007_rejection`, and
`tests/integration/test_realtime_phase3_http.py::test_real_parser_invalid_utf8_persists_protocol_error`.
The latter executes the actual Live handler, installed server parser and durable
polling, with a deterministic provider transport. See the
[Phase 3 handoff](realtime-agent-phase3-handoff.md) for the complete exact validation
record and HTTP/voice integration checks. No real provider or browser microphone,
Persian speech, network latency or transcription-quality acceptance was performed.
Executed final integration checks: **323 affected unit tests passed**;
**1724 provider-free tests passed**, two existing Windows-only path skips;
**162 affected PostgreSQL tests passed**, zero skips, including both adapters and
the raw UTF-8 polling cases. A prior full PostgreSQL checkpoint passed **393**;
final refinement coverage and exact commands are distinguished in the Phase 3
handoff. The two-provider explicit revoked-excerpt regression passed **2** additional
cases. Missing TEST_DATABASE_URL failed with the required prerequisite error.
Compose, executable JavaScript, AST/TOML, diff and preservation checks passed.
Task-owned acceptance database cleanup verified zero application schemas/tables
before removal. No provider, adapter, frozen voice configuration or corpus rewrite.
@@ -0,0 +1,513 @@
# Phase 3 document and knowledge HTTP handoff
The modular API exposes D01-D04, D06 preview/D07, K01/K02 and read-only F01 under
`/api/v1`. It uses the existing immutable intake, fenced worker, exact-output
review and atomic selection services. It preserves selected Gemini/OpenAI voice
configuration and the Phase 2 repairs. Production UI, text chat, settings editing,
deletion and real-provider certification remain outside this delivery.
## Startup and development origin
Install the API extra (including the bounded multipart parser) and the worker's
configured embedding/vision extras using the repository manifest. Apply migrations
and provision an enabled administrator as described in
[foundation setup](ingestion-foundation-setup.md). Applied migrations 0001–0005
remain unchanged.
### Direct run vs. Docker Compose ports
For local development matching the Vite development proxy (`http://localhost:8080`) and Docker Compose port mapping:
- **Docker Compose**: The API container listens internally on port 8000 and exposes host port 8080 via `${API_PORT:-8080}:8000`. Start `docker compose up -d db migrations api`; start `worker` separately only for an approved ingestion queue and budget. See the [Phase 4 operational procedure](phase4-backend-operations.md).
- **Direct run**: Start the API process with:
`python -m app.server --host 0.0.0.0 --port 8080`
(or `--port 8000` if matching container-internal default or behind a reverse proxy mapping host 8080 to container 8000), and start a separate worker with:
`python -m app.worker`.
Docker Compose forwards the OCR setting to API and worker; both mount the same original and extraction directories. Use `.env.example` for actual embedding identity, dimensions and provider credentials; they remain server-side.
### Proxy and trusted Host/Origin configuration
Use the [same-origin Vite proxy example](../../examples/vite-proxy.config.js) in the frontend's existing configuration. The Vite dev server runs at `http://localhost:5173` and proxies `/api` to the backend at `http://localhost:8080`.
- **Vite proxy with `changeOrigin: false` (recommended for development)**:
The proxy preserves browser headers (`Host: localhost:5173` and `Origin: http://localhost:5173`) and forwards both HTTP and WebSocket paths (`ws: true` for `/api/v1/live`). Set:
`TRUSTED_HOSTS=["localhost:5173"]`, `TRUSTED_ORIGINS=["http://localhost:5173"]`, `COOKIE_SECURE=false` (for loopback HTTP development only).
- **Direct API access (no frontend proxy)**:
When accessing the API directly on port 8080 without a frontend proxy, set:
`TRUSTED_HOSTS=["localhost:8080"]`, `TRUSTED_ORIGINS=["http://localhost:8080"]`.
HTTPS production uses Secure cookies and explicit trusted endpoints. Never use wildcard credentialed CORS. Cross-origin configured clients can preflight PATCH and Idempotency-Key; correlation/replay headers are exposed.
## Executable browser sequence
Use [DocumentClient](../../examples/document-client.js) with the existing
[VoiceClient](../../examples/voice-client.js). Run in the frontend module context; `inspectEvidence` is the frontend developer’s
human review interaction, never an automatic approval helper:
```js
import {VoiceClient} from './voice-client.js';
import {DocumentClient} from './document-client.js';
const voice = new VoiceClient(event => console.log(event));
await voice.login(username, password);
const documents = new DocumentClient(voice);
const configuration = await documents.configuration();
const uploadKey = crypto.randomUUID(); // retain until the upload outcome is resolved
const uploaded = await documents.upload(fileInput.files[0], 'Policy', uploadKey);
async function waitForProcessing(id) {
for (;;) {
const current = await documents.poll(id);
if (!['queued', 'processing'].includes(current.status)) return current;
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
let document = await waitForProcessing(uploaded.document_id);
while (document.review_required) {
const evidence = await documents.review(document.id);
for (const item of evidence.items) {
// Frontend-owned human inspection: show blocks and authenticated preview_path.
// This returns the person's decision, checked fields, note and whole-group exclusions.
const humanDecision = await inspectEvidence(item);
await documents.decide(document.id, {
...humanDecision, evidence_sha256: item.evidence_sha256
}, crypto.randomUUID()); // retain each decision/key if its outcome is ambiguous
}
document = await documents.poll(document.id);
if (document.review_required) continue; // fetch the next still-pending page
if (!document.job.can_retry) throw new Error(document.review_state);
await documents.retry(document.id, crypto.randomUUID()); // retain retry key
document = await waitForProcessing(document.id);
}
if (document.status !== 'ready') throw new Error(document.job.error?.code);
// Ready remains inactive and unsearchable until this explicit replacement.
const selection = await documents.selection();
await documents.replace(selection.revision, [...new Set([...selection.document_ids, document.id])]);
// Voice admission additionally requires configured credentials and measured calibration.
await voice.reserve();
await voice.connect();
```
The snippets use real server-returned UUIDs/digests. Branch on processing state;
do not execute review with an empty candidate list. Keep the exact File/title and
upload key on ambiguous timeout, then replay the same upload. Retain decision and
retry keys similarly; replay headers are `Idempotency-Replayed: true`. A changed
payload under an existing key returns `409 IDEMPOTENCY_CONFLICT`. New keys create
independent documents even when bytes match. Titles are normalized by intake.
Known replay retains its accepted byte bound even if the current new-upload
limit is lower; changed bytes/length still conflict. The helper leaves FormData
Content-Type/boundary to the browser. Upload has one
file and optional title; caller-supplied organizations, profiles or model selectors
are rejected. Retry accepts no body.
Lists return items, next_cursor and knowledge_revision. Document lists use limit
20 by default, max 100, stable descending created_at/id, and opaque cursors.
Review pagination defaults to 10, max 20; pass the returned evidence cursor unchanged.
Invalid/unknown cursors return 422. Detail never exposes private storage keys,
original paths, leases, raw provider messages or credential-bearing profiles.
Admin documents/review/selection are organization-scoped; hidden/deleted IDs are
404. Authenticated non-admin collection access is 403. F01 is available to both roles.
## OCR supervisor policy and truthful review state
`INGEST_OCR_REVIEW_REQUIRED=true` is a backend-only deployment setting, default
true. API enqueue freezes it as `processing_profile.extraction.ocr_review_required`
in the immutable one-document/one-job snapshot. Workers use that snapshot; a later
environment change affects only new uploads. Same-job retry preserves it. Existing
profiles lacking the field retain mandatory OCR review and their original digests.
No migration, backfill or profile rewrite is needed.
False admits OCR/vision transcription only after existing automatic validation
passes: identity/model, readable complete blocks, source relationships, byte/pixel/
page/character budgets, faithful normalization, original integrity and coverage.
Warning-bearing OCR still requires inspection; unreadable/invalid output fails.
Direct PDF and other non-OCR review requirements remain. Factual Q&A inclusion
requires its own retained-evidence human approval regardless of OCR policy.
Approvals never enqueue or activate. Publication is atomic, ready and inactive;
K02 is the only delivered activation route.
F01 capabilities.ocr_review_required reports the current deployment policy.
D03 ocr_review_required reports the document's frozen policy. D03 review_state is
not_evaluated, not_required, pending, approved or rejected and describes retained
required decisions. review_required means a current candidate lacks a decision;
rejection separately prevents retry. extraction_quality_decision is null before a
complete artifact, passed for automatic validation, reviewed when all extraction requiring inspection was actually inspected, or
partially_reviewed for mixed inspected pages and automatically admitted OCR. An automatically admitted extraction creates no
human approval annotation or audit event. approved factual review does not change
passed extraction into reviewed. Only inspected locators carry human annotations; automatic pages never do.
Factual candidates can remain pending independently of any extraction outcome.
D06 returns exact server-owned evidence and check lists; preview URLs require the
same admin cookie and return no-store validated image bytes. Preview cannot accept
a storage path. D07 requires a nonblank note and exact required checks for approval.
For factual candidates, exclusions are whole existing Q&A group IDs and cannot
include placeholders or leave no factual groups. Rejection stays failed with zero
chunks. Stale/removed evidence returns REVIEW_STALE; a new conflicting decision on
already-decided evidence returns REVIEW_ALREADY_DECIDED. Pending reviews prevent
retry even after changing the deployment default. Retry reuses the same failed job
and retained output rather than obtaining a new OCR response under an old approval.
## Selection, voice and errors
K02 replaces the full selected set using expected_revision; duplicate IDs return
422, unready IDs return DOCUMENT_NOT_READY with rejected IDs, and stale revision
returns REVISION_CONFLICT. After ambiguous timeout or conflict, read K01 before
constructing the next replacement. Additions increment revision without changing
epoch; no-op preserves both. Removal increments access_epoch, stales conversations,
closes older Live sessions, fails running tools and notifies the local runtime after
commit. Polling redacts revoked evidence. Stop ineligible output and create a fresh
conversation; never copy revoked context into recovery.
Cookie-only authentication, trusted Host/Origin and X-CSRF-Token apply to mutations.
Refresh the CSRF token through `/me`. Safe failures carry error.code, message,
request_id and retryable; X-Request-ID matches that correlation.
### Bounded request-body admission before parsing
D07 extraction-review decisions and K02 knowledge-selection authenticate BEFORE
consuming or accumulating request bodies:
- Unauthenticated requests are rejected immediately with 401 (or 403 for non-admins)
with zero bytes read from the network stream, preventing unauthenticated denial-of-service
via unbounded payload buffering.
- Finite receive-byte limits are enforced during streaming accumulation:
- `MAX_DECISION_BYTES = 60,151,072 bytes` for D07 decisions, accommodating
all supported DTO values: 10,000 exclusions and 16 checks of 500 characters,
a 2,000-character note, 12 bytes per character for escaped surrogate pairs,
three bytes per array entry for quotes/comma, and 1,024 bytes for fixed fields
and formatting. This finite cap admits raw UTF-8 and escaped JSON without
reducing semantic eligibility. Capacity is checked before buffer extension.
- `MAX_SELECTION_BYTES = 1 MiB` (1,048,576 bytes) for K02 selection, accommodating
up to 10,000 document UUID selections (~360 KiB).
- Actual received bytes are counted dynamically; absent or misleading `Content-Length`
headers cannot bypass bounds. Payloads exceeding limits return 413 `PAYLOAD_TOO_LARGE`.
- Finite receive-time deadline: 15 seconds (`JSON_RECEIVE_SECONDS = 15`). Stalled or
timed-out body receives return 503 `DEPENDENCY_UNAVAILABLE` and clean up.
- D04 retry enforces a finite 5-second deadline (`RETRY_RECEIVE_SECONDS = 5`) and rejects
any nonempty body with 422 `VALIDATION_ERROR`. Stalled streams, client disconnects, or cancellations release
request resources immediately and cannot invoke retry afterward.
### Upload admission and temporary spool separation
Upload intake decouples user-facing display filenames from filesystem temporary storage:
- Spooled upload bytes are written to a bounded, server-controlled temporary filename
(`payload`) in an isolated temporary directory (`UploadSpool(path, filename, title)`).
- The original validated display filename (up to 255 characters, valid extension, no
traversal) is preserved in `spool.filename` and passed explicitly to `import_document`.
- This eliminates Linux filesystem `NAME_MAX` (255 byte) collisions for long multibyte UTF-8
filenames (e.g. 128 Arabic characters `س` + `.md` = 259 bytes), which previously raised
`OSError: File name too long` (503 `DEPENDENCY_UNAVAILABLE`).
- Default normalized title derivation, replay hash idempotency semantics, CLI intake
compatibility, upload bounds, and temporary file cleanup on completion/cancellation
remain fully preserved.
- Upload admission uses request max = configured file bytes + 16 KiB, file max = configured bytes,
two parts, 4 KiB headers per part, 800 UTF-8 title bytes, a 60-second receive
deadline and four concurrent disk spools. Invalid/malformed input is INVALID_FILE (422),
too large is FILE_TOO_LARGE (413), unsupported format is 415, and capacity is RATE_LIMITED (429).
Stalled receive returns DEPENDENCY_UNAVAILABLE (503) after its deadline. Partial
multipart, rejection and disconnect clean temporary resources. Uncertain original
commits retain candidates for existing reconciliation rather than deleting evidence.
F01 voice/captions indicate configured credential/calibration prerequisites, not
verified provider/Persian quality. See the
[voice handoff](frontend-voice-integration-example.md) for mono PCM16LE 24 kHz,
application events, playback_progress, audio_ended, interruption and ten-second
uncommitted input behavior. Native UTF-8 rejection retains wire close 1007 and is
persisted as LIVE_PROTOCOL_ERROR; ordinary loss remains LIVE_TRANSPORT_FAILED.
Reconcile V03/poll, close the old reservation and use fresh IDs before reconnecting.
## Validation checkpoint
Executed checks and remaining external prerequisites are recorded below after
implementation validation. Deterministic providers, simulated browser requests and
local parser tests do not establish real provider quality or browser hardware readiness.
### Executed checks (2026-10-09)
- Repair regression test suite:
`.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py -q -p no:cacheprovider --tb=short`
— **23 passed** (9 repair tests in `test_phase3_repairs.py`, 14 in `test_upload_boundary.py`), 0.65 seconds.
- Bounded admission, upload spool, and document client unit tests:
`.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py tests/unit/test_intake.py tests/unit/test_document_client_example.py -q -p no:cacheprovider --tb=short`
— **36 passed**, 0.74 seconds.
- Provider-free regression suite:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1680 passed**, 2 skipped (Windows path alias semantics), 395 PostgreSQL tests deselected, 154.21 seconds. No real provider calls.
- PostgreSQL integration acceptance with isolated container (`rag-phase3-repair-acceptance` on loopback port 54930, tmpfs):
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **23 passed**, zero skips, 55.79 seconds; includes `test_unicode_filename_upload_persistence_and_replay`.
- PostgreSQL acceptance suite with intake:
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py tests/integration/test_intake.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **77 passed**, zero skips, 78.07 seconds.
- Required PostgreSQL acceptance configuration check:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_unicode_filename_upload_persistence_and_replay -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1 with **prerequisite error**: `TEST_DATABASE_URL is required for PostgreSQL acceptance`. Missing configuration fails acceptance rather than passing.
- Node syntax and contract checks:
`node --check examples/document-client.js examples/vite-proxy.config.js examples/voice-client.js examples/voice-audio-worklet.js`: passed.
- Formatting, git diff, and whitespace checks:
`git diff --check`: passed. Zero trailing whitespace or merge conflict markers.
### Acceptance coverage and focused integration review
| Area | Evidence |
| --- | --- |
| Auth and scope | Actual cookie login, admin/user roles, Host/Origin/CSRF checks, cross-organization 404 for detail/review/preview/retry/selection, safe shared correlation/error envelopes |
| Bounded request admission | D07 decisions (60,151,072-byte bound) and K02 selection (1 MiB bound) authenticate before body accumulation (0 bytes consumed unauthenticated); dynamic receive-byte counts prevent bypass via missing/misleading Content-Length; 15s receive deadline returns 503; D04 retry empty body deadline (5s) rejects nonempty payload and releases resources on timeout/cancellation without invoking retry |
| Upload intake & spools | Spooling writes to bounded server-controlled disk path (`payload`) decoupling Linux `NAME_MAX` (255 byte) limit from original display filename; 128 Arabic characters (`س` * 128 + `.md` = 259 bytes) accepted without filesystem error; display filename, extension validation, default normalized title derivation, exact replay hash idempotency, CLI intake, and cleanup on disconnect/finish preserved |
| Startup & proxy | Direct run on port 8080 (`python -m app.server --host 0.0.0.0 --port 8080`), Docker Compose port mapping (`${API_PORT:-8080}:8000`), and Vite proxy configuration (`http://localhost:8080`, `changeOrigin: false`, `ws: true`) reconciled and documented with corresponding trusted Host/Origin settings |
| Review/retry | Exact retained source previews, required checks and forged reviewer rejection, stale digest, approval/rejection and replay/conflict, approval alone leaves failed, same-job/generation replay, retained OCR reuse |
| Frozen OCR | True/false new profiles, legacy missing setting, deployment changes after enqueue, JPEG/PNG/scanned PDF, unreadable/model/placeholder/warning failures, independent factual inclusion, truthful passed/partially_reviewed outcomes, zero synthetic human records |
| Publication/selection | Ready but inactive after actual fenced publication, unready/duplicate/revision rejection, no-op and addition epoch rules, authenticated K02 removal closing both provider paths, revoked excerpts redacted, blocked actual runtime search cancelled without late sources/provider output |
| Transport | Filled capacity with a nonresponsive peer terminates without another cancel; complete and fragmented UTF-8 retain native 1007 and persist LIVE_PROTOCOL_ERROR through actual installed parser/Live handler |
Final integration review confirmed that all three Phase 3 findings are repaired without altering Phase 1 architecture, data migrations, provider abstractions, or unrelated working tree changes.
Preservation checks confirm:
- Existing Gemini and OpenAI Realtime adapters remain intact and configurable; Gemini remains the default provider without fallback.
- OCR supervisor policy defaults to true and remains frozen per job; legacy profiles retain mandatory review.
- Independent uploads, immutable originals, same-job retry, ready-but-inactive publication, explicit K02 selection, and shared retrieval are preserved.
- Database migrations 0001–0005 and protected corpus inputs are untouched.
- No production UI, public search endpoint, settings editor, background service, or extra external dependency was added.
Real OCR/transcription quality, funded provider calls, Persian voice, browser microphone/playback, production HTTPS/proxy deployment, and frontend UI acceptance remain explicitly unverified. Setting the OCR supervisor gate false is not quality certification.
Before cleanup, the temporary test database contained zero disposable application schemas and zero public application tables. The test container `rag-phase3-repair-acceptance` was stopped and automatically removed.
## Four verified findings repair (2026-10-09)
K02 submits its unchanged synchronous atomic service to the existing eight-slot
blocking pool. Exhaustion maps to 429 RATE_LIMITED; a six-second wait timeout maps
to 503 DEPENDENCY_UNAVAILABLE. A timed-out transaction can still commit, retaining
its slot until completion and issuing the existing post-commit notification.
Resolve ambiguous outcomes through K01 before submitting a new expected revision.
| Finding | Exact regression coverage |
| --- | --- |
| Selection blocking | `tests/unit/test_phase3_http_repairs.py::test_blocked_selection_keeps_event_loop_responsive`, `test_selection_blocking_safe_errors`; PostgreSQL `tests/integration/test_realtime_phase3_http.py::test_authenticated_selection_removal_closes_active_voice_and_redacts_polling` (Gemini and OpenAI), `test_http_selection_removal_cancels_running_runtime_tool`, `test_selection_addition_preserves_active_epoch_and_noop_revision` |
| Overwritten ingestion suite | `tests/unit/test_phase3_repairs.py` restored byte-for-byte from commit `9be4719`: all 55 DOCX fidelity, FAQ association, chunking, budgets and deadline regressions; the nine existing HTTP tests moved intact to `tests/unit/test_phase3_http_repairs.py` with cap-dependent fixtures updated |
| Decision admission budget | HTTP suite `test_decision_budget_covers_multibyte_and_escaped_identifiers`, `test_json_capacity_checked_before_buffer_extension`, `test_streamed_oversized_json_rejection`, `test_absent_and_misleading_content_length`, `test_slow_body_receive_timeout`, `test_unauthenticated_admission_zero_bytes_consumed`, `test_csrf_rejection_consumes_no_decision_body`; PostgreSQL `test_large_eligible_review_persists_and_replays` generates 9,000 retained blocks/4,500 groups, excludes 4,499 and resumes one eligible pair without repeated provider calls (ASCII and escaped Unicode variants) |
| D04 handoff | HTTP suite `test_retry_admission_and_cancellation`: nonempty body returns 422 VALIDATION_ERROR; stalled receive returns 503 and cancellation never invokes retry |
The new decision bound is 60,151,072 bytes. Existing semantic limits, review
eligibility, authentication/CSRF ordering and 15-second receive deadlines remain.
JSON with excessive formatting can exceed the finite admission budget even if
its parsed DTO would otherwise be valid; compact valid DTO encodings fit.
Executed repair checks (Linux `.venv/bin/python`; local socket access required):
```sh
.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_phase3_http_repairs.py -q -p no:cacheprovider --tb=short
# 71 passed in 5.55s: 55 restored ingestion + 16 HTTP cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# 1740 passed, 2 failed, 2 existing Windows-path skips, 397 deselected in 209.23s.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# 9 passed, 1 failed in 15.33s; same tool-response timeout reproduces alone.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'large_eligible or selection' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# 6 passed, 1 failed, 18 deselected in 644.49s; zero skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k large_eligible -m postgres --require-postgres -x -q -p no:cacheprovider --tb=short
# 2 passed, 23 deselected in 477.99s; zero skips.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected failure: 2 setup errors, TEST_DATABASE_URL required; zero skips.
git diff --check
# Passed; four affected Python AST parses and restored-suite byte comparison passed.
```
Full provider-free failures: unchanged
`test_native_tool_correlation_canonical_result_and_once_only_continuation[rows0-ok]`
times out waiting for Gemini toolResponse; `test_ordinary_suite_ignores_ambient_ingestion_configuration`
runs the suite in a subprocess and encounters that same failure. The independent
Gemini run reproduces it. No failing test or runtime was weakened or changed.
Focused PostgreSQL failure: `test_http_selection_removal_cancels_running_runtime_tool`
times out at `entered.wait(3)` before invoking K02. Both provider variants of
post-commit active-session closure/redaction passed, as did selection revision,
addition/no-op and large-decision persistence/replay/same-job resume.
A broader command with the same isolated URL,
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`,
was interrupted after 498.32s: 19 passed, two unchanged
`test_real_parser_invalid_utf8_persists_protocol_error` timeout failures; it is
not a completed acceptance run. Initial sandboxed unit/database runs encountered
existing socket-based timeout-validator setup errors; the checks above ran with
local socket access. An earlier focused unit checkpoint passed 69 cases before
the final two admission tests were added.
This repair edits only knowledge transport, JSON admission, the restored/separate
unit suites, generated HTTP integration cases, this handoff and the reference map.
All unrelated working-tree edits are retained. Neither provider adapter, OCR
policy/profile semantics, immutable originals, migrations 0001–0005, protected
inputs, shared retrieval, Phase 2 implementation, manifest or Compose changed.
No production UI, executor abstraction, dependency or service was added.
Remaining prerequisites include investigation of the recorded unchanged voice/
parser failures and actual funded provider, Persian speech, browser hardware and
HTTPS deployment acceptance. These tests use generated evidence and mocked
providers and certify none of those external behaviors.
The task-owned `rag-four-findings-test` container used `pgvector/pgvector:pg16`,
loopback port 55439 and the isolated `rag_repairs_test` database. Final inspection
found zero public tables and two disposable schemas left by the interrupted run.
Stopping the `--rm` container removed the database and remaining schemas; no
existing database/container was modified.
## Large JSON responsiveness and completed acceptance repair (2026-10-09)
This record supersedes the incomplete acceptance above for the affected final
code. D07 retains its 60,151,072-byte budget and all supported DTO semantics;
K02, all 55 restored ingestion cases, D04's 422 VALIDATION_ERROR and the separate
HTTP regression suite remain intact.
`receive_json` admits at most two requests before allocating/consuming their
body. It checks actual remaining byte capacity before each chunk, copies at most
64 KiB per iteration and yields even for a stream that never suspends. Bodies
above 64 KiB spill to private temporary files instead of growing an API buffer.
UTF-8 decoding, standard-library json.loads and full DTO validation run in a
short-lived local child process, with a separate GIL. The parent receives only
trusted child-validated field batches (at most 256 KiB each), yielding between
batches, and constructs the already-validated DTO without repeating validation.
Client data never enters a pickle loader; only the application's local child
produces the internal result frames. No provider credentials leave the server.
No external service, dependency, custom JSON parser or executor pool was added.
The 15-second JSON deadline now covers receive, parsing and result reconstruction.
Authentication and CSRF still precede consumption. Capacity exhaustion maps to
429 RATE_LIMITED, a receive/processing timeout to 503 DEPENDENCY_UNAVAILABLE,
and malformed encoding/JSON/DTOs to 422 VALIDATION_ERROR through the existing
correlated error envelope. A cancelled/timed-out caller cancels the independent
owner; admission remains held until pending disk writes finish, any child
(including one still being created) is killed/reaped, and the spool is removed.
At most two capped input spools and two decoder children can coexist. Normalized
D07 DTOs also have a separate two-transaction bound; model serialization stays
with the database work. Caller cancellation cannot recall a committing decision:
its worker retains admission and DTO ownership until actual completion. Replay
with the same decision/key resolves that ambiguous outcome as before.
### Wait investigation and cause evidence
Temporary test-only timestamp/stack diagnostics, outside the repository, observed:
- Fresh Gemini suite: 10 passed; first create_search_tool took 484.81 ms,
subsequent construction 0.12 ms, and the canonical worker completed promptly.
- Isolated PostgreSQL parser/running-tool diagnostic: both parser tests passed,
but the running-tool test failed at entered.wait(3). At 2.5 seconds the API
thread stack was importing langchain_core callbacks/manager/stdout and utility
modules through StructuredTool. First tool construction took 3,366.14 ms;
the test thread's three-second provider-entry wait expired before the framework
coroutine entered the search worker. The worker ran only after the failed
fixture began teardown. This is cold initialization crossing the fixture's
synchronization deadline, not evidence of a blocked embedding provider or
selection transaction. The unit Gemini wait for toolResponse has the same
first-framework-invocation placement; its nested-suite failure simply reran
the failing unit case and was not a separate configuration defect.
- API startup now prepares the existing optional framework through the bounded
blocking pool before reconciliation/readiness, so cold imports precede voice
admission and tool execution. The shared voice unit fixture follows the same
ordering. No wait was lengthened, assertion weakened or test skipped. The
framework remains optional for document-only installations; broken installed
dependencies still fail startup rather than being silently ignored.
- The historical parser failures stalled at connected-state observation (one
case) and the server's shutdown wait (the other). They did not reproduce in
the diagnostic or completed acceptance runs. Their original cause remains
unresolved: the interrupted, concurrently loaded earlier run does not provide
sufficient evidence to classify them as runtime, fixture, leaked work or
environment failures. No parser/transport runtime or assertion was changed.
Passing repetitions do not certify an intermittent parser defect fixed.
### Actual processing measurements and regression mapping
The generated transport tests cover 4,499 and 10,000 unique 500-character IDs
including escaped surrogate pairs, plus a 2,000-character Unicode note. A 10 ms
heartbeat runs across the actual receive/spool/decode/loads/validate/transfer path;
its maximum gap must stay below 100 ms, well below the reproduced old stalls.
No sleeping parser mock is used for this responsiveness assertion.
| Finding/invariant | Exact test source |
| --- | --- |
| Decoder/GIL responsiveness for actual 26.8/59.5 MB valid bodies | `tests/unit/test_json_processing.py::test_real_large_escaped_json_keeps_concurrent_loop_active` (4,499/10,000 IDs) |
| Timeout/cancellation retains admission and spool ownership through actual disk completion | `test_admission_retained_until_cancelled_disk_work_and_spool_release` (cancel/timeout) |
| Cancellation during process creation reaps the eventual real child before release | `test_cancel_during_child_creation_reaps_child_before_releasing_admission` |
| Malformed large JSON, invalid UTF-8, invalid DTO | `test_large_malformed_or_invalid_dto_is_safe` (three cases) |
| Cancelled review transaction retains normalized DTO and admission until completion | `test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes` |
| Cold framework preparation precedes live admission, outside the loop; optional dependency preserved | `tests/unit/test_phase3_acceptance_repairs.py::test_framework_prepared_off_loop_before_reconciliation_and_readiness`, `test_document_only_installation_keeps_framework_optional` |
| First real Gemini tool correlation and canonical result | Both variants of `tests/unit/test_gemini_live.py::test_native_tool_correlation_canonical_result_and_once_only_continuation`; complete ten-case Gemini suite |
| Real provider-entry/revocation synchronization, parser and large-review persistence | Complete `tests/integration/test_realtime_phase3_http.py` (25 cases), including `test_http_selection_removal_cancels_running_runtime_tool`, both `test_real_parser_invalid_utf8_persists_protocol_error` variants and both `test_large_eligible_review_persists_and_replays` variants |
| Prior repairs, streamed oversize/pre-extension rejection, zero unauthenticated/CSRF consumption, receive/retry timeouts | Unchanged cases in `tests/unit/test_phase3_http_repairs.py`; all 55 original `tests/unit/test_phase3_repairs.py` remain byte-identical to 9be4719 |
Observed baseline on this machine using the same actual JSON and ReviewDecision
validator: inline maximum heartbeat gaps 219.08/431.75 ms; a thread still produced
215.07/336.19 ms gaps. This directly supports using a separate GIL rather than
claiming that thread offload proves voice responsiveness. The final focused child
processing run measured 26,784,224 bytes in 1,069.90 ms (103 heartbeat ticks,
maximum gap 14.03 ms) and 59,504,172 bytes in 1,329.13 ms (130 ticks, maximum gap
11.64 ms). These are measured scheduler gaps and end-to-end processing latency,
not an SLA or real speech/hardware certification. Smaller intermediate focused
runs measured gaps of 10.71–13.42 ms; they are not substituted for the final run.
### Exact final commands and outcomes
All pytest commands used the existing Linux environment and local socket access;
there were no real provider calls. Final focused measurements above came from:
```sh
.venv/bin/python -m pytest tests/unit/test_json_processing.py tests/unit/test_phase3_acceptance_repairs.py tests/unit/test_phase3_http_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_gemini_live.py -q -s -p no:cacheprovider --tb=short
# 92 passed in 11.37s; includes all 55 restored ingestion cases and ten Gemini cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# FINAL: 1753 passed, 2 existing Windows-path skips, 397 PostgreSQL cases deselected;
# 161.89s. Includes the nested full-suite ambient-configuration acceptance driver.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# FINAL completed run: 25 passed, zero skips, 369.84s.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected exit 1: two setup errors, TEST_DATABASE_URL required, 0.57s; zero skips.
git diff --check
# Passed. Eight affected Python AST parses and new-file whitespace checks passed.
```
Diagnostic/intermediate commands and outcomes are preserved rather than silently
replaced by final successes:
```sh
PYTHONPATH=/tmp:. .venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Temporary timestamp/stack plugin: 10 passed in 1.82s; 484.81 ms cold construction.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# Without diagnostic wrappers: 10 passed in 1.50s, before the repair.
PYTHONPATH=/tmp:. TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Before framework preparation: 2 passed, 1 failed, 22 deselected in 30.47s;
# 3366.14 ms cold import with live stack evidence; no interruptions/skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# After preparation: 3 passed, 22 deselected, zero skips in 19.04s.
PYTHONPATH=. .venv/bin/python /tmp/phase3-thread-measure.py
# Temporary generated-body comparison: same decision_bytes(4499/10000) fixture,
# actual validate_json(raw, ReviewDecision), inline versus asyncio.to_thread,
# concurrent 10 ms monotonic heartbeat; measurements recorded above.
```
The temporary diagnostic plugin and comparison script live outside the repository.
An initial focused JSON run had 78 passes and one test-harness spawn error:
pytest's automatically generated name for 70,000 invalid bytes made
PYTEST_CURRENT_TEST exceed the OS environment-entry limit. Explicit short
parameter IDs corrected that harness error without changing payloads/assertions.
A 67-case HTTP/Gemini/startup checkpoint passed. Focused checkpoints passed 90 and
91 cases as lifetime and optional-framework regressions were added; complete
provider-free checkpoints passed 1,751 and 1,752 cases before the final 1,753-case
run. An earlier completed affected PostgreSQL run passed all 25 cases in 365.18s
before the final retained-DTO lifetime pass. No acceptance run in this follow-up
was interrupted or counted as success while unfinished.
At task start 238 repository files were hashed. Only seven baseline files changed:
`app/api/v1/dependencies.py`, `app/api/v1/documents.py`, `app/main.py`,
`app/modules/knowledge/langchain_tool.py`, `tests/unit/test_realtime_phase1.py`,
this handoff and the reference map. The other 231 remain byte-identical, including
all 55 restored ingestion regressions, both provider adapters/selection, OCR
profiles and independent factual approval, original/protected inputs, shared
retrieval and applied migrations 0001–0005. Three scoped files were added:
`app/infrastructure/json_processing.py`, `tests/unit/test_json_processing.py` and
`tests/unit/test_phase3_acceptance_repairs.py`. Unrelated prior working-tree edits
were retained. No production UI, dependency, external service, parser replacement
or unrelated refactor was introduced.
The only unresolved historical wait cause is the earlier parser connected-state/
shutdown stall; its origin is not inferred from later green runs. This follow-up
has completed affected acceptance, not real-provider quality certification.
Funded Gemini/OpenAI selected-model acceptance, Persian speech, browser
microphone/playback hardware, actual frontend UI and production HTTPS/proxy
acceptance remain unrun and require their respective credentials, opt-in,
approved corpus/calibration and deployment/hardware prerequisites.
Final database cleanup: `rag-phase3-json-test` was created with
`docker run --rm -d --name rag-phase3-json-test --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=fixture -e POSTGRES_DB=rag_json_test -p 127.0.0.1:55439:5432 pgvector/pgvector:pg16`.
After completed acceptance, SQL inspection found **zero application test schemas**
(excluding the intended test_vector extension namespace) and **zero public tables**.
`docker stop rag-phase3-json-test` removed the container and its tmpfs database.
No existing database/container was modified.
+8
View File
@@ -300,3 +300,11 @@ See [integration validation and operator handoff](ingestion-operator-handoff.md)
for the consolidated command sequence, JSON heartbeat/stage/error reporting, for the consolidated command sequence, JSON heartbeat/stage/error reporting,
end-to-end PostgreSQL acceptance and opt-in app.ingestion_smoke command. end-to-end PostgreSQL acceptance and opt-in app.ingestion_smoke command.
Existing chat remains on Chroma; scoped pgvector search/selection is next. Existing chat remains on Chroma; scoped pgvector search/selection is next.
## OCR supervisor startup setting
Set `INGEST_OCR_REVIEW_REQUIRED=true` (default) or `false` in the API/worker
deployment environment. API enqueue freezes the setting; workers ignore their
current value for existing jobs. Legacy snapshots remain mandatory-review and
retry preserves the same job/profile. Factual/non-OCR review and inactive ready
publication remain required. See [Phase 3 handoff](realtime-agent-phase3-handoff.md).
+30 -10
View File
@@ -1,15 +1,18 @@
# OpenAI Realtime Agent — Fast MVP Implementation Plan # OpenAI Realtime Agent — Fast MVP Implementation Plan
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
provider because an OpenAI Realtime voice key is unavailable.** The validated one backend adapter. Gemini remains the temporary default because an OpenAI
backend Gemini model/voice configuration is shared by reservation, stream and Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers, operator smoke share the selected model/voice/profile. Only the selected voice
frozen profiles, measured calibration and canonical search are unchanged. key is required; there is no fallback or frontend provider selector. Legacy
The provider-independent browser audio/events, direct document/chunk identities PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
and durable owner/replay/revocation rules remain authoritative. Historical aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
OpenAI checkpoints below remain historical. Gemini interruption closes safely embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
where native sample-level context truncation cannot be verified; seamless Pinned reservations cannot switch providers on connection or replay. Gemini
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
## 1. Goal and implementation decisions ## 1. Goal and implementation decisions
@@ -518,3 +521,20 @@ existing 50 ms test remain preserved. Historical results above remain distinct.
Real provider/speech/browser and isolated PostgreSQL acceptance remain unrun, Real provider/speech/browser and isolated PostgreSQL acceptance remain unrun,
subject to authorization/calibrated actor/corpus prerequisites and fail-closed subject to authorization/calibrated actor/corpus prerequisites and fail-closed
calibration/cancellation classification. Scope remains Phase 1. calibration/cancellation classification. Scope remains Phase 1.
## Phase 3 implementation checkpoint (2026-10-09)
The authenticated document/review/retry/selection/read-only configuration surface
and frontend developer handoff are implemented. Existing intake, review/resume,
fenced publication and atomic selection are reused; there is no new migration,
worker replacement, public search/text route, settings editor or production UI.
The two remaining Phase 2 transport findings are repaired. See the
[Phase 3 handoff and validation](../guides/realtime-agent-phase3-handoff.md).
The additional authorized backend OCR supervisor setting defaults to true and is
frozen in new jobs. False admits only clean automatically validated OCR; legacy
profiles, factual authority, non-OCR review, integrity and explicit selection
remain protected. Mixed extraction uses partially_reviewed rather than claiming
human inspection of automatically admitted pages. Provider selection and all
other Phase 2 repairs remain unchanged. Backend contract acceptance does not
certify real-provider/Persian quality, frontend implementation or browser hardware.
@@ -287,3 +287,22 @@ resources. Storage retention/purge remains an owner decision.
Read the implementation guide for work packages, API/database contracts for Read the implementation guide for work packages, API/database contracts for
transport/persistence and the English scenario report for concrete walkthroughs. transport/persistence and the English scenario report for concrete walkthroughs.
The reference map/setup guide remain the evidence of existing component progress. The reference map/setup guide remain the evidence of existing component progress.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
+60 -17
View File
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 API Catalog # RAG Assistant — Phase 1 API Catalog
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
provider because an OpenAI Realtime voice key is unavailable.** The validated one backend adapter. Gemini remains the temporary default because an OpenAI
backend Gemini model/voice configuration is shared by reservation, stream and Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers, operator smoke share the selected model/voice/profile. Only the selected voice
frozen profiles, measured calibration and canonical search are unchanged. key is required; there is no fallback or frontend provider selector. Legacy
The provider-independent browser audio/events, direct document/chunk identities PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
and durable owner/replay/revocation rules remain authoritative. Historical aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
OpenAI checkpoints below remain historical. Gemini interruption closes safely embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
where native sample-level context truncation cannot be verified; seamless Pinned reservations cannot switch providers on connection or replay. Gemini
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational. Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
@@ -93,7 +96,7 @@ No body. Same identity/CSRF/expiry shape as login. Missing/expired session retur
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive. `multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport remains planned. Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport is implemented; see the Phase 3 handoff.
```json ```json
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false} {"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
@@ -111,7 +114,7 @@ Query: common pagination; optional `status=queued|processing|ready|failed`, `is_
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}} {"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
``` ```
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail may include `review_required:false` for other outcomes. D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID. `searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail includes `review_required`, `review_state`, frozen `ocr_review_required` and `extraction_quality_decision` (null before complete extraction). D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
### D04 — Retry failed processing ### D04 — Retry failed processing
@@ -215,7 +218,7 @@ Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected ID
### F01 — Read ### F01 — Read
```json ```json
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}} {"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":20971520,"ocr_review_required":true}}
``` ```
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities. Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
@@ -276,15 +279,15 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost. Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — Gemini Live temporarily; frozen application audio/events ## 7. Voice contract — backend-selected provider; frozen application audio/events
The current provider is Gemini Live managed by the backend. Earlier OpenAI-specific The selected provider is backend-managed Gemini Live or OpenAI Realtime. The
provider mechanisms below describe the retained Realtime adapter; the Gemini OpenAI-specific mechanisms below describe the preserved Realtime adapter; the Gemini
adapter uses native setupComplete, voiceActivity, toolCall/toolResponse and adapter uses native setupComplete, voiceActivity, toolCall/toolResponse and
transcription. Missing verified input boundaries fail safely. Interruption transcription. Missing verified input boundaries fail safely. Interruption
requiring unheard-audio context repair closes the session rather than inventing requiring unheard-audio context repair closes the session rather than inventing
a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono
PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID. PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. Phase 0 freezes the application audio/event fields below. Technical implementation evidence and remaining live acceptance prerequisites are recorded in the Phase 2 repair report. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP) ### V01 — Create session (HTTP)
@@ -557,3 +560,43 @@ safe codes never return keys or native provider errors. HTTP authentication
failures normalize to `AUTH_REQUIRED`, CSRF to `CSRF_INVALID`, hidden resources failures normalize to `AUTH_REQUIRED`, CSRF to `CSRF_INVALID`, hidden resources
to `NOT_FOUND`, admission throttling to `RATE_LIMITED` with Retry-After, and to `NOT_FOUND`, admission throttling to `RATE_LIMITED` with Retry-After, and
unexpected dependency failures to `DEPENDENCY_UNAVAILABLE`. unexpected dependency failures to `DEPENDENCY_UNAVAILABLE`.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
### Phase 3/4 additive admission diagnostics (2026-10-09)
V01, by-request recovery and V03 polling expose calibration_status with values
calibrated, uncalibrated or unknown (legacy reservations without search metadata).
It is derived from the frozen server execution profile, never supplied by clients.
F01 capabilities additionally expose calibration_status and voice_transport_testing.
With explicit server VOICE_TRANSPORT_TESTING=true, missing/pending calibration
permits voice connectivity using configured embedding transport. This does not
change Section 7.2 evidence admission: search returns error/CALIBRATION_REQUIRED
without sources until measured calibration exists. Default false retains strict
admission. Origin/CSRF, ownership, epochs, deduplication and provider pinning remain.
Leading unstyled FAQ introductions appear in factual review and in each included
pair's source context. Recognition warnings or complete=false with legible blocks
produce extraction review candidates, including when frozen ocr_review_required is
false. D06/D07 and same-job D04 approval/retry semantics remain unchanged; no chunks
are published while review is pending. Approval attests to exact output, including
completeness; reject missing/inaccurate content rather than approve guesses. Fatal
format/provenance/readability failures still map to EXTRACTION_QUALITY_FAILED.
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 Database Design # RAG Assistant — Phase 1 Database Design
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
provider because an OpenAI Realtime voice key is unavailable.** The validated one backend adapter. Gemini remains the temporary default because an OpenAI
backend Gemini model/voice configuration is shared by reservation, stream and Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers, operator smoke share the selected model/voice/profile. Only the selected voice
frozen profiles, measured calibration and canonical search are unchanged. key is required; there is no fallback or frontend provider selector. Legacy
The provider-independent browser audio/events, direct document/chunk identities PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
and durable owner/replay/revocation rules remain authoritative. Historical aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
OpenAI checkpoints below remain historical. Gemini interruption closes safely embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
where native sample-level context truncation cannot be verified; seamless Pinned reservations cannot switch providers on connection or replay. Gemini
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations. Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
@@ -385,7 +388,7 @@ Keep source identity rows as tombstones if allowed. `available` in API is comput
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the OpenAI Realtime WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential. UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the OpenAI Realtime WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
API instance owns the direct OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice. The single API process owns the selected direct Gemini Live/OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
### 6.2 audit_events ### 6.2 audit_events
@@ -465,3 +468,22 @@ Text finalization/history/citation tests belong to the later text milestone.
## 10. Deliberately absent from Phase 1 ## 10. Deliberately absent from Phase 1
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements. No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 Implementation Guide # RAG Assistant — Phase 1 Implementation Guide
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
provider because an OpenAI Realtime voice key is unavailable.** The validated one backend adapter. Gemini remains the temporary default because an OpenAI
backend Gemini model/voice configuration is shared by reservation, stream and Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers, operator smoke share the selected model/voice/profile. Only the selected voice
frozen profiles, measured calibration and canonical search are unchanged. key is required; there is no fallback or frontend provider selector. Legacy
The provider-independent browser audio/events, direct document/chunk identities PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
and durable owner/replay/revocation rules remain authoritative. Historical aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
OpenAI checkpoints below remain historical. Gemini interruption closes safely embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
where native sample-level context truncation cannot be verified; seamless Pinned reservations cannot switch providers on connection or replay. Gemini
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md). interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence. Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
@@ -44,7 +47,7 @@ declared format/structure/resource limits must run without developer changes.
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count | | Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state | | QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need | | Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
| Voice | Direct OpenAI Realtime audio over backend WSS; shared LangChain knowledge tool | | Voice | Backend-selected Gemini Live/OpenAI Realtime audio over WSS; shared LangChain knowledge tool |
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics | | Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI | | Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities | | Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
@@ -126,7 +129,7 @@ Resolve `(user_id, organization_id, role)` exclusively from the session. Check o
embedding components. Validate original checksum and actual provider identity. embedding components. Validate original checksum and actual provider identity.
A legacy profile is dispatched explicitly, never silently reinterpreted. A legacy profile is dispatched explicitly, never silently reinterpreted.
6. Retain exact extraction output for review/reuse, then stage every embedding. 6. Retain exact extraction output for review/reuse, then stage every embedding.
The current PageBlockExtractor requires review for PDF pages and vision output; The current PageBlockExtractor requires review for direct PDF pages and, by default, OCR/vision output;
this is an actual implementation gate, not an optional UI decoration. this is an actual implementation gate, not an optional UI decoration.
7. Publish all chunks and ready/succeeded state in one fenced transaction. 7. Publish all chunks and ready/succeeded state in one fenced transaction.
Verify token, unexpired lease, original/profile, non-deletion, complete vectors, Verify token, unexpired lease, original/profile, non-deletion, complete vectors,
@@ -144,7 +147,8 @@ be indexed. Crash recovery must not attach uncommitted or stale candidates.
D06 shows retained candidates to the admin. D07 records approval/rejection of D06 shows retained candidates to the admin. D07 records approval/rejection of
the exact evidence digest and required checks. New OCR output has a different the exact evidence digest and required checks. New OCR output has a different
review identity and requires a new decision. Server validates/recomputes digests; review identity and requires a new decision when the frozen supervisor gate or
independent validation requires review. Server validates/recomputes digests;
client supplied text, paths, profile identity and reviewer identity are forbidden. client supplied text, paths, profile identity and reviewer identity are forbidden.
Use job/document locks and current failed-candidate identity for decisions. Use job/document locks and current failed-candidate identity for decisions.
Decisions neither activate nor mark a document ready. Decisions neither activate nor mark a document ready.
@@ -180,8 +184,9 @@ Factual preparation validates the whole retained source structure before selecti
groups. Explicit heading ancestry associates governing headings and introductory groups. Explicit heading ancestry associates governing headings and introductory
conditions with each descendant Q&A pair; existing whole-group context stays conditions with each descendant Q&A pair; existing whole-group context stays
exclusive to that pair. Preserve conditions, negation, exceptions and their real exclusive to that pair. Preserve conditions, negation, exceptions and their real
locators in every affected draft. Ambiguous unheaded preambles, detached prose or locators in every affected draft. Leading unheaded titles/preambles are top-level
unresolved relationships fail visibly instead of becoming unrestricted answers. document context and accompany each approved pair, including pairs under later
headings. Detached prose after pairs or unresolved relationships still fail visibly.
Factual review exposes that context from the same immutable complete artifact. Factual review exposes that context from the same immutable complete artifact.
Reviewer identity/checks/note are bounded review metadata, not machine quality Reviewer identity/checks/note are bounded review metadata, not machine quality
warnings; administrator prose never changes extraction readability decisions. warnings; administrator prose never changes extraction readability decisions.
@@ -227,7 +232,7 @@ If the browser times out, it queries the turn by client request ID. Retrying the
## 9. Live lifecycle ## 9. Live lifecycle
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct OpenAI Realtime WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake. Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to the pinned Gemini Live/OpenAI Realtime WSS profile, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations. Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
@@ -292,3 +297,45 @@ LangChain, existing embedding reuse and direct OpenAI Realtime are confirmed dir
Exact-output retention/review, FAQ inclusion decisions and their forward schema/ Exact-output retention/review, FAQ inclusion decisions and their forward schema/
HTTP mechanisms in this revision are implementation proposals made concrete for HTTP mechanisms in this revision are implementation proposals made concrete for
review, not already implemented behavior or approval of every fact in a file. review, not already implemented behavior or approval of every fact in a file.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
### Phase 3/4 recognition and transport-testing amendment (2026-10-09)
Vision complete=false and recognition warnings preserve nonempty legible candidate
blocks with their diagnostics. They force exact-output extraction review even when
the job's frozen OCR supervisor policy is false. They are not complete validated
artifacts until genuine review approves completeness and the other required checks.
Malformed/empty/truncated native output, invalid provenance/relationships, unreadable
source text and bounded input/output violations remain fatal. Warning wording alone
is not evidence of corrupt source text. Retained approved candidates resume without
repeating vision; separate factual approval and explicit knowledge selection remain.
VOICE_TRANSPORT_TESTING defaults false. Explicit true permits authenticated voice
transport testing without finalized calibration, after configured embedding adapter
construction validates credentials, identity and request limits without inference.
Uncalibrated reservations pin transport_testing and embedding identity in the existing
execution_profile JSON and expose calibration_status=uncalibrated through create,
recovery and poll. Shared canonical retrieval still returns CALIBRATION_REQUIRED
with no evidence; no arbitrary threshold or synthetic calibration is installed.
Current policy/profile must still match the reservation on stream admission; policy
changes cannot silently upgrade, downgrade or switch a reserved provider. Health
remains provider-free. Real voice/retrieval quality acceptance remains separate.
@@ -160,3 +160,22 @@ Rehearse browser upload -> review if needed -> ready -> activate -> real Persian
voice -> shared retrieval -> spoken answer/sources on target HTTPS/network. voice -> shared retrieval -> spoken answer/sources on target HTTPS/network.
Record actual errors/latency/provider usage and limits, not invented accuracy Record actual errors/latency/provider usage and limits, not invented accuracy
percentages or unexecuted acceptance claims. percentages or unexecuted acceptance claims.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
+41
View File
@@ -0,0 +1,41 @@
/* Use with the existing VoiceClient behind a same-origin /api proxy. */
export class DocumentClient {
constructor(voiceClient) { this.voice = voiceClient; }
async request(path, method = 'GET', body, key) {
const headers = {};
if (method !== 'GET') headers['X-CSRF-Token'] = this.voice.csrf;
if (key) headers['Idempotency-Key'] = key;
const multipart = body instanceof FormData;
if (body !== undefined && !multipart) headers['Content-Type'] = 'application/json';
const response = await fetch('/api/v1' + path, {
method, credentials: 'same-origin', headers,
...(body === undefined ? {} : {body: multipart ? body : JSON.stringify(body)})
});
const result = await response.json();
if (!response.ok) throw Object.assign(new Error(result.error?.code || 'REQUEST_FAILED'), {
status: response.status, requestID: result.error?.request_id, details: result.error?.details
});
return result;
}
upload(file, title, key) {
// Caller retains this key AND the exact file/title until replay is resolved.
const body = new FormData(); body.append('file', file);
if (title !== undefined) body.append('title', title);
return this.request('/documents', 'POST', body, key);
}
list(query = '') { return this.request('/documents' + (query ? '?' + query : '')); }
poll(id) { return this.request('/documents/' + encodeURIComponent(id)); }
review(id, cursor) {
return this.request('/documents/' + encodeURIComponent(id) + '/extraction-review' +
(cursor ? '?cursor=' + encodeURIComponent(cursor) : ''));
}
decide(id, decision, key) {
return this.request('/documents/' + encodeURIComponent(id) + '/extraction-review/decisions', 'POST', decision, key);
}
retry(id, key) { return this.request('/documents/' + encodeURIComponent(id) + '/retry', 'POST', undefined, key); }
selection() { return this.request('/knowledge-selection'); }
replace(revision, ids) {
return this.request('/knowledge-selection', 'PATCH', {expected_revision: revision, document_ids: ids});
}
configuration() { return this.request('/configuration'); }
}
+11
View File
@@ -0,0 +1,11 @@
/* Merge server into the frontend developer's Vite configuration.
* Targets port 8080 (matching Docker Compose host port and direct-run python -m app.server --port 8080).
* changeOrigin: false preserves the browser's Host (localhost:5173) and Origin headers.
* ws: true proxies WebSocket connections for Live voice streams.
*/
export default {
server: {
host: 'localhost', port: 5173, strictPort: true,
proxy: {'/api': {target: 'http://127.0.0.1:8080', ws: true, changeOrigin: false}}
}
};
+23 -10
View File
@@ -1,8 +1,14 @@
/* Application PCM16LE/24kHz contract. The context must actually run at 24kHz. */ /* Application PCM16LE/24kHz contract. The context must actually run at 24kHz. */
class Capture extends AudioWorkletProcessor { class Capture extends AudioWorkletProcessor {
constructor() { constructor() {
super(); this.samples = []; this.active = true; this.pending = 0; super(); this.samples = []; this.active = true; this.pending = 0; this.pendingBytes = 0;
this.port.onmessage = e => { if (e.data.type === 'stop') this.active = false; else if (e.data.type === 'accepted') this.pending = Math.max(0, this.pending - 1); }; this.port.onmessage = e => {
if (e.data.type === 'stop') this.active = false;
else if (e.data.type === 'accepted') {
this.pending = Math.max(0, this.pending - 1);
this.pendingBytes = Math.max(0, this.pendingBytes - (e.data.bytes || 480));
}
};
} }
process(inputs) { process(inputs) {
if (!this.active) return false; if (!this.active) return false;
@@ -12,8 +18,10 @@ class Capture extends AudioWorkletProcessor {
let mono = 0; for (const channel of channels) mono += channel[i] / channels.length; let mono = 0; for (const channel of channels) mono += channel[i] / channels.length;
this.samples.push(Math.max(-32768, Math.min(32767, Math.round(mono * 32768)))); this.samples.push(Math.max(-32768, Math.min(32767, Math.round(mono * 32768))));
if (this.samples.length === 240) { if (this.samples.length === 240) {
if (this.pending >= 100) {this.port.postMessage({type: 'overflow'}); this.active = false; return false;} if (this.pending >= 100 || this.pendingBytes + 480 > 96000) {
this.pending++; this.port.postMessage({type: 'overflow'}); this.active = false; return false;
}
this.pending++; this.pendingBytes += 480;
const bytes = new ArrayBuffer(480), view = new DataView(bytes); const bytes = new ArrayBuffer(480), view = new DataView(bytes);
this.samples.forEach((value, index) => view.setInt16(index * 2, value, true)); this.samples.forEach((value, index) => view.setInt16(index * 2, value, true));
this.samples.length = 0; this.samples.length = 0;
@@ -30,17 +38,19 @@ class Playback extends AudioWorkletProcessor {
if (data.type === 'start') { if (data.type === 'start') {
if (!this.refs.has(data.ref)) this.refs.set(data.ref, {played: 0, sealed: false}); if (!this.refs.has(data.ref)) this.refs.set(data.ref, {played: 0, sealed: false});
} else if (data.type === 'pcm') { } else if (data.type === 'pcm') {
const samples = new Float32Array(data.samples); const length = data.samples.byteLength / 4;
if (!this.refs.has(data.ref) || this.queued + samples.length > 48000) { if (!Number.isInteger(length) || !length || !this.refs.has(data.ref) || this.queue.length >= 100 || this.queued + length > 48000) {
this.port.postMessage({type: 'overflow'}); return; this.port.postMessage({type: 'overflow'}); return;
} }
this.queue.push({ref: data.ref, samples, position: 0}); this.queued += samples.length; const samples = new Float32Array(data.samples);
this.queue.push({ref: data.ref, id: data.packet_id, samples, position: 0}); this.queued += samples.length;
} else if (data.type === 'end') { } else if (data.type === 'end') {
const ref = this.refs.get(data.ref); if (ref) {ref.sealed = true; this.report(data.ref);} const ref = this.refs.get(data.ref); if (ref) {ref.sealed = true; this.report(data.ref);}
} else if (data.type === 'flush') { } else if (data.type === 'flush') {
const released = this.queue.map(part => part.id);
this.queue.length = 0; this.queued = 0; this.queue.length = 0; this.queued = 0;
for (const [ref] of this.refs) this.report(ref); for (const [ref] of this.refs) this.report(ref);
this.refs.clear(); this.port.postMessage({type: 'flushed', id: data.id}); this.refs.clear(); this.port.postMessage({type: 'flushed', id: data.id, released});
} }
}; };
} }
@@ -52,12 +62,15 @@ class Playback extends AudioWorkletProcessor {
process(inputs, outputs) { process(inputs, outputs) {
const output = outputs[0]?.[0]; if (!output) return true; const output = outputs[0]?.[0]; if (!output) return true;
output.fill(0); output.fill(0);
const touched = new Set(); const touched = new Set(), consumed = new Map();
for (let i = 0; i < output.length && this.queue.length; i++) { for (let i = 0; i < output.length && this.queue.length; i++) {
const part = this.queue[0], state = this.refs.get(part.ref); const part = this.queue[0], state = this.refs.get(part.ref);
output[i] = part.samples[part.position++]; this.queued--; state.played++; touched.add(part.ref); output[i] = part.samples[part.position++]; this.queued--; state.played++; touched.add(part.ref);
if (part.position === part.samples.length) this.queue.shift(); const update = consumed.get(part.id) || {type: 'consumed', packet_id: part.id, samples: 0, complete: false};
update.samples = part.position; consumed.set(part.id, update);
if (part.position === part.samples.length) {this.queue.shift(); update.complete = true;}
} }
for (const update of consumed.values()) this.port.postMessage(update);
// Reports count only samples actually consumed by this output process callback. // Reports count only samples actually consumed by this output process callback.
for (const ref of touched) this.report(ref); for (const ref of touched) this.report(ref);
return true; return true;
+85 -13
View File
@@ -34,12 +34,43 @@ export class VoiceClient {
const identity = await this.request('/me'); const identity = await this.request('/me');
this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity; this.csrf = identity.csrf_token; this.expiresAt = identity.expires_at; return identity;
} }
async reserve(conversationRequestID = crypto.randomUUID(), sessionRequestID = crypto.randomUUID()) { newCreationAttempt(conversationRequestID = crypto.randomUUID(), sessionRequestID = crypto.randomUUID()) {
await this.refreshIdentity(); if (this.connection) throw new Error('Close media before a fresh creation attempt');
this.conversation = await this.request('/conversations', 'POST', {client_request_id: conversationRequestID, mode: 'voice'}); const conversationPayload = Object.freeze({client_request_id: conversationRequestID, mode: 'voice'});
this.requestID = sessionRequestID; this.creationAttempt = {conversationRequestID, sessionRequestID, conversationPayload, sessionPayload: null};
this.session = await this.request('/voice/sessions', 'POST', {conversation_id: this.conversation.id, client_request_id: sessionRequestID}); Object.defineProperties(this.creationAttempt, {
return this.session; conversationRequestID: {writable: false, configurable: false}, sessionRequestID: {writable: false, configurable: false}, conversationPayload: {writable: false, configurable: false}
});
this.conversationRequestID = conversationRequestID; this.requestID = sessionRequestID;
this.conversation = this.session = null;
return this.creationAttempt;
}
async reserve(conversationRequestID, sessionRequestID) {
if (!this.creationAttempt) this.newCreationAttempt(conversationRequestID, sessionRequestID);
else if ((conversationRequestID && conversationRequestID !== this.creationAttempt.conversationRequestID)
|| (sessionRequestID && sessionRequestID !== this.creationAttempt.sessionRequestID)) {
throw new Error('Use newCreationAttempt for different request IDs');
}
return this.retryCreation();
}
async retryCreation() {
const attempt = this.creationAttempt;
if (!attempt) throw new Error('No creation attempt to retry');
if (attempt.pending) return attempt.pending;
attempt.pending = (async () => {
await this.refreshIdentity();
const conversation = await this.request('/conversations', 'POST', attempt.conversationPayload);
if (this.creationAttempt !== attempt) throw new Error('CREATION_CANCELLED');
if (!attempt.sessionPayload) Object.defineProperty(attempt, 'sessionPayload', {
value: Object.freeze({conversation_id: conversation.id, client_request_id: attempt.sessionRequestID}), writable: false, configurable: false
});
if (attempt.sessionPayload.conversation_id !== conversation.id) throw new Error('IDEMPOTENCY_CONFLICT');
this.conversation = conversation;
const session = await this.request('/voice/sessions', 'POST', attempt.sessionPayload);
if (this.creationAttempt !== attempt) throw new Error('CREATION_CANCELLED');
this.session = session; return session;
})().finally(() => {attempt.pending = null;});
return attempt.pending;
} }
async recover(requestID = this.requestID) {return this.request('/voice/sessions/by-request/' + requestID);} async recover(requestID = this.requestID) {return this.request('/voice/sessions/by-request/' + requestID);}
async poll() {return this.request('/voice/sessions/' + this.session.session_id);} async poll() {return this.request('/voice/sessions/' + this.session.session_id);}
@@ -56,7 +87,11 @@ export class VoiceClient {
c.playback = new AudioWorkletNode(c.context, 'rag-playback', {outputChannelCount: [1]}); c.playback = new AudioWorkletNode(c.context, 'rag-playback', {outputChannelCount: [1]});
c.playback.port.onmessage = ({data}) => { c.playback.port.onmessage = ({data}) => {
if (data.type === 'progress') this.progress(data.ref, data.played_ms, c); if (data.type === 'progress') this.progress(data.ref, data.played_ms, c);
else if (data.type === 'flushed') {c.pendingFlush.get(data.id)?.(); c.pendingFlush.delete(data.id);} else if (data.type === 'consumed') this.releasePlayback(c, data.packet_id, data.samples * 2, data.complete);
else if (data.type === 'flushed') {
for (const id of data.released || []) this.releasePlayback(c, id, Infinity, true);
c.pendingFlush.get(data.id)?.(); c.pendingFlush.delete(data.id);
}
else if (data.type === 'overflow' && this.eligible(c)) void this.cleanup(c); else if (data.type === 'overflow' && this.eligible(c)) void this.cleanup(c);
}; };
c.playback.connect(c.context.destination); await c.context.resume(); c.playback.connect(c.context.destination); await c.context.resume();
@@ -64,7 +99,7 @@ export class VoiceClient {
} }
async connect() { async connect() {
if (!this.session?.stream_path || this.connection) throw new Error('Fresh eligible reservation required'); if (!this.session?.stream_path || this.connection) throw new Error('Fresh eligible reservation required');
const c = {generation: ++this.generation, session: this.session, pendingFlush: new Map(), ready: false, stopping: false}; const c = {generation: ++this.generation, session: this.session, pendingFlush: new Map(), playbackPackets: new Map(), playbackBytes: 0, capturePackets: [], captureBytes: 0, drainTimer: null, ready: false, stopping: false};
this.connection = c; this.stopping = false; this.connection = c; this.stopping = false;
try { try {
await this.prepareAudio(c); await this.prepareAudio(c);
@@ -85,9 +120,12 @@ export class VoiceClient {
try { try {
if (typeof data !== 'string') { if (typeof data !== 'string') {
if (!c.ready || !c.audioRef || data.byteLength > 9600 || data.byteLength % 2) throw new Error('LIVE_PROTOCOL_ERROR'); if (!c.ready || !c.audioRef || data.byteLength > 9600 || data.byteLength % 2) throw new Error('LIVE_PROTOCOL_ERROR');
if (!data.byteLength || c.playbackPackets.size >= 100 || c.playbackBytes + data.byteLength > 96000) throw new Error('LIVE_BUFFER_OVERFLOW');
const packetID = crypto.randomUUID();
c.playbackPackets.set(packetID, {bytes: data.byteLength, consumed: 0}); c.playbackBytes += data.byteLength;
const view = new DataView(data), samples = new Float32Array(data.byteLength / 2); const view = new DataView(data), samples = new Float32Array(data.byteLength / 2);
for (let i = 0; i < samples.length; i++) samples[i] = view.getInt16(i * 2, true) / 32768; for (let i = 0; i < samples.length; i++) samples[i] = view.getInt16(i * 2, true) / 32768;
c.playback.port.postMessage({type: 'pcm', ref: c.audioRef, samples: samples.buffer}, [samples.buffer]); return; c.playback.port.postMessage({type: 'pcm', packet_id: packetID, ref: c.audioRef, samples: samples.buffer}, [samples.buffer]); return;
} }
const event = JSON.parse(data); const event = JSON.parse(data);
if (event.type === 'session_ready') { if (event.type === 'session_ready') {
@@ -111,20 +149,50 @@ export class VoiceClient {
const media = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1, echoCancellation: true}, video: false}); const media = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1, echoCancellation: true}, video: false});
if (!this.eligible(c)) {media.getTracks().forEach(track => track.stop()); throw new Error('CONNECTION_CANCELLED');} if (!this.eligible(c)) {media.getTracks().forEach(track => track.stop()); throw new Error('CONNECTION_CANCELLED');}
c.media = media; c.capture = new AudioWorkletNode(c.context, 'rag-capture'); c.media = media; c.capture = new AudioWorkletNode(c.context, 'rag-capture');
const drainCapture = () => {
if (!this.eligible(c) || !c.socket) {
if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; }
return;
}
const buffered = c.socket.bufferedAmount || 0;
let drained = Math.max(0, c.captureBytes - buffered);
while (c.capturePackets.length && drained >= c.capturePackets[0]) {
const packetBytes = c.capturePackets.shift();
c.captureBytes -= packetBytes;
drained -= packetBytes;
c.capture?.port.postMessage({type: 'accepted', bytes: packetBytes});
}
if (!c.capturePackets.length) {
c.captureBytes = 0;
if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; }
}
};
c.capture.port.onmessage = ({data}) => { c.capture.port.onmessage = ({data}) => {
if (!this.eligible(c)) return; if (!this.eligible(c)) return;
if (data.type === 'overflow') {void this.cleanup(c); return;} if (data.type === 'overflow') {void this.cleanup(c); return;}
if (data.type !== 'pcm') return; if (data.type !== 'pcm') return;
c.capture.port.postMessage({type: 'accepted'}); drainCapture();
if (!c.ready) return; if (!c.ready) return;
if (c.socket.readyState !== WebSocket.OPEN || c.socket.bufferedAmount + data.bytes.byteLength > 96000) {void this.cleanup(c); return;} const len = data.bytes.byteLength;
if (c.socket.readyState !== WebSocket.OPEN || c.capturePackets.length >= 100 || c.captureBytes + len > 96000) {
void this.cleanup(c); return;
}
c.capturePackets.push(len); c.captureBytes += len;
c.socket.send(data.bytes); c.socket.send(data.bytes);
if (!c.drainTimer) c.drainTimer = setInterval(drainCapture, 10);
}; };
c.input = c.context.createMediaStreamSource(media); c.input.connect(c.capture); c.input = c.context.createMediaStreamSource(media); c.input.connect(c.capture);
c.mute = c.context.createGain(); c.mute.gain.value = 0; c.mute = c.context.createGain(); c.mute.gain.value = 0;
c.capture.connect(c.mute); c.mute.connect(c.context.destination); c.capture.connect(c.mute); c.mute.connect(c.context.destination);
} catch (error) {await this.cleanup(c); throw error;} } catch (error) {await this.cleanup(c); throw error;}
} }
releasePlayback(c, id, bytes, complete) {
const packet = c.playbackPackets.get(id);
if (!packet) return; // Late/duplicate completion cannot release twice.
const consumed = Math.max(packet.consumed, Math.min(packet.bytes, bytes));
c.playbackBytes -= consumed - packet.consumed; packet.consumed = consumed;
if (complete) {c.playbackBytes -= packet.bytes - consumed; c.playbackPackets.delete(id);}
}
async flush(c = this.connection) { async flush(c = this.connection) {
if (!c?.playback || c.context?.state === 'closed') return; if (!c?.playback || c.context?.state === 'closed') return;
const id = crypto.randomUUID(); const id = crypto.randomUUID();
@@ -141,6 +209,7 @@ export class VoiceClient {
if (this.connection === c) {this.stopping = true; this.ready = false; ++this.generation;} if (this.connection === c) {this.stopping = true; this.ready = false; ++this.generation;}
c.cleaning = (async () => { c.cleaning = (async () => {
try { try {
if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; }
c.capture?.port.postMessage({type: 'stop'}); c.capture?.port.postMessage({type: 'stop'});
c.media?.getTracks().forEach(track => track.stop()); c.media?.getTracks().forEach(track => track.stop());
c.input?.disconnect(); c.capture?.disconnect(); c.mute?.disconnect(); c.input?.disconnect(); c.capture?.disconnect(); c.mute?.disconnect();
@@ -149,6 +218,9 @@ export class VoiceClient {
} finally { } finally {
try {c.playback?.disconnect(); if (c.context && c.context.state !== 'closed') await closeContext(c.context);} try {c.playback?.disconnect(); if (c.context && c.context.state !== 'closed') await closeContext(c.context);}
finally { finally {
if (c.drainTimer) { clearInterval(c.drainTimer); c.drainTimer = null; }
c.capturePackets = []; c.captureBytes = 0;
c.playbackPackets.clear(); c.playbackBytes = 0;
c.socket?.close(); c.socket?.close();
if (this.connection === c) {this.connection = null; this.socket = null;} if (this.connection === c) {this.connection = null; this.socket = null;}
} }
@@ -174,11 +246,11 @@ export class VoiceClient {
try { try {
try {await this.close();} catch (_) { /* Logout remains independently required. */ } try {await this.close();} catch (_) { /* Logout remains independently required. */ }
return await this.request('/auth/logout', 'POST'); return await this.request('/auth/logout', 'POST');
} finally {await this.cleanup(); this.csrf = this.expiresAt = this.session = this.conversation = this.requestID = null;} } finally {await this.cleanup(); this.csrf = this.expiresAt = this.session = this.conversation = this.requestID = this.conversationRequestID = this.creationAttempt = null;}
} }
async freshSession() { async freshSession() {
await this.close(); const recovered = await this.recover(); await this.close(); const recovered = await this.recover();
if (!['closed', 'failed'].includes(recovered.status)) throw new Error('OLD_SESSION_NOT_TERMINAL'); if (!['closed', 'failed'].includes(recovered.status)) throw new Error('OLD_SESSION_NOT_TERMINAL');
await this.reserve(); return this.connect(); this.newCreationAttempt(); await this.reserve(); return this.connect();
} }
} }
+1 -1
View File
@@ -14,7 +14,7 @@ dependencies = [
] ]
[project.optional-dependencies] [project.optional-dependencies]
api = ["fastapi>=0.115,<1", "uvicorn>=0.34,<1", "httpx>=0.27,<1"] api = ["fastapi>=0.115,<1", "uvicorn>=0.34,<1", "httpx>=0.27,<1", "python-multipart>=0.0.20,<0.1"]
search = ["langchain-core>=1,<2"] search = ["langchain-core>=1,<2"]
voice = ["langchain-core>=1,<2", "websockets>=15,<18"] voice = ["langchain-core>=1,<2", "websockets>=15,<18"]
embedding = ["tiktoken>=0.8,<1"] embedding = ["tiktoken>=0.8,<1"]
@@ -0,0 +1,140 @@
"""Real isolated database and ASGI evidence; synthetic providers only."""
import json
from uuid import UUID, uuid4
import pytest
from sqlalchemy import text
from app.api.v1 import dependencies, live
from tests.integration.test_phase2_postgres import seeded_env, api, login
from tests.integration.test_realtime_phase3_http import document_api, upload, process, polling
from tests.support.extraction import FakeVision
from tests.support.formats import image_bytes
from tests.unit.test_realtime_phase1 import until
@pytest.mark.parametrize('diagnostic', ['Uncertain order', 'unreadable margin'])
def test_warning_candidate_requires_decision_then_resumes_without_provider_repeat(document_api, diagnostic):
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required':False,'vision_provider':'gemini',
'vision_endpoint':'https://test.invalid','vision_model':'fixture-flash'})
uploaded = upload(client, headers, image_bytes('PNG'), 'warning.png').json()
identifier = uploaded['document_id']; vision = FakeVision(warnings=(diagnostic,))
process(e, vision)
detail = polling(client, identifier)
assert detail['review_required'] and detail['review_state'] == 'pending'
assert not detail['searchable'] and not detail['job']['can_retry']
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'),{'id':UUID(identifier)}).scalar_one() == 0
item, = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve',checked=item['required_checks'],note='Synthetic complete source inspection')
endpoint = f'/api/v1/documents/{identifier}/extraction-review/decisions'; key = str(uuid4())
assert client.post(endpoint,json=decision,headers=dict(headers,**{'Idempotency-Key':key})).status_code == 200
assert client.post(endpoint,json=decision,headers=dict(headers,**{'Idempotency-Key':key})).headers['Idempotency-Replayed'] == 'true'
retry = client.post(f'/api/v1/documents/{identifier}/retry',headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
assert retry.status_code == 202 and retry.json()['job_id'] == uploaded['job_id']
process(e, vision)
assert len(vision.calls) == 1
detail = polling(client,identifier)
assert detail['status'] == 'ready' and detail['extraction_quality_decision'] == 'reviewed'
assert not detail['is_active'] and not detail['searchable']
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
def test_uncalibrated_transport_reservation_replay_stream_and_shared_search_error(api,monkeypatch,tmp_path):
client, wire, runner, e = api
e.search.cutoff = None
report = tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
config = e.voice_config.model_copy(update={'voice_transport_testing':True,'search_calibration_report':report})
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
monkeypatch.setattr(live,'capability',_real_capability)
monkeypatch.setattr(live,'IngestionSettings',lambda:e.settings)
monkeypatch.setattr(live,'get_search_service',lambda engine:e.search)
headers=login(client,e)
conversation=client.post('/api/v1/conversations',json={'mode':'voice','client_request_id':str(uuid4())},headers=headers).json()
body={'conversation_id':conversation['id'],'client_request_id':str(uuid4())}
response=client.post('/api/v1/voice/sessions',json=body,headers=headers)
assert response.status_code == 201, response.text
result=response.json(); sid=UUID(result['session_id'])
assert result['calibration_status'] == 'uncalibrated'
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
assert replay.json()['session_id']==result['session_id'] and replay.headers['Idempotency-Replayed']=='true'
assert replay.json()['calibration_status']=='uncalibrated'
assert client.get(result['poll_url']).json()['calibration_status']=='uncalibrated'
disabled=config.model_copy(update={'voice_transport_testing':False})
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:disabled
# Creation replay precedes capability/embedding construction despite policy changes.
assert client.post('/api/v1/voice/sessions',json=body,headers=headers).json()['session_id']==result['session_id']
from starlette.websockets import WebSocketDisconnect
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}): pass
assert e.connections==[]
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
# Policy cannot silently relabel an existing uncalibrated reservation.
with e.engine.connect() as conn:
profile=conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()
assert profile['search']['mode']=='transport_testing' and 'distance' not in profile['search']
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
from app.infrastructure.realtime import RealtimeAdapter
ack={'setupComplete':{}} if config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire).setup()['session']}
client.portal.call(wire.inbound.put,ack)
assert ws.receive_json()['type']=='session_ready'
assert len(e.connections)==1
ws.send_bytes(bytes(4800))
client.portal.call(until,lambda: any('realtimeInput' in m or m.get('type')=='input_audio_buffer.append' for m in wire.sent))
from app.modules.knowledge.evidence import SearchExecution
result=e.search.search(SearchExecution(e.actor),'source query')
assert result['status']=='error' and result['sources']==[] and result['error']['code']=='CALIBRATION_REQUIRED'
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config.model_copy(update={'voice_transport_testing':False})
new=client.post('/api/v1/conversations',json={'mode':'voice','client_request_id':str(uuid4())},headers=headers).json()
rejected=client.post('/api/v1/voice/sessions',json={'conversation_id':new['id'],'client_request_id':str(uuid4())},headers=headers)
assert rejected.status_code==503 and rejected.json()['error']['code']=='CALIBRATION_REQUIRED'
assert len(e.connections)==1
_real_capability=live.capability
@pytest.mark.parametrize('kind',['text','docx'])
def test_initial_faq_context_reaches_independent_review_and_atomic_publication(document_api,kind):
client,_,_,e=document_api; headers=login(client,e)
paragraphs=['Benefits title','Only permanent employees.','Question: rate?','Answer: 5%.','Question: leave?','Answer: 10 days.']
content=('\n'.join(paragraphs)+'\n').encode(); filename='faq.md'
if kind=='docx':
from tests.support.formats import docx_bytes
xml='<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'
xml+=''.join('<w:p><w:r><w:t>'+p+'</w:t></w:r></w:p>' for p in paragraphs)
content=docx_bytes(document=(xml+'</w:body></w:document>').encode()); filename='faq.docx'
uploaded=upload(client,headers,content,filename).json(); identifier=uploaded['document_id']
process(e)
detail=polling(client,identifier)
assert detail['review_required'] and detail['review_state']=='pending'
item,=client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
assert item['review_kind']=='factual_corpus'
assert 'Benefits title' in ''.join(b['text'] for b in item['blocks'])
assert len([b for b in item['blocks'] if b.get('group_id') and 'Question:' in b['text']])==2
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'),{'id':UUID(identifier)}).scalar_one()==0
decision=dict(evidence_sha256=item['evidence_sha256'],decision='approve',checked=item['required_checks'],note='Synthetic factual authority check',excluded_group_ids=[])
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions',json=decision,
headers=dict(headers,**{'Idempotency-Key':str(uuid4())})).status_code==200
retry=client.post(f'/api/v1/documents/{identifier}/retry',headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
assert retry.status_code==202 and retry.json()['job_id']==uploaded['job_id']
process(e)
with e.engine.connect() as conn:
chunks=conn.execute(text('SELECT text FROM document_chunks WHERE document_id=:id ORDER BY ordinal'),{'id':UUID(identifier)}).scalars().all()
assert len(chunks)==2 and all('Benefits title' in c and 'Only permanent employees.' in c for c in chunks)
assert polling(client,identifier)['status']=='ready' and not polling(client,identifier)['searchable']
def test_configuration_reports_testing_availability_without_claiming_calibration(document_api,tmp_path):
from pydantic import SecretStr
client,_,_,e=document_api; login(client,e)
e.settings=e.settings.model_copy(update={'embedding_api_key':SecretStr('fixture-only')})
report=tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
config=e.voice_config.model_copy(update={'voice_transport_testing':True,'search_calibration_report':report})
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
response=client.get('/api/v1/configuration')
assert response.status_code==200
capabilities=response.json()['capabilities']
assert capabilities['voice'] and capabilities['voice_transport_testing']
assert capabilities['calibration_status']=='uncalibrated'
assert 'fixture-only' not in response.text and str(report) not in response.text
# A malformed embedding request policy still prevents configured availability.
e.settings=e.settings.model_copy(update={'embedding_limits':None})
assert not client.get('/api/v1/configuration').json()['capabilities']['voice']
+136 -13
View File
@@ -172,7 +172,7 @@ def test_cross_organization_provisioning_preserves_account(seeded_env):
assert conn.execute(text('SELECT password_hash,role,is_enabled FROM users WHERE id=:id'),{'id':e.actor}).one()==before assert conn.execute(text('SELECT password_hash,role,is_enabled FROM users WHERE id=:id'),{'id':e.actor}).one()==before
@pytest.fixture @pytest.fixture
def api(seeded_env,monkeypatch): def api(seeded_env,monkeypatch,request):
from app.main import app from app.main import app
from app.api.v1 import dependencies as d from app.api.v1 import dependencies as d
from app.api.v1 import live from app.api.v1 import live
@@ -180,7 +180,8 @@ def api(seeded_env,monkeypatch):
e=seeded_env;settings=e.settings e=seeded_env;settings=e.settings
from app.api.v1.auth import _ATTEMPTS, _LOCK from app.api.v1.auth import _ATTEMPTS, _LOCK
with _LOCK: _ATTEMPTS.clear() with _LOCK: _ATTEMPTS.clear()
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False) provider=getattr(request,'param','gemini')
config=VoiceSettings(_env_file=None,provider=provider,gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
cutoff=CalibratedCutoff(asdict(settings.embedding_profile),2,'deterministic-fixture-only') cutoff=CalibratedCutoff(asdict(settings.embedding_profile),2,'deterministic-fixture-only')
search=SearchService(e.engine,settings,DeterministicEmbeddings(settings),cutoff=cutoff) search=SearchService(e.engine,settings,DeterministicEmbeddings(settings),cutoff=cutoff)
e.search = search e.search = search
@@ -191,7 +192,7 @@ def api(seeded_env,monkeypatch):
async def connect(*args): async def connect(*args):
e.connections.append(1) e.connections.append(1)
return wire return wire
monkeypatch.setattr(live,'connect_gemini',connect) monkeypatch.setattr('app.infrastructure.voice_provider.connect_'+provider,connect)
monkeypatch.setattr(live,'capability',lambda config:cutoff) monkeypatch.setattr(live,'capability',lambda config:cutoff)
monkeypatch.setattr('app.main.config',config) monkeypatch.setattr('app.main.config',config)
app.dependency_overrides[d.get_engine]=lambda:e.engine app.dependency_overrides[d.get_engine]=lambda:e.engine
@@ -282,6 +283,7 @@ def test_actual_asgi_gemini_ready_and_blocked_browser_cleanup(api,ending):
saved=conn.execute(text('SELECT status,connected_at FROM live_sessions WHERE id=:id'),{'id':sid}).one() saved=conn.execute(text('SELECT status,connected_at FROM live_sessions WHERE id=:id'),{'id':sid}).one()
assert saved[0] in ('closed','failed') and saved[1] is not None assert saved[0] in ('closed','failed') and saved[1] is not None
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
@pytest.mark.parametrize('outcome',['ok','no_evidence','error']) @pytest.mark.parametrize('outcome',['ok','no_evidence','error'])
def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome): def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
from tests.unit.test_realtime_phase1 import until from tests.unit.test_realtime_phase1 import until
@@ -297,28 +299,52 @@ def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
def fail(*args,**kwargs):raise EmbeddingProviderError('fake remote unavailable',retryable=True) def fail(*args,**kwargs):raise EmbeddingProviderError('fake remote unavailable',retryable=True)
e.search.provider.embed=fail e.search.provider.embed=fail
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws: with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
client.portal.call(wire.inbound.put,{'setupComplete':{}}) from app.infrastructure.realtime import RealtimeAdapter
from tests.unit.test_realtime_phase1 import call as native_call,terminal,message
ack={'setupComplete':{}} if e.voice_config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire).setup()['session']}
client.portal.call(wire.inbound.put,ack)
assert ws.receive_json()['type']=='session_ready' assert ws.receive_json()['type']=='session_ready'
ws.send_bytes(bytes(4800));ws.send_bytes(bytes(4800)) ws.send_bytes(bytes(4800));ws.send_bytes(bytes(4800))
client.portal.call(until,lambda:len([m for m in wire.sent if 'realtimeInput' in m])==2) if e.voice_config.provider=='gemini':
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}}) client.portal.call(until,lambda:len([m for m in wire.sent if 'realtimeInput' in m])==2)
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}}) client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':query}} client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[fn]}}) fn={'id':'private-google-call','name':'search_knowledge','args':{'query':query}}
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[fn]}})
else:
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='input_audio_buffer.append'])==2)
for event in [dict(type='input_audio_buffer.speech_started',item_id='u1',audio_start_ms=0),
dict(type='input_audio_buffer.speech_stopped',item_id='u1',audio_end_ms=100),
dict(type='input_audio_buffer.committed',item_id='u1')]:client.portal.call(wire.inbound.put,event)
client.portal.call(until,lambda:any(m.get('type')=='response.create' for m in wire.sent))
intent=next(m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create')
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id='r1',metadata=intent)))
tool=native_call(call_id='private-google-call',query=query)
client.portal.call(wire.inbound.put,tool)
client.portal.call(wire.inbound.put,terminal(output=[dict(type='function_call',id=tool['item_id'],call_id=tool['call_id'],name=tool['name'],arguments=tool['arguments'])]))
events=[] events=[]
while True: while True:
event=ws.receive_json();events.append(event) event=ws.receive_json();events.append(event)
if event['type']=='sources':break if event['type']=='sources':break
client.portal.call(until,lambda:any('toolResponse' in m for m in wire.sent)) client.portal.call(until,lambda:any('toolResponse' in m or (m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output') for m in wire.sent))
with e.engine.connect() as conn: with e.engine.connect() as conn:
call=conn.execute(text('SELECT * FROM tool_calls WHERE live_session_id=:id'),{'id':sid}).mappings().one() call=conn.execute(text('SELECT * FROM tool_calls WHERE live_session_id=:id'),{'id':sid}).mappings().one()
assert call['arguments']['query']==query assert call['arguments']['query']==query
assert call['result_json']['status']==outcome assert call['result_json']['status']==outcome
assert call['knowledge_revision']==2 and call['access_epoch']==1 assert call['knowledge_revision']==2 and call['access_epoch']==1
assert str(call['public_ref'])==events[-1]['tool_call_id']!='private-google-call' assert str(call['public_ref'])==events[-1]['tool_call_id']!='private-google-call'
answer=next(m['toolResponse']['functionResponses'][0] for m in wire.sent if 'toolResponse' in m) if e.voice_config.provider=='gemini':
assert answer['id']=='private-google-call' and answer['response']==call['result_json'] answer=next(m['toolResponse']['functionResponses'][0] for m in wire.sent if 'toolResponse' in m)
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}}) assert answer['id']=='private-google-call' and answer['response']==call['result_json']
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
else:
answer=next(m['item'] for m in wire.sent if m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output')
assert answer['call_id']=='private-google-call' and json.loads(answer['output'])==call['result_json']
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='response.create'])==2)
intent=[m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create'][-1]
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id='r2',metadata=intent)))
client.portal.call(wire.inbound.put,dict(type='response.output_audio_transcript.done',response_id='r2',item_id='a_r2',output_index=0,content_index=0,transcript='fixture answer'))
client.portal.call(wire.inbound.put,terminal('r2',output=[message('r2')]))
while True: while True:
event=ws.receive_json() event=ws.receive_json()
if event.get('role')=='assistant' and event['status']=='completed':break if event.get('role')=='assistant' and event['status']=='completed':break
@@ -589,3 +615,100 @@ def test_real_database_dispatch_failure_is_durably_technical_not_revocation(api,
row=e.lifecycle.get_live_session(e.user,sid) row=e.lifecycle.get_live_session(e.user,sid)
assert row['status']=='failed' and row['error_code']=='DEPENDENCY_UNAVAILABLE' assert row['status']=='failed' and row['error_code']=='DEPENDENCY_UNAVAILABLE'
assert not any('toolResponse' in m for m in wire.sent) assert not any('toolResponse' in m for m in wire.sent)
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
def test_selected_provider_reservation_ready_audio_and_pinned_replay(api,monkeypatch):
from app.infrastructure.realtime import RealtimeAdapter
from app.api.v1 import dependencies
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
from tests.unit.test_realtime_phase1 import until
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
with e.engine.connect() as conn:
row=conn.execute(text('SELECT provider,model,execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).mappings().one()
assert row['provider']==e.voice_config.provider and row['model']==e.voice_config.selected_model
assert all(row['execution_profile'][k]==v for k,v in e.voice_config.profile().items())
assert 'fake-only' not in json.dumps(dict(row)) and 'api_key' not in json.dumps(result)
# Replay still returns the pinned reservation after backend configuration changes.
other=VoiceSettings(_env_file=None,provider='openai' if e.voice_config.provider=='gemini' else 'gemini',gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:other
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
assert replay.status_code==202 and replay.json()['session_id']==result['session_id']
from starlette.websockets import WebSocketDisconnect
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}):pass
assert not e.connections
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:e.voice_config
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
ack={'setupComplete':{}} if e.voice_config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire,model=e.voice_config.selected_model,voice=e.voice_config.selected_voice).setup()['session']}
client.portal.call(wire.inbound.put,ack)
assert ws.receive_json()['type']=='session_ready'
client.portal.call(until,lambda:bool(wire.sent))
ws.send_bytes(bytes(4800))
if e.voice_config.provider=='gemini':
client.portal.call(until,lambda:any('realtimeInput' in m for m in wire.sent))
native=next(m['realtimeInput']['audio']['data'] for m in wire.sent if 'realtimeInput' in m and 'audio' in m['realtimeInput'])
assert len(base64.b64decode(native))==3200
else:
client.portal.call(until,lambda:any(m.get('type')=='input_audio_buffer.append' for m in wire.sent))
native=next(m['audio'] for m in wire.sent if m.get('type')=='input_audio_buffer.append')
assert len(base64.b64decode(native))==4800
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
try:
while True:ws.receive_json()
except WebSocketDisconnect:pass
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
assert wire.closed==1 and len(e.connections)==1
with e.engine.connect() as conn:
saved=conn.execute(text('SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id'),{'id':sid}).one()
assert saved==('closed','user_requested',None)
@pytest.mark.parametrize('failure,code',[('saturation','SEARCH_SATURATED'),('timeout','SEARCH_TIMEOUT'),('sql','DEPENDENCY_UNAVAILABLE'),('revocation','CONTEXT_REVOKED')])
def test_authority_monitor_failure_classification_real_terminal_state(api,monkeypatch,failure,code):
from threading import Event
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
from app.infrastructure.blocking import blocking
from tests.unit.test_realtime_phase1 import until
from starlette.websockets import WebSocketDisconnect
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
released=Event();workers=[]
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
client.portal.call(wire.inbound.put,{'setupComplete':{}})
assert ws.receive_json()['type']=='session_ready'
with e.engine.connect() as conn: pass
def connected():
with e.engine.connect() as conn:return conn.execute(text('SELECT status FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()=='connected'
client.portal.call(until,connected)
if failure=='saturation':
entered=[Event() for _ in range(8)]
def occupy(event):event.set();released.wait(5)
async def saturate():
tasks=[asyncio.create_task(blocking(occupy,event)) for event in entered]
await until(lambda:all(event.is_set() for event in entered));return tasks
workers=client.portal.call(saturate)
elif failure=='revocation':
# Change real authority without a registry notification: the monitor must verify it.
with e.engine.begin() as conn:
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:org'),{'org':e.org})
else:
original=e.lifecycle.validate_stream
def check(*args,**kwargs):
if failure=='timeout':raise TimeoutError('private timeout')
if failure=='sql':
with e.engine.connect() as conn:conn.execute(text('SELECT * FROM intentionally_missing_authority_relation'))
return original(*args,**kwargs)
monkeypatch.setattr(e.lifecycle,'validate_stream',check)
try:
event=ws.receive_json();assert event['type']=='error' and event['error']['code']==code
assert 'private' not in json.dumps(event)
finally:released.set()
try:
while True:ws.receive_json()
except WebSocketDisconnect:pass
async def complete():
await asyncio.gather(*workers,return_exceptions=True)
await until(lambda:sid not in ACTIVE_MEDIA_SESSIONS)
client.portal.call(complete)
with e.engine.connect() as conn:
saved=conn.execute(text('SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id'),{'id':sid}).one()
assert saved==('closed' if failure=='revocation' else 'failed',code,None if failure=='revocation' else code)
assert wire.closed==1
+3 -3
View File
@@ -1210,12 +1210,12 @@ def test_negated_unreadability_notes_resume_approved_ocr_without_repeating_it(wo
assert (work["candidates"].directory / pointer["key"]).read_bytes() == candidate_bytes assert (work["candidates"].directory / pointer["key"]).read_bytes() == candidate_bytes
@pytest.mark.parametrize("warning", ["unreadable source region", "\u0646\u0627\u062e\u0648\u0627\u0646\u0627"]) @pytest.mark.parametrize("text", ["\ufffd", "(cid:12)"])
def test_genuine_unreadable_provider_warning_remains_terminal(work, warning): def test_corrupt_provider_source_text_remains_terminal(work, text):
review_source(work) review_source(work)
class UnreadableVision(ReviewedVision): class UnreadableVision(ReviewedVision):
def transcribe(self, *args, **kwargs): def transcribe(self, *args, **kwargs):
return tuple(b.model_copy(update={"warnings": (warning,)}) return tuple(b.model_copy(update={"text": text})
for b in super().transcribe(*args, **kwargs)) for b in super().transcribe(*args, **kwargs))
review_worker(work, UnreadableVision()).run_once("unreadable") review_worker(work, UnreadableVision()).run_once("unreadable")
doc, job, count = rows(work) doc, job, count = rows(work)
@@ -0,0 +1,515 @@
"""Authenticated Phase 3 HTTP workflows on real isolated PostgreSQL."""
import json
from uuid import UUID, uuid4
import pytest
from sqlalchemy import text
from app.api.v1 import dependencies
from app.modules.documents.worker import Worker
from app.modules.documents.extraction import PageBlockExtractor
from app.modules.documents.review import FACTUAL_CHECKS
from app.modules.knowledge.service import selection_get
from tests.support.embedding import DeterministicEmbeddings
from tests.support.extraction import FakeVision, pdf_bytes
from tests.support.formats import image_bytes
from tests.integration.test_phase2_postgres import seeded_env, api, login, session
@pytest.fixture
def document_api(api, tmp_path):
client, wire, runner, e = api
e.settings = e.settings.model_copy(update={'original_directory': tmp_path / 'originals', 'extraction_directory': tmp_path / 'extractions'})
client.app.dependency_overrides[dependencies.get_ingestion_settings] = lambda: e.settings
return client, wire, runner, e
def upload(client, headers, content=b'Article 1: fee is 5%.', filename='source.md', key=None, title='Source'):
return client.post('/api/v1/documents', files={'file': (filename, content)}, data={'title': title},
headers=dict(headers, **{'Idempotency-Key': str(key or uuid4())}))
def process(e, vision=None, provider=None):
from app.api.v1.documents import get_document_services
services = get_document_services(e.engine, e.settings)
worker = Worker(services[4], services[1], services[2], lambda _: PageBlockExtractor(vision),
lambda _: (provider or DeterministicEmbeddings(e.settings), None), e.settings)
assert worker.run_once('http-acceptance')
return services
def polling(client, identifier):
response = client.get('/api/v1/documents/' + str(identifier))
assert response.status_code == 200, response.text
return response.json()
def test_upload_replay_independent_identity_polling_selection_configuration(document_api):
client, _, _, e = document_api; headers = login(client, e); key = uuid4()
first = upload(client, headers, key=key)
assert first.status_code == 202, first.text
identifier = first.json()['document_id']
assert not first.json()['is_active'] and not first.json()['searchable']
frozen = e.settings.processing_profile()
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'max_original_bytes': 10})
replay = upload(client, headers, key=key)
assert replay.status_code == 202 and replay.json()['document_id'] == identifier
assert replay.headers['Idempotency-Replayed'] == 'true'
assert upload(client, headers, content=b'changed', key=key).status_code == 409
assert upload(client, headers, content=b'x'*50, key=key).status_code == 409
e.settings = e.settings.model_copy(update={'max_original_bytes': 20 * 1024 * 1024})
assert upload(client, headers).json()['document_id'] != identifier
with e.engine.connect() as conn:
assert conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one() == frozen
assert polling(client, identifier)['review_state'] == 'not_evaluated'
cfg = client.get('/api/v1/configuration')
assert cfg.status_code == 200, cfg.text
assert cfg.json()['capabilities']['ocr_review_required'] is False
assert cfg.json()['capabilities']['max_upload_bytes'] == e.settings.max_original_bytes
assert not cfg.json()['capabilities']['text'] and not cfg.json()['capabilities']['voice']
assert all(value not in cfg.text for value in ('database_url', 'storage_key', 'api_key', str(e.settings.original_directory)))
pending = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': [identifier]}, headers=headers)
assert pending.status_code == 409 and pending.json()['error']['code'] == 'DOCUMENT_NOT_READY'
assert pending.json()['error']['details']['document_ids'] == [identifier]
process(e)
ready = polling(client, identifier)
assert ready['status'] == 'ready' and not ready['is_active'] and not ready['searchable']
assert ready['extraction_quality_decision'] == 'passed' and not ready['job']['can_retry']
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': [identifier]}, headers=headers)
assert result.status_code == 200 and result.json()['revision'] == 3 and result.json()['access_epoch'] == 2 # removes original fixture
assert polling(client, identifier)['searchable']
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers).status_code == 409
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': [identifier, identifier]}, headers=headers).status_code == 422
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': [identifier], 'scope': 'forged'}, headers=headers).status_code == 422
listed = client.get('/api/v1/documents?limit=1').json()
assert len(listed['items']) == 1 and listed['next_cursor'] and listed['knowledge_revision'] == 3
assert client.get('/api/v1/documents', params={'cursor': listed['next_cursor']}).status_code == 200
assert client.get('/api/v1/documents?cursor=invalid').status_code == 422
assert client.get('/api/v1/documents?limit=101').status_code == 422
assert client.post('/api/v1/documents/'+identifier+'/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
def test_unicode_filename_upload_persistence_and_replay(document_api):
client, _, _, e = document_api
headers = login(client, e)
key = uuid4()
long_filename = 'س' * 128 + '.md'
content = b'# Persian Article\nContent.'
res = client.post('/api/v1/documents', files={'file': (long_filename, content)},
headers=dict(headers, **{'Idempotency-Key': str(key)}))
assert res.status_code == 202, res.text
identifier = res.json()['document_id']
# Detail query verifies stored original_filename is intact and not truncated
detail = polling(client, identifier)
assert detail['filename'] == long_filename
assert detail['title'] == 'س' * 128
# Replay same upload with same key
replay = client.post('/api/v1/documents', files={'file': (long_filename, content)},
headers=dict(headers, **{'Idempotency-Key': str(key)}))
assert replay.status_code == 202
assert replay.headers['Idempotency-Replayed'] == 'true'
assert replay.json()['document_id'] == identifier
@pytest.mark.parametrize('required', [True, False])
@pytest.mark.parametrize('kind', ['image', 'scan'])
def test_ocr_snapshot_worker_publication_and_explicit_human_review(document_api, required, kind):
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': required, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
content = image_bytes('PNG')
if kind == 'scan': content = pdf_bytes([[('image', content, 10, 20)]])
result = upload(client, headers, content, 'scan.pdf' if kind == 'scan' else 'image.png')
assert result.status_code == 202, result.text
identifier, job = result.json()['document_id'], result.json()['job_id']
e.settings = e.settings.model_copy(update={'ocr_review_required': not required})
vision = FakeVision(); services = process(e, vision)
detail = polling(client, identifier)
assert detail['ocr_review_required'] is required
if required:
assert detail['status'] == 'failed' and detail['review_state'] == 'pending' and not detail['job']['can_retry']
items = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
assert len(items) == 1
item = items[0]
preview = client.get(item['preview_path'])
assert preview.status_code == 200 and preview.headers['cache-control'] == 'no-store'
retry_url = f'/api/v1/documents/{identifier}/retry'
assert client.post(retry_url, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Fixture inspection')
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, reviewer='forged'), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 422
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, checked=[]), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 422
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, evidence_sha256='a'*64), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
key = str(uuid4()); decision_headers = dict(headers, **{'Idempotency-Key': key})
url = f'/api/v1/documents/{identifier}/extraction-review/decisions'
assert client.post(url, json=decision, headers=decision_headers).status_code == 200
replay = client.post(url, json=decision, headers=decision_headers)
assert replay.status_code == 200 and replay.headers['Idempotency-Replayed'] == 'true'
assert client.post(url, json=dict(decision, note='changed'), headers=decision_headers).status_code == 409
assert polling(client, identifier)['status'] == 'failed' and polling(client, identifier)['job']['can_retry']
retry_headers = dict(headers, **{'Idempotency-Key': str(uuid4())})
retry = client.post(retry_url, headers=retry_headers)
assert retry.status_code == 202 and retry.json()['job_id'] == job and retry.json()['retry_generation'] == 1
assert client.post(retry_url, headers=retry_headers).headers['Idempotency-Replayed'] == 'true'
process(e, vision)
assert len(vision.calls) == 1 # resume exact retained evidence
else:
assert detail['review_state'] == 'not_required' and detail['extraction_quality_decision'] == 'passed'
assert client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'] == []
with e.engine.connect() as conn:
assert conn.execute(text("SELECT count(*) FROM audit_events WHERE target_id=:id AND action='extraction_review'"), {'id': UUID(identifier)}).scalar_one() == 0
detail = polling(client, identifier)
assert detail['status'] == 'ready' and detail['job']['status'] == 'succeeded'
assert detail['job']['id'] == job and not detail['is_active'] and not detail['searchable']
def test_factual_review_remains_independent_and_rejection_stays_failed(document_api):
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False})
response = upload(client, headers, b'Question: fee?\nAnswer: 5%\n')
identifier = response.json()['document_id']; process(e)
assert polling(client, identifier)['review_required']
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
assert item['review_kind'] == 'factual_corpus' and item['preview_path'] is None
decision = dict(evidence_sha256=item['evidence_sha256'], decision='reject', checked=[], note='Not authoritative')
result = client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision,
headers=dict(headers, **{'Idempotency-Key': str(uuid4())}))
assert result.status_code == 200
detail = polling(client, identifier)
assert detail['review_state'] == 'rejected' and not detail['job']['can_retry'] and not detail['searchable']
retry = client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())}))
assert retry.status_code == 409
def test_auth_roles_cross_organization_csrf_and_safe_upload_errors(document_api):
client, _, _, e = document_api
assert client.get('/api/v1/documents').status_code == 401
headers = login(client, e)
assert upload(client, {'Origin': headers['Origin']}).status_code == 403
assert upload(client, dict(headers, Origin='https://untrusted.invalid')).status_code == 403
assert client.post('/api/v1/documents', files={'file': ('source.md', b'a')}, headers=headers).status_code == 422
assert upload(client, headers, b'not PDF', 'wrong.pdf').status_code == 422
assert upload(client, headers, b'abc', 'file.exe').status_code == 415
e.settings = e.settings.model_copy(update={'max_original_bytes': 10})
assert upload(client, headers, b'a' * 11).status_code == 413
identifier = upload(client, headers, b'abc').json()['document_id']
other_org, other_actor = __import__('tests.support.search', fromlist=['administrator']).administrator(e.engine)
with e.engine.begin() as conn:
conn.execute(text('UPDATE users SET organization_id=:org WHERE id=:id'), {'org': other_org, 'id': other_actor})
# Real second administrator/session; cookie identity alone determines scope.
from argon2 import PasswordHasher
with e.engine.begin() as conn:
conn.execute(text('UPDATE users SET password_hash=:hash WHERE id=:id'), {'id': other_actor, 'hash': PasswordHasher().hash('fixture-password')})
client.post('/api/v1/auth/logout', headers=headers)
e.actor = other_actor; other_headers = login(client, e)
assert client.get('/api/v1/documents/'+identifier).status_code == 404
assert client.get(f'/api/v1/documents/{identifier}/extraction-review').status_code == 404
assert client.get(f'/api/v1/documents/{identifier}/extraction-review/' + 'a'*64 + '/preview').status_code == 404
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(other_headers, **{'Idempotency-Key': str(uuid4())})).status_code == 404
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': [identifier]}, headers=other_headers).status_code == 404
with e.engine.begin() as conn:
conn.execute(text("UPDATE users SET role='user' WHERE id=:id"), {'id': other_actor})
assert client.get('/api/v1/configuration').status_code == 200
assert client.get('/api/v1/documents').status_code == 403
assert upload(client, other_headers, b'abc').status_code == 403
assert client.get('/api/v1/knowledge-selection').status_code == 403
@pytest.mark.parametrize('api', ['gemini', 'openai'], indirect=True)
def test_authenticated_selection_removal_closes_active_voice_and_redacts_polling(document_api):
client, wire, runner, e = document_api
headers, result, _ = session(client, e)
sid = result['session_id']
with client.websocket_connect(f'ws://localhost:8000/api/v1/voice/sessions/{sid}/stream', headers={'Origin': headers['Origin']}) as ws:
from app.infrastructure.realtime import RealtimeAdapter
ack = {'setupComplete': {}} if e.voice_config.provider == 'gemini' else {'type': 'session.updated', 'session': RealtimeAdapter(wire, model=e.voice_config.selected_model, voice=e.voice_config.selected_voice).setup()['session']}
client.portal.call(wire.inbound.put, ack)
assert ws.receive_json()['type'] == 'session_ready'
from tests.unit.test_realtime_phase1 import until
from app.modules.knowledge.evidence import SearchExecution
from app.modules.auth.service import COOKIE_NAME
user = e.auth.get_current_user(client.cookies.get(COOKIE_NAME))
client.portal.call(until, lambda: e.lifecycle.get_live_session(user, UUID(sid))['status'] == 'connected')
execution = SearchExecution(e.actor)
call = e.lifecycle.admit_tool(user, UUID(sid), 'completed-before-removal', str(uuid4()), {'query': 'fee'}, execution)
with e.engine.connect() as conn:
chunk = conn.execute(text('SELECT id,text FROM document_chunks WHERE document_id=:id'), {'id': e.doc}).mappings().first()
evidence = {'status': 'ok', 'sources': [dict(document_id=str(e.doc), chunk_id=str(chunk['id']), source_ref='S1', title='Pump', text=chunk['text'], location={'page': None, 'section': None})]}
assert e.lifecycle.complete_tool(user, UUID(sid), call['id'], evidence, execution)
running = e.lifecycle.admit_tool(user, UUID(sid), 'running-before-removal', str(uuid4()), {'query': 'fee'}, SearchExecution(e.actor))
response = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers)
assert response.status_code == 200 and response.json()['conversations_invalidated']
assert response.json()['access_epoch'] == 2
terminal = ws.receive_json()
assert terminal['type'] == 'error' and terminal['error']['code'] == 'CONTEXT_REVOKED'
poll = client.get('/api/v1/voice/sessions/' + sid).json()
assert poll['status'] == 'closed' and poll['close_reason'] == 'epoch_invalidated'
assert not poll['recent_tool_results'][0]['sources'][0]['available']
assert 'text' not in poll['recent_tool_results'][0]['sources'][0]
assert poll['recent_tool_results'][0]['sources'][0]['excerpt'] is None
with e.engine.connect() as conn:
assert conn.execute(text('SELECT status FROM tool_calls WHERE id=:id'), {'id': running['id']}).scalar_one() == 'failed'
assert e.connections == [1]
@pytest.mark.parametrize('fragmented', [False, True])
def test_real_parser_invalid_utf8_persists_protocol_error(document_api, fragmented):
"""Raw complete/fragmented UTF-8 traverses the installed parser and real Live handler."""
import asyncio
import base64
import os
import struct
import uvicorn
from app.server import server_config
from app.modules.auth.service import COOKIE_NAME
from tests.unit.test_realtime_phase1 import until
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
client, wire, _, e = document_api
headers, result, _ = session(client, e)
sid = UUID(result['session_id'])
async def run():
server = uvicorn.Server(server_config(client.app, port=0, lifespan='off', log_level='error'))
task = asyncio.create_task(server.serve())
reader = writer = None
try:
await until(lambda: server.started)
port = server.servers[0].sockets[0].getsockname()[1]
reader, writer = await asyncio.open_connection('127.0.0.1', port)
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET {result["stream_path"]} HTTP/1.1\r\nHost: localhost:8000\r\nOrigin: http://localhost:8000\r\nCookie: {COOKIE_NAME}={client.cookies.get(COOKIE_NAME)}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
assert b'101 Switching Protocols' in await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 2)
await wire.inbound.put({'setupComplete': {}})
await until(lambda: e.lifecycle.get_live_session(e.auth.get_current_user(client.cookies.get(COOKIE_NAME)), sid)['status'] == 'connected')
bad = b'\x01\x81\0\0\0\0\xc3\x80\x81\0\0\0\0\x28' if fragmented else b'\x81\x82\0\0\0\0\xc3\x28'
writer.write(bad); await writer.drain()
# Drain readiness and then the protocol close. Never echo invalid text.
while True:
head = await asyncio.wait_for(reader.readexactly(2), 2)
size = head[1] & 127
if size == 126: size = struct.unpack('!H', await reader.readexactly(2))[0]
if size == 127: size = struct.unpack('!Q', await reader.readexactly(8))[0]
payload = await reader.readexactly(size)
if head[0] & 15 == 8:
assert struct.unpack('!H', payload[:2])[0] == 1007
writer.write(b'\x88\x82\0\0\0\0' + payload[:2]); await writer.drain()
writer.close(); await writer.wait_closed()
break
async with asyncio.timeout(12):
while sid in ACTIVE_MEDIA_SESSIONS: await asyncio.sleep(.005)
finally:
if writer:
writer.close(); await writer.wait_closed()
server.should_exit = True
await asyncio.wait_for(task, 5)
asyncio.run(run())
poll = client.get('/api/v1/voice/sessions/' + str(sid)).json()
assert poll['status'] == 'failed' and poll['error_code'] == 'LIVE_PROTOCOL_ERROR'
def test_legacy_profile_keeps_gate_and_same_profile_on_retry(document_api, monkeypatch):
from app.modules.documents.settings import IngestionSettings
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
original = IngestionSettings.processing_profile
def legacy(self):
value = original(self); value['extraction'].pop('ocr_review_required'); return value
monkeypatch.setattr(IngestionSettings, 'processing_profile', legacy)
response = upload(client, headers, image_bytes('PNG'), 'image.png')
identifier = response.json()['document_id']; process(e, FakeVision())
detail = polling(client, identifier)
assert detail['ocr_review_required'] and detail['review_required'] and not detail['job']['can_retry']
with e.engine.connect() as conn:
frozen = conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one()
monkeypatch.setattr(IngestionSettings, 'processing_profile', original)
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Legacy fixture inspection')
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 200
retry = client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())}))
assert retry.status_code == 202
process(e, FakeVision())
with e.engine.connect() as conn:
assert conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one() == frozen
assert polling(client, identifier)['status'] == 'ready'
@pytest.mark.parametrize('failure', ['warnings', 'unreadable', 'model', 'placeholder'])
def test_optional_ocr_validation_failure_never_publishes(document_api, failure):
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
response = upload(client, headers, image_bytes('PNG'), 'image.png')
identifier = response.json()['document_id']
vision = FakeVision(warnings=('uncertain order',) if failure == 'warnings' else (),
actual_model='wrong' if failure == 'model' else 'fixture-flash',
text='\ufffd' if failure == 'unreadable' else '[TODO]' if failure == 'placeholder' else 'Evidence')
process(e, vision)
detail = polling(client, identifier)
assert detail['status'] == 'failed' and detail['chunk_count'] == 0 and not detail['searchable']
if failure == 'warnings':
assert detail['review_required'] and not detail['job']['can_retry']
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'), {'id': UUID(identifier)}).scalar_one() == 0
def test_automatic_ocr_factual_candidate_requires_separate_approval(document_api):
from app.modules.documents.types import ExtractedBlock
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
calls = []
class FactualVision:
def transcribe(self, image, *, page, section, processing_profile):
calls.append(1)
return tuple(ExtractedBlock(ordinal=i, block_id=f'{section}/{i}', source_locator=f'{section}/{i}',
page=page, method='vision', actual_model='fixture-flash', text=value, block_type=role, group_id='faq-pair')
for i, (role, value) in enumerate([('question', 'Question: fee?'), ('answer', 'Answer: 5%')]))
response = upload(client, headers, image_bytes('PNG'), 'faq.png')
identifier = response.json()['document_id']; process(e, FactualVision())
detail = polling(client, identifier)
assert detail['status'] == 'failed' and detail['extraction_quality_decision'] == 'passed' and detail['review_required']
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
assert item['review_kind'] == 'factual_corpus' and set(item['required_checks']) == set(FACTUAL_CHECKS)
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Independent factual approval')
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 200
assert polling(client, identifier)['status'] == 'failed'
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
process(e, FactualVision())
detail = polling(client, identifier)
assert detail['status'] == 'ready' and not detail['is_active'] and calls == [1]
assert detail['extraction_quality_decision'] == 'passed'
def test_selection_addition_preserves_active_epoch_and_noop_revision(document_api):
client, _, _, e = document_api; headers = login(client, e)
identifier = upload(client, headers).json()['document_id']; process(e)
selection = client.get('/api/v1/knowledge-selection').json()
ids = selection['document_ids'] + [identifier]
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': ids}, headers=headers)
assert result.status_code == 200 and result.json()['access_epoch'] == 1 and not result.json()['conversations_invalidated']
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': ids}, headers=headers)
assert result.status_code == 200 and result.json()['revision'] == 3 and result.json()['access_epoch'] == 1
def test_http_selection_removal_cancels_running_runtime_tool(document_api):
from threading import Event
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
from tests.unit.test_realtime_phase1 import until
client, wire, runner, e = document_api
headers, result, _ = session(client, e); sid = UUID(result['session_id'])
entered, release = Event(), Event()
original = e.search.provider.embed
def block(texts):
entered.set()
assert release.wait(5), 'Fixture provider release timed out'
return original(texts)
e.search.provider.embed = block
with client.websocket_connect('ws://localhost:8000'+result['stream_path'], headers={'Origin': headers['Origin']}) as ws:
try:
client.portal.call(wire.inbound.put, {'setupComplete': {}})
assert ws.receive_json()['type'] == 'session_ready'
ws.send_bytes(bytes(4800)); ws.send_bytes(bytes(4800))
client.portal.call(until, lambda: len([m for m in wire.sent if 'realtimeInput' in m]) == 2)
client.portal.call(wire.inbound.put, {'voiceActivity': {'type': 'ACTIVITY_START', 'audioOffset': '0s'}})
client.portal.call(wire.inbound.put, {'voiceActivity': {'type': 'ACTIVITY_END', 'audioOffset': '0.1s'}})
client.portal.call(wire.inbound.put, {'toolCall': {'functionCalls': [{'id': 'blocked-tool', 'name': 'search_knowledge', 'args': {'query': 'Pump pressure?'}}]}})
assert entered.wait(3)
response = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers)
assert response.status_code == 200
release.set()
while True:
event = ws.receive_json()
assert event['type'] != 'sources'
if event['type'] == 'error':
assert event['error']['code'] == 'CONTEXT_REVOKED'; break
finally:
release.set()
client.portal.call(until, lambda: sid not in ACTIVE_MEDIA_SESSIONS)
with e.engine.connect() as conn:
saved = conn.execute(text('SELECT status,error_code,result_json FROM tool_calls WHERE live_session_id=:sid'), {'sid': sid}).mappings().one()
assert saved['status'] == 'failed' and saved['error_code'] == 'CONTEXT_REVOKED' and saved['result_json'] is None
assert not any('toolResponse' in m for m in wire.sent)
@pytest.mark.parametrize('required', [True, False])
def test_f01_reports_configured_policy_and_only_available_capabilities(document_api, tmp_path, required):
from pydantic import SecretStr
client, _, _, e = document_api; login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': required, 'embedding_api_key': SecretStr('fake-only')})
report = tmp_path / 'calibration.json'
report.write_text(json.dumps({'status': 'calibrated', 'calibration_id': 'fixture-only',
'cutoff': {'profile': e.settings.processing_profile()['embedding'], 'distance': 1.0}}))
config = e.voice_config.model_copy(update={'search_calibration_report': report})
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
response = client.get('/api/v1/configuration')
assert response.status_code == 200
capability = response.json()['capabilities']
assert capability['ocr_review_required'] is required and capability['voice'] and capability['captions']
assert not capability['text'] and 'fake-only' not in response.text and str(report) not in response.text
report.write_text('{}')
assert not client.get('/api/v1/configuration').json()['capabilities']['voice']
assert client.patch('/api/v1/configuration', json={'ocr_review_required': not required}).status_code == 405
assert client.post('/api/v1/documents/'+str(e.doc)+'/retry', json={'profile': 'forged'}, headers={'Origin':'http://localhost:8000','X-CSRF-Token':client.get('/api/v1/me').json()['csrf_token'], 'Idempotency-Key': str(uuid4())}).status_code == 422
def test_mixed_pdf_never_labels_automatic_ocr_as_fully_reviewed(document_api):
client, _, _, e = document_api; headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
content = pdf_bytes([[('image', image_bytes('PNG'), 10, 20)], [('text', 'Article 1: fee is 5%.', 10, 20)]])
response = upload(client, headers, content, 'mixed.pdf')
identifier = response.json()['document_id']; vision = FakeVision(); process(e, vision)
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
assert item['location']['page'] == 2
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Inspected direct page only')
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 200
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
services = process(e, vision)
detail = polling(client, identifier)
assert detail['status'] == 'ready' and not detail['is_active']
assert detail['extraction_quality_decision'] == 'partially_reviewed'
with e.engine.connect() as conn:
doc = dict(conn.execute(text('SELECT * FROM documents WHERE id=:id'), {'id': UUID(identifier)}).mappings().one())
envelope = services.candidates.inspect_pointer(doc['extraction_state']['complete_artifact'], document=doc)
assert {annotation.locator for annotation in envelope.review_annotations} == {'pdf/page/2'}
assert any(block.method == 'vision' and block.page == 1 for block in envelope.blocks)
@pytest.mark.parametrize('escaped', [False, True])
def test_large_eligible_review_persists_and_replays(document_api, escaped):
from app.modules.documents.types import ExtractedBlock
client, _, _, e = document_api
headers = login(client, e)
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'vision_provider': 'gemini',
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
suffix = ('😀"\\' * 165) if escaped else ('x' * 495)
groups = [str(i).zfill(5) + suffix for i in range(4500)]
calls = []
class Vision:
def transcribe(self, image, *, page, section, processing_profile):
calls.append(1)
return tuple(ExtractedBlock(ordinal=2*i+j, block_id=f'{section}/{2*i+j}',
source_locator=f'{section}/{2*i+j}', page=page, method='vision', actual_model='fixture-flash',
text=('Question: fee?' if j == 0 else 'Answer: 5%'),
block_type=('question' if j == 0 else 'answer'), group_id=group)
for i, group in enumerate(groups) for j in range(2))
identifier = upload(client, headers, image_bytes('PNG'), 'large-faq.png').json()['document_id']
process(e, Vision())
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'],
note='Generated retained evidence inspected', excluded_group_ids=groups[:-1])
raw = json.dumps(decision, ensure_ascii=escaped, separators=(',', ':')).encode()
assert len(raw) > 2 * 1024 * 1024
url = f'/api/v1/documents/{identifier}/extraction-review/decisions'
request_headers = dict(headers, **{'Idempotency-Key': str(uuid4()), 'Content-Type': 'application/json'})
response = client.post(url, content=raw, headers=request_headers)
assert response.status_code == 200, response.text
replay = client.post(url, content=raw, headers=request_headers)
assert replay.status_code == 200 and replay.headers['Idempotency-Replayed'] == 'true'
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
process(e, Vision())
detail = polling(client, identifier)
assert detail['status'] == 'ready' and not detail['is_active'] and calls == [1]
with e.engine.connect() as conn:
state = conn.execute(text('SELECT extraction_state FROM documents WHERE id=:id'), {'id': identifier}).scalar_one()
assert set(state['factual_inclusion']['excluded_group_ids']) == set(groups[:-1])
+265
View File
@@ -0,0 +1,265 @@
import fs from 'node:fs';
import vm from 'node:vm';
import assert from 'node:assert/strict';
import {VoiceClient,environment,tick} from './voice_client_harness.mjs';
const processors={};
globalThis.AudioWorkletProcessor=class {constructor(){this.messages=[];this.port={postMessage:m=>this.messages.push(m)};}};
globalThis.registerProcessor=(name,p)=>processors[name]=p;
vm.runInThisContext(fs.readFileSync(new URL('../../examples/voice-audio-worklet.js',import.meta.url),'utf8'));
function playback(){const p=new processors['rag-playback']();p.send=data=>p.port.onmessage({data});return p;}
// Independent count bound retains partially consumed messages across references.
{
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
for(let n=0;n<100;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(2).buffer});
assert.equal(p.queue.length,100);assert.equal(p.messages.length,0);
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,100);
p.send({type:'pcm',ref:'a',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,99);
p.send({type:'pcm',ref:'a',packet_id:'accepted',samples:new Float32Array(1).buffer});assert.equal(p.queue.length,100);
p.send({type:'flush',id:'flush'});assert.equal(p.queue.length,0);assert.equal(p.queued,0);
assert.equal(p.messages.at(-1).released.length,100);assert.equal(p.messages.filter(m=>m.type==='progress').every(m=>m.played_ms===0),true);
}
// Exact byte boundary is independent of packet count and references.
{
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
for(let n=0;n<10;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(4800).buffer});
assert.equal(p.queued,48000);
p.send({type:'pcm',ref:'b',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
p.process([],[[new Float32Array(120)]]);assert.equal(p.messages.at(-1).played_ms,5);
p.send({type:'flush',id:'f'});assert.equal(p.messages.at(-2).played_ms,5);
}
// Real client with delayed MessagePort deliveries: pending handoffs count immediately.
for(const bytes of [2,9600]) {
const e=environment(),c=e.client();let processor,mail=[];
globalThis.AudioWorkletNode=class {
constructor(context,name){this.name=name;this.port={postMessage:m=>{
if(name!=='rag-playback')return;
if(m.type==='pcm')mail.push(m);else processor.port.onmessage({data:m});
}};
if(name==='rag-playback') {processor=playback();processor.port.postMessage=m=>this.port.onmessage?.({data:m});}}
connect(){} disconnect(){}
};
const pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
const socket=c.socket,connection=c.connection;
const control=event=>socket.onmessage({data:JSON.stringify(event)});
control({type:'audio_started',audio_ref:'a'});
const count=bytes===2?100:10;
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
assert.equal(connection.playbackPackets.size,count);assert.equal(connection.playbackBytes,bytes*count);
// Deliver/consume part of one packet; only actual consumption reduces bytes.
for(const m of mail)processor.port.onmessage({data:m});mail=[];
processor.process([],[[new Float32Array(1)]]);
assert.equal(connection.playbackBytes,bytes*count-2);
if(bytes===9600) {
const packetID=processor.queue[0].id;
c.releasePlayback(connection,packetID,2,false); // Duplicate cumulative consumption is inert.
assert.equal(connection.playbackBytes,bytes*count-2);
}
if(bytes===9600)assert.equal(connection.playbackPackets.size,10);
// Interruption flush releases every remaining reservation once, without fabricated progress.
control({type:'turn_interrupted'});await tick();assert.equal(connection.playbackPackets.size,0);assert.equal(connection.playbackBytes,0);
control({type:'audio_started',audio_ref:'b'});
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
socket.onmessage({data:new ArrayBuffer(2)});await c.cleanup(connection);
assert.equal(c.connection,null);assert.equal(connection.playbackBytes,0);assert.equal(connection.playbackPackets.size,0);
const progress=socket.sent.filter(m=>typeof m==='string').map(m=>JSON.parse(m)).filter(m=>m.type==='playback_progress');
assert.equal(progress.every(m=>m.played_ms===0),true);
}
// C01 and V01 commit but lose their first response. Retry identical retained payloads.
for(const lost of ['/conversations','/voice/sessions']) {
const c=new VoiceClient(()=>{}),attempt=c.newCreationAttempt(),requests=[],committed=new Map();let dropped=false;
c.request=async(path,method,body)=>{
if(path==='/me')return {csrf_token:'csrf'};
if(path.includes('/by-request/'))return committed.get('/voice/sessions');
requests.push({path,body:JSON.stringify(body)});
if(committed.has(path)&&committed.get(path).payload!==JSON.stringify(body))throw new Error('IDEMPOTENCY_CONFLICT');
const response=path==='/conversations'?{id:'cid'}:{session_id:'sid',status:'connecting',stream_path:'/stream'};
committed.set(path,{...response,payload:JSON.stringify(body)});
assert.equal(c.creationAttempt,attempt);assert.equal(c.conversationRequestID,attempt.conversationRequestID);assert.equal(c.requestID,attempt.sessionRequestID);
if(path===lost&&!dropped){dropped=true;throw new Error('lost committed response');}
return response;
};
await assert.rejects(c.reserve(),/lost committed response/);
assert.equal(c.creationAttempt,attempt);assert.equal(c.connection,null);
if(lost==='/voice/sessions'){const recovered=await c.recover();assert.equal(recovered.session_id,'sid');assert.equal(c.connection,null);}
await c.retryCreation();assert.equal(c.session.session_id,'sid');assert.equal(c.connection,null);
const duplicates=requests.filter(r=>r.path===lost);assert.equal(duplicates.length,2);assert.equal(duplicates[0].body,duplicates[1].body);
assert.throws(()=>{attempt.conversationPayload.mode='text';},TypeError);
assert.throws(()=>{attempt.sessionPayload.conversation_id='changed';},TypeError);
await assert.rejects(c.reserve('changed','changed'),/newCreationAttempt/);
const fresh=c.newCreationAttempt();assert.notEqual(fresh.conversationRequestID,attempt.conversationRequestID);assert.notEqual(fresh.sessionRequestID,attempt.sessionRequestID);
}
console.log('Playback bounds, consumed capacity, flush, cleanup and lost-response replay passed');
// Intentional freshSession performs reconciliation before a new C01/V01 attempt and media.
{
const c=new VoiceClient(()=>{}),old=c.newCreationAttempt(),order=[];
c.session={session_id:'old'};
c.close=async()=>{order.push('close');};
c.recover=async()=>{order.push('recover');return {status:'closed'};};
c.request=async(path,method,body)=>{
if(path==='/me')return {csrf_token:'fresh'};
if(path==='/conversations'){order.push('C01');assert.notEqual(body.client_request_id,old.conversationRequestID);return {id:'fresh-cid'};}
order.push('V01');assert.equal(body.conversation_id,'fresh-cid');assert.notEqual(body.client_request_id,old.sessionRequestID);return {session_id:'fresh',stream_path:'/fresh'};
};
c.connect=async()=>{order.push('connect');assert.equal(c.session.session_id,'fresh');};
await c.freshSession();assert.deepEqual(order,['close','recover','C01','V01','connect']);
}
// Standalone delivered worklet 100/101 boundary
{
const capture = new processors['rag-capture']();
const delivered = [];
capture.port.postMessage = m => delivered.push(m);
for (let i = 0; i < 100; i++) capture.process([[new Float32Array(240).fill(0.1)]]);
assert.equal(delivered.length, 100);
assert.equal(capture.pending, 100);
assert.equal(capture.pendingBytes, 48000);
const overflowed = !capture.process([[new Float32Array(240).fill(0.1)]]);
assert.equal(overflowed, true);
assert.equal(delivered.at(-1).type, 'overflow');
assert.equal(capture.active, false);
}
// Delivered client + worklet: 100/101 boundary with stalled socket (48,000 bytes, exactly 100 packets admitted)
{
const e = environment();
let captureProc = null;
globalThis.AudioWorkletNode = class {
constructor(ctx, name) {
this.name = name;
if (name === 'rag-capture') {
captureProc = new processors['rag-capture']();
this.port = {
postMessage: m => captureProc.port.onmessage?.({data: m}),
onmessage: null
};
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
} else {
this.port = { postMessage: () => {}, onmessage: null };
}
}
connect() {} disconnect() {}
};
const c = e.client();
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
const socket = c.socket;
const origSend = socket.send.bind(socket);
socket.bufferedAmount = 0;
socket.send = (m) => {
origSend(m);
socket.bufferedAmount += m.byteLength || 0;
};
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
assert.equal(socket.sent.length, 100);
assert.equal(socket.bufferedAmount, 48000);
assert.equal(c.connection.capturePackets.length, 100);
assert.equal(c.connection.captureBytes, 48000);
assert.equal(captureProc.pending, 100);
// 101st chunk into worklet triggers overflow, stopping capture and cleaning up client
captureProc.process([[new Float32Array(240).fill(0.1)]]);
await tick();
await c.cleanup();
assert.equal(c.connection, null);
assert.equal(socket.sent.length, 100);
assert.equal(socket.bufferedAmount, 48000);
}
// Partial drain releases capacity conservatively only for fully drained packets
{
const e = environment();
let captureProc = null;
globalThis.AudioWorkletNode = class {
constructor(ctx, name) {
this.name = name;
if (name === 'rag-capture') {
captureProc = new processors['rag-capture']();
this.port = {
postMessage: m => captureProc.port.onmessage?.({data: m}),
onmessage: null
};
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
} else {
this.port = { postMessage: () => {}, onmessage: null };
}
}
connect() {} disconnect() {}
};
const c = e.client();
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
const socket = c.socket;
socket.bufferedAmount = 0;
socket.send = (m) => { socket.sent.push(m); socket.bufferedAmount += m.byteLength || 0; };
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
assert.equal(socket.bufferedAmount, 48000);
assert.equal(captureProc.pending, 100);
// Partial drain of 240 bytes (half a packet): must not drain packet
socket.bufferedAmount -= 240;
let drained = Math.max(0, c.connection.captureBytes - socket.bufferedAmount);
assert.equal(drained < c.connection.capturePackets[0], true);
// Drain 4800 bytes total (10 packets):
socket.bufferedAmount -= 4560;
for (let n = 0; n < 10 && c.connection.capturePackets.length; n++) {
const p = c.connection.capturePackets.shift();
c.connection.captureBytes -= p;
captureProc.port.onmessage?.({data: {type: 'accepted', bytes: p}});
}
assert.equal(c.connection.capturePackets.length, 90);
assert.equal(captureProc.pending, 90);
assert.equal(c.connection.captureBytes, 43200);
// Worklet can now admit 10 more packets
for (let i = 0; i < 10; i++) {
const ok = captureProc.process([[new Float32Array(240).fill(0.1)]]);
assert.equal(ok, true);
}
assert.equal(captureProc.pending, 100);
await c.cleanup();
}
// Delayed handoffs, terminal cleanup, and stale callbacks cannot mutate newer session
{
const e = environment();
let captureProc = null;
globalThis.AudioWorkletNode = class {
constructor(ctx, name) {
this.name = name;
if (name === 'rag-capture') {
captureProc = new processors['rag-capture']();
this.port = {
postMessage: m => captureProc.port.onmessage?.({data: m}),
onmessage: null
};
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
} else {
this.port = { postMessage: () => {}, onmessage: null };
}
}
connect() {} disconnect() {}
};
const c = e.client();
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
const oldConn = c.connection;
const oldSocket = c.socket;
oldSocket.bufferedAmount = 4800;
oldConn.capturePackets = [480, 480, 480];
oldConn.captureBytes = 1440;
await c.cleanup(oldConn);
assert.equal(oldConn.capturePackets.length, 0);
assert.equal(oldConn.captureBytes, 0);
assert.equal(oldConn.drainTimer, null);
assert.equal(c.connection, null);
// Stale callback on old connection is inert
oldConn.capturePackets.push(480);
oldConn.captureBytes = 480;
e.resetPermission();
const pending2 = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending2;
assert.notEqual(c.connection, oldConn);
assert.equal(c.connection.capturePackets.length, 0);
assert.equal(c.connection.captureBytes, 0);
await c.cleanup();
}
console.log('Capture bounds, 100/101 stalled socket, drain, delayed handoffs and cleanup passed');
@@ -0,0 +1,35 @@
"""Execute the delivered HTTP helper; multipart boundaries stay browser-owned."""
from pathlib import Path
import shutil
import subprocess
def test_executable_document_http_handoff():
node = shutil.which('node')
assert node, 'Node is required for the executable frontend handoff check'
source = Path('examples/document-client.js').read_text()
script = '''
import assert from 'node:assert/strict';
const {DocumentClient} = await import('data:text/javascript;base64,' + Buffer.from(SOURCE).toString('base64'));
const calls = [];
globalThis.fetch = async (path, options) => {calls.push({path, options}); return {ok:true,json:async()=>({status:'queued'})};};
const client = new DocumentClient({csrf:'session-csrf'});
const file = new File(['original'], 'source.md');
await client.upload(file, 'Source', 'stable-upload-key');
assert.equal(calls[0].options.body.get('file').name, 'source.md');
assert.equal(calls[0].options.headers['Content-Type'], undefined);
assert.equal(calls[0].options.headers['Idempotency-Key'], 'stable-upload-key');
assert.equal(calls[0].options.headers['X-CSRF-Token'], 'session-csrf');
assert.equal(calls[0].options.credentials, 'same-origin');
await client.retry('document-id', 'retry-key');
assert.equal(calls[1].options.body, undefined);
await client.replace(3, ['document-id']);
assert.deepEqual(JSON.parse(calls[2].options.body), {expected_revision:3,document_ids:['document-id']});
await client.review('document-id', 'digest');
assert.equal(calls[3].path, '/api/v1/documents/document-id/extraction-review?cursor=digest');
globalThis.fetch = async () => ({ok:false,status:409,json:async()=>({error:{code:'REVISION_CONFLICT',request_id:'correlation',details:{}}})});
await assert.rejects(client.replace(1, []), {message:'REVISION_CONFLICT',requestID:'correlation'});
'''
import json
result = subprocess.run([node, '--input-type=module', '-e', 'const SOURCE = ' + json.dumps(source) + ';\n' + script], capture_output=True, text=True, timeout=10)
assert result.returncode == 0, result.stderr
+1 -1
View File
@@ -144,7 +144,7 @@ def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monke
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}}) await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
wire=Scripted() wire=Scripted()
async def connection(*args):return wire async def connection(*args):return wire
monkeypatch.setattr('app.infrastructure.gemini_live.connect_gemini',connection) monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connection)
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model') config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
service=canonical_service(settings,monkeypatch,[row()]) service=canonical_service(settings,monkeypatch,[row()])
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0 assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
+1 -1
View File
@@ -45,7 +45,7 @@ def test_complete_ordered_native_conversion_and_prompt(profile, monkeypatch):
assert body["generationConfig"]["responseMimeType"] == "application/json" assert body["generationConfig"]["responseMimeType"] == "application/json"
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "incomplete", "warnings", "unreadable", "wrong_page", "wrong_method", "wrong_block_model"]) @pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "wrong_page", "wrong_method", "wrong_block_model"])
def test_invalid_native_response_fails_safely(profile, monkeypatch, change): def test_invalid_native_response_fails_safely(profile, monkeypatch, change):
value = native(profile) value = native(profile)
if change == "alias": if change == "alias":
@@ -0,0 +1,131 @@
"""Deterministic source/review and uncalibrated admission regressions."""
import hashlib
import json
from uuid import uuid4
import pytest
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired
from app.modules.documents.chunking import factual_review_blocks
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
from tests.unit.test_phase5_repairs import factual
from tests.unit.test_gemini_vision import native, run
from tests.support.formats import docx_bytes, image_bytes
from tests.support.extraction import FakeVision
@pytest.mark.parametrize('heading', ['', '# Benefits\n'])
def test_initial_context_is_shared_and_requires_independent_factual_approval(settings, heading):
content = 'Benefits title\nOnly permanent employees; except contractors.\n' + heading
content += ''.join(f'Question: allowance {i}?\nAnswer: {i}% unless excluded.\n' for i in range(100))
raw, profile, envelope, state = factual(content, settings)
assert ''.join(b.text for b in envelope.blocks).encode() == raw
assert factual_review_blocks(envelope) == envelope.blocks
with pytest.raises(FactualReviewRequired):
prepare_chunks(envelope, profile, {}, 'a'*64)
chunks = prepare_chunks(envelope, profile, state, 'a'*64)
assert len(chunks) == 100
for i, chunk in enumerate(chunks):
assert 'Benefits title' in chunk.text and 'except contractors' in chunk.text
assert f'allowance {i}?' in chunk.text and f'{i}% unless excluded' in chunk.text
assert envelope.blocks[0].source_locator in chunk.section
def test_unstyled_word_title_preserves_all_pairs(settings):
paragraphs = ['Unstyled FAQ title', 'Question: rate?', 'Answer: 5%.', 'Question: leave?', 'Answer: 10 days.']
xml = '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'
xml += ''.join('<w:p><w:r><w:t>'+p+'</w:t></w:r></w:p>' for p in paragraphs)
content = docx_bytes(document=(xml+'</w:body></w:document>').encode())
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ',
original_sha256=hashlib.sha256(content).hexdigest(), content=content,
mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
processing_profile=settings.processing_profile())
units = factual_review_blocks(envelope)
assert units == envelope.blocks and len([b for b in units if b.block_type == 'question']) == 2
@pytest.mark.parametrize('provider', ['gemini', 'openrouter'])
@pytest.mark.parametrize('diagnostic', ['incomplete', 'warning', 'region'])
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic):
profile = settings.model_copy(update={'ocr_review_required': False, 'vision_provider': provider,
'vision_endpoint': 'https://example.invalid/v1beta', 'vision_model': 'fixture-flash'}).processing_profile()
payload = native(profile)
transcript = json.loads(payload['candidates'][0]['content']['parts'][0]['text'])
if diagnostic == 'incomplete': transcript['complete'] = False
if diagnostic == 'warning': transcript['warnings'] = ['Uncertain order']
if diagnostic == 'region': transcript['blocks'][1]['warnings'] = ['unreadable margin']
text = json.dumps(transcript)
if provider == 'gemini':
payload['candidates'][0]['content']['parts'][0]['text'] = text
blocks = run(profile, payload, monkeypatch)
else:
from io import BytesIO
from app.infrastructure.openrouter_vision import OpenRouterVision
class Opener:
def open(self, request, *, timeout):
return BytesIO(json.dumps({'choices':[{'message':{'content':text}}]}).encode())
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener', lambda *a: Opener())
blocks = OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',
api_key='fixture-only', timeout_seconds=60).transcribe(image_bytes(), page=None, section='image', processing_profile=profile)
assert [b.text for b in blocks] == [b['text'] for b in transcript['blocks']]
assert any(b.warnings for b in blocks)
class RetainedVision:
def transcribe(self, *args, **kw): return blocks
raw = image_bytes('PNG')
with pytest.raises(ReviewRequired) as pending:
PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
assert tuple(pending.value.blocks) == blocks
def test_pending_calibration_is_opt_in_transport_policy(settings, monkeypatch, tmp_path):
from app.api.v1 import live
from app.modules.voice.configuration import VoiceSettings
monkeypatch.setattr(live, 'IngestionSettings', lambda: settings.model_copy(update={'embedding_api_key': 'fixture'}))
report = tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
config = VoiceSettings(_env_file=None,gemini_api_key='fixture',search_calibration_report=report)
with pytest.raises(ValueError, match='CALIBRATION_REQUIRED'): live.capability(config)
assert live.capability(config.model_copy(update={'voice_transport_testing':True})) is None
assert live.search_profile(None, settings)['calibration_status'] == 'uncalibrated'
assert 'distance' not in live.search_profile(None, settings)
@pytest.mark.parametrize('testing',[False,True])
def test_search_dependency_pending_report_keeps_calibration_gate(settings,monkeypatch,tmp_path,testing):
from app.api.v1 import dependencies as d
from app.modules.voice.configuration import VoiceSettings
from app.modules.knowledge.evidence import SearchExecution
from fastapi import HTTPException
report=tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
config=VoiceSettings(_env_file=None,search_calibration_report=report,voice_transport_testing=testing)
monkeypatch.setattr(d,'VoiceSettings',lambda:config)
monkeypatch.setattr(d,'IngestionSettings',lambda:settings)
monkeypatch.setattr(d,'_SEARCH_SERVICE',None)
constructions=[]
def provider(profile):
constructions.append(profile)
return object(),None
monkeypatch.setattr('app.worker.factories',lambda settings:(None,provider))
if not testing:
with pytest.raises(HTTPException) as error: d.get_search_service(object())
assert error.value.status_code==503 and constructions==[]
else:
service=d.get_search_service(object())
assert service.cutoff is None and len(constructions)==1
result=service.search(SearchExecution(uuid4()),'source question')
assert result['sources']==[] and result['error']['code']=='CALIBRATION_REQUIRED'
@pytest.mark.parametrize('failure',['invalid_json','empty','truncated','unreadable_text'])
def test_openrouter_fatal_output_stays_fatal(settings,monkeypatch,failure):
from io import BytesIO
from app.infrastructure.openrouter_vision import OpenRouterVision
from app.modules.documents.extraction import ExtractionError
profile=settings.model_copy(update={'vision_provider':'openrouter','vision_endpoint':'https://example.invalid/v1beta','vision_model':'fixture-flash'}).processing_profile()
blocks=FakeVision().transcribe(b'',page=None,section='image',processing_profile=profile)
transcript={'complete':True,'warnings':[],'blocks':[b.model_dump(mode='json') for b in blocks]}
if failure=='empty': transcript['blocks']=[]
if failure=='unreadable_text': transcript['blocks'][1]['text']='\ufffd'
content='broken json' if failure=='invalid_json' else json.dumps(transcript)
value={'choices':[{'finish_reason':'length' if failure=='truncated' else 'stop','message':{'content':content}}]}
class Opener:
def open(self,request,*,timeout): return BytesIO(json.dumps(value).encode())
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener',lambda *a:Opener())
with pytest.raises(ExtractionError):
OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',api_key='fixture',timeout_seconds=60).transcribe(image_bytes(),page=None,section='image',processing_profile=profile)
+177
View File
@@ -0,0 +1,177 @@
"""Actual escaped JSON/GIL isolation, admission and resource ownership."""
import asyncio
import json
from pathlib import Path
from threading import BoundedSemaphore, Event
import time
import pytest
from fastapi import HTTPException
from app.api.v1 import dependencies as deps
from app.infrastructure import json_processing as processing
from app.modules.documents.review import ReviewDecision
def decision_bytes(count):
groups = tuple(str(i).zfill(5) + '😀' * 495 for i in range(count))
payload = dict(evidence_sha256='a'*64, decision='approve', checked=['factual_authority'],
note='😀'*2000, excluded_group_ids=groups)
return json.dumps(payload, ensure_ascii=True, separators=(',', ':')).encode(), groups
class Request:
headers = {}
def __init__(self, raw):
self.raw = raw
async def stream(self):
for start in range(0, len(self.raw), processing.INLINE_BYTES):
yield self.raw[start:start + processing.INLINE_BYTES]
await asyncio.sleep(0)
@pytest.mark.parametrize('count', [4499, 10000])
def test_real_large_escaped_json_keeps_concurrent_loop_active(count):
raw, groups = decision_bytes(count)
assert 26_000_000 < len(raw) < deps.MAX_DECISION_BYTES
async def run():
gaps, done = [], asyncio.Event()
async def heartbeat():
previous = time.monotonic()
while not done.is_set():
await asyncio.sleep(.01)
now = time.monotonic()
gaps.append(now - previous)
previous = now
tick = asyncio.create_task(heartbeat())
await asyncio.sleep(0)
start = time.monotonic()
try:
result = await deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES)
assert result.excluded_group_ids == groups
assert result.note == '😀'*2000
assert result.model_fields_set == {'evidence_sha256', 'decision', 'checked', 'note', 'excluded_group_ids'}
await asyncio.sleep(.01)
finally:
done.set()
await tick
print(f'JSON_RESPONSIVENESS bytes={len(raw)} elapsed_ms={(time.monotonic()-start)*1000:.2f} '
f'ticks={len(gaps)} max_gap_ms={max(gaps)*1000:.2f}')
# Actual decode/loads/validation + result transfer, not a sleeping mock.
# The old 187/561 ms stalls exceed this bound; all processing is covered.
assert len(gaps) >= 5
assert max(gaps) < .1
asyncio.run(run())
@pytest.mark.parametrize('stop', ['cancel', 'timeout'])
def test_admission_retained_until_cancelled_disk_work_and_spool_release(monkeypatch, stop):
slots = BoundedSemaphore(1)
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
entered, release = Event(), Event()
paths = []
original = deps.owned_io
async def disk(function, *args):
if function.__name__ == 'write' and not entered.is_set():
paths.append(Path(function.__self__.name).parent)
def blocked():
entered.set()
assert release.wait(3)
return function(*args)
return await original(blocked)
return await original(function, *args)
monkeypatch.setattr(deps, 'owned_io', disk)
raw, _ = decision_bytes(100)
async def run():
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES,
timeout_seconds=.05 if stop == 'timeout' else 3))
try:
assert await asyncio.to_thread(entered.wait, 1)
if stop == 'cancel':
task.cancel()
with pytest.raises(asyncio.CancelledError): await task
else:
with pytest.raises(HTTPException) as exc: await task
assert exc.value.status_code == 503
with pytest.raises(HTTPException) as exc:
await deps.receive_json(Request(b'{}'), ReviewDecision, deps.MAX_DECISION_BYTES)
assert exc.value.status_code == 429 and paths[0].exists()
finally:
release.set()
async with asyncio.timeout(2):
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
slots.release()
assert not paths[0].exists()
asyncio.run(run())
def test_cancel_during_child_creation_reaps_child_before_releasing_admission(monkeypatch):
slots = BoundedSemaphore(1)
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
original = processing.asyncio.create_subprocess_exec
children = []
async def run():
entered, release = asyncio.Event(), asyncio.Event()
async def spawn(*args, **kwargs):
child = await original(*args, **kwargs)
children.append(child)
entered.set()
await release.wait()
return child
monkeypatch.setattr(processing.asyncio, 'create_subprocess_exec', spawn)
raw, _ = decision_bytes(100)
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
await asyncio.wait_for(entered.wait(), 2)
task.cancel()
with pytest.raises(asyncio.CancelledError): await task
await asyncio.sleep(0)
assert not slots.acquire(blocking=False)
release.set()
async with asyncio.timeout(2):
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
slots.release()
assert children[0].returncode is not None
asyncio.run(run())
@pytest.mark.parametrize('raw', [b'{"bad":' + b' '*70000, b'\xff'*70000,
b'{"note":"' + b'x'*70000 + b'"}'],
ids=["malformed-json", "invalid-utf8", "invalid-dto"])
def test_large_malformed_or_invalid_dto_is_safe(raw):
with pytest.raises(HTTPException) as exc:
asyncio.run(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
assert exc.value.status_code == 422 and exc.value.detail['code'] == 'VALIDATION_ERROR'
def test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes(monkeypatch):
from app.api.v1 import documents
from fastapi import Response
from types import SimpleNamespace
from uuid import uuid4
slots = BoundedSemaphore(1)
monkeypatch.setattr(documents, '_DECISION_SLOTS', slots)
entered, release, finished = Event(), Event(), Event()
def commit(*args, **kwargs):
entered.set()
assert release.wait(3)
finished.set()
return {'decision': 'approve'}
services = SimpleNamespace(review=SimpleNamespace(decide=commit))
user = SimpleNamespace(id=uuid4(), organization_id=uuid4())
raw, _ = decision_bytes(1)
async def call():
return await documents.decide(uuid4(), Request(raw), Response(), user, services, uuid4(), None)
async def run():
task = asyncio.create_task(call())
try:
assert await asyncio.to_thread(entered.wait, 1)
task.cancel()
with pytest.raises(asyncio.CancelledError): await task
with pytest.raises(HTTPException) as exc: await call()
assert exc.value.status_code == 429 and not finished.is_set()
finally:
release.set()
assert await asyncio.to_thread(finished.wait, 1)
async with asyncio.timeout(1):
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
slots.release()
asyncio.run(run())
+92
View File
@@ -0,0 +1,92 @@
"""Frozen OCR admission: automatic validation, legacy policy and non-OCR gates."""
import hashlib
from uuid import uuid4
import pytest
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired, ExtractionError
from app.modules.documents.worker import validate_source
from app.modules.documents.extraction_artifacts import ocr_review_required
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
from tests.support.extraction import FakeVision, pdf_bytes
from tests.support.formats import image_bytes
def profile(settings, required):
value = settings.model_copy(update={'ocr_review_required': required}).processing_profile()
value['extraction']['vision'] = dict(provider='gemini', endpoint='https://test.invalid', model='fixture-flash', timeout_seconds=5)
return value
@pytest.mark.parametrize('kind', ['png', 'jpeg', 'scan'])
@pytest.mark.parametrize('required', [True, False, None])
def test_ocr_gate_and_worker_source_validation(settings, kind, required):
frozen = profile(settings, required is not False)
if required is None:
frozen['extraction'].pop('ocr_review_required')
content = image_bytes('JPEG' if kind == 'jpeg' else 'PNG')
mime = 'image/jpeg' if kind == 'jpeg' else 'image/png'
if kind == 'scan':
content = pdf_bytes([[('image', content, 10, 20)]])
mime = 'application/pdf'
doc = dict(id=uuid4(), title='OCR', file_sha256=hashlib.sha256(content).hexdigest(), processing_profile=frozen, mime_type=mime)
kwargs = dict(document_id=doc['id'], title=doc['title'], original_sha256=doc['file_sha256'], content=content, mime_type=mime, processing_profile=frozen)
if required is not False:
with pytest.raises(ReviewRequired):
PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
else:
envelope = PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
assert envelope.quality_decision == 'passed' and not envelope.review_annotations
validate_source(envelope, doc, content)
legacy = dict(frozen, extraction={k: v for k, v in frozen['extraction'].items() if k != 'ocr_review_required'})
with pytest.raises(ExtractionError):
validate_source(envelope, dict(doc, processing_profile=legacy), content)
@pytest.mark.parametrize('warning', ['Uncertain order', 'unreadable region', 'ناخوانا'])
def test_disabling_supervisor_preserves_quality_failures(settings, warning):
frozen = profile(settings, False)
content = image_bytes('PNG')
with pytest.raises(ReviewRequired):
PageBlockExtractor(FakeVision(warnings=(warning,))).extract_for_review(document_id=uuid4(), title='OCR',
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=frozen)
@pytest.mark.parametrize('text,model', [('', 'fixture-flash'), ('\ufffd', 'fixture-flash'), ('[TODO]', 'fixture-flash'), ('Evidence', 'wrong-model')])
def test_automatic_validation_is_not_waived(settings, text, model):
content = image_bytes('PNG')
with pytest.raises(ValueError):
PageBlockExtractor(FakeVision(text=text, actual_model=model)).extract_for_review(document_id=uuid4(), title='OCR',
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=profile(settings, False))
def test_direct_pdf_still_needs_review(settings):
content = pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]])
with pytest.raises(ReviewRequired):
PageBlockExtractor().extract_for_review(document_id=uuid4(), title='PDF', original_sha256=hashlib.sha256(content).hexdigest(),
content=content, mime_type='application/pdf', processing_profile=profile(settings, False))
def test_factual_approval_independent(settings):
frozen = profile(settings, False)
content = b'Question: fee?\nAnswer: 5%\n'
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ', original_sha256=hashlib.sha256(content).hexdigest(),
content=content, mime_type='text/markdown', processing_profile=frozen)
with pytest.raises(FactualReviewRequired):
prepare_chunks(envelope, frozen, {}, 'a' * 64)
@pytest.mark.parametrize('bad', [None, 'false', 0, 1, []])
def test_invalid_snapshot_fails_closed(settings, bad):
frozen = profile(settings, False); frozen['extraction']['ocr_review_required'] = bad
with pytest.raises(ValueError):
ocr_review_required(frozen)
def test_setting_defaults_and_enqueue_snapshot(settings, monkeypatch):
assert settings.ocr_review_required is True
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'false')
values = settings.model_dump(); values.pop('ocr_review_required')
configured = type(settings)(_env_file=None, **values)
frozen = configured.processing_profile()
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'true')
assert ocr_review_required(frozen) is False
assert type(settings)(_env_file=None, **values).ocr_review_required is True
+1 -1
View File
@@ -19,7 +19,7 @@ def test_gemini_configuration_requires_no_openai_voice_key(monkeypatch):
assert config.provider=='gemini' and config.profile()['model']=='intended-profile' assert config.provider=='gemini' and config.profile()['model']=='intended-profile'
assert 'fixture' not in repr(config) assert 'fixture' not in repr(config)
@pytest.mark.parametrize('changes', [{'provider':'openai'},{'trusted_origins':['http://evil/path']}, @pytest.mark.parametrize('changes', [{'provider':'unknown'},{'trusted_origins':['http://evil/path']},
{'trusted_hosts':['*']},{'gemini_proxy':'https://user:secret@proxy'}, {'trusted_hosts':['*']},{'gemini_proxy':'https://user:secret@proxy'},
{'trusted_origins':['https://prod.example'],'cookie_secure':False},{'live_session_seconds':0}]) {'trusted_origins':['https://prod.example'],'cookie_secure':False},{'live_session_seconds':0}])
def test_invalid_configuration_fails_before_remote_setup(changes): def test_invalid_configuration_fails_before_remote_setup(changes):
@@ -0,0 +1,157 @@
"""Selected-provider construction, authority truthfulness and continuous idle admission."""
import asyncio
from types import SimpleNamespace
from uuid import uuid4
import pytest
from sqlalchemy.exc import OperationalError
from app.modules.voice.configuration import VoiceSettings
from app.infrastructure import voice_provider
from app.infrastructure.gemini_live import GeminiLiveAdapter
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup
from tests.unit.test_realtime_phase1 import runner, persisted, until
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
def test_selected_credentials_factory_profile_and_native_audio(provider,adapter,rate,monkeypatch):
config=VoiceSettings(_env_file=None,provider=provider,**{('gemini_api_key' if provider=='gemini' else 'openai_realtime_api_key'):'fake-only'})
config.require_voice()
with pytest.raises(ValueError,match='LIVE_PROVIDER_UNAVAILABLE'):
VoiceSettings(_env_file=None,provider=provider).require_voice()
wire=FakeGoogleTransport();seen=[]
async def connect(*args):seen.append(args);return wire
monkeypatch.setattr(voice_provider,'connect_'+provider,connect)
async def scenario():
selected=await voice_provider.create_adapter(config,RuntimeSettings())
assert isinstance(selected,adapter)
assert seen[0][:3]==('fake-only',config.selected_model,config.selected_proxy)
assert config.profile()['input_sample_rate']==rate
setup=selected.setup()
if provider=='openai':
assert setup['session']['audio']['input']['format']['rate']==24000
await selected.send({'type':'input_audio_buffer.append','audio':'AAAA'})
assert wire.sent[-1]['audio']=='AAAA'
await selected.send({'type':'conversation.item.truncate','item_id':'private','content_index':0,'audio_end_ms':5})
assert wire.sent[-1]['audio_end_ms']==5
await selected.close();assert wire.closed==1
asyncio.run(scenario())
def test_provider_alias_priority_conflicts_and_embedding_independence(monkeypatch,tmp_path):
monkeypatch.setenv('PROVIDER','gemini');monkeypatch.setenv('VOICE_PROVIDER','gemini')
monkeypatch.setenv('OPENAI_API_KEY','embedding-only')
assert VoiceSettings(_env_file=None).provider=='gemini'
assert VoiceSettings(_env_file=None,provider='openai').provider=='openai'
monkeypatch.setenv('VOICE_PROVIDER','openai')
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=None)
monkeypatch.delenv('PROVIDER')
assert not VoiceSettings(_env_file=None).openai_realtime_api_key.get_secret_value()
env=tmp_path/'.env';env.write_text('PROVIDER=gemini\n')
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=env)
monkeypatch.delenv('VOICE_PROVIDER');assert VoiceSettings(_env_file=env).provider=='gemini'
with pytest.raises(ValueError,match='Conflicting'):
VoiceSettings(_env_file=None,VOICE_PROVIDER='openai',provider='gemini')
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
(ValueError('SESSION_EXPIRED'),'CONTEXT_REVOKED'),(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),
(ValueError('LIVE_SESSION_EXPIRED'),'CONTEXT_REVOKED'),
(ValueError('ACCOUNT_DISABLED'),'CONTEXT_REVOKED'),
(RuntimeError('private'),'DEPENDENCY_UNAVAILABLE')])
def test_runtime_authority_failure_truthful_and_fail_closed(runner,exc,code):
async def scenario():
wire=FakeGoogleTransport();out=[]
async def check(_):raise exc
async def emit(e):out.append(e)
r=VoiceRuntime(RealtimeAdapter(wire),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check)
await r.start()
assert not r.usable and r.failure==code and not wire.sent
await r.close()
assert all(not isinstance(e,bytes) for e in out)
asyncio.run(scenario())
def test_actual_authority_check_deadline(runner):
async def scenario():
wire=FakeGoogleTransport()
async def check(_):await asyncio.Event().wait()
async def emit(_):pass
limits=RuntimeSettings(_env_file=None,authority_timeout_seconds=.01)
r=VoiceRuntime(RealtimeAdapter(wire,settings=limits),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check,settings=limits)
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
asyncio.run(scenario())
def test_ten_seconds_continuous_uncommitted_silence_keeps_frozen_bound(runner,persisted):
async def scenario():
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
try:
for _ in range(100):
await r.input_audio(bytes(4800))
await until(lambda:r.input_transport_count==0 or not r.usable)
assert r.usable,r.failure
assert r.input_dispatched_total==480000
await r.input_audio(bytes(2))
assert r.failure=='LIVE_BUFFER_OVERFLOW'
assert not any('toolResponse' in m for m in wire.sent)
finally:await cleanup(r,receive)
asyncio.run(scenario())
def test_selected_openai_actual_runtime_tool_audio_continuation_and_truncation(settings,monkeypatch,runner,persisted):
from tests.unit.test_realtime_phase1 import input_turn,response,call,done,delta,commands
from tests.unit.test_search_phase2 import service,row
search=service(settings,monkeypatch,[row()]);wire=FakeGoogleTransport();out=[]
async def connect(*_):return wire
monkeypatch.setattr(voice_provider,'connect_openai',connect)
async def scenario():
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only')
adapter=await voice_provider.create_adapter(config,RuntimeSettings())
async def emit(e):out.append(e)
async def authority(execution):return execution.capture(dict(id=execution.user_id,organization_id='fixture',role='user'),1)
r=VoiceRuntime(adapter,search,runner,uuid4(),emit,authority_check=authority)
try:
await r.start();await until(lambda:commands(wire,'session.update'))
assert not r.ready
await r.handle({'type':'session.updated','session':adapter.setup()['session']});await until(lambda:r.ready)
await input_turn(r);await response(r,wire)
await r.handle(call());await done(r)
await until(lambda:len(commands(wire,'response.create'))==2)
result=commands(wire,'conversation.item.create')[0]['item']
import json
assert json.loads(result['output'])['status']=='ok'
await response(r,wire,'r2');await r.handle(delta(960,response_id='r2',item_id='a2'))
await until(lambda:any(isinstance(e,bytes) for e in out))
started=next(e for e in out if isinstance(e,dict) and e['type']=='audio_started')
await r.client_control(__import__('json').dumps(dict(type='playback_progress',audio_ref=started['audio_ref'],played_ms=5)).encode())
await input_turn(r,item='u2',start=200)
await until(lambda:commands(wire,'response.cancel'))
await done(r,'r2',status='cancelled')
await until(lambda:commands(wire,'conversation.item.truncate'))
assert commands(wire,'conversation.item.truncate')[0]['audio_end_ms']==5
assert r.usable,r.failure
finally:await r.close()
assert wire.closed==1
asyncio.run(scenario())
@pytest.mark.parametrize('phase',['release','output'])
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
(ValueError('CONTEXT_REVOKED'),'CONTEXT_REVOKED')])
def test_authority_failure_suppresses_response_release_and_output(phase,exc,code,runner,persisted):
from tests.unit.test_realtime_phase1 import make as openai_make,input_turn,response,delta,commands
async def scenario():
r,wire,out=await openai_make(SimpleNamespace(engine=None),runner,persisted)
try:
async def unavailable(_):raise exc
if phase=='release':
r.authority_check=unavailable
await input_turn(r)
else:
await input_turn(r);await response(r,wire)
r.authority_check=unavailable
await r.handle(delta(960))
await asyncio.wait_for(r.failure_signal.wait(),2)
assert r.failure==code
assert not any(isinstance(e,bytes) or (isinstance(e,dict) and e.get('type') in ('transcript','sources','audio_started')) for e in out)
if phase=='release':assert not commands(wire,'response.create')
finally:await r.close()
asyncio.run(scenario())
+4 -2
View File
@@ -154,9 +154,11 @@ def test_rejected_direct_reading_order_falls_back_without_guessing(profile):
@pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"]) @pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"])
def test_image_unreadable_regions_fail_before_chunks(profile, warning): def test_image_region_warnings_retain_candidate_without_chunks(profile, warning):
with pytest.raises(ExtractionError, match="unreadable"): with pytest.raises(ReviewRequired) as pending:
extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,))) extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,)))
assert any(warning in b.warnings for b in pending.value.blocks)
assert all(b.text.strip() for b in pending.value.blocks)
def test_infographic_parent_children_and_order(profile): def test_infographic_parent_children_and_order(profile):
@@ -0,0 +1,42 @@
"""Framework preparation must precede live admission and tool deadlines."""
import asyncio
from threading import get_ident
from types import SimpleNamespace
from app.main import lifespan
from app.api.v1 import dependencies
def test_framework_prepared_off_loop_before_reconciliation_and_readiness(monkeypatch):
app = SimpleNamespace(state=SimpleNamespace(ready=False))
order = []
loop_thread = get_ident()
prepare = dependencies.prepare_search_tools
def framework():
assert not app.state.ready and get_ident() != loop_thread
prepare()
order.append('framework')
def reconcile():
assert order == ['framework'] and not app.state.ready
order.append('reconcile')
monkeypatch.setattr(dependencies, 'prepare_search_tools', framework)
monkeypatch.setattr(dependencies, 'get_engine', lambda: SimpleNamespace(dispose=lambda: order.append('dispose')))
monkeypatch.setattr(dependencies, 'get_lifecycle_service', lambda engine: SimpleNamespace(reconcile_startup=reconcile))
monkeypatch.setattr(dependencies, '_TOOL_RUNNER', None)
async def run():
async with lifespan(app):
assert order == ['framework', 'reconcile'] and app.state.ready
assert not app.state.ready and order[-1] == 'dispose'
asyncio.run(run())
def test_document_only_installation_keeps_framework_optional(monkeypatch):
import builtins
from app.modules.knowledge.langchain_tool import prepare_search_tools
original = builtins.__import__
def optional(name, *args, **kwargs):
if name == 'langchain_core.tools':
raise ModuleNotFoundError(name='langchain_core')
return original(name, *args, **kwargs)
monkeypatch.setattr(builtins, '__import__', optional)
assert prepare_search_tools() is None
+459
View File
@@ -0,0 +1,459 @@
"""Regression coverage for Phase 3 repairs: body admission, Unicode filenames, proxy configs."""
import asyncio
import json
import tempfile
from pathlib import Path
from unittest.mock import MagicMock
from uuid import UUID, uuid4
import httpx
import pytest
from app.main import app
from app.api.v1 import dependencies
from app.api.v1.dependencies import (
MAX_DECISION_BYTES, MAX_SELECTION_BYTES,
receive_json, receive_empty,
)
from app.api.v1.documents import get_document_services
from app.api.v1.uploads import receive_upload
from app.modules.auth.service import UserContext
from app.modules.documents.intake import (
IntakeError, prepare_file, replay_payload_hash, normalized_title,
)
from app.modules.documents.review import ReviewDecision
from app.api.v1.knowledge import SelectionRequest
from app.modules.voice.configuration import VoiceSettings
from tests.unit.test_upload_boundary import Request as UploadRequest, multipart
@pytest.fixture
def test_admin():
return UserContext(
id=uuid4(), organization_id=uuid4(), username='admin', role='admin',
is_enabled=True, auth_session_id=uuid4(), access_epoch=1,
)
@pytest.fixture
def auth_overrides(test_admin):
app.state.ready = True
app.dependency_overrides[dependencies.require_admin] = lambda: test_admin
app.dependency_overrides[dependencies.require_csrf] = lambda: None
mock_services = MagicMock()
app.dependency_overrides[get_document_services] = lambda: mock_services
app.dependency_overrides[dependencies.get_engine] = lambda: MagicMock()
yield mock_services
app.dependency_overrides.clear()
def test_unauthenticated_admission_zero_bytes_consumed():
app.state.ready = True
mock_auth = MagicMock()
mock_auth.get_current_user.side_effect = ValueError('No session')
app.dependency_overrides[dependencies.get_auth_service] = lambda: mock_auth
bytes_consumed = 0
async def counting_app(scope, receive, send):
nonlocal bytes_consumed
async def counting_receive():
nonlocal bytes_consumed
msg = await receive()
if msg.get('type') == 'http.request':
bytes_consumed += len(msg.get('body', b''))
return msg
await app(scope, counting_receive, send)
async def stream_8mb():
for _ in range(128):
yield b'X' * 65536
async def run():
nonlocal bytes_consumed
transport = httpx.ASGITransport(app=counting_app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
# 1. Decisions route unauthenticated
bytes_consumed = 0
doc_id = str(uuid4())
res1 = await client.post(
f'/api/v1/documents/{doc_id}/extraction-review/decisions',
content=stream_8mb(),
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())}
)
assert res1.status_code == 401
assert res1.json()['error']['code'] == 'AUTH_REQUIRED'
assert bytes_consumed == 0
# 2. Knowledge selection route unauthenticated
bytes_consumed = 0
res2 = await client.patch(
'/api/v1/knowledge-selection',
content=stream_8mb(),
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
)
assert res2.status_code == 401
assert res2.json()['error']['code'] == 'AUTH_REQUIRED'
assert bytes_consumed == 0
try:
asyncio.run(run())
finally:
app.dependency_overrides.clear()
def test_streamed_oversized_json_rejection(auth_overrides):
async def stream_oversized(size):
remaining = size
chunk = 65536
while remaining > 0:
yield b' ' * min(chunk, remaining)
remaining -= chunk
async def run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
# Decisions exceeding MAX_DECISION_BYTES (DTO-derived bound)
res1 = await client.post(
f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
content=stream_oversized(MAX_DECISION_BYTES + 1024),
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())}
)
assert res1.status_code == 413
assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
# Selection exceeding MAX_SELECTION_BYTES (1 MiB)
res2 = await client.patch(
'/api/v1/knowledge-selection',
content=stream_oversized(MAX_SELECTION_BYTES + 1024),
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
)
assert res2.status_code == 413
assert res2.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
asyncio.run(run())
def test_absent_and_misleading_content_length(auth_overrides):
async def run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
# 1. Content-Length header declaring oversized payload (e.g. 10 MB)
res1 = await client.post(
f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
content=b'{}',
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
'Content-Length': str(MAX_DECISION_BYTES + 1), 'Idempotency-Key': str(uuid4())}
)
assert res1.status_code == 413
assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
# 2. Misleading Content-Length (Content-Length smaller than actual received bytes)
valid_payload = json.dumps({'expected_revision': 1, 'document_ids': []}).encode()
res2 = await client.patch(
'/api/v1/knowledge-selection',
content=valid_payload,
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
'Content-Length': str(len(valid_payload) - 5)}
)
assert res2.status_code == 422
assert res2.json()['error']['code'] == 'VALIDATION_ERROR'
# 3. Negative or invalid Content-Length
res3 = await client.patch(
'/api/v1/knowledge-selection',
content=valid_payload,
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
'Content-Length': '-1'}
)
assert res3.status_code == 422
assert res3.json()['error']['code'] == 'VALIDATION_ERROR'
asyncio.run(run())
def test_slow_body_receive_timeout(auth_overrides, monkeypatch):
monkeypatch.setattr(dependencies, 'JSON_RECEIVE_SECONDS', 0.05)
async def slow_stream():
yield b'{"expected_revision":'
await asyncio.sleep(0.1)
yield b' 1, "document_ids": []}'
async def run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
res = await client.patch(
'/api/v1/knowledge-selection',
content=slow_stream(),
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
)
assert res.status_code == 503
assert res.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE'
asyncio.run(run())
def test_valid_large_dtos(auth_overrides):
# 1. 10,000 UUIDs in SelectionRequest (~400 KB)
doc_ids = [uuid4() for _ in range(10000)]
sel = SelectionRequest(expected_revision=1, document_ids=doc_ids)
assert len(sel.document_ids) == 10000
serialized_sel = json.dumps({'expected_revision': 1, 'document_ids': [str(u) for u in doc_ids]}).encode()
assert len(serialized_sel) < MAX_SELECTION_BYTES
# 2. 10,000 excluded group IDs in ReviewDecision (~500 KB)
group_ids = tuple(f'group_{i}' for i in range(10000))
rev = ReviewDecision(
evidence_sha256='a' * 64,
decision='approve',
checked=('factual_authority',),
note='Validated 10,000 exclusions',
excluded_group_ids=group_ids,
)
assert len(rev.excluded_group_ids) == 10000
serialized_rev = json.dumps(rev.model_dump(mode='json')).encode()
assert len(serialized_rev) < MAX_DECISION_BYTES
def test_retry_admission_and_cancellation(auth_overrides, monkeypatch):
mock_services = auth_overrides
async def run():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
# 1. Nonempty body rejected before worker retry
res1 = await client.post(
f'/api/v1/documents/{uuid4()}/retry',
content=b'data',
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())}
)
assert res1.status_code == 422
assert res1.json()['error']['code'] == 'VALIDATION_ERROR'
assert mock_services.worker.retry.call_count == 0
# 2. Content-Length > 0 rejected before worker retry
res2 = await client.post(
f'/api/v1/documents/{uuid4()}/retry',
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4()), 'Content-Length': '10'}
)
assert res2.status_code == 422
assert res2.json()['error']['code'] == 'VALIDATION_ERROR'
assert mock_services.worker.retry.call_count == 0
# 3. Stalled / unfinished retry body times out with 503
monkeypatch.setattr(dependencies, 'RETRY_RECEIVE_SECONDS', 0.05)
async def stalled():
await asyncio.sleep(0.1)
yield b''
res3 = await client.post(
f'/api/v1/documents/{uuid4()}/retry',
content=stalled(),
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())}
)
assert res3.status_code == 503
assert res3.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE'
assert mock_services.worker.retry.call_count == 0
# 4. Cancelled retry stream does not invoke worker
class CancelledRequest:
headers = {}
async def stream(self):
yield b''
raise asyncio.CancelledError()
with pytest.raises(asyncio.CancelledError):
await receive_empty(CancelledRequest())
assert mock_services.worker.retry.call_count == 0
asyncio.run(run())
def test_unicode_filename_boundary_and_replay_preservation(settings):
with tempfile.TemporaryDirectory() as td:
file_path = Path(td) / 'payload'
content = b'# Heading\nBody text.'
file_path.write_bytes(content)
# 128 Arabic chars + .md = 131 chars, 259 UTF-8 bytes (exceeds 255-byte filesystem limit)
long_name = 'س' * 128 + '.md'
assert len(long_name) == 131
assert len(long_name.encode('utf-8')) == 259
# Prepare with no title: default title is NFC normalized stem
prepared = prepare_file(file_path, None, settings, filename=long_name)
assert prepared['filename'] == long_name
assert prepared['title'] == 'س' * 128
assert len(prepared['title']) == 128
# Replay payload hash matches
replay_hash = replay_payload_hash(file_path, None, len(content), filename=long_name)
assert replay_hash == prepared['payload_hash']
# Replay with changed title produces different hash
changed_title_hash = replay_payload_hash(file_path, 'Other', len(content), filename=long_name)
assert changed_title_hash != prepared['payload_hash']
# Replay with changed size produces conflict
with pytest.raises(IntakeError) as exc:
replay_payload_hash(file_path, None, len(content) + 1, filename=long_name)
assert exc.value.code == 'IDEMPOTENCY_CONFLICT'
def test_temporary_file_cleanup_on_upload(settings):
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
# 1. Success cleans spool
async def run_success():
req = UploadRequest(multipart([('file', b'test', 'test.md')]))
async with receive_upload(req, settings) as (path, filename, title):
assert path.exists()
parent = path.parent
assert not parent.exists()
asyncio.run(run_success())
# 2. Rejection cleans spool
async def run_rejection():
req = UploadRequest(multipart([('file', b'too large', 'test.md')]))
with pytest.raises(IntakeError):
async with receive_upload(req, settings.model_copy(update={'max_original_bytes': 3})):
pass
asyncio.run(run_rejection())
def test_documented_proxy_configurations(monkeypatch):
# Config 1: Vite proxy configuration
# Vite proxy preserves browser Host ('localhost:5173') and Origin ('http://localhost:5173')
voice_vite = VoiceSettings(
trusted_hosts=('localhost:5173', '127.0.0.1:5173'),
trusted_origins=('http://localhost:5173', 'http://127.0.0.1:5173'),
cookie_secure=False,
)
monkeypatch.setattr('app.main.config', voice_vite)
async def run_vite():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:5173') as client:
res = await client.get('/health/live', headers={'Host': 'localhost:5173'})
assert res.status_code == 200
# Untrusted host through Vite proxy
res_bad = await client.get('/health/live', headers={'Host': 'untrusted.com'})
assert res_bad.status_code == 403
assert res_bad.json()['error']['code'] == 'FORBIDDEN'
asyncio.run(run_vite())
# Config 2: Direct-run / Docker Compose mapping configuration (port 8080)
voice_direct = VoiceSettings(
trusted_hosts=('localhost:8080', '127.0.0.1:8080'),
trusted_origins=('http://localhost:8080', 'http://127.0.0.1:8080'),
cookie_secure=False,
)
monkeypatch.setattr('app.main.config', voice_direct)
async def run_direct():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8080') as client:
res = await client.get('/health/live', headers={'Host': 'localhost:8080'})
assert res.status_code == 200
res_bad = await client.get('/health/live', headers={'Host': 'evil.invalid'})
assert res_bad.status_code == 403
assert res_bad.json()['error']['code'] == 'FORBIDDEN'
asyncio.run(run_direct())
def test_blocked_selection_keeps_event_loop_responsive(auth_overrides, monkeypatch):
from threading import Event
from app.api.v1 import knowledge
entered, release = Event(), Event()
def stalled(*args):
entered.set()
assert release.wait(3)
return {'revision': 2}
monkeypatch.setattr(knowledge, 'selection_replace', stalled)
async def run():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
task = asyncio.create_task(client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []}))
try:
assert await asyncio.to_thread(entered.wait, 1)
# This coroutine runs while the selection worker still waits.
assert not task.done()
assert (await client.get('/health/live')).status_code == 200
finally:
release.set()
assert (await task).status_code == 200
asyncio.run(run())
@pytest.mark.parametrize('exception, status, code', [
(ValueError('SERVICE_BUSY'), 429, 'RATE_LIMITED'),
(TimeoutError(), 503, 'DEPENDENCY_UNAVAILABLE'),
])
def test_selection_blocking_safe_errors(auth_overrides, monkeypatch, exception, status, code):
from app.api.v1 import knowledge
async def fail(*args):
raise exception
monkeypatch.setattr(knowledge, 'blocking', fail)
async def run():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
response = await client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []})
assert response.status_code == status
assert response.json()['error']['code'] == code
asyncio.run(run())
@pytest.mark.parametrize('ensure_ascii', [False, True])
def test_decision_budget_covers_multibyte_and_escaped_identifiers(ensure_ascii):
ids = tuple(str(i).zfill(5) + '😀"\\' * 165 for i in range(10000))
decision = ReviewDecision(evidence_sha256='a'*64, decision='approve', checked=('factual_authority',),
note='😀'*2000, excluded_group_ids=ids)
raw = json.dumps(decision.model_dump(mode='json'), ensure_ascii=ensure_ascii).encode()
assert 2 * 1024 * 1024 < len(raw) <= MAX_DECISION_BYTES
class Request:
headers = {}
async def stream(self):
for offset in range(0, len(raw), 65536):
yield raw[offset:offset+65536]
assert asyncio.run(receive_json(Request(), ReviewDecision, MAX_DECISION_BYTES)) == decision
def test_json_capacity_checked_before_buffer_extension(monkeypatch):
extended = []
class Buffer(bytearray):
def extend(self, chunk):
extended.append(len(chunk))
super().extend(chunk)
monkeypatch.setattr(dependencies, 'bytearray', Buffer, raising=False)
class Request:
headers = {}
async def stream(self):
yield b' ' * 8
yield b' ' * 9
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc:
asyncio.run(receive_json(Request(), ReviewDecision, 16))
assert exc.value.status_code == 413 and extended == [8]
def test_csrf_rejection_consumes_no_decision_body(test_admin):
app.state.ready = True
app.dependency_overrides[dependencies.require_admin] = lambda: test_admin
app.dependency_overrides[get_document_services] = lambda: MagicMock()
def reject():
raise dependencies.error('CSRF_INVALID')
app.dependency_overrides[dependencies.require_csrf] = reject
consumed = []
async def body():
consumed.append(True)
yield b'{}'
async def run():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
result = await client.post(f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
content=body(), headers={'Idempotency-Key': str(uuid4())})
assert result.status_code == 403 and consumed == []
try:
asyncio.run(run())
finally:
app.dependency_overrides.clear()
+2 -4
View File
@@ -78,7 +78,6 @@ def test_excluded_pairs_and_exclusive_context_are_absent(settings):
@pytest.mark.parametrize("content", [ @pytest.mark.parametrize("content", [
"These answers apply only to permanent employees.\nQuestion: fee?\nAnswer: 5%.\n",
"## Eligibility\nQuestion: fee?\nAnswer: 5%.\n## Exceptions\nContractors are not eligible.\n", "## Eligibility\nQuestion: fee?\nAnswer: 5%.\n## Exceptions\nContractors are not eligible.\n",
"Question: fee?\nAnswer: 5%.\nArticle 2\nOnly permanent employees.\nQuestion: leave?\nAnswer: 10.\n", "Question: fee?\nAnswer: 5%.\nArticle 2\nOnly permanent employees.\nQuestion: leave?\nAnswer: 10.\n",
]) ])
@@ -157,8 +156,7 @@ def test_resume_keeps_note_once_as_bounded_metadata(settings, note):
decision["note"] = "x" * 2001 decision["note"] = "x" * 2001
with pytest.raises(ValueError): with pytest.raises(ValueError):
PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs) PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
body["blocks"][0]["warnings"] = ["unreadable source region"] body["blocks"][0]["text"] = "\ufffd"
decision["note"] = note decision["note"] = note
broken = PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
with pytest.raises(ExtractionError, match="Unreadable"): with pytest.raises(ExtractionError, match="Unreadable"):
validate_source(broken, dict(title="review", mime_type="image/png", processing_profile=profile), raw) PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
+7 -6
View File
@@ -33,6 +33,8 @@ class Transport:
@pytest.fixture @pytest.fixture
def runner(): def runner():
# Match API startup: framework imports precede voice/tool deadlines.
boundary.prepare_search_tools()
value = boundary.SearchToolRunner(running=2, waiting=2, timeout=2) value = boundary.SearchToolRunner(running=2, waiting=2, timeout=2)
yield value yield value
value.close() value.close()
@@ -711,7 +713,7 @@ def test_new_speech_during_normal_tail_cleanup_preserves_completion(runner, pers
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")]) @pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
def test_operator_harness_actual_fake_transport_tool_correlation( def test_operator_harness_actual_fake_transport_tool_correlation(
settings, monkeypatch, runner, persisted, capsys, rows, status): settings, monkeypatch, runner, persisted, capsys, rows, status):
from pydantic import SecretStr from app.modules.voice.configuration import VoiceSettings
from app import voice_smoke from app import voice_smoke
from app.modules.voice import runtime as runtime_module from app.modules.voice import runtime as runtime_module
service = canonical_service(settings, monkeypatch, rows) service = canonical_service(settings, monkeypatch, rows)
@@ -742,11 +744,10 @@ def test_operator_harness_actual_fake_transport_tool_correlation(
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer"))) response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer")))
await self.incoming.put(canonical_json(terminal(rid, output=output))) await self.incoming.put(canonical_json(terminal(rid, output=output)))
transport = Scripted() transport = Scripted()
async def connection(config, limits): async def connection(*args):
return RealtimeAdapter(transport, settings=limits) return transport
monkeypatch.setattr(voice_smoke, "create_adapter", connection) monkeypatch.setattr("app.infrastructure.voice_provider.connect_openai", connection)
config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"), config = VoiceSettings(_env_file=None, provider="openai", openai_realtime_api_key="fake-only")
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0 assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0
logs = [json.loads(line) for line in capsys.readouterr().out.splitlines()] logs = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
correlation = next(e for e in logs if e["type"] == "smoke_correlation") correlation = next(e for e in logs if e["type"] == "smoke_correlation")
+129
View File
@@ -0,0 +1,129 @@
"""Actual parser callbacks and ASGI receive admission, including cancellation cleanup."""
import asyncio
from pathlib import Path
import tempfile
from types import SimpleNamespace
import pytest
from app.api.v1.uploads import receive_upload
from app.modules.documents.errors import IntakeError
def multipart(parts, end=True):
body = b''
for name, value, filename in parts:
disposition = f'Content-Disposition: form-data; name="{name}"'
if filename is not None:
disposition += f'; filename="{filename}"'
body += b'--boundary\r\n' + disposition.encode() + b'\r\n\r\n' + value + b'\r\n'
return body + (b'--boundary--\r\n' if end else b'')
class Request:
headers = {'content-type': 'multipart/form-data; boundary=boundary'}
def __init__(self, body, size=7, cancel=False):
self.body, self.size, self.cancel = body, size, cancel
async def stream(self):
for index in range(0, len(self.body), self.size):
yield self.body[index:index + self.size]
if self.cancel:
raise asyncio.CancelledError()
def test_streamed_upload_and_cleanup(settings):
async def run():
request = Request(multipart([('title', 'سند'.encode(), None), ('file', b'content', 'source.md')]))
async with receive_upload(request, settings) as (path, filename, title):
assert title == 'سند' and filename == 'source.md' and path.name == 'payload' and path.read_bytes() == b'content'
parent = path.parent
assert not parent.exists()
asyncio.run(run())
def test_unicode_filename_exceeding_filesystem_limit(settings):
async def run():
name = 'س' * 128 + '.md'
assert len(name.encode('utf-8')) > 255 # Exceeds Linux NAME_MAX (255 bytes)
assert len(name) <= 255 # Within display character length limit
request = Request(multipart([('file', b'# content', name)]))
async with receive_upload(request, settings) as (path, filename, title):
assert filename == name and path.name == 'payload' and path.read_bytes() == b'# content'
assert title is None
parent = path.parent
assert not parent.exists()
asyncio.run(run())
def test_display_filename_character_boundary(settings):
async def run():
# Exactly 255 display characters
name_255 = 'س' * 252 + '.md'
assert len(name_255) == 255
async with receive_upload(Request(multipart([('file', b'# ok', name_255)])), settings) as (path, filename, title):
assert filename == name_255 and path.name == 'payload'
# 256 display characters exceeds limit
name_256 = 'س' * 253 + '.md'
assert len(name_256) == 256
with pytest.raises(IntakeError) as exc:
async with receive_upload(Request(multipart([('file', b'# fail', name_256)])), settings):
pytest.fail('256-char filename accepted')
assert exc.value.code == 'INVALID_FILE'
asyncio.run(run())
@pytest.mark.parametrize('parts,end,code', [
([('file', b'x' * 21, 'a.md')], True, 'FILE_TOO_LARGE'),
([('title', b'x' * 801, None), ('file', b'a', 'a.md')], True, 'INVALID_FILE'),
([('file', b'a', 'a.md'), ('file', b'b', 'b.md')], True, 'INVALID_FILE'),
([('file', b'a', '../a.md')], True, 'INVALID_FILE'),
([('scope', b'forged', None)], True, 'INVALID_FILE'),
([('file', b'a', 'a.md')], False, 'INVALID_FILE'),
([('title', b'a', None)], True, 'INVALID_FILE'),
([('file', b'a', 'a.md'), ('title', b'a', None), ('other', b'a', None)], True, 'INVALID_FILE'),
])
def test_rejection_cleans_spool(settings, monkeypatch, tmp_path, parts, end, code):
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
async def run():
with pytest.raises(IntakeError) as exc:
async with receive_upload(Request(multipart(parts, end)), settings.model_copy(update={'max_original_bytes': 20})):
pytest.fail('Rejected upload reached intake')
assert exc.value.code == code
assert not list(tmp_path.iterdir())
asyncio.run(run())
def test_disconnect_cleans_spool(settings, monkeypatch, tmp_path):
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
async def run():
with pytest.raises(asyncio.CancelledError):
async with receive_upload(Request(multipart([('file', b'x', 'a.md')]), cancel=True), settings):
pytest.fail('Cancelled upload reached intake')
assert not list(tmp_path.iterdir())
asyncio.run(run())
def test_aggregate_bytes_rejected_before_parser(settings):
async def run():
with pytest.raises(IntakeError) as exc:
async with receive_upload(Request(b'x' * 20000, size=20000), settings.model_copy(update={'max_original_bytes': 20})):
pytest.fail('Oversized request admitted')
assert exc.value.code == 'FILE_TOO_LARGE'
asyncio.run(run())
def test_stalled_receive_releases_spool_and_capacity(settings, monkeypatch, tmp_path):
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
monkeypatch.setattr('app.api.v1.uploads.UPLOAD_RECEIVE_SECONDS', .01)
class Stalled(Request):
async def stream(self):
yield b'--boundary\r\n'
await asyncio.Event().wait()
async def run():
with pytest.raises(IntakeError) as exc:
async with receive_upload(Stalled(b''), settings):
pytest.fail('Stalled body admitted')
assert exc.value.code == 'DEPENDENCY_UNAVAILABLE' and not list(tmp_path.iterdir())
async with receive_upload(Request(multipart([('file', b'x', 'a.md')])), settings):
pass
assert not list(tmp_path.iterdir())
asyncio.run(run())
+7
View File
@@ -41,3 +41,10 @@ def test_delivered_voice_client_async_ownership_errors_logout_and_close():
if not node:pytest.fail('Node is required to exercise VoiceClient') if not node:pytest.fail('Node is required to exercise VoiceClient')
result=subprocess.run([node,str(ROOT/'tests/support/voice_client_harness.mjs'),'unit'],capture_output=True,text=True,timeout=20) result=subprocess.run([node,str(ROOT/'tests/support/voice_client_harness.mjs'),'unit'],capture_output=True,text=True,timeout=20)
assert result.returncode==0,result.stdout+result.stderr assert result.returncode==0,result.stdout+result.stderr
def test_delivered_playback_bounds_and_creation_replay():
node=shutil.which('node')
if not node:pytest.fail('Node is required to exercise the delivered example')
result=subprocess.run([node,str(ROOT/'tests/support/voice_phase2_repairs.mjs')],capture_output=True,text=True,timeout=20)
assert result.returncode==0,result.stdout+result.stderr
@@ -0,0 +1,371 @@
"""Real loopback transport: pre-payload rejection, fragments, compression and backlog."""
import asyncio
import base64
import os
import struct
import pytest
import uvicorn
from websockets.asyncio.client import connect
from websockets.exceptions import ConnectionClosed
from app.modules.voice.runtime import RuntimeSettings
from app.server import server_config
async def serve(scenario, settings=None):
delivered=[]; gate=asyncio.Event();gate.set()
async def app(scope,receive,send):
assert scope['type']=='websocket'
await receive();await send({'type':'websocket.accept'})
while True:
await gate.wait()
message=await receive()
if message['type']=='websocket.disconnect':return
delivered.append(message)
await send({'type':'websocket.send','text':'accepted'})
server=uvicorn.Server(server_config(app,port=0,lifespan='off',log_level='error',settings=settings))
task=asyncio.create_task(server.serve())
try:
async with asyncio.timeout(3):
while not server.started:await asyncio.sleep(.001)
port=server.servers[0].sockets[0].getsockname()[1]
await scenario(port,delivered,gate,server)
finally:
gate.set();server.should_exit=True
await asyncio.wait_for(task,5)
@pytest.mark.parametrize('binary', [False,True])
def test_valid_and_fragmented_message_boundaries(binary):
async def scenario(port,delivered,gate,server):
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
value=bytes(9600) if binary else 'é'*2048
await ws.send(value);assert await ws.recv()=='accepted'
await ws.send([value[:len(value)//2],value[len(value)//2:]])
assert await ws.recv()=='accepted';assert len(delivered)==2
assert delivered[-1]['bytes' if binary else 'text']==value
asyncio.run(serve(scenario))
@pytest.mark.parametrize('binary,fragmented',[(False,False),(True,False),(False,True),(True,True)])
def test_oversized_messages_are_never_delivered(binary,fragmented):
async def scenario(port,delivered,gate,server):
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
value=bytes(9602) if binary else 'é'*2049
await ws.send([value[:len(value)//2],value[len(value)//2:]] if fragmented else value)
with pytest.raises(ConnectionClosed) as exc:await ws.recv()
assert exc.value.rcvd.code==1009 and not delivered
asyncio.run(serve(scenario))
@pytest.mark.parametrize('opcode,size,code',[(2,9601,1009),(1,4097,1009),(0x42,100,1002)])
def test_header_only_rejection_precedes_payload_allocation(opcode,size,code):
async def scenario(port,delivered,gate,server):
reader,writer=await asyncio.open_connection('127.0.0.1',port)
try:
key=base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n').encode());await writer.drain()
response=await reader.readuntil(b'\r\n\r\n')
assert b'101 Switching Protocols' in response
assert b'sec-websocket-extensions' not in response.lower()
# No mask or payload is sent: rejection must occur from declared length/RSV alone.
writer.write(bytes([0x80|opcode,0x80|126])+struct.pack('!H',size));await writer.drain()
head=await asyncio.wait_for(reader.readexactly(2),1)
assert head[0]==0x88
payload=await reader.readexactly(head[1]&127)
assert struct.unpack('!H',payload[:2])[0]==code and not delivered
finally:writer.close();await writer.wait_closed()
asyncio.run(serve(scenario))
def test_installed_backend_queue_is_bounded_and_compression_not_negotiated():
async def scenario(port,delivered,gate,server):
async with connect(f'ws://127.0.0.1:{port}',compression='deflate',proxy=None) as ws:
assert not ws.protocol.extensions
await ws.send(b'first');await ws.recv()
gate.clear()
# One ASGI receive may already be waiting; the remainder must backpressure.
for _ in range(30):await ws.send(bytes(9600))
await asyncio.sleep(.05)
protocol=next(iter(server.server_state.connections))
assert protocol.max_queue==8 and len(protocol.messages)<=8
assert protocol.max_size==9600 and not protocol.extensions
gate.set()
for _ in range(30):assert await asyncio.wait_for(ws.recv(),2)=='accepted'
assert len(delivered)==31
asyncio.run(serve(scenario))
def test_bounded_fragment_reassembly_long_empty_and_tiny_sequences():
async def scenario(port, delivered, gate, server):
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
# 20,001 empty continuation frames reassembled without unbounded metadata growth
empty_chunks = [b''] * 20001
await ws.send(empty_chunks)
assert await ws.recv() == 'accepted'
assert delivered[-1]['bytes'] == b''
conn = next(iter(server.server_state.connections))
assert conn.assembling_scratch is None
# Tiny fragment sequence exact boundary: 96 fragments of 100 bytes = 9600 bytes binary
binary_chunks = [b'x' * 100] * 96
await ws.send(binary_chunks)
assert await ws.recv() == 'accepted'
assert delivered[-1]['bytes'] == b'x' * 9600
assert conn.assembling_scratch is None
# Tiny fragment sequence exact boundary: 64 fragments of 64 bytes = 4096 bytes UTF-8
text_chunks = ['a' * 64] * 64
await ws.send(text_chunks)
assert await ws.recv() == 'accepted'
assert delivered[-1]['text'] == 'a' * 4096
assert conn.assembling_scratch is None
asyncio.run(serve(scenario))
def test_interleaved_protocol_controls_during_fragmentation():
async def scenario(port, delivered, gate, server):
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
assert b'101 Switching Protocols' in await reader.readuntil(b'\r\n\r\n')
# Send fragment 1 (opcode 2, fin=0, data=b'first ')
writer.write(bytes([0x02, 0x80 | 6, 0, 0, 0, 0]) + b'first ')
await writer.drain()
await asyncio.sleep(0.01)
conn = next(iter(server.server_state.connections))
assert conn.assembling_scratch == bytearray(b'first ')
# Client sends Ping control frame (opcode 9)
writer.write(bytes([0x89, 0x80 | 4, 0, 0, 0, 0]) + b'ping')
await writer.drain()
# Client receives Pong control frame (opcode 10)
head = await asyncio.wait_for(reader.readexactly(2), 2)
assert head[0] == 0x8A
pong_len = head[1] & 127
assert await reader.readexactly(pong_len) == b'ping'
# Send fragment 2 (opcode 0, fin=1, data=b'second')
writer.write(bytes([0x80, 0x80 | 6, 0, 0, 0, 0]) + b'second')
await writer.drain()
head = await asyncio.wait_for(reader.readexactly(2), 2)
assert head[0] == 0x81
reply = await reader.readexactly(head[1] & 127)
assert reply == b'accepted'
assert delivered[-1]['bytes'] == b'first second'
assert conn.assembling_scratch is None
finally:
writer.close()
await writer.wait_closed()
asyncio.run(serve(scenario))
def test_malformed_fragmentation_sequences_and_resource_cleanup():
async def scenario(port, delivered, gate, server):
# 1. Unexpected continuation (opcode 0 without starting frame) -> 1002
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
await reader.readuntil(b'\r\n\r\n')
writer.write(bytes([0x80, 0x80 | 4, 0, 0, 0, 0]) + b'cont')
await writer.drain()
head = await asyncio.wait_for(reader.readexactly(2), 2)
assert head[0] == 0x88
payload = await reader.readexactly(head[1] & 127)
assert struct.unpack('!H', payload[:2])[0] == 1002 and not delivered
finally:
writer.close()
await writer.wait_closed()
# 2. Interleaved data frame during fragmentation -> 1002
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
await reader.readuntil(b'\r\n\r\n')
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'part')
await writer.drain()
await asyncio.sleep(0.01)
writer.write(bytes([0x81, 0x80 | 4, 0, 0, 0, 0]) + b'text')
await writer.drain()
head = await asyncio.wait_for(reader.readexactly(2), 2)
assert head[0] == 0x88
payload = await reader.readexactly(head[1] & 127)
assert struct.unpack('!H', payload[:2])[0] == 1002
finally:
writer.close()
await writer.wait_closed()
# 3. Unfinished message: client disconnect releases scratch resources
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
await reader.readuntil(b'\r\n\r\n')
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'frag')
await writer.drain()
await asyncio.sleep(0.01)
conn = next(iter(server.server_state.connections))
assert conn.assembling_scratch is not None
finally:
writer.close()
await writer.wait_closed()
await asyncio.sleep(0.05)
assert conn.assembling_scratch is None
asyncio.run(serve(scenario))
def test_lower_trusted_runtime_limits_and_prepayload_rejection():
settings = RuntimeSettings(
max_binary_message_bytes=1200,
max_client_control_bytes=500,
output_credit_window_bytes=1200,
max_queued_audio_bytes=2400,
max_queued_audio_messages=10,
)
async def scenario(port, delivered, gate, server):
# 1. Header-only pre-payload rejection on lowered binary limit (1201 > 1200) and text limit (501 > 500)
for opcode, size in [(2, 1201), (1, 501)]:
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain()
await reader.readuntil(b'\r\n\r\n')
# Header only: no mask, no payload
writer.write(bytes([0x80 | opcode, 0x80 | 126]) + struct.pack('!H', size))
await writer.drain()
head = await asyncio.wait_for(reader.readexactly(2), 2)
assert head[0] == 0x88
payload = await reader.readexactly(head[1] & 127)
assert struct.unpack('!H', payload[:2])[0] == 1009 and not delivered
finally:
writer.close()
await writer.wait_closed()
# 2. Exact lower limits (1200 binary and 500 text) are accepted
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
await ws.send(bytes(1200))
assert await ws.recv() == 'accepted'
assert len(delivered[-1]['bytes']) == 1200
await ws.send('c' * 500)
assert await ws.recv() == 'accepted'
assert delivered[-1]['text'] == 'c' * 500
asyncio.run(serve(scenario, settings=settings))
def test_small_message_budgets_one_and_two_deadlock_free():
# Message budget of 1
settings_1 = RuntimeSettings(
max_binary_message_bytes=1200,
max_client_control_bytes=500,
output_credit_window_bytes=1200,
max_queued_audio_bytes=2400,
max_queued_audio_messages=1,
)
async def scenario_1(port, delivered, gate, server):
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
conn = next(iter(server.server_state.connections))
assert conn.max_queued_audio_messages == 1
assert conn.max_queue == 1
await ws.send(b'm1')
assert await ws.recv() == 'accepted'
gate.clear()
await ws.send(b'm2')
await asyncio.sleep(0.02)
assert conn.in_flight_message == b'm2'
await ws.send(b'm3')
await asyncio.sleep(0.05)
assert len(conn.messages) == 0
gate.set()
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
assert len(delivered) == 3
asyncio.run(serve(scenario_1, settings=settings_1))
# Message budget of 2 and audio byte capacity bound
settings_2 = RuntimeSettings(
max_binary_message_bytes=1200,
max_client_control_bytes=500,
output_credit_window_bytes=1200,
max_queued_audio_bytes=2400,
max_queued_audio_messages=2,
)
async def scenario_2(port, delivered, gate, server):
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
conn = next(iter(server.server_state.connections))
assert conn.max_queued_audio_messages == 2
await ws.send(b'm1')
assert await ws.recv() == 'accepted'
gate.clear()
await ws.send(b'm2')
await asyncio.sleep(0.02)
assert conn.in_flight_message == b'm2'
await ws.send(b'm3')
await asyncio.sleep(0.02)
assert len(conn.messages) == 1
# m4 exceeds total message capacity (1 in-flight + 1 queued = 2)
await ws.send(b'm4')
await asyncio.sleep(0.05)
assert len(conn.messages) == 1
gate.set()
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
assert len(delivered) == 4
asyncio.run(serve(scenario_2, settings=settings_2))
def test_capacity_failure_terminates_receive_with_nonresponsive_peer():
"""Protocol failure cancels the capacity waiter without another cancellation."""
async def scenario(port, delivered, gate, server):
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
gate.clear()
# ASGI retains one delivered message; queued messages fill the rest.
writer.write((b'\x82\x81\x00\x00\x00\x00x') * 30)
await writer.drain()
conn = next(iter(server.server_state.connections))
async with asyncio.timeout(1):
while conn.has_capacity(): await asyncio.sleep(.001)
assert not conn.transfer_data_task.done()
conn.close_timeout = .05
conn.fail_connection(1008)
# Shield ensures the assertion's timeout cannot perform a second cancel.
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(asyncio.shield(conn.transfer_data_task), .3)
await asyncio.wait_for(asyncio.shield(conn.close_connection_task), 1)
assert conn.transport.is_closing()
assert conn.assembling_scratch is None and conn.in_flight_message is None
finally:
writer.close(); await writer.wait_closed()
asyncio.run(serve(scenario, settings=RuntimeSettings(max_queued_audio_messages=1)))
@pytest.mark.parametrize('fragmented', [False, True])
def test_invalid_utf8_retains_standard_1007_rejection(fragmented):
async def scenario(port, delivered, gate, server):
reader, writer = await asyncio.open_connection('127.0.0.1', port)
try:
key = base64.b64encode(os.urandom(16)).decode()
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
wire = b'\x01\x81\0\0\0\0\xc3\x80\x81\0\0\0\0\x28' if fragmented else b'\x81\x82\0\0\0\0\xc3\x28'
writer.write(wire); await writer.drain()
header = await asyncio.wait_for(reader.readexactly(2), 1)
payload = await reader.readexactly(header[1] & 127)
assert header[0] == 0x88 and struct.unpack('!H', payload[:2])[0] == 1007
assert not delivered
finally:
writer.close(); await writer.wait_closed()
asyncio.run(serve(scenario))