"""Pure artifact validation. Attachment requires later transactional worker fencing.""" import hashlib import json from collections.abc import Mapping from uuid import UUID from .types import ExtractionEnvelope from .normalization import normalized_inputs 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" if profile.get("profile_schema") == 2 and profile.get("extractor") == "page-block-v1": return "page-block-v1" raise ValueError("Unsupported processing profile") 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. encoded = json.dumps(profile["extraction"], sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def validate_extraction_provenance(envelope: ExtractionEnvelope, processing_profile: Mapping) -> None: extraction = processing_profile["extraction"] if extraction["strategy"] != "direct-quality-fallback-v1": raise ValueError("Unsupported extraction strategy") vision = extraction["vision"] for block in envelope.blocks: if block.method in ("vision", "ocr"): if (not all(isinstance(vision.get(key), str) and vision[key].strip() for key in ("provider", "endpoint", "model")) or block.actual_model != vision["model"]): raise ValueError("Extraction model differs from the frozen processing profile") elif block.actual_model is not None: raise ValueError("Direct extraction cannot assert a provider model identity") # Requested/resolved IDs must match exactly. Aliases and implicit routing # are unsupported; future adapters need a frozen explicit resolution rule. def validate_artifact(content: bytes, *, artifact_sha256: str, document_id: UUID, original_sha256: str, processing_profile: Mapping) -> ExtractionEnvelope: expected_profile_digest = extraction_profile_digest(processing_profile) limits = processing_profile["extraction"] if len(content) > limits["max_extraction_artifact_bytes"]: raise ValueError("Extraction artifact exceeds byte limit") if hashlib.sha256(content).hexdigest() != artifact_sha256: raise ValueError("Extraction artifact integrity mismatch") envelope = ExtractionEnvelope.model_validate_json(content) if (envelope.document_id != document_id or envelope.original_sha256 != original_sha256 or envelope.extraction_profile_sha256 != expected_profile_digest or envelope.normalization_policy != processing_profile["normalizer"] or len(envelope.blocks) > limits["max_extracted_blocks"]): raise ValueError("Extraction artifact identity, profile or block limit mismatch") validate_extraction_provenance(envelope, processing_profile) normalized_inputs(envelope, processing_profile) return envelope def bounded_json_size(value, limit): """Count exact UTF-8 JSON bytes before allocating the assembled artifact.""" remaining = limit def spend(count): nonlocal remaining remaining -= count if remaining < 0: raise ValueError("Extraction artifact exceeds byte limit") def visit(item): if isinstance(item, str): spend(2) for character in item: if character in '"\\': spend(2) elif character in "\b\f\n\r\t": spend(2) elif ord(character) < 32: spend(6) else: try: spend(len(character.encode("utf-8"))) except UnicodeError: raise ValueError("Invalid artifact Unicode") from None elif isinstance(item, dict): spend(2 + max(0, len(item) - 1)) for key, child in item.items(): visit(key) spend(1) visit(child) elif isinstance(item, (tuple, list)): spend(2 + max(0, len(item) - 1)) for child in item: visit(child) else: spend(len(json.dumps(item, allow_nan=False))) visit(value) return limit - remaining def bounded_json_bytes(value, limit): bounded_json_size(value, limit) return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8") def serialize_artifact(envelope, processing_profile): return bounded_json_bytes(envelope.model_dump(mode="json"), processing_profile["extraction"]["max_extraction_artifact_bytes"])