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:
@@ -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
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user