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
+6 -3
View File
@@ -250,7 +250,7 @@ def factual_context_units(blocks):
source_units.append([block.group_id, [block], True])
else:
source_units.append([None, [block], False])
scopes, resolved = [], []
scopes, resolved, preamble = [], [], []
def close_scope():
scope = scopes.pop()
@@ -263,7 +263,7 @@ def factual_context_units(blocks):
raise ExtractionError("Unresolved non-FAQ source group")
# Validate every group, including excluded groups, before selection.
associate_dependencies([(group, unit, True)])
context = [b for scope in scopes for b in scope["blocks"]]
context = preamble + [b for scope in scopes for b in scope["blocks"]]
for scope in scopes:
scope["used"] = True
resolved.append([group, context + unit, True])
@@ -278,10 +278,13 @@ def factual_context_units(blocks):
while scopes and scopes[-1]["level"] >= level:
close_scope()
scopes.append(dict(level=level, blocks=[block], used=False))
elif not scopes and not resolved and block.parent_block_id is None:
# Initial source prose is document-wide context, never pair-local.
preamble.append(block)
elif scopes and not scopes[-1]["used"] and block.parent_block_id is None:
scopes[-1]["blocks"].append(block)
else:
# Unheaded preambles and prose between pairs have no reliable scope.
# Prose after pairs still has no reliable association.
raise ExtractionError("Ambiguous governing context for factual FAQ")
while scopes:
close_scope()
+9 -5
View File
@@ -11,7 +11,7 @@ import unicodedata
from uuid import UUID
from zipfile import ZipFile
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact, ocr_review_required
from .formats import DOCX_MIME, validate_docx, validate_image
from .normalization import normalize_search_text, normalized_inputs
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
@@ -230,6 +230,7 @@ class PageBlockExtractor:
self.owned()
self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider
self.original_hash, self.profile, self.reviewed = original_hash, profile, False
self.automatic_ocr = False
self.document_id, self.title = document_id, title
self.annotations = []
extraction = profile["extraction"]
@@ -273,7 +274,8 @@ class PageBlockExtractor:
blocks = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate(blocks))
envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"],
complete=True, quality_decision="reviewed" if self.reviewed else "passed",
complete=True, quality_decision=("partially_reviewed" if self.reviewed and self.automatic_ocr
else "reviewed" if self.reviewed else "passed"),
review_annotations=tuple(self.annotations), blocks=blocks)
normalized_inputs(envelope, profile)
payload = serialize_artifact(envelope, profile)
@@ -795,7 +797,8 @@ class PageBlockExtractor:
data = {"artifact_schema": 1, "document_id": str(self.document_id), "title": self.title,
"original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest,
"normalization_policy": self.profile["normalizer"], "complete": True,
"quality_decision": "reviewed" if self.reviewed else "passed", "warnings": [],
"quality_decision": ("partially_reviewed" if self.reviewed and getattr(self, "automatic_ocr", False)
else "reviewed" if self.reviewed else "passed"), "warnings": [],
"review_annotations": [a.model_dump(mode="json") for a in self.annotations],
"blocks": [dict(b.model_dump(mode="json"), ordinal=i) for i, b in enumerate(blocks)]}
bounded_json_size(data, self.profile["extraction"]["max_extraction_artifact_bytes"])
@@ -824,11 +827,12 @@ class PageBlockExtractor:
or b.page != page or not b.source_locator.startswith(locator + "/")
or unreadable(b.text)):
raise ExtractionError("Vision evidence identity, location or readability mismatch")
if any("unreadable" in w.lower() or "ناخوانا" in w for w in b.warnings):
raise ExtractionError("Vision reports unreadable source regions")
# Validate local source relationships before manually attesting to the result.
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
complete=True, quality_decision="passed",
blocks=tuple(blocks))
if not ocr_review_required(self.profile) and not any(b.warnings for b in blocks):
self.automatic_ocr = True
return blocks
return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))
@@ -11,6 +11,14 @@ class LegacyProcessingProfile(ValueError):
pass
def ocr_review_required(profile: Mapping) -> bool:
"""Fail closed for legacy snapshots; deployment defaults never reinterpret jobs."""
value = profile.get("extraction", {}).get("ocr_review_required", True)
if type(value) is not bool:
raise ValueError("Invalid frozen OCR review policy")
return value
def processing_profile_kind(profile: Mapping) -> str:
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
return "legacy-v1"
@@ -20,6 +28,7 @@ def processing_profile_kind(profile: Mapping) -> str:
def extraction_profile_digest(profile: Mapping) -> str:
ocr_review_required(profile)
if processing_profile_kind(profile) == "legacy-v1":
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
# Faithful extraction is reusable across chunk/embedding/normalization changes.
+13 -11
View File
@@ -22,9 +22,10 @@ def unsafe_display_character(character: str) -> bool:
{"RLO", "LRO", "RLE", "LRE", "PDF", "LRI", "RLI", "FSI", "PDI"})
def normalized_title(path: Path, title: str | None) -> str:
filename = unicodedata.normalize("NFC", Path(path).name)
value = unicodedata.normalize("NFC", title if title is not None else Path(filename).stem)
def normalized_title(path: Path, title: str | None, *, filename: str | None = None) -> str:
name = filename if filename is not None else Path(path).name
nfc_name = unicodedata.normalize("NFC", name)
value = unicodedata.normalize("NFC", title if title is not None else Path(nfc_name).stem)
return " ".join(value.split())
@@ -34,7 +35,7 @@ def payload_hash(sha: str, title: str) -> str:
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
def replay_payload_hash(path: Path, title: str | None, size_bytes: int, *, filename: str | None = None) -> str:
"""Stream at most the accepted length plus one byte, with constant memory."""
path = Path(path)
digest, total = hashlib.sha256(), 0
@@ -54,12 +55,13 @@ def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
raise IntakeError("INVALID_FILE", "Cannot read input file") from None
if total != size_bytes:
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
return payload_hash(digest.hexdigest(), normalized_title(path, title))
return payload_hash(digest.hexdigest(), normalized_title(path, title, filename=filename))
def prepare_file(path: Path, title: str | None, settings) -> dict:
def prepare_file(path: Path, title: str | None, settings, *, filename: str | None = None) -> dict:
path = Path(path)
filename = unicodedata.normalize("NFC", path.name)
display_name = filename if filename is not None else path.name
filename = unicodedata.normalize("NFC", display_name)
# Display names are portable and reject path delimiters, controls and bidi marks.
if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename
or any(c in '<>:"/\\|?*' or unsafe_display_character(c)
@@ -69,7 +71,7 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
extension = Path(filename).suffix.lower()
if extension not in settings.accepted_formats:
raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
canonical_title = normalized_title(path, title)
canonical_title = normalized_title(path, title, filename=filename)
if (not canonical_title or len(canonical_title) > 200
or any(unsafe_display_character(c) for c in canonical_title)):
raise IntakeError("INVALID_FILE", "Title must contain 1-200 display characters")
@@ -96,16 +98,16 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
def import_document(repository: IntakeRepository, store: FileStore, settings, *, path,
administrator_id, request_id, title=None):
administrator_id, request_id, title=None, filename=None):
administrator_id, request_id = UUID(str(administrator_id)), UUID(str(request_id))
org, previous = repository.lookup(settings, administrator_id, request_id)
if previous is not None:
# Existing requests compare payloads independently of current acceptance policy.
# File I/O is outside database transactions and creates no candidate.
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"])
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"], filename=filename)
result = repository.replay(org, administrator_id, previous, submitted_hash)
return {"replayed": True, "document": result}
prepared = prepare_file(path, title, settings)
prepared = prepare_file(path, title, settings, filename=filename)
key = store.put(prepared["content"])
replayed, conflict, result = repository.create(
settings, prepared, key, administrator_id, request_id, org)
+2
View File
@@ -58,6 +58,7 @@ class IngestionSettings(BaseSettings):
vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
ocr_review_required: bool = True
normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
chunking_policy: str = Field(default="paragraph-v1", min_length=1)
render_dpi: int = Field(default=144, gt=0, le=600)
@@ -211,6 +212,7 @@ class IngestionSettings(BaseSettings):
"vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
"ocr_review_required": self.ocr_review_required,
"render_dpi": self.render_dpi,
"max_rendered_page_pixels": self.max_rendered_page_pixels,
"max_pdf_pages": self.max_pdf_pages,
+1 -1
View File
@@ -67,7 +67,7 @@ class ExtractionEnvelope(BaseModel):
extraction_profile_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
normalization_policy: str = Field(min_length=1)
complete: Literal[True]
quality_decision: Literal["passed", "reviewed"]
quality_decision: Literal["passed", "reviewed", "partially_reviewed"]
warnings: tuple[str, ...] = ()
review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1)
+21 -6
View File
@@ -10,7 +10,7 @@ from threading import Event, Thread
from .chunking import chunk_extraction
from .embeddings import EmbeddingError, stage_document
from .extraction import ExtractionError, ReviewRequired
from .extraction_artifacts import extraction_profile_digest
from .extraction_artifacts import extraction_profile_digest, ocr_review_required
from .review import FactualReviewRequired, prepare_chunks
from .operational_limits import validate_worker_durations
@@ -63,21 +63,36 @@ def validate_source(envelope, document, content):
if envelope.title != document["title"]:
raise ExtractionError("Extraction title differs from immutable source")
warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings))
if warnings and envelope.quality_decision != "reviewed":
from .extraction import unreadable, PLACEHOLDER
from .review import factual_groups
groups = factual_groups(envelope)
if any(unreadable(b.text) or (PLACEHOLDER.search(b.text) and b.group_id not in groups)
for b in envelope.blocks):
raise ExtractionError("Unreadable or placeholder extracted evidence")
if warnings and envelope.quality_decision not in ("reviewed", "partially_reviewed"):
raise ExtractionError("Unreviewed extraction warnings")
if any("unreadable" in w.lower() or "\u0646\u0627\u062e\u0648\u0627\u0646\u0627" in w for w in warnings):
raise ExtractionError("Unreadable retained evidence")
mime = document["mime_type"]
if envelope.quality_decision == "partially_reviewed":
inspected = {annotation.locator for annotation in envelope.review_annotations}
automatic = [b for b in envelope.blocks if not any(
b.source_locator.startswith(locator + "/") for locator in inspected)]
if (mime != "application/pdf" or ocr_review_required(document["processing_profile"])
or not inspected or not automatic or envelope.warnings
or any(b.method not in ("vision", "ocr") or b.warnings for b in automatic)):
raise ExtractionError("Mixed extraction requires exact inspected non-automatic evidence")
automatic_ocr = (not ocr_review_required(document["processing_profile"])
and envelope.quality_decision == "passed" and not warnings
and all(b.method in ("vision", "ocr") for b in envelope.blocks))
if mime == "application/pdf":
import pymupdf
with pymupdf.open(stream=content, filetype="pdf") as source:
if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"]
or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))):
raise ExtractionError("Incomplete PDF source coverage")
if envelope.quality_decision != "reviewed":
if envelope.quality_decision not in ("reviewed", "partially_reviewed") and not automatic_ocr:
raise ExtractionError("PDF extraction requires inspection")
elif mime in ("image/jpeg", "image/png"):
if envelope.quality_decision != "reviewed" or any(
if (envelope.quality_decision != "reviewed" and not automatic_ocr) or any(
b.page is not None or b.method not in ("vision", "ocr") for b in envelope.blocks):
raise ExtractionError("Image extraction requires inspected complete evidence")
elif mime in ("text/markdown", "text/plain",