"""Bounded immutable partial-review files, distinct from complete envelopes.""" import base64 import hashlib import json import os from pathlib import Path import re import tempfile from types import SimpleNamespace from uuid import uuid4 from app.modules.documents.extraction import review_digest, unreadable from app.modules.documents.extraction_artifacts import ( bounded_json_bytes, extraction_profile_digest, validate_extraction_provenance, ) from app.modules.documents.formats import validate_image from app.modules.documents.normalization import normalized_inputs from app.modules.documents.review import factual_digest, factual_groups from app.modules.documents.chunking import factual_review_blocks from app.modules.documents.types import ExtractedBlock class LocalReviewCandidates: def __init__(self, candidates): # Reuse the already validated separate extraction root. self.directory = candidates.directory def _path(self, key): if not isinstance(key, str) or not re.fullmatch(r"[0-9a-f]{32}\.[0-9a-f]{32}\.review.json", key): raise ValueError("Invalid review key") path = self.directory / key if path.is_symlink(): raise ValueError("Review candidate cannot be a symlink") return path def put(self, document, *, error=None, envelope=None, artifact=None): profile = document["processing_profile"] body = dict(review_schema=1, document_id=str(document["id"]), original_sha256=document["file_sha256"], extraction_profile_sha256=extraction_profile_digest(profile)) if error is not None: body.update(review_kind="extraction", locator=error.locator, image=base64.b64encode(error.image).decode("ascii"), blocks=[b.model_dump(mode="json") for b in error.blocks], reasons=list(error.reasons), evidence_sha256=error.evidence_sha256) else: body.update(review_kind="factual_corpus", locator="factual_corpus", image="", blocks=[b.model_dump(mode="json") for b in factual_review_blocks(envelope)], reasons=[], artifact_sha256=artifact["sha256"], evidence_sha256=factual_digest(artifact["sha256"], envelope)) content = bounded_json_bytes(body, profile["extraction"]["max_extraction_artifact_bytes"]) self._validate(body, document) self.directory.mkdir(parents=True, exist_ok=True) key = document["id"].hex + "." + uuid4().hex + ".review.json" descriptor, temporary = tempfile.mkstemp(prefix=".review-", dir=self.directory) try: with os.fdopen(descriptor, "wb") as stream: stream.write(content) stream.flush() os.fsync(stream.fileno()) os.link(temporary, self._path(key)) finally: Path(temporary).unlink(missing_ok=True) if os.name != "nt": descriptor = os.open(self.directory, os.O_RDONLY) try: os.fsync(descriptor) finally: os.close(descriptor) return dict(key=key, sha256=hashlib.sha256(content).hexdigest(), evidence_sha256=body["evidence_sha256"], review_kind=body["review_kind"], locator=body["locator"], original_sha256=body["original_sha256"], extraction_profile_sha256=body["extraction_profile_sha256"]) def inspect(self, pointer, document): limit = document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"] with self._path(pointer["key"]).open("rb") as stream: content = stream.read(limit + 1) if len(content) > limit or hashlib.sha256(content).hexdigest() != pointer["sha256"]: raise ValueError("Review candidate byte limit or digest mismatch") body = json.loads(content) self._validate(body, document) for field in ("evidence_sha256", "review_kind", "locator", "original_sha256", "extraction_profile_sha256"): if pointer.get(field) != body[field]: raise ValueError("Review pointer identity mismatch") return body def _validate(self, body, document): profile = document["processing_profile"] if (body["review_schema"] != 1 or body["document_id"] != str(document["id"]) or body["original_sha256"] != document["file_sha256"] or body["extraction_profile_sha256"] != extraction_profile_digest(profile)): raise ValueError("Review source/profile mismatch") raw = body["blocks"] if not isinstance(raw, list) or not 0 < len(raw) <= profile["extraction"]["max_extracted_blocks"]: raise ValueError("Review block limit") blocks = tuple(ExtractedBlock.model_validate(b) for b in raw) if any(unreadable(b.text) for b in blocks): raise ValueError("Unreadable review evidence") view = SimpleNamespace(blocks=blocks, normalization_policy=profile["normalizer"]) validate_extraction_provenance(view, profile) normalized_inputs(view, profile) if len({b.block_id for b in blocks}) != len(blocks): raise ValueError("Duplicate review block identity") if body["review_kind"] == "extraction": image = base64.b64decode(body["image"], validate=True) if not image or len(image) > profile["limits"]["max_original_bytes"]: raise ValueError("Review preview byte limit") # Rendering and accepted originals are PNG/JPEG. Validate actual format. extension = ".png" if image.startswith(b"\x89PNG\r\n\x1a\n") else ".jpg" validate_image(extension, image, SimpleNamespace(**profile["intake"])) locator = body["locator"] if not isinstance(locator, str) or not locator or any( not b.source_locator.startswith(locator + "/") for b in blocks): raise ValueError("Review source locator mismatch") if locator == "image": if document["mime_type"] not in ("image/png", "image/jpeg") or any(b.page is not None for b in blocks): raise ValueError("Review image source mismatch") elif re.fullmatch(r"pdf/page/[1-9][0-9]*", locator): page = int(locator.rsplit("/", 1)[1]) if document["mime_type"] != "application/pdf" or any(b.page != page for b in blocks): raise ValueError("Review PDF source mismatch") else: raise ValueError("Unsupported review source locator") digest = review_digest(original_sha256=document["file_sha256"], profile_digest=body["extraction_profile_sha256"], locator=locator, image=image, blocks=blocks) if digest != body["evidence_sha256"]: raise ValueError("Review evidence digest mismatch") elif body["review_kind"] == "factual_corpus": if body["image"] or body["locator"] != "factual_corpus": raise ValueError("Invalid factual review candidate") groups = {b.group_id for b in blocks if b.block_type in ("question", "answer")} expected = hashlib.sha256(json.dumps( dict(artifact_sha256=body["artifact_sha256"], groups=sorted(groups)), sort_keys=True, separators=(",", ":")).encode()).hexdigest() if not groups or expected != body["evidence_sha256"]: raise ValueError("Factual review identity mismatch") else: raise ValueError("Unsupported review kind")