From 39ed0422c542bb2cb6db1d001f8e60cf16bed07d Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Wed, 7 Oct 2026 16:21:17 +0330 Subject: [PATCH] feat(ingestion): implement Phase 4 chunking and vector embedding generation - Add heading and paragraph-preserving chunking algorithms with bounded overlap - Implement OpenAI embeddings client adapter with explicit token limits and batching - Implement stage_document pipeline with strict operational limits and memory protections - Add unit and integration tests covering chunking boundaries, timeouts, and vector generation --- app/infrastructure/openai_embeddings.py | 316 ++++++++++++ app/modules/documents/chunking.py | 397 +++++++++++++++ app/modules/documents/embeddings.py | 372 ++++++++++++++ app/modules/documents/operational_limits.py | 28 ++ app/modules/documents/processing.py | 34 ++ tests/integration/test_phase4.py | 211 ++++++++ tests/support/embedding.py | 25 + tests/unit/test_phase4.py | 358 +++++++++++++ tests/unit/test_phase4_closure.py | 471 ++++++++++++++++++ tests/unit/test_phase4_repairs.py | 264 ++++++++++ .../test_phase4_vector_timeout_repairs.py | 354 +++++++++++++ 11 files changed, 2830 insertions(+) create mode 100644 app/infrastructure/openai_embeddings.py create mode 100644 app/modules/documents/chunking.py create mode 100644 app/modules/documents/embeddings.py create mode 100644 app/modules/documents/operational_limits.py create mode 100644 app/modules/documents/processing.py create mode 100644 tests/integration/test_phase4.py create mode 100644 tests/support/embedding.py create mode 100644 tests/unit/test_phase4.py create mode 100644 tests/unit/test_phase4_closure.py create mode 100644 tests/unit/test_phase4_repairs.py create mode 100644 tests/unit/test_phase4_vector_timeout_repairs.py diff --git a/app/infrastructure/openai_embeddings.py b/app/infrastructure/openai_embeddings.py new file mode 100644 index 0000000..6cef7f1 --- /dev/null +++ b/app/infrastructure/openai_embeddings.py @@ -0,0 +1,316 @@ +"""One-call OpenAI-compatible REST adapter. No SDK or provider auto retries.""" +from collections.abc import Sequence +from copy import deepcopy +from http.client import HTTPException +import json +import math +from queue import Queue, Empty +import re +from threading import BoundedSemaphore, Thread +import time +from urllib.error import HTTPError, URLError +from urllib.parse import urlsplit +from urllib.request import Request, HTTPRedirectHandler, build_opener + +from app.modules.documents.embeddings import ( + EmbeddingError, EmbeddingProviderError, EmbeddingLimits, packed_vector, + validate_embedding_profile, validate_counter, validated_limits, + is_representable_timeout, validate_endpoint_hostname, +) + +_CAPACITY = BoundedSemaphore(1) +_ERROR_BODY_LIMIT = 64 * 1024 +# Current official OpenAI codes + the broader/legacy quota category. +_PERMANENT_QUOTA_CODES = frozenset({ + "credit_balance_exhausted", "organization_spend_limit_exceeded", + "project_spend_limit_exceeded", "organization_usage_limit_exceeded", + "insufficient_quota", +}) + + +class TiktokenCounter: + """Explicit encoding. Deployment must establish endpoint/model compatibility.""" + def __init__(self, encoding): + import tiktoken + self.identity = "tiktoken:" + encoding + self._encoding = tiktoken.get_encoding(encoding) + + def count(self, text): + return len(self._encoding.encode(text, disallowed_special=())) + + +def _bounded_json(content): + """Limit structural depth before decoding; reject ambiguous/nonstandard JSON.""" + text = content.decode("utf-8-sig") + depth, quoted, escaped = 0, False, False + for character in text: + if quoted: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + quoted = False + elif character == '"': + quoted = True + elif character in "[{": + depth += 1 + if depth > 64: + raise ValueError("Excessive JSON nesting") + elif character in "]}": + depth -= 1 + + def unique_fields(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate JSON field") + result[key] = value + return result + + def invalid_constant(value): + raise ValueError("Nonstandard JSON number") + + return json.loads(text, object_pairs_hook=unique_fields, parse_constant=invalid_constant) + + +def _quota_exhausted(content): + if content is None: + return False + try: + native = _bounded_json(content) + error = native.get("error") if isinstance(native, dict) else None + if isinstance(error, dict): + return any(isinstance(error.get(field), str) and error[field] in _PERMANENT_QUOTA_CODES + for field in ("code", "type")) + except (ValueError, TypeError, RecursionError): + pass + return False + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +class _ResponseLimit(EmbeddingError): + pass + + +class OpenAICompatibleEmbeddings: + def __init__(self, *, profile, api_key, limits, timeout_seconds=60, + send_dimensions=False, max_response_bytes=16 * 1024 * 1024, + token_counter=None): + validate_embedding_profile(profile) + invalid = False + try: + endpoint = profile.endpoint + endpoint.encode("ascii") + parsed = urlsplit(endpoint) + is_local = parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1", "::1") + if ((parsed.scheme != "https" and not is_local) or not parsed.hostname or parsed.username or parsed.password + or parsed.query or parsed.fragment or parsed.port == 0 or parsed.netloc.endswith(":") + or (":" in parsed.hostname and not parsed.netloc.startswith("[")) + or not validate_endpoint_hostname(parsed.hostname) + or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path) + or any(c.isspace() or ord(c) < 32 for c in endpoint) + or any(c in endpoint for c in ("@", "?", "#", "%", "\\", ";"))): + invalid = True + if not is_representable_timeout(timeout_seconds): + invalid = True + else: + timeout_seconds = float(timeout_seconds) + except (ValueError, TypeError, UnicodeError, OverflowError): + invalid = True + if invalid: + raise EmbeddingError("Invalid hosted embedding endpoint or timeout") + if (not isinstance(api_key, str) or not api_key + or any(not 33 <= ord(c) <= 126 for c in api_key)): + raise EmbeddingError("Embedding credentials require visible ASCII header characters") + # http.client encodes headers as Latin-1; visible ASCII is compatible and + # excludes control/header injection before any provider work. + ("Bearer " + api_key).encode("ascii") + if type(max_response_bytes) is not int or max_response_bytes <= 0: + raise EmbeddingError("Bounded embedding response limit required") + if type(send_dimensions) is not bool: + raise EmbeddingError("Dimension capability must be explicit") + self._profile = deepcopy(profile) + self._key = api_key + self.limits = validated_limits(limits) + self.timeout = timeout_seconds + self.send_dimensions = send_dimensions + self.response_limit = max_response_bytes + self.counter = token_counter + validate_counter(self.counter, self.limits) + + @property + def profile(self): + return self._profile + + @property + def request_policy(self): + return dict(limits=self.limits.model_dump(), timeout_seconds=self.timeout, + send_dimensions=self.send_dimensions, max_response_bytes=self.response_limit) + + @classmethod + def from_settings(cls, settings, *, token_counter=None): + from pydantic import SecretStr + from app.modules.documents.settings import IngestionSettings + if not isinstance(settings, IngestionSettings): + raise EmbeddingError("Valid ingestion settings required") + if not isinstance(settings.embedding_api_key, SecretStr): + raise EmbeddingError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter") + if settings.embedding_limits is None: + raise EmbeddingError("Explicit endpoint-specific embedding limits required") + invalid = False + try: + profile = settings.embedding_profile + except (ValueError, TypeError, AttributeError, OverflowError): + invalid = True + if invalid: + raise EmbeddingError("Invalid configured embedding profile") + return cls(profile=profile, api_key=settings.embedding_api_key.get_secret_value(), + limits=settings.embedding_limits, timeout_seconds=settings.embedding_timeout_seconds, + send_dimensions=settings.embedding_send_dimensions, + max_response_bytes=settings.embedding_max_response_bytes, token_counter=token_counter) + + def embed(self, texts): + # The port takes a bounded sequence. Do not consume an arbitrary iterator. + if not isinstance(texts, Sequence) or isinstance(texts, (str, bytes, bytearray)): + raise EmbeddingError("Embedding inputs require a bounded text sequence") + if not texts or len(texts) > self.limits.max_batch_inputs: + raise EmbeddingError("Embedding batch input limit exceeded") + identity, policy = deepcopy(self.profile), deepcopy(self.request_policy) + bounded_texts = [] + for text in texts: + if len(bounded_texts) >= self.limits.max_batch_inputs: + raise EmbeddingError("Embedding batch input limit exceeded") + bounded_texts.append(text) + texts = tuple(bounded_texts) + self.limits.validate_batch(texts, self.counter) + if self.profile != identity or self.request_policy != policy: + raise EmbeddingError("Embedding profile changed during input validation") + body = dict(model=identity.model, input=texts, encoding_format="float") + if self.send_dimensions: + body["dimensions"] = identity.dimensions + request = Request(identity.endpoint.rstrip("/") + "/embeddings", + data=json.dumps(body, allow_nan=False).encode("utf-8"), + headers={"Authorization": "Bearer " + self._key, "Content-Type": "application/json"}) + content = self._request_once(request) + if self.profile != identity or self.request_policy != policy: + raise EmbeddingError("Embedding profile changed during provider work") + invalid = False + try: + native = _bounded_json(content) + if native["model"] != identity.model: + raise ValueError() + data = native["data"] + if not isinstance(data, list) or len(data) != len(texts): + raise ValueError() + ordered = [None] * len(texts) + for item in data: + index = item["index"] + if type(index) is not int or not 0 <= index < len(texts) or ordered[index] is not None: + raise ValueError() + vector = item["embedding"] + if not isinstance(vector, list): + raise ValueError() + captured_vec = tuple(vector) + packed_vector(captured_vec, identity.dimensions) + ordered[index] = captured_vec + if any(v is None for v in ordered): + raise ValueError() + except (KeyError, TypeError, ValueError, OverflowError, RecursionError): + invalid = True + if invalid: + raise EmbeddingError("Invalid embedding provider response") + return tuple(ordered) + + def _request_once(self, request): + deadline = time.monotonic() + self.timeout + + def remaining(): + left = deadline - time.monotonic() + if left <= 0: + raise EmbeddingProviderError("Embedding deadline exceeded", retryable=True) + return left + + def read_body(stream, limit): + expected = getattr(stream, "length", None) + content = bytearray() + while True: + remaining() + part = stream.read(min(65536, limit + 1 - len(content))) + remaining() + if not part: + if expected is not None and len(content) != expected: + raise EmbeddingProviderError("Incomplete embedding HTTP response", retryable=True) + return bytes(content) + content.extend(part) + if len(content) > limit: + raise _ResponseLimit("Embedding response byte limit exceeded") + + def collect(): + failure = None + try: + with build_opener(_NoRedirect()).open(request, timeout=remaining()) as response: + return read_body(response, self.response_limit) + except HTTPError as error: + code = error.code + body = None + cleanup_failed = False + try: + if code == 429 and error.fp is not None: + try: + body = read_body(error, min(self.response_limit, _ERROR_BODY_LIMIT)) + except (_ResponseLimit, EmbeddingProviderError, HTTPException, URLError, TimeoutError, OSError): + # Partial/oversized/unavailable evidence cannot establish + # a billing code. Preserve the safe status fallback. + body = None + retryable = (code in (408, 429) or 500 <= code < 600) + if code == 429 and _quota_exhausted(body): + retryable = False + finally: + try: + error.close() + except OSError: + cleanup_failed = True + remaining() # Includes error parsing and response cleanup. + failure = EmbeddingProviderError( + "Embedding provider cleanup failed" if cleanup_failed else "Embedding provider request failed", + retryable=retryable) + except (HTTPException, URLError, TimeoutError, OSError): + failure = EmbeddingProviderError("Embedding transport failed", retryable=True) + # Raise after leaving the raw exception handler so URLs, bodies and + # secret-bearing transport exceptions are not retained as context. + raise failure + + outcome = Queue(maxsize=1) + def run(): + try: + result = (True, collect()) + except Exception as error: + # Carry unexpected programming failures to the caller unchanged; + # normalization occurs only at known transport/input boundaries. + result = (False, error) + finally: + _CAPACITY.release() + outcome.put(result) + + if not _CAPACITY.acquire(blocking=False): + raise EmbeddingProviderError("Embedding transport capacity occupied", retryable=True) + try: + Thread(target=run, daemon=True, name="embedding-request").start() + except Exception as error: + _CAPACITY.release() + if isinstance(error, (OSError, RuntimeError)): + raise EmbeddingProviderError("Embedding transport unavailable", retryable=True) from None + raise + try: + success, result = outcome.get(timeout=remaining()) + except Empty: + raise EmbeddingProviderError("Embedding deadline exceeded", retryable=True) from None + remaining() + if not success: + raise result + return result diff --git a/app/modules/documents/chunking.py b/app/modules/documents/chunking.py new file mode 100644 index 0000000..19d6f83 --- /dev/null +++ b/app/modules/documents/chunking.py @@ -0,0 +1,397 @@ +"""Deterministic faithful chunk drafts; atomic semantic groups never lose exceptions.""" +import hashlib +import re +import unicodedata + +from .extraction import ExtractionError, RULE, PLACEHOLDER, HEADING +from .extraction_artifacts import validate_artifact, serialize_artifact +from .normalization import normalize_search_text +from .types import ChunkDraft + + +DEPENDENT_HEADING = re.compile( + r"^\s*(?:#{1,6}\s*)?(?:Notes?|Exceptions?|Conditions?|Exclusions?|" + r"(?:تبصره|یادداشت)(?:(?:‌| )?ها(?:ی)?)?|استثنا(?:‌?ها|ئات|ء)?|شرایط|شروط|ملاحظات)" + r"(?=\s|[::]|$)", re.I) +RULE_LABELS = r"Articles?|Clauses?|Circulars?|Decisions?|مواد|ماده|بند|بخشنامه|تصمیم" +# A date qualifier introduces metadata, not an identifier (e.g. Decision dated). +NOT_DATE_QUALIFIER = r"(?![ \t]+(?:dated|مورخ)(?=[ \t]|$))" +GOVERNING_RULE = re.compile( + r"^\s*(?:#{1,6}\s*)?(?:" + RULE_LABELS + r")" + NOT_DATE_QUALIFIER + r"(?=[ \t]|\d|$)", re.I) + + +DEPENDENT_PROSE = re.compile( + r"^\s*(?:Except|Unless|Provided(?:\s+that)?|Only\s+(?:if|when)|به\s+شرط|مشروط|مگر)" + r"(?=\s|[::]|$)", re.I) + + +def dependent_content(text): + return bool(DEPENDENT_HEADING.match(text) or DEPENDENT_PROSE.match(text)) + + +REFERENCE = re.compile(r"(?" + RULE_LABELS + r")" + NOT_DATE_QUALIFIER + r"(?=[ \t]|\d|$)[ \t]*", re.I) +IDENTIFIER = re.compile(r"\d+(?:[./]\d+)*(?:\((?:\d+|[^\W\d_]+)\))*") +REFERENCE_KINDS = {"article": 0, "ماده": 0, "clause": 1, "بند": 1, + "circular": 2, "بخشنامه": 2, "decision": 3, "تصمیم": 3, + "articles": 0, "مواد": 0, "clauses": 1, "circulars": 2, "decisions": 3} +INCIDENTAL_CITATION = re.compile( + r"^\s*(?:See\b|Refer\s+to\b|According\s+to\b|For\s+background\b|" + r"مطابق\s|طبق\s|رجوع\s|مراجعه\s|ارجاع\s)", re.I) +# A citation sentence is incidental only when it does not also state applicability. +APPLICABILITY = re.compile( + r"\b(?:appl(?:y|ies|icable)|governs?|only|except|unless)\b|" + r"فقط|صرفاً|تنها|اعمال|شامل|مربوط", re.I) + + +def reference_identity(match, text): + # Read the entire token, then validate it: a valid numeric prefix is not an ID. + token = re.match(r"[^\s::,،;؛!?؟]+", text[match.end():]) + identifier = token[0] if token else "" + if token and re.match(r"[ \t]+(?:\.|/|\(|\[|-|–|—|ـ)", text[match.end() + token.end():]): + raise ExtractionError("Unsupported spaced governing-rule identifier") + if identifier.endswith("."): + identifier = identifier[:-1] # One sentence-final stop, not an internal dot. + if not IDENTIFIER.fullmatch(identifier): + raise ExtractionError("Unsupported governing-rule identifier") + # Digit-script equivalence is local to association; faithful/search text is untouched. + identifier = "".join(str(unicodedata.decimal(c)) if c.isdecimal() else c for c in identifier) + return REFERENCE_KINDS[match["label"].lower()], identifier + + +CONNECTOR = re.compile(r"[ \t]*(?:(?P,|،|and\b|or\b|&|و(?=\s)|یا(?=\s))|(?Pthrough\b|to\b|تا(?=\s)|الی(?=\s)))[ \t]*", re.I) +ORDINARY_DECISION = re.compile(r"(?:is|was|will|shall|has|remains|must)\b|نهایی|قطعی|است", re.I) + + +def rule_references(text): + references = set() + for match in REFERENCE.finditer(text): + rest = text[match.end():] + if match["label"].lower() == "decision" and ORDINARY_DECISION.match(rest): + continue + first = reference_identity(match, text) + references.add(first) + token = re.match(r"[^\s::,،;؛!?؟]+", rest) + offset = match.end() + token.end() + previous = first + while connector := CONNECTOR.match(text, offset): + offset = connector.end() + labelled = REFERENCE.match(text, offset) + if labelled: + current = reference_identity(labelled, text) + token_start = labelled.end() + else: + synthetic = REFERENCE.match(match["label"] + " ") + current = reference_identity(synthetic, match["label"] + " " + text[offset:]) + token_start = offset + token = re.match(r"[^\s::,،;؛!?؟]+", text[token_start:]) + offset = token_start + token.end() + if connector["range"]: + if current[0] != previous[0] or not previous[1].isdigit() or not current[1].isdigit(): + raise ExtractionError("Unsupported governing-rule identifier range") + if int(current[1]) < int(previous[1]): + raise ExtractionError("Unsupported governing-rule identifier range") + references.add(current) + previous = current + return references + + +def governing_lines(blocks): + lines = [line for b in blocks for line in b.text.splitlines() + if GOVERNING_RULE.match(line) and rule_references(line)] + for line in lines: + rule_references(line) # Reject unsupported forms even without a dependent unit. + return lines + + +def validate_reference_line(line, governing): + expected = {reference_identity(REFERENCE.search(governing), governing)} + rule_references(line) # Validate complete tokens before sentence segmentation. + for sentence in re.split(r"\.(?=\s|$)|[;؛]", line): + references = rule_references(sentence) + if not references: + continue + if INCIDENTAL_CITATION.match(sentence) and not APPLICABILITY.search(sentence): + continue + if references != expected: + raise ExtractionError("Ambiguous explicit governing rule reference") + + +def validate_dependency_references(blocks, governing): + """Inspect every dependent line, including dependencies inside a source group.""" + in_dependency = False + for block in blocks: + for line in block.text.splitlines(): + if GOVERNING_RULE.match(line): + in_dependency = False + elif dependent_content(line): + in_dependency = True + if in_dependency: + validate_reference_line(line, governing) + + +def validate_faq_rule_scopes(blocks): + """Heading ancestry bounds FAQ dependencies regardless of rule count.""" + stack = [] + governing, dependent = None, False + for block in blocks: + for line in block.text.splitlines(): + heading = HEADING.match(line) + rule = GOVERNING_RULE.match(line) + if heading: + level = len(heading[1]) + while stack and stack[-1][0] >= level: + stack.pop() + governing, dependent = stack[-1][1:] if stack else (None, False) + if rule: + if dependent: + raise ExtractionError("Ambiguous rule inside FAQ dependency") + governing, dependent = line, False + else: + dependent = dependent or dependent_content(line) + stack.append((level, governing, dependent)) + elif rule: + raise ExtractionError("Multiple FAQ rules require explicit heading hierarchy") + elif dependent_content(line): + dependent = True + if stack: + stack[-1] = (stack[-1][0], governing, dependent) + if dependent: + if governing is None: + raise ExtractionError("Ambiguous governing rule in FAQ hierarchy") + validate_reference_line(line, governing) + + +def validate_visual_rule_scopes(blocks, *, faq=False): + """Resolve a dependency through its explicit ancestor, never a sibling.""" + contexts = {} + for index, block in enumerate(blocks): + parent = block.parent_block_id + if index and parent not in contexts and not (faq and parent is None): + raise ExtractionError("Visual dependencies require explicit parent links") + governing, dependent = contexts[parent] if parent is not None else (None, False) + own_rules = governing_lines([block]) + if len(own_rules) > 1 or (dependent and own_rules): + raise ExtractionError("Ambiguous rule inside visual dependency") + if own_rules: + governing, dependent = own_rules[0], False + for line in block.text.splitlines(): + if dependent_content(line): + dependent = True + if dependent: + if governing is None: + raise ExtractionError("Ambiguous governing rule in visual hierarchy") + validate_reference_line(line, governing) + contexts[block.block_id] = (governing, dependent) + + +def associate_dependencies(units): + """Only an explicit adjacent governing rule can receive a separate note unit.""" + associated = [] + for group, blocks, atomic in units: + faq = any(b.block_type == "question" for b in blocks) and any(b.block_type == "answer" for b in blocks) + dependent = dependent_content(blocks[0].text) and not faq + own_rules = governing_lines(blocks) + if dependent and own_rules: + raise ExtractionError("Ambiguous governing rule inside dependent source group") + if any(dependent_content(line) for b in blocks for line in b.text.splitlines()): + if own_rules: + if faq and any(b.parent_block_id is not None for b in blocks): + validate_visual_rule_scopes(blocks, faq=True) + elif faq and (len(own_rules) > 1 or any(HEADING.match(line) for line in own_rules)): + validate_faq_rule_scopes(blocks) + elif blocks[0].block_type == "visual_group": + validate_visual_rule_scopes(blocks) + elif len(own_rules) == 1: + validate_dependency_references(blocks, own_rules[0]) + else: + raise ExtractionError("Ambiguous governing rule inside dependent source group") + elif not dependent and not faq and not (blocks[0].block_type == "visual_group" + and all(b.parent_block_id == blocks[0].block_id for b in blocks[1:])): + raise ExtractionError("Ambiguous governing rule for dependent source content") + if dependent: + if not associated: + raise ExtractionError("Ambiguous governing rule for dependent source content") + previous = associated[-1] + rule_lines = governing_lines(previous[1]) + if len(rule_lines) != 1: + raise ExtractionError("Ambiguous governing rule for dependent source content") + validate_dependency_references(blocks, rule_lines[0]) + previous[1].extend(blocks) + previous[2] = True + else: + if associated and not semantic_boundary(blocks[0]): + previous_rules = [line for b in associated[-1][1] for line in b.text.splitlines() + if GOVERNING_RULE.match(line)] + own_rules = [line for b in blocks for line in b.text.splitlines() + if GOVERNING_RULE.match(line)] + own_heading = (blocks[0].block_type in ("heading", "visual_group") + and bool(blocks[0].heading)) + if previous_rules and not own_rules and not own_heading: + raise ExtractionError("Ambiguous unlabelled rule continuation across source groups") + associated.append([group, list(blocks), atomic]) + return associated + + +def semantic_boundary(block): + return (bool(RULE.match(block.text) or GOVERNING_RULE.match(block.text)) or block.block_type == "heading") and not DEPENDENT_HEADING.match(block.text) + + +def factual_context_units(blocks): + """Resolve full FAQ source structure before inclusion; never infer prose scope.""" + source_units, seen = [], set() + for block in blocks: + if block.group_id is not None: + if source_units and source_units[-1][0] == block.group_id: + source_units[-1][1].append(block) + else: + if block.group_id in seen: + raise ExtractionError("Noncontiguous source group") + seen.add(block.group_id) + source_units.append([block.group_id, [block], True]) + else: + source_units.append([None, [block], False]) + scopes, resolved = [], [] + + def close_scope(): + scope = scopes.pop() + if not scope["used"]: + raise ExtractionError("Governing FAQ context has no associated pairs") + + for group, unit, _ in source_units: + if group is not None: + if not any(b.block_type == "question" for b in unit): + 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"]] + for scope in scopes: + scope["used"] = True + resolved.append([group, context + unit, True]) + continue + block = unit[0] + lines = [line for line in block.text.splitlines() if line.strip()] + heading = HEADING.match(lines[0]) if lines else None + if heading: + if sum(bool(HEADING.match(line)) for line in lines) != 1: + raise ExtractionError("Ambiguous FAQ context heading structure") + level = len(heading[1]) + while scopes and scopes[-1]["level"] >= level: + close_scope() + scopes.append(dict(level=level, blocks=[block], used=False)) + 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. + raise ExtractionError("Ambiguous governing context for factual FAQ") + while scopes: + close_scope() + # Run the established dependency checks with each pair's complete context. + return associate_dependencies(resolved) + + +def factual_review_blocks(envelope): + """Expose each retained context block once, in its real source order.""" + units = factual_context_units(envelope.blocks) + identities = {b.block_id for _, blocks, _ in units for b in blocks} + return tuple(b for b in envelope.blocks if b.block_id in identities) + + +def chunk_extraction(envelope, processing_profile, *, corpus_purpose="source_document", included_group_ids=None): + # Treat even an in-memory envelope as untrusted consumption input. + payload = serialize_artifact(envelope, processing_profile) + envelope = validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(), + document_id=envelope.document_id, original_sha256=envelope.original_sha256, + processing_profile=processing_profile) + if corpus_purpose not in ("source_document", "approved_factual"): + raise ExtractionError("Behavioral evaluation and live-data placeholders are not knowledge") + if any(b.block_type in ("question", "answer") for b in envelope.blocks) and corpus_purpose != "approved_factual": + raise ExtractionError("FAQ requires separately approved factual corpus") + profile = processing_profile + if profile["chunker"] not in ("paragraph-v1", "semantic-boundaries-v1") or profile["size_unit"] != "characters": + raise ExtractionError("Unsupported frozen chunk policy or size unit") + size, overlap = profile["chunk_size"], profile["overlap"] + if size <= 0 or not 0 <= overlap < size: + raise ExtractionError("Invalid frozen chunk bounds") + # Source groups must be contiguous; regrouping distant blocks would reorder evidence. + blocks_to_chunk = envelope.blocks + if included_group_ids is not None: + groups = {b.group_id for b in envelope.blocks if b.block_type in ("question", "answer")} + if (corpus_purpose != "approved_factual" or not included_group_ids + or not set(included_group_ids) <= groups): + raise ExtractionError("Invalid whole-group factual inclusion") + context_units = factual_context_units(envelope.blocks) + blocks_to_chunk = () + units, seen_groups = [], set() + for block in blocks_to_chunk: + if PLACEHOLDER.search(block.text): + raise ExtractionError("Placeholder is not authoritative knowledge") + if block.group_id: + if units and units[-1][0] == block.group_id: + units[-1][1].append(block) + else: + if block.group_id in seen_groups: + raise ExtractionError("Noncontiguous source group") + units.append([block.group_id, [block], True]) + seen_groups.add(block.group_id) + elif units and units[-1][0] is None and not semantic_boundary(block) and not dependent_content(block.text): + # A circular decision, conditions and exclusions remain together until an + # explicit article/clause/heading boundary. PDF page breaks do not split rules. + units[-1][1].append(block) + else: + units.append([None, [block], False]) + if included_group_ids is not None: + units = [unit for unit in context_units if unit[0] in included_group_ids] + for _, blocks, _ in units: + if any(PLACEHOLDER.search(b.text) for b in blocks): + raise ExtractionError("Placeholder is not authoritative knowledge") + chunks = [] + for group, blocks, atomic in associate_dependencies(units): + parts = [] + for index, block in enumerate(blocks): + if (index and not blocks[index - 1].text.endswith(("\n", "\r")) + and not block.text.startswith(("\n", "\r"))): + parts.append("\n") + parts.append(block.text) + text = "".join(parts) + if not text.strip(): + continue + sections = list(dict.fromkeys(value for b in blocks for value in (b.section, b.source_locator) if value)) + pages = list(dict.fromkeys(b.page for b in blocks)) + section = " | ".join(sections) + page = pages[0] if len(pages) == 1 else None + # Keep page ranges in section when a semantic rule spans pages. + if len(pages) > 1: + section = "pages/" + ",".join(str(p) for p in pages if p is not None) + " | " + section + # FAQ, visual groups, regulations and conditional circulars are indivisible. + protected = atomic or any(RULE.match(b.text) or GOVERNING_RULE.match(b.text) for b in blocks) or bool(re.search( + r"تبصره|استثنا|مگر|مشروط|به\s+شرط|نمی|نباید|نیست|" + r"\b(?:except|unless|provided|condition|not|exclusion|note)\b", text, re.I)) + normalized = normalize_search_text(text, profile["normalizer"]) + if protected and len(normalized) > size: + raise ExtractionError("Semantic group exceeds chunk bound; cannot separate required context") + if len(normalized) <= size: + chunks.append(ChunkDraft(len(chunks), text, page, section)) + else: + # Faithful character windows, bounded by actual normalized length; no trim. + start = 0 + while start < len(text): + end = min(len(text), start + size) + while len(normalize_search_text(text[start:end], profile["normalizer"])) > size: + end -= 1 + if end <= start: + raise ExtractionError("Chunk cannot fit character bound") + if end < len(text): + boundary = text.rfind("\n", start + size // 2, end) + if boundary >= 0: + end = boundary + 1 + chunks.append(ChunkDraft(len(chunks), text[start:end], page, section)) + if len(chunks) > profile["limits"]["max_chunks"]: + raise ExtractionError("Chunk count limit exceeded") + if end == len(text): + break + start = max(start + 1, end - min(overlap, end - start - 1)) + if len(chunks) > profile["limits"]["max_chunks"]: + raise ExtractionError("Chunk count limit exceeded") + if not chunks: + raise ExtractionError("No indexable chunks") + return tuple(chunks) diff --git a/app/modules/documents/embeddings.py b/app/modules/documents/embeddings.py new file mode 100644 index 0000000..b72301e --- /dev/null +++ b/app/modules/documents/embeddings.py @@ -0,0 +1,372 @@ +"""Bounded embedding preparation. No database connections or publication.""" +from array import array +from collections.abc import Mapping +from contextlib import contextmanager +from copy import deepcopy +from dataclasses import asdict, replace +import ipaddress +import json +import math +import re +import socket +import struct +from typing import Literal, Protocol + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from .normalization import NORMALIZATION_POLICY, normalize_search_text +from .types import ChunkDraft, EmbeddingProfile, StagedDocument + + +class EmbeddingError(ValueError): + """Safe permanent configuration, input, response or staging failure.""" + retryable = False + + +class EmbeddingProviderError(EmbeddingError): + def __init__(self, message, *, retryable): + super().__init__(message) + self.retryable = retryable + + +class TokenCounter(Protocol): + identity: str + def count(self, text: str) -> int: ... + + +class EmbeddingLimits(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + unit: Literal["tokens", "utf8_bytes"] + max_input_units: int = Field(gt=0, strict=True) + max_batch_units: int = Field(gt=0, strict=True) + max_batch_inputs: int = Field(gt=0, strict=True) + tokenizer: str | None = None + + @model_validator(mode="after") + def coherent(self): + if self.max_batch_units < self.max_input_units: + raise ValueError("Batch limit must accommodate one maximum input") + if self.unit == "tokens" and (not self.tokenizer or not self.tokenizer.strip()): + raise ValueError("Token limits require an explicit compatible tokenizer") + if self.unit == "utf8_bytes" and self.tokenizer is not None: + raise ValueError("Byte limits do not specify a tokenizer") + if self.tokenizer is not None: + validate_database_string(self.tokenizer) + return self + + def measure(self, text, counter=None): + if not isinstance(text, str) or not text.strip(): + raise EmbeddingError("Embedding input must be nonempty text") + encoded = validate_database_string(text) + validate_counter(counter, self) + if self.unit == "tokens": + failed = False + try: + count = counter.count(text) + except EmbeddingError: + raise + except (ValueError, TypeError, OverflowError): + failed = True + if failed: + raise EmbeddingError("Token counting failed") + validate_counter(counter, self) + if type(count) is not int or not 0 < count <= 2**31 - 1: + raise EmbeddingError("Invalid token count") + else: + count = len(encoded) + if count > self.max_input_units: + raise EmbeddingError("Embedding input limit exceeded") + return count + + def validate_batch(self, texts, counter=None): + if not texts or len(texts) > self.max_batch_inputs: + raise EmbeddingError("Embedding batch input limit exceeded") + counts = tuple(self.measure(text, counter) for text in texts) + if sum(counts) > self.max_batch_units: + raise EmbeddingError("Embedding batch unit limit exceeded") + return counts + +def validate_database_string(value): + """PostgreSQL UTF-8 text/JSONB compatibility; never rewrite evidence.""" + if not isinstance(value, str) or "\x00" in value: + raise EmbeddingError("Embedding evidence requires database-compatible text") + invalid = False + try: + encoded = value.encode("utf-8") + except UnicodeEncodeError: + invalid = True + if invalid: + raise EmbeddingError("Embedding evidence requires valid UTF-8 text") + return encoded + + +def validate_embedding_profile(profile): + if not isinstance(profile, EmbeddingProfile): + raise EmbeddingError("Explicit embedding profile required") + if type(profile.dimensions) is not int or not 1 <= profile.dimensions <= 16000: + raise EmbeddingError("Embedding dimension must be a supported positive integer") + for name in ("provider", "endpoint", "model", "preprocessing_version"): + value = getattr(profile, name) + validate_database_string(value) + if not value.strip() or any(ord(c) < 32 or ord(c) == 127 for c in value): + raise EmbeddingError("Invalid embedding profile identity") + + +def validated_limits(value): + from pydantic import ValidationError + if isinstance(value, EmbeddingLimits): + value = value.model_dump() + if not isinstance(value, Mapping): + raise EmbeddingError("Explicit embedding input and batch limits required") + invalid = False + try: + result = EmbeddingLimits.model_validate(dict(value)) + except ValidationError: + invalid = True + if invalid: + raise EmbeddingError("Invalid embedding input or batch limits") + return result + + +def validate_counter(counter, limits): + if counter is not None: + identity = getattr(counter, "identity", None) + if not isinstance(identity, str) or not identity.strip() or not callable(getattr(counter, "count", None)): + raise EmbeddingError("Valid compatible token counter required") + validate_database_string(identity) + if limits.unit == "tokens" and (counter is None or counter.identity != limits.tokenizer): + raise EmbeddingError("Compatible configured token counter required") + + + +def validate_endpoint_hostname(hostname: str) -> bool: + """Validate runtime hostname syntax and IDNA encoding without DNS or network calls.""" + if not isinstance(hostname, str) or not hostname or len(hostname) > 253: + return False + if not re.fullmatch(r"[A-Za-z0-9.:-]+", hostname): + return False + # Check IPv6 + if ":" in hostname: + try: + ipaddress.IPv6Address(hostname) + return True + except ValueError: + return False + labels = hostname.split(".") + # Empty interior, leading, or trailing DNS labels, or labels longer than 63 characters + if any(len(label) == 0 or len(label) > 63 for label in labels): + return False + try: + hostname.encode("idna") + except (UnicodeError, ValueError): + return False + # If all numeric, must be valid IPv4 + if all(label.isdigit() for label in labels): + try: + ipaddress.IPv4Address(hostname) + return True + except ValueError: + return False + for label in labels: + if not re.fullmatch(r"[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?", label): + return False + return True + + +def is_representable_timeout(seconds: object) -> bool: + """Account for runtime synchronization and socket timeout representation limits.""" + if type(seconds) not in (int, float): + return False + val = float(seconds) + if not math.isfinite(val) or val <= 0: + return False + # Platform socket and synchronization bounds (e.g. 32-bit timeval microseconds / milliseconds) + if val > (2**31 - 1) / 1000.0: + return False + try: + sock = socket.socket() + try: + sock.settimeout(val) + finally: + sock.close() + except (OverflowError, OSError, ValueError): + return False + return True + + +def packed_vector(vector, dimensions): + """Validate the float32 representation pgvector will actually consume.""" + if type(dimensions) is not int or dimensions <= 0: + raise EmbeddingError("Embedding dimension mismatch") + if isinstance(vector, (str, bytes, bytearray, Mapping)): + raise EmbeddingError("Embedding vector must be a sequence of numbers") + captured = [] + try: + iterator = iter(vector) + except TypeError: + raise EmbeddingError("Embedding vector must be an iterable sequence of numbers") + for item in iterator: + captured.append(item) + if len(captured) > dimensions: + break + if len(captured) != dimensions: + raise EmbeddingError("Embedding dimension mismatch") + try: + if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in captured): + raise ValueError() + packed = array("f", captured) + if len(packed) != dimensions or len(packed.tobytes()) != 4 * dimensions: + raise ValueError() + # pgvector cosine accumulates products and squared norms in float32, + # even though its final division is double precision. + # Smallest positive normal float32: FLT_MIN = 2**-126 (~1.17549435e-38). + # Reject subnormal or zero accumulated norms and ensure at least one + # component has a normal float32 square, preventing precision distortion + # (e.g. [3e-23, 0, 0] and [1e-21] * 16000) while preserving safe + # mixed-scale vectors (e.g. [1e-30, 1, 0]). + FLT_MIN = struct.unpack("=f", struct.pack("=f", 2**-126))[0] + def float32(value): + return struct.unpack("=f", struct.pack("=f", value))[0] + norm = 0.0 + max_component_sq = 0.0 + for value in packed: + v_sq = float32(value * value) + if v_sq > max_component_sq: + max_component_sq = v_sq + norm = float32(norm + v_sq) + if (not all(math.isfinite(v) for v in packed) + or not math.isfinite(norm) + or norm < FLT_MIN + or max_component_sq < FLT_MIN): + raise ValueError() + except (ValueError, TypeError, OverflowError): + raise EmbeddingError("Embedding must have a finite nonzero float32 cosine norm") from None + return packed.tobytes() + + +@contextmanager +def stage_document(provider, *, document_id, chunks, processing_profile, token_counter=None): + """Yield only complete staging; clear owned payload on failure/context exit. + + A future fenced publisher must consume the value inside this context. + The budget measures UTF-8 text/metadata + packed float32 vectors, not RSS. + """ + staged = None + drafts, vectors, inputs, counts, batch_vectors = [], [], [], [], [] + try: + validation_failed = False + in_provider_work = False + try: + identity = deepcopy(provider.profile) + request_policy = deepcopy(provider.request_policy) + validate_embedding_profile(identity) + + def check_provider(): + if provider.profile != identity or provider.request_policy != request_policy: + raise EmbeddingError("Embedding profile changed during processing") + + check_provider() + if not isinstance(processing_profile, Mapping): + raise EmbeddingError("Processing profile must be a mapping") + profile = deepcopy(dict(processing_profile)) + if any(not isinstance(profile.get(key), Mapping) for key in ("embedding", "embedding_request", "limits")): + raise EmbeddingError("Required processing profile structure is invalid") + if profile.get("normalizer") != NORMALIZATION_POLICY: + raise EmbeddingError("Unsupported or missing normalization policy") + if profile.get("embedding") != asdict(identity): + raise EmbeddingError("Embedding adapter differs from frozen profile") + if profile.get("embedding_request") != request_policy: + raise EmbeddingError("Explicit frozen embedding request policy required") + limits = validated_limits(profile["embedding_request"]["limits"]) + budget = profile["limits"]["max_staged_bytes"] + batch_size = profile["limits"]["embedding_batch_size"] + max_chunks = profile["limits"]["max_chunks"] + if any(type(n) is not int or n <= 0 for n in (budget, batch_size, max_chunks)): + raise EmbeddingError("Invalid staging limits") + batch_size = min(batch_size, limits.max_batch_inputs) + used = len(json.dumps(profile, ensure_ascii=False, allow_nan=False).encode("utf-8")) + 16 + for ordinal, chunk in enumerate(iter(chunks)): + check_provider() + if not isinstance(chunk, ChunkDraft) or not isinstance(chunk.text, str): + raise EmbeddingError("Staging requires typed text chunk drafts") + if ordinal >= max_chunks or type(chunk.ordinal) is not int or chunk.ordinal != ordinal: + raise EmbeddingError("Chunks require bounded contiguous unique ordinals") + if chunk.page is not None and (type(chunk.page) is not int or chunk.page <= 0): + raise EmbeddingError("Invalid chunk page") + if chunk.section is not None and not isinstance(chunk.section, str): + raise EmbeddingError("Invalid chunk section") + validate_database_string(chunk.text) + if chunk.section is not None: + validate_database_string(chunk.section) + text = normalize_search_text(chunk.text, profile["normalizer"]) + count = limits.measure(text, token_counter) + check_provider() + actual_tokens = count if limits.unit == "tokens" else None + if chunk.token_count is not None and (type(chunk.token_count) is not int or chunk.token_count != actual_tokens): + raise EmbeddingError("Chunk token count differs from actual tokenizer") + chunk = replace(chunk, token_count=actual_tokens) + metadata = json.dumps(asdict(chunk), ensure_ascii=False, allow_nan=False).encode("utf-8") + # Include retained evidence metadata and reserved vector bytes; input + # normalization is a temporary copy, also charged conservatively. + used += len(metadata) + len(text.encode("utf-8")) + 4 * identity.dimensions + if used > budget: + raise EmbeddingError("Staged document memory budget exceeded") + drafts.append(chunk) + inputs.append(text) + counts.append(count) + if not drafts: + raise EmbeddingError("Cannot stage an empty document") + start = 0 + check_provider() + while start < len(inputs): + end, units = start, 0 + while end < len(inputs) and end - start < batch_size and units + counts[end] <= limits.max_batch_units: + units += counts[end] + end += 1 + if end == start: + raise EmbeddingError("Input cannot fit an embedding batch") + check_provider() + in_provider_work = True + result = provider.embed(inputs[start:end]) + in_provider_work = False + check_provider() + if len(result) != end - start: + raise EmbeddingError("Exactly one vector per chunk is required") + batch_vectors.clear() + for batch_ordinal, vector in enumerate(result): + if batch_ordinal >= end - start: + raise EmbeddingError("Exactly one vector per chunk is required") + batch_vectors.append(packed_vector(vector, identity.dimensions)) + if len(batch_vectors) != end - start: + raise EmbeddingError("Exactly one vector per chunk is required") + check_provider() + vectors.extend(batch_vectors) + start = end + check_provider() + staged = StagedDocument(document_id, profile, tuple(drafts), tuple(vectors), identity, used) + inputs.clear() + counts.clear() + except EmbeddingError: + # Worker retry classification from the adapter remains authoritative. + raise + except (KeyError, TypeError, AttributeError, ValueError, OverflowError, RecursionError): + if in_provider_work: + raise + validation_failed = True + # Do not retain raw validation exceptions (possibly containing source + # text/secrets) as the public exception's context. + if validation_failed: + raise EmbeddingError("Invalid embedding staging profile or drafts") + check_provider() + yield staged + finally: + inputs.clear() + counts.clear() + drafts.clear() + vectors.clear() + batch_vectors.clear() + result = None + vector = None + profile = None + if staged is not None: + staged.close() diff --git a/app/modules/documents/operational_limits.py b/app/modules/documents/operational_limits.py new file mode 100644 index 0000000..8cb832b --- /dev/null +++ b/app/modules/documents/operational_limits.py @@ -0,0 +1,28 @@ +"""Conservative operational bounds shared by configuration and runtime consumers.""" +import math +from threading import TIMEOUT_MAX + +MAX_OPERATIONAL_SECONDS = min(TIMEOUT_MAX, (2**31 - 1) / 1000.0) +MIN_OPERATIONAL_SECONDS = 1e-6 # PostgreSQL interval/timestamp microsecond precision. + + +def validate_duration(value): + valid = False + if type(value) in (int, float): + try: + valid = math.isfinite(value) and MIN_OPERATIONAL_SECONDS <= value <= MAX_OPERATIONAL_SECONDS + except OverflowError: + pass + if not valid: + raise ValueError("Operational duration is not representable by runtime or PostgreSQL") + return float(value) + + +def validate_worker_durations(settings): + for name in ("poll_seconds", "heartbeat_seconds", "lease_seconds", + "retry_base_seconds", "retry_cap_seconds"): + validate_duration(getattr(settings, name)) + if settings.heartbeat_seconds >= settings.lease_seconds: + raise ValueError("Heartbeat must be shorter than lease") + if settings.retry_base_seconds > settings.retry_cap_seconds: + raise ValueError("Retry base must not exceed retry cap") diff --git a/app/modules/documents/processing.py b/app/modules/documents/processing.py new file mode 100644 index 0000000..7f538f2 --- /dev/null +++ b/app/modules/documents/processing.py @@ -0,0 +1,34 @@ +"""Phase 3 preparation only. No claims, attachment, embedding or publication.""" +from dataclasses import dataclass +import hashlib + +from .chunking import chunk_extraction +from .types import ChunkDraft, ExtractionEnvelope +from .extraction import ExtractionError +from .extraction_artifacts import validate_artifact, serialize_artifact + + +@dataclass(frozen=True) +class PreparedExtraction: + envelope: ExtractionEnvelope + chunks: tuple[ChunkDraft, ...] + candidate: object + + +def prepare_extraction(store, candidates, extractor, *, document, corpus_purpose="source_document"): + profile = document["processing_profile"] + content = store.read(document["storage_key"]) + if (len(content) != document["size_bytes"] + or hashlib.sha256(content).hexdigest() != document["file_sha256"]): + raise ExtractionError("Immutable original integrity mismatch") + envelope = extractor.extract(document_id=document["id"], title=document["title"], + original_sha256=document["file_sha256"], content=content, + mime_type=document["mime_type"], processing_profile=profile) + payload = serialize_artifact(envelope, profile) + envelope = validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(), + document_id=document["id"], original_sha256=document["file_sha256"], processing_profile=profile) + # Candidate retention is independent of OCR/chunk/embedding identity. Nothing + # here attaches a pointer to a document or accepts a candidate for runtime reuse. + candidate = candidates.put(envelope, processing_profile=profile) + chunks = chunk_extraction(envelope, profile, corpus_purpose=corpus_purpose) + return PreparedExtraction(envelope, chunks, candidate) diff --git a/tests/integration/test_phase4.py b/tests/integration/test_phase4.py new file mode 100644 index 0000000..cf0210b --- /dev/null +++ b/tests/integration/test_phase4.py @@ -0,0 +1,211 @@ +"""Real PostgreSQL: failed final embedding batch has no publication effects.""" +from concurrent.futures import ThreadPoolExecutor +from uuid import uuid4 +import pytest +from sqlalchemy import text + +from app.infrastructure.file_store import LocalFileStore +from app.infrastructure.intake_repository import SqlIntakeRepository +from app.modules.documents.embeddings import EmbeddingLimits, EmbeddingProviderError, stage_document +from app.modules.documents.intake import import_document, status +from app.modules.documents.types import ChunkDraft +from tests.unit.test_phase4 import FakeProvider + + +def test_concurrent_final_batch_failures_preserve_zero_chunks(migrated_db, settings, tmp_path): + engine, _ = migrated_db + organization, administrator = uuid4(), uuid4() + with engine.begin() as conn: + conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'phase4')"), {"id": organization}) + conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role) + VALUES (:id,:org,:name,'fixture-only','admin')"""), + dict(id=administrator, org=organization, name=str(administrator))) + settings = settings.model_copy(update={"embedding_limits": EmbeddingLimits( + unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)}) + store = LocalFileStore(tmp_path / "originals") + source = tmp_path / "sample.md" + source.write_text("immutable evidence", encoding="utf-8") + repository = SqlIntakeRepository(engine) + document = import_document(repository, store, settings, path=source, + administrator_id=administrator, request_id=uuid4())["document"] + before = status(repository, administrator_id=administrator, document_id=document["id"]) + def process(_): + provider = FakeProvider(settings, fail_at=2) + # The application has no engine/connection dependency. + with pytest.raises(EmbeddingProviderError): + with stage_document(provider, document_id=document["id"], + chunks=[ChunkDraft(i, "a") for i in range(3)], + processing_profile=document["processing_profile"]): + pytest.fail("Incomplete staged document escaped") + assert len(provider.calls) == 2 + with ThreadPoolExecutor(max_workers=2) as pool: + list(pool.map(process, range(2))) + assert status(repository, administrator_id=administrator, document_id=document["id"]) == before + assert store.read(document["storage_key"]) == source.read_bytes() + with engine.connect() as conn: + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 + +@pytest.mark.parametrize("scale", [1e-30, 1e20]) +def test_pgvector_unsafe_cosine_norm_is_rejected(migrated_db, scale): + import math + from app.modules.documents.embeddings import EmbeddingError, packed_vector + engine, _ = migrated_db + vector = [scale, 0, 0] + value = "[" + ",".join(map(str, vector)) + "]" + with engine.connect() as conn: + distance = conn.execute(text("SELECT CAST(:value AS vector) <=> CAST(:value AS vector)"), + {"value": value}).scalar_one() + assert not math.isfinite(distance) + with pytest.raises(EmbeddingError): + packed_vector(vector, 3) + + +def test_pgvector_distorted_subnormal_vector_is_rejected(migrated_db): + """pgvector cosine distance suffers ~20% distortion on [3e-23,0,0] vs [1,0,0], rejected by application.""" + from app.modules.documents.embeddings import EmbeddingError, packed_vector + engine, _ = migrated_db + with engine.connect() as conn: + distance = conn.execute( + text("SELECT CAST(:a AS vector) <=> CAST(:b AS vector)"), + {"a": "[3e-23,0,0]", "b": "[1,0,0]"}, + ).scalar_one() + # High-precision theoretical distance is 0.0 (same direction), but pgvector gives ~0.1986 + assert abs(distance - 0.198588) < 0.01 + with pytest.raises(EmbeddingError): + packed_vector([3e-23, 0, 0], 3) + with pytest.raises(EmbeddingError): + packed_vector([1e-21] * 16000, 16000) + + +def test_accepted_packed_vectors_have_valid_pgvector_cosine_distances(migrated_db): + from array import array + import math + from app.modules.documents.embeddings import packed_vector + engine, _ = migrated_db + vectors = [ + [1, 0, 0], [-1, 0, 0], [0, 1, 0], [1e-18, 0, 0], + [-1e-18, 0, 0], [1e18, 0, 0], [-1e18, 0, 0], + [1e-30, 1, 0], [1e19, 1e19, 1e19], + ] + packed = [] + for vector in vectors: + value = array("f") + value.frombytes(packed_vector(vector, 3)) + packed.append(tuple(value)) + with engine.connect() as conn: + for left in packed: + for right in packed: + result = conn.execute(text("SELECT CAST(:left AS vector) <=> CAST(:right AS vector)"), { + "left": "[" + ",".join(map(str, left)) + "]", + "right": "[" + ",".join(map(str, right)) + "]", + }).scalar_one() + expected = 1 - sum(a * b for a, b in zip(left, right)) / ( + math.sqrt(sum(a * a for a in left)) * math.sqrt(sum(b * b for b in right))) + assert math.isfinite(result) and 0 <= result <= 2 + assert result == pytest.approx(expected, abs=1e-6) + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 + + +@pytest.mark.parametrize("dim,vectors", [ + (1, [[1.0], [-1.0], [1e-18], [1e18]]), + (2, [[1.0, 0.0], [0.0, -1.0], [-1e-18, 1e-18], [1e18, 1e18]]), + (4, [ + [1.0, 0.0, 0.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [1e-18, 1e-18, 1e-18, 1e-18], + [-1e18, -1e18, -1e18, -1e18], + [1e-30, 1.0, 0.0, 0.0], + ]), +]) +def test_pgvector_cosine_references_across_dimensions_magnitudes_signs(migrated_db, dim, vectors): + from array import array + import math + from app.modules.documents.embeddings import packed_vector + engine, _ = migrated_db + packed = [] + for vector in vectors: + val = array("f") + val.frombytes(packed_vector(vector, dim)) + packed.append(tuple(val)) + with engine.connect() as conn: + for left in packed: + for right in packed: + result = conn.execute(text("SELECT CAST(:left AS vector) <=> CAST(:right AS vector)"), { + "left": "[" + ",".join(map(str, left)) + "]", + "right": "[" + ",".join(map(str, right)) + "]", + }).scalar_one() + dot = sum(a * b for a, b in zip(left, right)) + norm_a = math.sqrt(sum(a * a for a in left)) + norm_b = math.sqrt(sum(b * b for b in right)) + expected = 1.0 - (dot / (norm_a * norm_b)) + assert math.isfinite(result) and 0 <= result <= 2 + assert result == pytest.approx(expected, abs=1e-5) + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 + + +@pytest.mark.parametrize("field", ["text", "section"]) +def test_postgres_nul_strings_rejected_before_provider(migrated_db, settings, field): + import json + from dataclasses import replace + from sqlalchemy.exc import DBAPIError + from app.modules.documents.embeddings import EmbeddingError + from tests.unit.test_phase4 import profile + from tests.unit.test_phase4_closure import vision_chunks + engine, _ = migrated_db + provider, frozen, document, chunks = vision_chunks(settings, "image\x00section") + if field == "text": + chunks = [replace(chunks[0], text="evidence\x00text", section="valid")] + location = dict(page=chunks[0].page, section=chunks[0].section) + raw = json.dumps(location if field == "section" else {"text": chunks[0].text}) + with engine.connect() as conn: + with pytest.raises(DBAPIError) as caught: + conn.execute(text("SELECT CAST(:raw AS jsonb)"), {"raw": raw}) + assert caught.value.orig.sqlstate == "22P05" + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=document, chunks=chunks, processing_profile=frozen): + pytest.fail("Database-incompatible evidence escaped staging") + assert not caught.value.retryable and not provider.calls + with engine.connect() as conn: + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 + + +def test_postgres_valid_unicode_staging_roundtrip(migrated_db, settings): + import json + from tests.unit.test_phase4 import profile + engine, _ = migrated_db + provider = FakeProvider(settings) + evidence = "\u0645\u062a\u0646\u200c \u0641\u0627\u0631\u0633\u06cc\r\n\u0634\u0631\u0627\u06cc\u0637" + section = "\u0628\u062e\u0634\u200c\n\u06cc\u06a9" + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, evidence, section=section)], + processing_profile=profile(settings, provider)) as staged: + retained = staged.chunks[0] + location = dict(page=retained.page, section=retained.section) + with engine.connect() as conn: + row = conn.execute(text("SELECT CAST(:evidence AS text), CAST(:location AS jsonb)"), + dict(evidence=retained.text, location=json.dumps(location))).one() + assert row[0] == evidence and row[1] == location + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 + assert staged.closed + + +def test_postgres_token_count_range_rejected_before_provider(migrated_db, settings): + from types import SimpleNamespace + from sqlalchemy.exc import DBAPIError + from app.modules.documents.embeddings import EmbeddingError + from tests.unit.test_phase4 import profile + engine, _ = migrated_db + with engine.connect() as conn: + with pytest.raises(DBAPIError) as caught: + conn.execute(text("SELECT CAST(:count AS integer)"), {"count": 2**31}) + assert caught.value.orig.sqlstate == "22003" + provider = FakeProvider(settings) + counter = SimpleNamespace(identity="fake:closure", count=lambda text: 2**31) + provider.request_policy["limits"] = EmbeddingLimits(unit="tokens", max_input_units=2**31, + max_batch_units=2**31, max_batch_inputs=2, tokenizer=counter.identity).model_dump() + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider), token_counter=counter): + pytest.fail("Database-incompatible token count escaped") + assert not provider.calls + with engine.connect() as conn: + assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0 diff --git a/tests/support/embedding.py b/tests/support/embedding.py new file mode 100644 index 0000000..734065f --- /dev/null +++ b/tests/support/embedding.py @@ -0,0 +1,25 @@ +"""Deterministic provider for database acceptance; no network or tokenizer.""" +import hashlib + +from app.modules.documents.embeddings import EmbeddingProviderError + + +class DeterministicEmbeddings: + def __init__(self, settings, *, observe=None, fail_at=None): + self.profile = settings.embedding_profile + self.request_policy = settings.processing_profile()["embedding_request"] + self.calls = [] + self.observe, self.fail_at = observe, fail_at + + @staticmethod + def vector(value): + digest = hashlib.sha256(value.encode("utf-8")).digest() + return [float(1 + digest[i]) for i in range(3)] + + def embed(self, texts): + self.calls.append(tuple(texts)) + if self.observe: + self.observe(len(self.calls)) + if len(self.calls) == self.fail_at: + raise EmbeddingProviderError("injected secret provider payload", retryable=False) + return [self.vector(value) for value in texts] diff --git a/tests/unit/test_phase4.py b/tests/unit/test_phase4.py new file mode 100644 index 0000000..0dbb824 --- /dev/null +++ b/tests/unit/test_phase4.py @@ -0,0 +1,358 @@ +"""Fake HTTP only; never contact a real embedding provider.""" +from dataclasses import asdict, replace +from io import BytesIO +import json +import math +from threading import Event +from urllib.error import HTTPError, URLError +from uuid import uuid4 + +import pytest + +from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings +from app.modules.documents.embeddings import ( + EmbeddingError, EmbeddingProviderError, EmbeddingLimits, stage_document, +) +from app.modules.documents.types import ChunkDraft + + +def adapter(settings, **kwargs): + defaults = dict(profile=settings.embedding_profile, api_key="private-secret", + limits=dict(unit="utf8_bytes", max_input_units=100, + max_batch_units=200, max_batch_inputs=2)) + defaults.update(kwargs) + return OpenAICompatibleEmbeddings(**defaults) + + +def response(model="deterministic-test", data=None): + return json.dumps(dict(model=model, data=data if data is not None else [ + dict(index=1, embedding=[0, 1, 0]), dict(index=0, embedding=[1, 0, 0])])).encode() + + +def fake_http(monkeypatch, payload=None, error=None): + requests = [] + class Opener: + def open(self, request, timeout): + requests.append(request) + if error is not None: + raise error + return BytesIO(payload) + monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener()) + return requests + + +def profile(settings, provider, **limits): + value = settings.processing_profile() + value["embedding_request"] = provider.request_policy + value["limits"].update(limits) + return value + + +def test_shuffled_indexes_optional_dimensions_and_secret(settings, monkeypatch): + requests = fake_http(monkeypatch, response()) + provider = adapter(settings) + assert provider.embed(["a", "b"]) == ((1, 0, 0), (0, 1, 0)) + assert "dimensions" not in json.loads(requests[0].data) + assert json.loads(requests[0].data)["input"] == ["a", "b"] + assert requests[0].full_url == "https://test.invalid/v1/embeddings" + assert "private-secret" not in repr(provider) + provider = adapter(settings, send_dimensions=True) + provider.embed(["a", "b"]) + assert json.loads(requests[1].data)["dimensions"] == 3 + + +@pytest.mark.parametrize("data", [ + [dict(index=0, embedding=[1, 0, 0])], + [dict(index=0, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])], + [dict(index=-1, embedding=[1, 0, 0]), dict(index=1, embedding=[0, 1, 0])], + [dict(index=True, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])], + [dict(index=2, embedding=[1, 0, 0]), dict(index=0, embedding=[0, 1, 0])], + [dict(index=0, embedding=[1, 0]), dict(index=1, embedding=[0, 1, 0])], + *[[dict(index=0, embedding=[v, 0, 0]), dict(index=1, embedding=[0, 1, 0])] + for v in (float("nan"), float("inf"), -float("inf"), 0, 1e100, 1e-100, True, "1")], +]) +def test_bad_response_rejected(settings, monkeypatch, data): + fake_http(monkeypatch, response(data=data)) + with pytest.raises(EmbeddingError) as caught: + adapter(settings).embed(["a", "b"]) + assert not caught.value.retryable + + +@pytest.mark.parametrize("payload", [b"garbage", b"null", b"{}", response(model="other")]) +def test_bad_envelope(settings, monkeypatch, payload): + fake_http(monkeypatch, payload) + with pytest.raises(EmbeddingError): + adapter(settings).embed(["a", "b"]) + + +@pytest.mark.parametrize("code,retryable", [(408, True), (429, True), (500, True), (503, True), + (400, False), (401, False), (403, False), (404, False), (302, False)]) +def test_http_errors_once_redacted_and_closed(settings, monkeypatch, code, retryable): + stream = BytesIO(b"private-secret provider details") + error = HTTPError("https://secret.invalid", code, "private-secret", {}, stream) + requests = fake_http(monkeypatch, error=error) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.retryable == retryable + assert "private-secret" not in str(caught.value) + assert len(requests) == 1 and stream.closed + + +@pytest.mark.parametrize("error", [TimeoutError("private-secret"), URLError("private-secret"), OSError("private-secret")]) +def test_network_errors(settings, monkeypatch, error): + requests = fake_http(monkeypatch, error=error) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.retryable and len(requests) == 1 + assert "private-secret" not in str(caught.value) + + +def test_absolute_deadline_late_result_and_shared_capacity(settings, monkeypatch): + entered, release, closed = Event(), Event(), Event() + class Slow(BytesIO): + def read(self, size): + entered.set() + release.wait(3) + return super().read(size) + def close(self): + super().close() + closed.set() + class Opener: + def open(self, *args, **kwargs): + return Slow(response(data=[dict(index=0, embedding=[1, 0, 0])])) + monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener()) + try: + with pytest.raises(EmbeddingProviderError, match="deadline"): + adapter(settings, timeout_seconds=.3).embed(["a"]) + assert entered.is_set() + with pytest.raises(EmbeddingProviderError, match="capacity"): + adapter(settings).embed(["a"]) + finally: + release.set() + assert closed.wait(2) + # Synchronize release of capacity by joining the actual thread. + import threading + for thread in threading.enumerate(): + if thread.name == "embedding-request": + thread.join(2) + + +def test_response_size(settings, monkeypatch): + fake_http(monkeypatch, b"x" * 101) + with pytest.raises(EmbeddingError, match="byte limit"): + adapter(settings, max_response_bytes=100).embed(["a"]) + + +class Counter: + identity = "fake:compatible" + def count(self, text): + return 3 if text == "a" else 6 + + +def test_token_limits_require_compatible_counter(settings): + limits = dict(unit="tokens", max_input_units=5, max_batch_units=5, + max_batch_inputs=2, tokenizer=Counter.identity) + with pytest.raises(EmbeddingError, match="counter"): + adapter(settings, limits=limits) + provider = adapter(settings, limits=limits, token_counter=Counter()) + with pytest.raises(EmbeddingError, match="input limit"): + provider.embed(["b"]) + with pytest.raises(EmbeddingError, match="batch unit"): + provider.embed(["a", "a"]) + + +@pytest.mark.parametrize("texts", [[], ["a", "b", "c"], ["x" * 101], [" "], ["é" * 51]]) +def test_input_and_byte_limits_before_request(settings, texts): + with pytest.raises(EmbeddingError): + adapter(settings).embed(texts) + + +def test_limits_configuration(): + with pytest.raises(ValueError): + EmbeddingLimits(unit="tokens", max_input_units=5, max_batch_units=10, max_batch_inputs=2) + with pytest.raises(ValueError): + EmbeddingLimits(unit="utf8_bytes", max_input_units=5, max_batch_units=4, max_batch_inputs=2) + + +class FakeProvider: + def __init__(self, settings, fail_at=None, vectors=None): + self.profile = settings.embedding_profile + self.request_policy = adapter(settings).request_policy + self.calls = [] + self.fail_at = fail_at + self.vectors = vectors + def embed(self, texts): + self.calls.append(tuple(texts)) + if len(self.calls) == self.fail_at: + raise EmbeddingProviderError("batch failed", retryable=True) + return self.vectors if self.vectors is not None else [[1, 0, 0] for _ in texts] + + +def test_complete_staging_and_release(settings): + provider = FakeProvider(settings) + chunks = [ChunkDraft(i, "a") for i in range(3)] + frozen = profile(settings, provider) + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged: + assert len(staged.chunks) == len(staged.vectors) == 3 + assert tuple(staged.vectors[0]) == (1, 0, 0) + assert staged.processing_profile == frozen + assert provider.calls == [("a", "a"), ("a",)] + copy = staged.processing_profile + copy["embedding"]["model"] = "evil" + assert staged.processing_profile == frozen + assert staged.closed + with pytest.raises(ValueError): + _ = staged.vectors + + +def test_consumer_failure_releases_staging(settings): + provider = FakeProvider(settings) + with pytest.raises(RuntimeError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider)) as staged: + raise RuntimeError() + assert staged.closed + + +def test_failed_final_batch_never_yields(settings): + provider = FakeProvider(settings, fail_at=2) + with pytest.raises(EmbeddingProviderError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(3)], + processing_profile=profile(settings, provider)): + pytest.fail("Incomplete staging became publishable") + assert len(provider.calls) == 2 + + +@pytest.mark.parametrize("chunks", [ + [], [ChunkDraft(1, "a")], [ChunkDraft(0, "a"), ChunkDraft(0, "a")], + [ChunkDraft(0, "a", page=0)], [ChunkDraft(0, "a", token_count=2)], + [ChunkDraft(0, " ")], +]) +def test_invalid_drafts(settings, chunks): + provider = FakeProvider(settings) + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=profile(settings, provider)): + pytest.fail("Bad draft became publishable") + assert not provider.calls + + +@pytest.mark.parametrize("vectors", [[], [[0, 0, 0]], [[float("nan"), 0, 0]], [[1, 0]]]) +def test_provider_neutral_validation(settings, vectors): + provider = FakeProvider(settings, vectors=vectors) + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider)): + pytest.fail("Bad vectors became publishable") + + +def test_budget_exact_boundary_and_no_calls_on_overflow(settings): + provider = FakeProvider(settings) + frozen = profile(settings, provider) + chunks = [ChunkDraft(0, "a", section="large metadata")] + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged: + used = staged.payload_bytes + # Profile itself includes the budget; choose equal digit lengths. + frozen["limits"]["max_staged_bytes"] = 10000 + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen) as staged: + used = staged.payload_bytes + # Replacing 10000 with smaller values changes profile byte length by one. + frozen["limits"]["max_staged_bytes"] = used - 1 + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen): + pass + frozen["limits"]["max_staged_bytes"] -= 1 + provider.calls.clear() + with pytest.raises(EmbeddingError, match="memory budget"): + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=frozen): + pytest.fail("Budget overflow yielded") + assert not provider.calls + + +def test_frozen_identity_policy_and_chunk_limit(settings): + provider = FakeProvider(settings) + for key in ("embedding", "embedding_request"): + frozen = profile(settings, provider) + frozen.pop(key) + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen): + pytest.fail("Missing frozen profile yielded") + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(2)], + processing_profile=profile(settings, provider, max_chunks=1)): + pytest.fail("Too many chunks yielded") + + +def test_token_staging_batch_partition_and_counts(settings): + provider = FakeProvider(settings) + limits = dict(unit="tokens", max_input_units=6, max_batch_units=6, + max_batch_inputs=2, tokenizer=Counter.identity) + provider.request_policy["limits"] = EmbeddingLimits(**limits).model_dump() + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, text) for i, text in enumerate(["a", "a", "b"])], + processing_profile=profile(settings, provider), token_counter=Counter()) as staged: + assert [c.token_count for c in staged.chunks] == [3, 3, 6] + assert provider.calls == [("a", "a"), ("b",)] + + +def test_settings_snapshot_without_credentials(settings): + configured = settings.model_copy(update={"embedding_limits": EmbeddingLimits( + unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)}) + assert "embedding_request" in configured.processing_profile() + assert "api_key" not in json.dumps(configured.processing_profile()) + +def test_normalized_input_preserves_faithful_chunk(settings): + provider = FakeProvider(settings) + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a\r\nb")], + processing_profile=profile(settings, provider)) as staged: + assert staged.chunks[0].text == "a\r\nb" + assert provider.calls == [("a\nb",)] + assert staged.vectors[0].readonly + + +@pytest.mark.parametrize("change", ["profile", "request_policy"]) +def test_provider_profile_cannot_change_between_batches(settings, change): + provider = FakeProvider(settings) + original = provider.embed + def embed(texts): + result = original(texts) + if change == "profile": + provider.profile = replace(provider.profile, model="other") + else: + provider.request_policy["timeout_seconds"] += 1 + return result + provider.embed = embed + with pytest.raises(EmbeddingError, match="changed"): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(i, "a") for i in range(3)], + processing_profile=profile(settings, provider)): + pytest.fail("Changed profile escaped") + + +def test_tiktoken_counter_uses_explicit_encoding_without_special_rejection(monkeypatch): + import sys + from types import SimpleNamespace + from app.infrastructure.openai_embeddings import TiktokenCounter + calls = [] + class Encoding: + def encode(self, text, *, disallowed_special): + calls.append((text, disallowed_special)) + return [1, 2, 3] + def get_encoding(name): + assert name == "explicit-encoding" + return Encoding() + monkeypatch.setitem(sys.modules, "tiktoken", SimpleNamespace(get_encoding=get_encoding)) + counter = TiktokenCounter("explicit-encoding") + assert counter.identity == "tiktoken:explicit-encoding" + assert counter.count("a") == 3 + assert calls == [("a", ())] + + +def test_adapter_composition_requires_secret_and_explicit_limits(settings): + from pydantic import SecretStr + with pytest.raises(ValueError, match="API_KEY"): + OpenAICompatibleEmbeddings.from_settings(settings) + configured = settings.model_copy(update={"embedding_api_key": SecretStr("private-secret")}) + with pytest.raises(EmbeddingError, match="limits"): + OpenAICompatibleEmbeddings.from_settings(configured) + configured = configured.model_copy(update={"embedding_limits": EmbeddingLimits( + unit="utf8_bytes", max_input_units=100, max_batch_units=200, max_batch_inputs=2)}) + provider = OpenAICompatibleEmbeddings.from_settings(configured) + assert provider.request_policy == configured.processing_profile()["embedding_request"] + assert "private-secret" not in json.dumps(configured.processing_profile()) diff --git a/tests/unit/test_phase4_closure.py b/tests/unit/test_phase4_closure.py new file mode 100644 index 0000000..76bcb76 --- /dev/null +++ b/tests/unit/test_phase4_closure.py @@ -0,0 +1,471 @@ +"""Remaining Phase 4 closure defects; fake providers and local byte streams only.""" +from copy import deepcopy +from dataclasses import replace +from io import BytesIO +import hashlib +import json +from types import SimpleNamespace +from urllib.error import HTTPError +from uuid import uuid4 + +import pytest + +from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings +from app.modules.documents.embeddings import EmbeddingError, EmbeddingProviderError, EmbeddingLimits, stage_document +from app.modules.documents.types import ChunkDraft, EmbeddingProfile, ExtractedBlock, ExtractionEnvelope +from app.modules.documents.chunking import chunk_extraction +from app.modules.documents.extraction_artifacts import extraction_profile_digest, serialize_artifact, validate_artifact +from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response +from tests.unit.test_phase4_repairs import real_response + + +def drift(provider, kind): + if kind == "model": + provider.profile = replace(provider.profile, model="changed") + elif kind == "dimension": + provider.profile = replace(provider.profile, dimensions=4) + else: + provider.request_policy["timeout_seconds"] += 1 + + +@pytest.mark.parametrize("when", ["iterator", "counter"]) +@pytest.mark.parametrize("kind", ["model", "dimension", "policy"]) +def test_preparation_drift_has_no_provider_work(settings, when, kind): + provider = FakeProvider(settings) + counter = None + chunks = [ChunkDraft(0, "a")] + if when == "counter": + class Counter: + identity = "fake:closure" + def count(self, text): + drift(provider, kind) + return 1 + counter = Counter() + provider.request_policy["limits"] = EmbeddingLimits(unit="tokens", max_input_units=100, + max_batch_units=200, max_batch_inputs=2, tokenizer=counter.identity).model_dump() + else: + def drafts(): + drift(provider, kind) + yield ChunkDraft(0, "a") + chunks = drafts() + frozen = deepcopy(profile(settings, provider)) + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=chunks, + processing_profile=frozen, token_counter=counter): + pytest.fail("Preparation drift yielded inconsistent staging") + assert not caught.value.retryable and not provider.calls + + +def test_iterator_exhaustion_drift_is_preflight(settings): + provider = FakeProvider(settings) + def drafts(): + yield ChunkDraft(0, "a") + drift(provider, "model") + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=drafts(), + processing_profile=deepcopy(profile(settings, provider))): + pytest.fail("End-of-iteration drift yielded") + assert not provider.calls + + +def test_result_consumption_drift_cannot_yield(settings): + provider = FakeProvider(settings) + class Results: + def __len__(self): return 1 + def __iter__(self): + yield [1, 0, 0] + drift(provider, "model") + provider.embed = lambda texts: Results() + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=deepcopy(profile(settings, provider))): + pytest.fail("Result-consumption drift yielded") + + +@pytest.mark.parametrize("field", ["text", "section"]) +@pytest.mark.parametrize("invalid", ["nul\x00value", "bad\ud800", "bad\udfff"]) +def test_database_incompatible_strings_fail_before_embedding(settings, field, invalid): + provider = FakeProvider(settings) + chunk = replace(ChunkDraft(0, "a", section="source"), **{field: invalid}) + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[chunk], + processing_profile=profile(settings, provider)): + pytest.fail("Database-incompatible chunk yielded") + assert not caught.value.retryable and not provider.calls + + +def vision_chunks(settings, section): + configured = settings.model_copy(update={"vision_provider": "test-vision", + "vision_endpoint": "https://vision.invalid/v1", "vision_model": "actual-model"}) + provider = FakeProvider(configured) + frozen = profile(configured, provider) + envelope = ExtractionEnvelope(document_id=uuid4(), title="sample", original_sha256="a" * 64, + extraction_profile_sha256=extraction_profile_digest(frozen), normalization_policy=frozen["normalizer"], + complete=True, quality_decision="passed", + blocks=(ExtractedBlock(ordinal=0, block_id="image", text="Reliable complete source evidence.", + section=section, source_locator="image/1", method="vision", actual_model="actual-model"),)) + payload = serialize_artifact(envelope, frozen) + restored = validate_artifact(payload, artifact_sha256=hashlib.sha256(payload).hexdigest(), + document_id=envelope.document_id, original_sha256=envelope.original_sha256, processing_profile=frozen) + return provider, frozen, envelope.document_id, chunk_extraction(restored, frozen) + + +def test_vision_envelope_chunking_nul_location_reproduction(settings): + provider, frozen, document, chunks = vision_chunks(settings, "image\x00section") + assert "\x00" in chunks[0].section + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=document, chunks=chunks, processing_profile=frozen): + pytest.fail("NUL from vision evidence escaped staging") + assert not caught.value.retryable and not provider.calls + + +def test_persian_zwnj_newlines_remain_faithful(settings): + provider = FakeProvider(settings) + text, section = "متن معتبر\u200c فارسی\r\nشرایط کامل", "بخش\u200c یک\nصفحه" + provider.request_policy["limits"]["max_input_units"] = 200 + provider.request_policy["limits"]["max_batch_units"] = 400 + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, text, section=section)], + processing_profile=profile(settings, provider)) as staged: + assert staged.chunks[0].text == text and staged.chunks[0].section == section + assert provider.calls == [(text.replace("\r\n", "\n"),)] + + +PERMANENT_CODES = ["insufficient_quota", "credit_balance_exhausted", + "organization_spend_limit_exceeded", "project_spend_limit_exceeded", + "organization_usage_limit_exceeded"] + + +def error_http(monkeypatch, body, *, status=429, stream=None, headers=None): + stream = BytesIO(body) if stream is None else stream + error = HTTPError("https://secret.invalid", status, "private-secret", headers or {}, stream) + calls = fake_http(monkeypatch, error=error) + return stream, calls + + +@pytest.mark.parametrize("field", ["code", "type"]) +@pytest.mark.parametrize("code", PERMANENT_CODES) +def test_quota_credit_spend_errors_are_permanent(settings, monkeypatch, field, code): + body = json.dumps({"error": {field: code, "message": "private-secret"}}).encode() + stream, calls = error_http(monkeypatch, body) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert not caught.value.retryable + assert "private-secret" not in str(caught.value) and len(calls) == 1 and stream.closed + + +@pytest.mark.parametrize("code", ["rate_limit_exceeded", "slow_down", "unknown_vendor_code"]) +def test_temporary_or_unknown_429_is_transient(settings, monkeypatch, code): + stream, calls = error_http(monkeypatch, json.dumps({"error": {"code": code}}).encode()) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.retryable and len(calls) == 1 and stream.closed + + +@pytest.mark.parametrize("body", [b"", b"not JSON private-secret", b"null", b"[]", + b'{"error":null}', b'{"error":{"code":[]}}', b"[" * 65 + b"0" + b"]" * 65, + b"bad\xff", b'{"error":{"code":"insufficient_quota"}}' + b" " * 200]) +def test_unusable_error_body_falls_back_to_status(settings, monkeypatch, body): + stream, calls = error_http(monkeypatch, body) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings, max_response_bytes=100).embed(["a"]) + assert caught.value.retryable and len(calls) == 1 and stream.closed + assert "private-secret" not in str(caught.value) + + +def test_incomplete_quota_json_prefix_does_not_establish_permanent_quota(settings, monkeypatch): + body = b'{"error":{"code":"insufficient_quota"}}' + native, stream, _ = real_response(monkeypatch, body, declared_length=len(body) + 1) + _, calls = error_http(monkeypatch, b"", stream=native) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.retryable and stream.closed and native.closed and len(calls) == 1 + + +@pytest.mark.parametrize("override", [ + {"profile": None}, {"profile": "private-secret"}, {"profile": {}}, + {"api_key": None}, {"api_key": 5}, {"api_key": b"private-secret"}, + {"api_key": "key\x00secret"}, {"api_key": "key\ud800"}, {"api_key": "کلید"}, + {"api_key": "key\x7f"}, {"api_key": "key with space"}, + {"limits": None}, {"limits": "private-secret"}, {"limits": {}}, + {"timeout_seconds": "private-secret"}, {"timeout_seconds": None}, + {"timeout_seconds": True}, {"timeout_seconds": float("nan")}, + {"max_response_bytes": False}, {"send_dimensions": 1}, +]) +def test_direct_constructor_redacted_permanent(settings, monkeypatch, override): + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError) as caught: + adapter(settings, **override) + assert not caught.value.retryable and not calls + assert "private-secret" not in str(caught.value) + + +@pytest.mark.parametrize("field,value", [ + ("endpoint", "https://host:wrong/v1"), ("endpoint", "https://host/v1\x00secret"), + ("endpoint", "https://host/v1%2fkey"), ("endpoint", "https://host/v1\\key"), + ("model", "private-secret\ud800"), ("model", "model\x00secret"), + ("dimensions", True), ("dimensions", 3.5), +]) +def test_direct_profile_values(settings, monkeypatch, field, value): + native = deepcopy(settings.embedding_profile) + object.__setattr__(native, field, value) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError) as caught: + adapter(settings, profile=native) + assert not caught.value.retryable and not calls and "private-secret" not in str(caught.value) + + +@pytest.mark.parametrize("counter", [object(), SimpleNamespace(identity="fake:closure"), + SimpleNamespace(identity="fake:closure", count=5), SimpleNamespace(identity=[], count=lambda text: 1)]) +def test_direct_counter_shape(settings, monkeypatch, counter): + calls = fake_http(monkeypatch, response()) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, + max_batch_inputs=2, tokenizer="fake:closure") + with pytest.raises(EmbeddingError) as caught: + adapter(settings, limits=limits, token_counter=counter) + assert not caught.value.retryable and not calls + + +@pytest.mark.parametrize("mode", ["tokens", "utf8_bytes"]) +@pytest.mark.parametrize("texts", [None, 4, "a", b"a", [None], [4], [b"a"], ["bad\ud800"], ["bad\udfff"]]) +def test_direct_embed_preflight(settings, monkeypatch, mode, texts): + counter = SimpleNamespace(identity="fake:closure", count=lambda text: 1) + limits = dict(unit=mode, max_input_units=100, max_batch_units=200, max_batch_inputs=2, + tokenizer=counter.identity if mode == "tokens" else None) + provider = adapter(settings, limits=limits, token_counter=counter) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError) as caught: + provider.embed(texts) + assert not caught.value.retryable and not calls + + +def test_unbounded_iterable_not_consumed_by_direct_embed(settings, monkeypatch): + provider = adapter(settings) + calls = fake_http(monkeypatch, response()) + consumed = [] + def inputs(): + for _ in range(100): + consumed.append(1) + yield "a" + with pytest.raises(EmbeddingError): + provider.embed(inputs()) + assert len(consumed) <= 3 and not calls + + +def test_duplicate_json_response_fields_are_invalid(settings, monkeypatch): + fake_http(monkeypatch, b'{"model":"deterministic-test","data":[{"index":9,"index":0,"embedding":[1,0,0]}]}') + with pytest.raises(EmbeddingError) as caught: + adapter(settings).embed(["a"]) + assert not caught.value.retryable + + +def test_programming_failure_in_counter_is_not_hidden(settings, monkeypatch): + def buggy(text): raise RuntimeError("programming defect") + counter = SimpleNamespace(identity="fake:closure", count=buggy) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, + max_batch_inputs=2, tokenizer=counter.identity) + calls = fake_http(monkeypatch, response()) + with pytest.raises(RuntimeError, match="programming defect"): + adapter(settings, limits=limits, token_counter=counter).embed(["a"]) + assert not calls + + +def test_programming_failure_in_transport_is_not_hidden(settings, monkeypatch): + error = RuntimeError("programming defect") + fake_http(monkeypatch, error=error) + with pytest.raises(RuntimeError) as caught: + adapter(settings).embed(["a"]) + assert caught.value is error + + +def test_classified_counter_error_is_preserved(settings): + error = EmbeddingProviderError("classified", retryable=False) + def fail(text): raise error + counter = SimpleNamespace(identity="fake:closure", count=fail) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, + max_batch_inputs=2, tokenizer=counter.identity) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings, limits=limits, token_counter=counter).embed(["a"]) + assert caught.value is error + +@pytest.mark.parametrize("actual", [0, 2]) +def test_response_iterator_cardinality_must_match_ordinals(settings, actual): + provider = FakeProvider(settings) + class DishonestLength: + def __len__(self): return 1 + def __iter__(self): + for _ in range(actual): + yield [1, 0, 0] + provider.embed = lambda texts: DishonestLength() + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider)): + pytest.fail("Response iterator cardinality mismatch yielded") + + +@pytest.mark.parametrize("operation", ["read", "close"]) +def test_error_body_deadline_cleanup_capacity_and_late_rejection(settings, monkeypatch, operation): + from threading import Event, enumerate as threads + entered, release = Event(), Event() + class SlowError(BytesIO): + def read(self, size): + if operation == "read": + entered.set() + release.wait(3) + return super().read(size) + def close(self): + if operation == "close": + entered.set() + release.wait(3) + super().close() + stream = SlowError(b'{"error":{"code":"insufficient_quota"}}') + _, calls = error_http(monkeypatch, b"", stream=stream) + try: + with pytest.raises(EmbeddingProviderError, match="deadline") as caught: + adapter(settings, timeout_seconds=.3).embed(["a"]) + assert caught.value.retryable and entered.is_set() + with pytest.raises(EmbeddingProviderError, match="capacity"): + adapter(settings).embed(["a"]) + assert len(calls) == 1 + finally: + release.set() + for thread in threads(): + if thread.name == "embedding-request": + thread.join(2) + assert stream.closed + fake_http(monkeypatch, response()) + assert len(adapter(settings).embed(["a", "b"])) == 2 + + +def test_error_body_reads_have_a_fixed_upper_bound(settings, monkeypatch): + class Recording(BytesIO): + consumed = 0 + def read(self, size): + part = super().read(size) + self.consumed += len(part) + return part + stream = Recording(b'{"error":{"code":"insufficient_quota"}}' + b" " * 70000) + error_http(monkeypatch, b"", stream=stream) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings, max_response_bytes=128 * 1024).embed(["a"]) + assert caught.value.retryable and stream.closed and stream.consumed == 64 * 1024 + 1 + + +@pytest.mark.parametrize("status,retryable", [(400, False), (403, False), (408, True), (429, True), (500, True)]) +def test_empty_native_error_stream_status_fallback(settings, monkeypatch, status, retryable): + error = HTTPError("https://private-secret.invalid", status, "private-secret", {}, None) + calls = fake_http(monkeypatch, error=error) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.retryable == retryable and len(calls) == 1 + + +@pytest.mark.parametrize("kind", ["http", "network"]) +def test_normalized_transport_errors_do_not_retain_raw_context(settings, monkeypatch, kind): + from urllib.error import URLError + if kind == "http": + error_http(monkeypatch, b'{"error":{"code":"insufficient_quota","message":"private-secret"}}') + else: + fake_http(monkeypatch, error=URLError("private-secret")) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert caught.value.__context__ is None + assert "private-secret" not in str(caught.value) + + +def test_error_stream_cleanup_oserror_is_redacted(settings, monkeypatch): + class BadClose(BytesIO): + def close(self): + super().close() + raise OSError("private-secret") + stream = BadClose(b'{"error":{"code":"insufficient_quota"}}') + error_http(monkeypatch, b"", stream=stream) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a"]) + assert stream.closed and not caught.value.retryable + assert "private-secret" not in str(caught.value) and caught.value.__context__ is None + + +@pytest.mark.parametrize("bad_count", [None, True, -1, 0, 1.5, "1"]) +def test_invalid_actual_token_counts_fail_preflight(settings, monkeypatch, bad_count): + counter = SimpleNamespace(identity="fake:closure", count=lambda text: bad_count) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2, + tokenizer=counter.identity) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError): + adapter(settings, limits=limits, token_counter=counter).embed(["a"]) + assert not calls + + +def test_surrogate_input_is_rejected_before_tokenizer(settings, monkeypatch): + counted = [] + def count(text): + counted.append(text) + return 1 + counter = SimpleNamespace(identity="fake:closure", count=count) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2, + tokenizer=counter.identity) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError): + adapter(settings, limits=limits, token_counter=counter).embed(["bad\ud800"]) + assert not counted and not calls + + +def test_latin1_and_unicode_header_keys_are_local_permanent_failures(settings, monkeypatch): + calls = fake_http(monkeypatch, response()) + for key in ("cl\u00e9", "کلید", "key\r\nsecret"): + with pytest.raises(EmbeddingError): + adapter(settings, api_key=key) + assert not calls + +def test_counter_identity_drift_during_count_is_preflight(settings, monkeypatch): + class ChangingCounter: + identity = "fake:closure" + def count(self, text): + self.identity = "different-tokenizer" + return 1 + counter = ChangingCounter() + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2, + tokenizer=counter.identity) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError): + adapter(settings, limits=limits, token_counter=counter).embed(["a"]) + assert not calls + + +def test_unbounded_sequence_iteration_is_bounded(settings, monkeypatch): + from collections.abc import Sequence + visited = [] + class DishonestSequence(Sequence): + def __len__(self): return 1 + def __getitem__(self, index): + if index == 100: + raise IndexError() + visited.append(index) + return "a" + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError): + adapter(settings).embed(DishonestSequence()) + assert len(visited) <= 3 and not calls + + +def test_actual_token_count_must_fit_persisted_integer(settings): + provider = FakeProvider(settings) + counter = SimpleNamespace(identity="fake:closure", count=lambda text: 2**31) + provider.request_policy["limits"] = EmbeddingLimits(unit="tokens", max_input_units=2**31, + max_batch_units=2**31, max_batch_inputs=2, tokenizer=counter.identity).model_dump() + with pytest.raises(EmbeddingError): + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider), token_counter=counter): + pytest.fail("Database-incompatible token count yielded") + assert not provider.calls + + +@pytest.mark.parametrize("identity", ["nul\x00identity", "bad\ud800"]) +def test_tokenizer_identity_is_valid_utf8_database_metadata(settings, monkeypatch, identity): + counter = SimpleNamespace(identity=identity, count=lambda text: 1) + limits = dict(unit="tokens", max_input_units=100, max_batch_units=200, max_batch_inputs=2, + tokenizer=identity) + calls = fake_http(monkeypatch, response()) + with pytest.raises(EmbeddingError): + adapter(settings, limits=limits, token_counter=counter) + assert not calls diff --git a/tests/unit/test_phase4_repairs.py b/tests/unit/test_phase4_repairs.py new file mode 100644 index 0000000..ad7fd8b --- /dev/null +++ b/tests/unit/test_phase4_repairs.py @@ -0,0 +1,264 @@ +"""Phase 4 repair regressions; real HTTPResponse framing, no live network.""" +from array import array +from copy import deepcopy +from dataclasses import replace +from http.client import HTTPResponse +from io import BytesIO +import json +import math +import sys +from uuid import uuid4 + +import pytest + +from app.modules.documents.embeddings import EmbeddingError, EmbeddingProviderError, packed_vector, stage_document +from app.modules.documents.types import ChunkDraft +from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response + + +@pytest.mark.parametrize("vector", [[1e-30, 0, 0], [1e20, 0, 0], [1e19] * 4]) +def test_float32_cosine_norm_rejects_unsafe_vectors(vector): + with pytest.raises(EmbeddingError) as caught: + packed_vector(vector, len(vector)) + assert caught.value.retryable is False + + +@pytest.mark.parametrize("vector", [[1, 0, 0], [1e-18, 0, 0], [1e18, 0, 0], [1e-30, 1, 0], [1e19] * 3]) +def test_accepted_vectors_remain_unscaled(vector): + assert packed_vector(vector, len(vector)) == array("f", vector).tobytes() + + +class SocketBytes: + def __init__(self, wire): + self.stream = BytesIO(wire) + def makefile(self, *args): + return self.stream + + +def real_response(monkeypatch, body, *, declared_length=None, chunked=False): + headers = (b"Transfer-Encoding: chunked\r\n" if chunked else + b"Content-Length: " + str(len(body) if declared_length is None else declared_length).encode() + b"\r\n") + socket = SocketBytes(b"HTTP/1.1 200 OK\r\n" + headers + b"\r\n" + body) + native = HTTPResponse(socket) + native.begin() + calls = [] + class Opener: + def open(self, request, timeout): + calls.append(request) + return native + monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener()) + return native, socket.stream, calls + + +@pytest.mark.parametrize("complete_prefix", [False, True]) +def test_content_length_premature_eof_is_transient(settings, monkeypatch, complete_prefix): + valid = response() + body = valid if complete_prefix else valid[:-8] + native, stream, calls = real_response(monkeypatch, body, declared_length=len(valid) + 50) + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a", "b"]) + assert caught.value.retryable + assert stream.closed and native.closed and len(calls) == 1 + # The slot must be available after stream cleanup, without waiting/retrying. + fake_http(monkeypatch, valid) + assert len(adapter(settings).embed(["a", "b"])) == 2 + + +def test_exact_content_length_is_success(settings, monkeypatch): + native, stream, calls = real_response(monkeypatch, response()) + assert adapter(settings).embed(["a", "b"]) == ((1, 0, 0), (0, 1, 0)) + assert stream.closed and native.closed and len(calls) == 1 + + +@pytest.mark.parametrize("complete", [False, True]) +def test_chunked_framing_cleanup(settings, monkeypatch, complete): + payload = response() + body = format(len(payload), "x").encode() + b"\r\n" + payload + b"\r\n" + if complete: + body += b"0\r\n\r\n" + native, stream, calls = real_response(monkeypatch, body, chunked=True) + if complete: + assert len(adapter(settings).embed(["a", "b"])) == 2 + else: + with pytest.raises(EmbeddingProviderError) as caught: + adapter(settings).embed(["a", "b"]) + assert caught.value.retryable + assert stream.closed and native.closed and len(calls) == 1 + + +def test_framed_response_byte_limit_preserved(settings, monkeypatch): + native, stream, _ = real_response(monkeypatch, response()) + with pytest.raises(EmbeddingError, match="byte limit"): + adapter(settings, max_response_bytes=10).embed(["a", "b"]) + assert stream.closed and native.closed + + +def test_deep_json_is_redacted_permanent(settings, monkeypatch): + nesting = max(2000, sys.getrecursionlimit() + 100) + fake_http(monkeypatch, b"[" * nesting + b'"private-secret"' + b"]" * nesting) + with pytest.raises(EmbeddingError) as caught: + adapter(settings).embed(["a"]) + assert not caught.value.retryable and "private-secret" not in str(caught.value) + + +def test_decoder_recursion_is_redacted_permanent(settings, monkeypatch): + provider = adapter(settings) + monkeypatch.setattr(provider, "_request_once", lambda request: b"{}") + def recursive(*args, **kwargs): + raise RecursionError("private-secret") + monkeypatch.setattr("app.infrastructure.openai_embeddings.json.loads", recursive) + with pytest.raises(EmbeddingError) as caught: + provider.embed(["a"]) + assert not caught.value.retryable and "private-secret" not in str(caught.value) + + +def test_excessive_nesting_in_unused_field_is_rejected(settings, monkeypatch): + # Valid shallow result must not permit pathological nesting elsewhere. + body = response()[:-1] + b',"unused":' + b"[" * 65 + b"0" + b"]" * 65 + b"}" + fake_http(monkeypatch, body) + with pytest.raises(EmbeddingError) as caught: + adapter(settings).embed(["a", "b"]) + assert not caught.value.retryable + + +def test_json_string_braces_and_escapes_do_not_count_as_nesting(settings, monkeypatch): + value = json.loads(response()) + value["unused"] = '{"' * 100 + '\\' + '"' + fake_http(monkeypatch, json.dumps(value).encode()) + assert len(adapter(settings).embed(["a", "b"])) == 2 + + +PROFILE_CASES = [ + ("root", None), ("root", []), ("root", "private-secret"), + ("limits", None), ("limits", []), ("limits", {}), + ("limits.max_staged_bytes", None), ("limits.max_staged_bytes", "private-secret"), + ("limits.max_staged_bytes", True), ("limits.max_staged_bytes", 0), + ("limits.max_staged_bytes", 1.5), + ("limits.embedding_batch_size", None), ("limits.embedding_batch_size", "private-secret"), + ("limits.embedding_batch_size", 100.5), ("limits.embedding_batch_size", 0), + ("limits.embedding_batch_size", True), + ("limits.max_chunks", None), ("limits.max_chunks", "private-secret"), + ("limits.max_chunks", False), ("limits.max_chunks", -1), ("limits.max_chunks", 1.5), + ("normalizer", None), ("normalizer", []), ("normalizer", "private-secret"), + ("missing", "limits"), ("missing", "normalizer"), +] + + +@pytest.mark.parametrize("path,value", PROFILE_CASES) +def test_malformed_profiles_are_permanent_and_no_provider_call(settings, path, value): + provider = FakeProvider(settings) + frozen = deepcopy(profile(settings, provider)) + if path == "root": + frozen = value + elif path == "missing": + frozen.pop(value) + elif "." in path: + parent, child = path.split(".") + frozen[parent][child] = value + else: + frozen[path] = value + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen): + pytest.fail("Malformed profile yielded") + assert not caught.value.retryable and "private-secret" not in str(caught.value) + assert not provider.calls + + +@pytest.mark.parametrize("field", ["max_staged_bytes", "embedding_batch_size", "max_chunks"]) +def test_missing_staging_limit_is_permanent(settings, field): + provider = FakeProvider(settings) + frozen = profile(settings, provider) + frozen["limits"].pop(field) + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen): + pytest.fail("Missing limit yielded") + assert not caught.value.retryable and not provider.calls + + +@pytest.mark.parametrize("chunks", [ + None, 5, [None], [object()], [{"ordinal": 0, "text": "private-secret"}], ["private-secret"], + [ChunkDraft(0, None)], [ChunkDraft(0, 10)], [ChunkDraft(0, ["private-secret"])], + [ChunkDraft(0, b"private-secret")], [ChunkDraft(0, "private-secret\ud800")], +]) +def test_malformed_drafts_are_redacted_permanent(settings, chunks): + provider = FakeProvider(settings) + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=chunks, processing_profile=profile(settings, provider)): + pytest.fail("Malformed draft yielded") + assert not caught.value.retryable and "private-secret" not in str(caught.value) + assert not provider.calls + + +def test_invalid_profile_json_is_redacted(settings): + provider = FakeProvider(settings) + frozen = profile(settings, provider) + frozen["unexpected"] = float("nan") + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=frozen): + pytest.fail("Invalid profile serialization yielded") + assert not caught.value.retryable + + +def test_classified_provider_error_is_preserved(settings): + provider = FakeProvider(settings) + error = EmbeddingProviderError("safe transient", retryable=True) + def fail(texts): + raise error + provider.embed = fail + with pytest.raises(EmbeddingProviderError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=profile(settings, provider)): + pytest.fail("Failed provider yielded") + assert caught.value is error and caught.value.retryable + + +def test_consumer_validation_exception_is_not_reclassified_and_releases(settings): + provider = FakeProvider(settings) + error = KeyError("consumer fault") + with pytest.raises(KeyError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], processing_profile=profile(settings, provider)) as staged: + raise error + assert caught.value is error and staged.closed + +def test_premature_eof_cleanup_retains_capacity_until_exit(settings, monkeypatch): + from threading import Event, enumerate as threads + entered, release = Event(), Event() + native, stream, _ = real_response(monkeypatch, response(), declared_length=len(response()) + 1) + close = native.close + def blocked_close(): + entered.set() + release.wait(3) + close() + native.close = blocked_close + try: + with pytest.raises(EmbeddingProviderError, match="deadline"): + adapter(settings, timeout_seconds=.3).embed(["a", "b"]) + assert entered.is_set() + with pytest.raises(EmbeddingProviderError, match="capacity"): + adapter(settings).embed(["a", "b"]) + finally: + release.set() + for thread in threads(): + if thread.name == "embedding-request": + thread.join(2) + assert native.closed and stream.closed + fake_http(monkeypatch, response()) + assert len(adapter(settings).embed(["a", "b"])) == 2 + + +def test_depth_limit_boundary(settings, monkeypatch): + # Root object contributes one level: 63 arrays give total depth 64. + body = response()[:-1] + b',"unused":' + b"[" * 63 + b"0" + b"]" * 63 + b"}" + fake_http(monkeypatch, body) + assert len(adapter(settings).embed(["a", "b"])) == 2 + + +@pytest.mark.parametrize("broken", [None, {}, {"unit": "private-secret"}]) +def test_invalid_frozen_request_limits_are_redacted(settings, broken): + provider = FakeProvider(settings) + provider.request_policy["limits"] = broken + with pytest.raises(EmbeddingError) as caught: + with stage_document(provider, document_id=uuid4(), chunks=[ChunkDraft(0, "a")], + processing_profile=profile(settings, provider)): + pytest.fail("Malformed request limits yielded") + assert not caught.value.retryable and "private-secret" not in str(caught.value) + assert not provider.calls diff --git a/tests/unit/test_phase4_vector_timeout_repairs.py b/tests/unit/test_phase4_vector_timeout_repairs.py new file mode 100644 index 0000000..e88c2e8 --- /dev/null +++ b/tests/unit/test_phase4_vector_timeout_repairs.py @@ -0,0 +1,354 @@ +"""Phase 4 repairs for vector validation, float32 cosine safety, timeout limits, and endpoint hostnames.""" +from array import array +from copy import deepcopy +from dataclasses import replace +from io import BytesIO +import json +import math +import threading +from threading import Event, Thread +import time +from uuid import uuid4 + +from pydantic import ValidationError +import pytest + +from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings, _CAPACITY +from app.modules.documents.embeddings import ( + EmbeddingError, EmbeddingProviderError, packed_vector, stage_document, + is_representable_timeout, validate_endpoint_hostname, +) +from app.modules.documents.settings import IngestionSettings +from app.modules.documents.types import ChunkDraft +from tests.unit.test_phase4 import FakeProvider, adapter, fake_http, profile, response + + +# --------------------------------------------------------------------------- +# Finding 1: Vector validation and packing +# --------------------------------------------------------------------------- + +class DishonestSequence: + def __init__(self, reported_len, items): + self.reported_len = reported_len + self.items = items + + def __len__(self): + return self.reported_len + + def __iter__(self): + return iter(self.items) + + +class EndlessSequence: + def __init__(self, reported_len): + self.reported_len = reported_len + self.consumed = 0 + + def __len__(self): + return self.reported_len + + def __iter__(self): + while True: + self.consumed += 1 + yield 1.0 + + +class ChangingSequence: + def __init__(self, first_items, second_items): + self.first_items = first_items + self.second_items = second_items + self.traversals = 0 + + def __len__(self): + return len(self.first_items) + + def __iter__(self): + self.traversals += 1 + if self.traversals == 1: + return iter(self.first_items) + return iter(self.second_items) + + +def test_packed_vector_rejects_dishonest_longer_sequence(): + dishonest = DishonestSequence(3, [1.0, 0.0, 0.0, 0.0]) + with pytest.raises(EmbeddingError, match="dimension mismatch"): + packed_vector(dishonest, 3) + + +def test_packed_vector_rejects_dishonest_shorter_sequence(): + dishonest = DishonestSequence(3, [1.0, 0.0]) + with pytest.raises(EmbeddingError, match="dimension mismatch"): + packed_vector(dishonest, 3) + + +def test_packed_vector_bounded_stopping_on_endless_sequence(): + endless = EndlessSequence(3) + with pytest.raises(EmbeddingError, match="dimension mismatch"): + packed_vector(endless, 3) + # Must stop after consuming at most D + 1 (3 + 1 = 4) elements + assert endless.consumed == 4 + + +def test_packed_vector_validates_and_packs_captured_elements_once(): + # If traversed a second time, it would yield NaN which fails validation. + # Because packed_vector traverses only once and packs the captured elements, it succeeds. + changing = ChangingSequence([1.0, 0.0, 0.0], [float("nan"), 0.0, 0.0]) + result = packed_vector(changing, 3) + assert result == array("f", [1.0, 0.0, 0.0]).tobytes() + assert changing.traversals == 1 + + +def test_packed_vector_accepts_single_use_iterator(): + iterator = iter([1.0, 0.0, 0.0]) + result = packed_vector(iterator, 3) + assert result == array("f", [1.0, 0.0, 0.0]).tobytes() + + +def test_packed_vector_exact_byte_storage(): + for d in (1, 3, 16, 128): + vec = [1.0] + [0.0] * (d - 1) + packed = packed_vector(vec, d) + assert len(packed) == 4 * d + + +def test_stage_document_cleans_up_on_failed_final_batch(settings): + # Setup document with two batches of chunks + doc_id = uuid4() + chunks = [ + ChunkDraft(0, "text 0", token_count=1), + ChunkDraft(1, "text 1", token_count=1), + ] + + class FailingSecondBatchProvider: + def __init__(self, base_profile): + self.profile = base_profile + self.request_policy = dict( + limits=dict(unit="tokens", tokenizer="tiktoken:cl100k_base", + max_input_units=100, max_batch_units=200, max_batch_inputs=1), + timeout_seconds=60.0, send_dimensions=False, max_response_bytes=1048576, + ) + self.batch_count = 0 + + def embed(self, texts): + self.batch_count += 1 + if self.batch_count == 1: + return [[1.0, 0.0, 0.0]] + # Second batch returns mismatched vector + return [[1.0, 0.0]] + + prov = FailingSecondBatchProvider(settings.embedding_profile) + prof = profile(settings, prov, embedding_batch_size=1) + prof["embedding_request"] = prov.request_policy + + class Counter: + identity = "tiktoken:cl100k_base" + def count(self, text): + return 1 + + with pytest.raises(EmbeddingError, match="dimension mismatch"): + with stage_document(prov, document_id=doc_id, chunks=chunks, + processing_profile=prof, token_counter=Counter()): + pass + + +def test_stage_document_dishonest_vector_does_not_bypass_staging_budget(settings): + doc_id = uuid4() + chunks = [ChunkDraft(0, "text 0", token_count=1)] + + class DishonestProvider: + def __init__(self, base_profile): + self.profile = base_profile + self.request_policy = dict( + limits=dict(unit="tokens", tokenizer="tiktoken:cl100k_base", + max_input_units=100, max_batch_units=200, max_batch_inputs=1), + timeout_seconds=60.0, send_dimensions=False, max_response_bytes=1048576, + ) + + def embed(self, texts): + return [DishonestSequence(3, [1.0] * 1000)] + + prov = DishonestProvider(settings.embedding_profile) + prof = profile(settings, prov, max_staged_bytes=100_000) + prof["embedding_request"] = prov.request_policy + + class Counter: + identity = "tiktoken:cl100k_base" + def count(self, text): + return 1 + + with pytest.raises(EmbeddingError, match="dimension mismatch"): + with stage_document(prov, document_id=doc_id, chunks=chunks, + processing_profile=prof, token_counter=Counter()): + pass + + +# --------------------------------------------------------------------------- +# Finding 2: Float32 cosine safety without rescaling +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("vector", [ + [3e-23, 0, 0], + [1e-21] * 16000, + [1e-21] * 3, + [1e-30, 0, 0], + [1e20, 0, 0], + [1e19] * 4, +]) +def test_float32_cosine_safety_rejects_unsafe_vectors(vector): + with pytest.raises(EmbeddingError) as exc: + packed_vector(vector, len(vector)) + assert exc.value.retryable is False + + +@pytest.mark.parametrize("vector", [ + [1, 0, 0], + [1e-18, 0, 0], + [1e18, 0, 0], + [1e-30, 1, 0], + [1e19] * 3, +]) +def test_float32_cosine_safety_preserves_safe_vectors_unscaled(vector): + assert packed_vector(vector, len(vector)) == array("f", vector).tobytes() + + +# --------------------------------------------------------------------------- +# Finding 3: Reject runtime-unrepresentable embedding timeouts +# --------------------------------------------------------------------------- + +def test_timeout_1e20_rejected_before_mock_transport_without_starting_thread(settings, monkeypatch): + entered = Event() + class Opener: + def open(self, request, timeout): + entered.set() + return BytesIO(b"{}") + monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener()) + + initial_threads = threading.active_count() + # Capacity must not be held + assert _CAPACITY.acquire(blocking=False) + _CAPACITY.release() + + with pytest.raises(EmbeddingError) as exc: + adapter(settings, timeout_seconds=1e20) + assert exc.value.retryable is False + assert "private-secret" not in str(exc.value) + + # Verify no mock transport was entered and no thread started + assert not entered.is_set() + assert threading.active_count() == initial_threads + # Transport capacity must still be free + assert _CAPACITY.acquire(blocking=False) + _CAPACITY.release() + + +def test_timeout_1e20_rejected_from_settings(settings): + values = settings.model_dump() + values["embedding_timeout_seconds"] = 1e20 + with pytest.raises(ValidationError) as exc: + IngestionSettings(_env_file=None, **values) + assert "private-secret" not in str(exc.value) + + +@pytest.mark.parametrize("invalid_timeout", [ + 1e20, 1e10, 2147484.0, 0, -1, float("inf"), float("nan"), "60", True, None, +]) +def test_timeout_boundaries_rejected(settings, invalid_timeout): + with pytest.raises(EmbeddingError): + adapter(settings, timeout_seconds=invalid_timeout) + + +def test_timeout_representable_boundary_accepted(settings): + # 2147483.0 is the valid boundary for 32-bit timeval + adv = adapter(settings, timeout_seconds=2147483.0) + assert adv.timeout == 2147483.0 + assert adv.request_policy["timeout_seconds"] == 2147483.0 + + +def test_ordinary_deadline_expires_and_cleans_up_capacity(settings, monkeypatch): + release = Event() + entered = Event() + calls = [] + + class Opener: + def open(self, request, timeout): + calls.append(1) + entered.set() + release.wait(2) + return BytesIO(response()) + + monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener()) + adv = adapter(settings, timeout_seconds=0.1) + + try: + with pytest.raises(EmbeddingProviderError) as exc: + adv.embed(["test"]) + assert exc.value.retryable is True + assert entered.is_set() + finally: + release.set() + + # Once released, capacity is freed and next call succeeds + deadline = time.monotonic() + 1.0 + while time.monotonic() < deadline: + try: + adv2 = adapter(settings, timeout_seconds=1.0) + break + except EmbeddingProviderError: + time.sleep(0.01) + + +# --------------------------------------------------------------------------- +# Finding 4: Reject locally invalid endpoint hostnames +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("invalid_endpoint", [ + "https://example..com/v1", + "https://.example.com/v1", + "https://example.com./v1", + "https://" + "a" * 64 + ".com/v1", + "https://-example.com/v1", + "https://example-.com/v1", + "https://999.999.999.999/v1", + "https://::1/v1", + "https://[invalid::ipv6]/v1", +]) +def test_endpoint_hostname_rejected_direct_and_settings(settings, invalid_endpoint): + prof = replace(settings.embedding_profile, endpoint=invalid_endpoint) + with pytest.raises(EmbeddingError): + adapter(settings, profile=prof) + + values = settings.model_dump() + values["embedding_endpoint"] = invalid_endpoint + with pytest.raises(ValidationError) as exc: + IngestionSettings(_env_file=None, **values) + assert "dummy-url-secret" not in str(exc.value) + + +@pytest.mark.parametrize("valid_endpoint", [ + "https://api.openai.com/v1", + "https://" + "a" * 63 + ".com/v1", + "https://localhost:8080/v1", + "https://127.0.0.1:8000/v1", + "https://[::1]:8000/v1", + "https://[2001:db8::1]/v1", + "https://Example.invalid:8443/tenant/deployment-01/v1/", +]) +def test_endpoint_hostname_preserves_valid_endpoints(settings, valid_endpoint): + prof = replace(settings.embedding_profile, endpoint=valid_endpoint) + adv = adapter(settings, profile=prof) + assert adv.profile.endpoint == valid_endpoint + + +def test_programming_failures_propagate_without_blanket_handler(settings, monkeypatch): + from collections.abc import Mapping + class BuggyLimits(Mapping): + def __getitem__(self, key): + raise ZeroDivisionError("Simulated programming bug") + def __iter__(self): + raise ZeroDivisionError("Simulated programming bug") + def __len__(self): + return 1 + + prof = settings.embedding_profile + with pytest.raises(ZeroDivisionError): + OpenAICompatibleEmbeddings(profile=prof, api_key="secret", limits=BuggyLimits())