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
+105
View File
@@ -0,0 +1,105 @@
"""Safe document polling projections and scoped pagination over existing repositories."""
import base64
from datetime import datetime
import json
from uuid import UUID
from sqlalchemy import text
from app.infrastructure.intake_repository import administrator, document_status
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.modules.documents.errors import IntakeError
from app.modules.documents.review import pending_review, reviews_approved
from app.modules.documents.extraction_artifacts import ocr_review_required
def encode_cursor(document):
return base64.urlsafe_b64encode(json.dumps([document['created_at'].isoformat(), str(document['id'])]).encode()).decode()
def decode_cursor(cursor):
try:
if len(cursor) > 256:
raise ValueError()
stamp, identifier = json.loads(base64.b64decode(cursor, altchars=b'-_', validate=True))
stamp = datetime.fromisoformat(stamp)
if stamp.tzinfo is None:
raise ValueError()
return stamp, UUID(identifier)
except (ValueError, TypeError, UnicodeError):
raise IntakeError('VALIDATION_ERROR', 'Invalid document cursor') from None
class DocumentQueries:
def __init__(self, engine, settings, store, candidates):
self.engine, self.settings, self.store, self.candidates = engine, settings, store, candidates
self.worker = SqlWorkerRepository(engine, settings)
def project(self, row):
job, state = row['job'], row['extraction_state']
can_retry = False
if row['status'] == 'failed' and job['status'] == 'failed':
try:
self.worker.validate_retry_snapshot(row, self.store, self.candidates)
can_retry = (job['error_code'] not in ('EXTRACTION_REVIEW_REQUIRED', 'EXTRACTION_REVIEW_REJECTED')
or reviews_approved(state))
except (IntakeError, OSError, ValueError):
pass
rejected = any((p.get('decision') or {}).get('decision') == 'reject' for p in state.get('candidates', ()))
review_state = ('rejected' if rejected else 'pending' if pending_review(state)
else 'approved' if reviews_approved(state)
else 'not_required' if state.get('complete_artifact') else 'not_evaluated')
quality = None
if state.get('complete_artifact'):
quality = self.candidates.inspect_pointer(state['complete_artifact'], document=row).quality_decision
return dict(id=row['id'], title=row['title'], filename=row['original_filename'],
status=row['status'], is_active=row['is_active'], searchable=row['searchable'],
created_at=row['created_at'], chunk_count=row['chunk_count'],
review_required=pending_review(state), review_state=review_state,
extraction_quality_decision=quality,
ocr_review_required=ocr_review_required(row['processing_profile']),
job=dict(id=job['id'], status=job['status'], stage=job['stage'],
attempt_count=job['attempt_count'], retry_generation=job['retry_generation'],
can_retry=can_retry, error=(dict(code=job['error_code'],
message='Ingestion could not complete; use the error code and review state.',
retryable=job['error_retryable']) if job['error_code'] else None)))
def detail(self, actor, identifier):
with self.engine.begin() as conn:
org = administrator(conn, actor)
row = document_status(conn, org, identifier)
self.visible(row)
return self.project(row)
@staticmethod
def visible(row):
if row['deleted_at'] is not None or row['content_purged_at'] is not None:
raise IntakeError('DOCUMENT_NOT_FOUND', 'Document unavailable')
def list(self, actor, *, limit=20, cursor=None, status=None, is_active=None):
params = dict(limit=limit + 1, status=status, active=is_active)
condition = ''
if cursor is not None:
stamp, identifier = decode_cursor(cursor)
params.update(stamp=stamp, identifier=identifier)
condition = ' AND (d.created_at,d.id)<(:stamp,:identifier)'
with self.engine.begin() as conn:
params['org'] = administrator(conn, actor)
revision = conn.execute(text('SELECT knowledge_revision FROM organization_settings WHERE organization_id=:org'), params).scalar_one()
if cursor is not None:
known = conn.execute(text('SELECT 1 FROM documents WHERE organization_id=:org AND id=:identifier AND created_at=:stamp AND deleted_at IS NULL AND content_purged_at IS NULL'), params).scalar_one_or_none()
if known is None:
raise IntakeError('VALIDATION_ERROR', 'Unknown document cursor')
rows = conn.execute(text('''
SELECT d.*, row_to_json(j) AS job FROM documents d JOIN ingestion_jobs j
ON j.document_id=d.id AND j.organization_id=d.organization_id
WHERE d.organization_id=:org AND d.deleted_at IS NULL AND d.content_purged_at IS NULL
AND (CAST(:status AS text) IS NULL OR d.status=:status)
AND (CAST(:active AS boolean) IS NULL OR d.is_active=:active)
''' + condition + ' ORDER BY d.created_at DESC,d.id DESC LIMIT :limit'), params).mappings().all()
items = []
for row in rows[:limit]:
row = dict(row)
row['searchable'] = row['status'] == 'ready' and row['is_active']
items.append(self.project(row))
return dict(items=items, next_cursor=encode_cursor(rows[limit - 1]) if len(rows) > limit else None,
knowledge_revision=revision)
+7 -3
View File
@@ -165,8 +165,8 @@ class GeminiVision:
if any("text" not in p for p in parts):
raise ExtractionError("Unexpected vision response parts")
transcript = Transcription.model_validate_json("".join(p["text"] for p in parts))
if not transcript.complete or transcript.warnings or not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain")
if not transcript.blocks:
raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = []
@@ -174,10 +174,14 @@ class GeminiVision:
if (block.ordinal != index or block.method != "vision" or block.actual_model != self.model or block.page != page
or not block.source_locator.startswith(section + "/")):
raise ExtractionError("Vision returned incompatible evidence provenance")
if unreadable(block.text) or any("unreadable" in w.lower() or "ناخوانا" in w for w in block.warnings):
if unreadable(block.text):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={"search_text":
normalize_search_text(block.text, processing_profile["normalizer"])}))
# Recognition diagnostics belong to the exact review candidate.
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+143
View File
@@ -0,0 +1,143 @@
"""Two admitted JSON requests; large decoding/validation has a separate GIL.
Only backend-chosen DTO classes enter the child. Its bounded pickle frames are
trusted local results, never client pickle input. Admission outlives cancellation
until the owner has joined disk I/O, reaped its child and removed its spool.
"""
import asyncio
import importlib
import json
import pickle
from pathlib import Path
import struct
import sys
from threading import BoundedSemaphore
JSON_SLOTS = BoundedSemaphore(2)
INLINE_BYTES = 64 * 1024
FRAME_BYTES = 256 * 1024
async def owned_io(function, *args):
"""A cancelled owner must join a write before closing/deleting its file."""
task = asyncio.get_running_loop().run_in_executor(None, function, *args)
try:
return await asyncio.shield(task)
except asyncio.CancelledError:
while not task.done():
try:
await asyncio.shield(task)
except asyncio.CancelledError:
continue
task.result()
raise
def validate_json(body, model_cls):
try:
return model_cls.model_validate(json.loads(body.decode('utf-8')))
except (ValueError, UnicodeError, RecursionError):
raise ValueError('VALIDATION_ERROR') from None
async def validate_spool(path, model_cls):
# No large process-pool argument/result pickling in the API process: input is
# spooled, and validated flat DTO fields return in bounded batches.
spawning = asyncio.create_task(asyncio.create_subprocess_exec(
sys.executable, '-m', 'app.infrastructure.json_processing',
model_cls.__module__, model_cls.__name__, str(path),
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
limit=FRAME_BYTES,
))
try:
child = await asyncio.shield(spawning)
except OSError:
raise ValueError('DEPENDENCY_UNAVAILABLE') from None
except asyncio.CancelledError:
# Cancellation during process creation still owns the eventual child.
while not spawning.done():
try:
await asyncio.shield(spawning)
except asyncio.CancelledError:
continue
child = spawning.result()
if child.returncode is None:
child.kill()
reap = asyncio.create_task(child.wait())
while not reap.done():
try:
await asyncio.shield(reap)
except asyncio.CancelledError:
continue
reap.result()
raise
values, kinds, fields_set = {}, {}, None
try:
while True:
length = struct.unpack('!I', await child.stdout.readexactly(4))[0]
if length > FRAME_BYTES:
raise ValueError('DEPENDENCY_UNAVAILABLE')
name, kind, value = pickle.loads(await child.stdout.readexactly(length))
if name is None:
if value is None:
raise ValueError('VALIDATION_ERROR')
fields_set = value
break
if kind == 0:
values[name] = value
else:
values.setdefault(name, []).extend(value)
kinds[name] = kind
await asyncio.sleep(0)
if await child.wait() != 0:
raise ValueError('DEPENDENCY_UNAVAILABLE')
for name, kind in kinds.items():
if kind == 2:
values[name] = tuple(values[name])
# These exact values and fields_set were validated in our child. Repeating
# validation here would put the expensive work back on the API's loop.
return model_cls.model_construct(_fields_set=fields_set, **values)
except (asyncio.IncompleteReadError, OSError, pickle.UnpicklingError):
raise ValueError('DEPENDENCY_UNAVAILABLE') from None
finally:
if child.returncode is None:
child.kill()
reap = asyncio.create_task(child.wait())
while not reap.done():
try:
await asyncio.shield(reap)
except asyncio.CancelledError:
continue
reap.result()
def _send(record):
payload = pickle.dumps(record, protocol=5)
if len(payload) > FRAME_BYTES:
raise ValueError('Validated DTO field exceeds internal frame bound')
sys.stdout.buffer.write(struct.pack('!I', len(payload)))
sys.stdout.buffer.write(payload)
def _worker(module, name, path):
model_cls = getattr(importlib.import_module(module), name)
try:
model = validate_json(Path(path).read_bytes(), model_cls)
except ValueError:
_send((None, 0, None))
return
for field in model_cls.model_fields:
value = getattr(model, field)
if isinstance(value, (tuple, list)):
kind = 2 if isinstance(value, tuple) else 1
# 64 supported 500-character identifiers fit well below FRAME_BYTES,
# even as raw four-byte UTF-8 scalars. Empty arrays still carry type.
for offset in range(0, max(1, len(value)), 64):
_send((field, kind, value[offset:offset + 64]))
else:
_send((field, 0, value))
_send((None, 0, model.model_fields_set))
if __name__ == '__main__':
_worker(*sys.argv[1:])
+10 -4
View File
@@ -149,7 +149,9 @@ class OpenRouterVision:
try:
native = json.loads(content)
choices = native.get("choices")
if not choices or not isinstance(choices, list):
if not isinstance(choices, list) or len(choices) != 1:
raise ExtractionError("Vision transcription incomplete or blocked")
if choices[0].get("finish_reason") not in (None, "stop"):
raise ExtractionError("Vision transcription incomplete or blocked")
message = choices[0].get("message", {})
raw_text = message.get("content", "")
@@ -168,14 +170,14 @@ class OpenRouterVision:
if "ordinal" not in b or type(b["ordinal"]) is not int:
b["ordinal"] = i
transcript = Transcription.model_validate(raw_dict)
if not transcript.complete or transcript.warnings or not transcript.blocks:
raise ExtractionError("Vision transcription incomplete or uncertain")
if not transcript.blocks:
raise ExtractionError("Vision transcription has no candidate blocks")
if len(transcript.blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = []
for index, block in enumerate(transcript.blocks):
locator = block.source_locator if block.source_locator and block.source_locator.startswith(section + "/") else f"{section}/block/{index + 1}"
if unreadable(block.text) or any("unreadable" in w.lower() or "ناخوانا" in w for w in block.warnings):
if unreadable(block.text):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={
"ordinal": index,
@@ -185,6 +187,10 @@ class OpenRouterVision:
"source_locator": locator,
"search_text": normalize_search_text(block.text, processing_profile["normalizer"])
}))
# Recognition diagnostics belong to the exact review candidate.
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+2 -2
View File
@@ -1,4 +1,4 @@
"""Trusted admin review services; HTTP authentication/Origin/CSRF is not implemented."""
"""Trusted admin review services; HTTP identity/Origin/CSRF is enforced by the API."""
import base64
import json
from uuid import UUID, uuid4
@@ -92,7 +92,7 @@ class SqlReviewRepository:
if after is not None:
matches = [i for i, p in enumerate(pointers) if p["evidence_sha256"] == after]
if not matches:
raise IntakeError("REVIEW_STALE", "Review cursor no longer available")
raise IntakeError("VALIDATION_ERROR", "Review cursor no longer available")
start = matches[0] + 1
from app.modules.documents.extraction_artifacts import bounded_json_size
remaining = document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"]
+17
View File
@@ -0,0 +1,17 @@
"""Selected voice transport construction shared by the API and operator smoke."""
import asyncio
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
async def create_adapter(config, limits):
config.require_voice()
connect = connect_gemini if config.provider == 'gemini' else connect_openai
transport = await asyncio.wait_for(connect(config.selected_key.get_secret_value(),
config.selected_model, config.selected_proxy, limits), limits.connect_timeout_seconds)
try:
adapter = GeminiLiveAdapter if config.provider == 'gemini' else RealtimeAdapter
return adapter(transport, model=config.selected_model, voice=config.selected_voice, settings=limits)
except BaseException:
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
raise
+214
View File
@@ -0,0 +1,214 @@
"""Pre-payload limits and bounded reassembly for Uvicorn legacy WebSocket backend.
Eight queued messages plus one assembling and one delivered message fit the
96,000-byte application receive budget even for maximum-size binary messages.
Validated LIVE_* settings lower binary/control limits and queue/audio capacity.
"""
import asyncio
import codecs
from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
from websockets.exceptions import ProtocolError
from websockets.legacy.framing import Frame
from app.modules.voice.settings import RuntimeSettings
class BoundedWebSocketProtocol(WebSocketProtocol):
def __init__(self, config, server_state, app_state, _loop=None):
settings = getattr(config, 'ws_settings', None) or RuntimeSettings()
self.settings = settings
self.max_binary_message_bytes = settings.max_binary_message_bytes
self.max_client_control_bytes = settings.max_client_control_bytes
self.max_queued_audio_bytes = settings.max_queued_audio_bytes
self.max_queued_audio_messages = settings.max_queued_audio_messages
max_size = max(self.max_binary_message_bytes, self.max_client_control_bytes)
config.ws_max_size = max_size
config.ws_per_message_deflate = False
audio_budget = min(
self.max_queued_audio_messages,
max(1, self.max_queued_audio_bytes // self.max_binary_message_bytes)
)
queue_cap = max(1, audio_budget - 2) if audio_budget > 2 else 1
config.ws_max_queue = queue_cap
self.max_audio_messages = audio_budget
super().__init__(config, server_state, app_state, _loop)
self.message_remaining = None
self.assembling_scratch = None
self.assembling_type = None
self.in_flight_message = None
self.capacity_available = asyncio.Event()
self.capacity_available.set()
self.rejection_code = None
@property
def total_message_count(self):
count = 1 if self.assembling_type is not None else 0
count += len(self.messages)
if self.in_flight_message is not None:
count += 1
return count
@property
def current_audio_bytes(self):
total = len(self.assembling_scratch) if (self.assembling_scratch is not None and self.assembling_type == 2) else 0
total += sum(len(m) for m in self.messages if isinstance(m, (bytes, bytearray)))
if self.in_flight_message is not None and isinstance(self.in_flight_message, (bytes, bytearray)):
total += len(self.in_flight_message)
return total
def has_capacity(self):
if self.closed_event.is_set():
return True
if self.total_message_count >= self.max_audio_messages:
return False
if self.current_audio_bytes + self.max_binary_message_bytes > self.max_queued_audio_bytes:
return False
return True
async def wait_for_capacity(self):
while not self.closed_event.is_set():
if self.has_capacity():
return
self.capacity_available.clear()
await self.capacity_available.wait()
async def read_frame(self, max_size):
header = await self.reader.readexactly(2)
# Reject compressed/reserved bits before reading lengths, masks or payloads.
if header[0] & 0x70:
raise ProtocolError('Reserved bits are unsupported')
opcode = header[0] & 0x0f
if opcode in (1, 2):
if self.message_remaining is not None:
raise ProtocolError('Interleaved data message')
limit = self.max_client_control_bytes if opcode == 1 else self.max_binary_message_bytes
self.message_remaining = limit
elif opcode == 0:
if self.message_remaining is None:
raise ProtocolError('Unexpected continuation')
elif opcode not in (8, 9, 10):
raise ProtocolError('Invalid opcode')
bound = self.message_remaining if opcode in (0, 1, 2) else 125
if max_size is not None and opcode in (0, 1, 2):
bound = min(bound, max_size)
first = True
async def read(size):
nonlocal first
if first:
first = False
return header
return await self.reader.readexactly(size)
try:
frame = await Frame.read(read, mask=True, max_size=bound, extensions=[])
except Exception:
if opcode in (0, 1, 2):
self.message_remaining = None
raise
if opcode in (0, 1, 2):
self.message_remaining -= len(frame.data)
if frame.fin:
self.message_remaining = None
return frame
async def read_message(self):
await self.wait_for_capacity()
if self.closed_event.is_set():
return None
frame = await self.read_data_frame(max_size=self.max_size)
if frame is None:
return None
if frame.opcode == 1:
text = True
elif frame.opcode == 2:
text = False
else:
raise ProtocolError('unexpected opcode')
if frame.fin:
if text:
return frame.data.decode('utf-8')
return bytes(frame.data)
# Fragmentation with finite retained metadata and scratch storage
scratch = bytearray()
self.assembling_scratch = scratch
self.assembling_type = 1 if text else 2
try:
if text:
decoder = codecs.getincrementaldecoder('utf-8')(errors='strict')
decoder.decode(frame.data, frame.fin)
if frame.data:
scratch.extend(frame.data)
while not frame.fin:
frame = await self.read_data_frame(max_size=self.message_remaining)
if frame is None:
raise ProtocolError('incomplete fragmented message')
if frame.opcode != 0:
raise ProtocolError('expected continuation frame')
if text:
decoder.decode(frame.data, frame.fin)
if frame.data:
scratch.extend(frame.data)
if text:
return scratch.decode('utf-8')
return bytes(scratch)
finally:
self.assembling_scratch = None
self.assembling_type = None
self.message_remaining = None
self.capacity_available.set()
async def recv(self):
self._release_in_flight()
msg = await super().recv()
self._record_in_flight(msg)
return msg
def _release_in_flight(self):
if self.in_flight_message is not None:
self.in_flight_message = None
self.capacity_available.set()
def _record_in_flight(self, msg):
self.in_flight_message = msg
def _cleanup_resources(self):
self.assembling_scratch = None
self.assembling_type = None
self.message_remaining = None
self.in_flight_message = None
self.capacity_available.set()
def connection_lost(self, exc):
self._cleanup_resources()
super().connection_lost(exc)
def fail_connection(self, code=1006, reason=''):
if code in (1002, 1007, 1009):
self.rejection_code = code
self._cleanup_resources()
super().fail_connection(code, reason)
async def asgi_receive(self):
message = await super().asgi_receive()
if message['type'] == 'websocket.disconnect' and self.rejection_code is not None:
# A failed parser stops reading, so close_code can be 1006 even after
# sending a standards-compliant 1007. Preserve the actual rejection.
message = dict(message, code=self.rejection_code)
return message
async def close(self, code=1000, reason=''):
self._cleanup_resources()
return await super().close(code, reason)
+27 -17
View File
@@ -237,23 +237,7 @@ class SqlWorkerRepository:
"""), dict(org=org, actor=administrator_id, document=document_id, request=request_id)).scalar_one_or_none()
if previous is not None:
return dict(replayed=True, **previous)
try:
read_original(store, snapshot)
except (OSError, ValueError, KeyError):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Retained original is unavailable or incompatible") from None
review_state = snapshot.get("extraction_state", {})
if review_state.get("candidates"):
if any((p.get("decision") or {}).get("decision") == "reject" for p in review_state["candidates"]):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Rejected evidence cannot be retried")
if not reviews_approved(review_state):
raise IntakeError("EXTRACTION_REVIEW_PENDING", "All current evidence must be approved before retry")
if candidates is None:
from .extraction_candidates import LocalExtractionCandidates
candidates = LocalExtractionCandidates(self.settings.extraction_directory, original_directory=store.directory)
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)
for pointer in review_state["candidates"]:
service._body(pointer, snapshot)
self.validate_retry_snapshot(snapshot, store, candidates)
with self.engine.begin() as connection:
check_compatibility(connection, self.settings.embedding_profile)
org = administrator(connection, administrator_id)
@@ -300,6 +284,32 @@ class SqlWorkerRepository:
request=request_id, response=json.dumps(response)))
return dict(replayed=False, **response)
def validate_retry_snapshot(self, snapshot, store, candidates=None):
"""Shared eligibility for polling and retry; frozen policy cannot waive retained reviews."""
if (snapshot["status"] != "failed" or snapshot["deleted_at"] is not None
or snapshot["content_purged_at"] is not None or snapshot["is_active"]
or snapshot["chunk_count"] != 0):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Only eligible failed documents can be retried")
try:
from app.modules.documents.extraction_artifacts import ocr_review_required
ocr_review_required(snapshot["processing_profile"])
read_original(store, snapshot)
except (OSError, ValueError, KeyError):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Retained original is unavailable or incompatible") from None
review_state = snapshot.get("extraction_state", {})
if review_state.get("candidates"):
if any((p.get("decision") or {}).get("decision") == "reject" for p in review_state["candidates"]):
raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Rejected evidence cannot be retried")
if not reviews_approved(review_state):
raise IntakeError("EXTRACTION_REVIEW_PENDING", "All current evidence must be approved before retry")
if candidates is None:
from .extraction_candidates import LocalExtractionCandidates
candidates = LocalExtractionCandidates(self.settings.extraction_directory, original_directory=store.directory)
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)
for pointer in review_state["candidates"]:
service._body(pointer, snapshot)
def review_resume(self, claim, candidates, store):
from .review_repository import SqlReviewRepository
service = SqlReviewRepository(self.engine, self.settings, candidates, store)