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
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:21:17 +03:30
parent 5ef02d39a9
commit 39ed0422c5
11 changed files with 2830 additions and 0 deletions
+397
View File
@@ -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"(?<!\w)(?P<label>" + 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<list>,|،|and\b|or\b|&|و(?=\s)|یا(?=\s))|(?P<range>through\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)
+372
View File
@@ -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()
@@ -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")
+34
View File
@@ -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)