"""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()