feat(search): add calibrated retrieval and LangChain knowledge tool

Add exact and semantic evidence admission, measured calibration, bounded tool execution, and independent held-out evaluation preparation with regression coverage and operator guides. Real-provider quality gates remain pending.

Validation: 1300 provider-free tests passed; 3 Windows symlink skips. PostgreSQL acceptance not rerun because TEST_DATABASE_URL is unset.
This commit is contained in:
amirhosein mazaheri
2026-10-08 12:58:59 +03:30
parent 4d36f2ba35
commit fef381c41b
36 changed files with 6679 additions and 45 deletions
+176
View File
@@ -0,0 +1,176 @@
"""Opt-in ten-query calibration against operator-bound approved originals."""
import argparse
from dataclasses import asdict
import hashlib
import json
from pathlib import Path
import sys
import time
from uuid import UUID, uuid4
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from app.ingest import json_value
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.calibration import select_cutoff, validate_cases
from app.modules.knowledge.evidence import RETRIEVAL_POLICY, SearchExecution
from app.modules.knowledge.service import KnowledgeError, SearchService, authority, transaction, sql_error
CASES_PATH = Path(__file__).resolve().parents[1] / "docs/calibration/phase2-cases.json"
class CountingProvider:
"""Count actual adapter invocations without hiding dynamic adapter identity."""
def __init__(self, provider):
self.provider = provider
self.calls = 0
@property
def profile(self):
return self.provider.profile
@property
def request_policy(self):
return self.provider.request_policy
def embed(self, texts):
self.calls += 1
return self.provider.embed(texts)
def run(engine, settings, provider, counter, user_id, annotations, bindings):
cases = annotations["cases"]
validate_cases(cases)
execution = SearchExecution(user_id)
measured_provider = CountingProvider(provider)
service = SearchService(engine, settings, measured_provider, counter)
with transaction(engine) as conn:
current, snapshot = authority(conn, user_id)
execution.capture(current, snapshot["access_epoch"])
for digest in {c["original_sha256"] for c in cases}:
document_id = UUID(bindings[digest])
row = conn.execute(text("""
SELECT id FROM documents WHERE id=:id AND organization_id=:org
AND file_sha256=:digest AND status='ready' AND is_active
AND deleted_at IS NULL AND content_purged_at IS NULL
AND processing_profile->'embedding'=CAST(:profile AS jsonb)
"""), dict(id=document_id, org=current["organization_id"], digest=digest,
profile=json.dumps(asdict(settings.embedding_profile)))).one_or_none()
if row is None:
raise KnowledgeError("CALIBRATION_BINDING_INVALID", "Approved original binding is not eligible")
observations = {}
for case in cases:
calls_before = measured_provider.calls
started = time.monotonic()
try:
result = service.candidates(execution, case["query"])
if result["knowledge_revision"] != snapshot["knowledge_revision"]:
raise KnowledgeError("CONTEXT_REVOKED", "Calibration selection changed")
observations[case["id"]] = dict(status="completed", candidates=result["candidates"],
retrieval_policy=RETRIEVAL_POLICY, latency_seconds=time.monotonic() - started)
observations[case["id"]]["provider_calls"] = measured_provider.calls - calls_before
except KnowledgeError as exc:
observations[case["id"]] = dict(status="error",
error=dict(code=exc.code, message=str(exc), retryable=exc.retryable),
latency_seconds=time.monotonic() - started)
observations[case["id"]]["provider_calls"] = measured_provider.calls - calls_before
# An error is never counted as an unsupported success; stop remote work.
for remaining in cases:
observations.setdefault(remaining["id"], dict(status="error",
error=dict(code="NOT_RUN", message="Calibration stopped after technical error")))
break
# Freeze/revalidate the full execution and selected corpus even after the last call.
finalization_error = None
try:
with transaction(engine) as conn:
final, settings_row = authority(conn, user_id)
if (not execution.capture(final, settings_row["access_epoch"])
or settings_row["knowledge_revision"] != snapshot["knowledge_revision"]):
raise KnowledgeError("CONTEXT_REVOKED", "Calibration access or selection changed")
except KnowledgeError as exc:
if exc.code == "ACTOR_UNAVAILABLE":
exc = KnowledgeError("CONTEXT_REVOKED", "Actor access changed before calibration handoff")
finalization_error = dict(code=exc.code, message=str(exc), retryable=exc.retryable)
except SQLAlchemyError as exc:
failure = sql_error(exc)
finalization_error = dict(code=failure.code, message=str(failure), retryable=failure.retryable)
if finalization_error is not None:
# Keep completed observations' safe metrics/status, without any evidence
# whose final authorization could not be confirmed.
observations = {case["id"]: dict(
{key: value for key, value in observations[case["id"]].items()
if key in ("provider_calls", "latency_seconds", "retrieval_policy")},
status="error", retrieval_status=observations[case["id"]]["status"],
error=dict(finalization_error),
**({"retrieval_error": observations[case["id"]]["error"]}
if "error" in observations[case["id"]] else {}))
for case in cases}
report = select_cutoff(cases, observations, bindings, settings.embedding_profile)
report.update(calibration_id=str(uuid4()), knowledge_revision=snapshot["knowledge_revision"],
access_epoch=snapshot["access_epoch"], organization_id=str(current["organization_id"]),
profile=asdict(settings.embedding_profile), retrieval_policy=RETRIEVAL_POLICY,
embedding_request=settings.processing_profile()["embedding_request"],
bindings=bindings, annotations=annotations, observations=observations,
provider_calls=measured_provider.calls, provider_call_budget=10, usage="unavailable", billing="unavailable")
report["final_authorization_confirmed"] = finalization_error is None
if finalization_error is not None:
report["finalization_error"] = finalization_error
# Preserve the frozen labels and original identity, not literal evidence.
report["annotations"] = dict(
original_file=annotations["original_file"],
original_sha256=annotations["original_sha256"],
cases=[{key: case[key] for key in ("id", "answerable", "original_sha256")}
for case in cases])
return report
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--bindings", type=Path, required=True,
help="JSON original SHA-256 to selected document UUID mapping")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize at most ten configured compatible query embedding calls")
args = parser.parse_args(argv)
engine = None
try:
if args.output.exists() or not args.output.parent.is_dir():
raise ValueError("A new report path in an existing directory is required")
annotation_bytes = CASES_PATH.read_bytes()
annotations = json.loads(annotation_bytes)
validate_cases(annotations["cases"])
original = CASES_PATH.parent / annotations["original_file"]
if hashlib.sha256(original.read_bytes()).hexdigest() != annotations["original_sha256"]:
raise ValueError("Calibration original differs from frozen annotations")
bindings = json.loads(args.bindings.read_text(encoding="utf-8"))
settings = IngestionSettings()
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
engine = create_database(settings.database_url.get_secret_value())
report = run(engine, settings, provider, counter, args.user_id, annotations, bindings)
report["annotations_sha256"] = hashlib.sha256(annotation_bytes).hexdigest()
# Refuse overwrite: each real run retains its independent measurements.
with args.output.open("x", encoding="utf-8") as output:
json.dump(report, output, default=json_value, ensure_ascii=False, allow_nan=False, indent=2)
output.write("\n")
print(json.dumps(dict(status=report["status"], output=str(args.output),
complete_support=report.get("complete_support")), ensure_ascii=True))
return 0 if report["status"] == "calibrated" else 1
except KnowledgeError as exc:
print(json.dumps(dict(status="error", error=dict(code=exc.code, message=str(exc)))), file=sys.stderr)
return 1
except Exception:
print(json.dumps(dict(status="error", error=dict(code="CALIBRATION_FAILED",
message="Verify approved original bindings, profile, database and output path"))), file=sys.stderr)
return 1
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
sys.exit(main())
+104
View File
@@ -0,0 +1,104 @@
"""Ten-case profile-specific cutoff selection, separate from held-out evaluation."""
from dataclasses import asdict
import math
import re
import unicodedata
from app.modules.knowledge.evidence import RETRIEVAL_POLICY, admit_candidates, CalibratedCutoff
def validate_cases(cases):
if (len(cases) != 10 or len({c["id"] for c in cases}) != 10
or sum(c["answerable"] is True for c in cases) != 6
or sum(c["answerable"] is False for c in cases) != 4):
raise ValueError("Exactly six answerable and four unsupported separate cases required")
for case in cases:
groups = case["evidence_groups"]
if (not case["query"].strip() or not case["original_sha256"]
or bool(groups) != case["answerable"]
or any(not g or any(not p.strip() for p in g) for g in groups)):
raise ValueError("Original-bound independent evidence annotations required")
def _token_character(character):
# Python's \w omits combining marks and format joiners used inside
# Unicode words. Treat those as continuations too, without normalizing
# or rewriting independently annotated literal evidence.
category = unicodedata.category(character)
return category[0] in "LNM" or category in ("Pc", "Cf")
def _literal_boundary(text, index, direction):
if not 0 <= index < len(text):
return True
character = text[index]
if _token_character(character) or character in "/-+\u066b\u066c":
return False
if character == ".":
outward = index + direction
# A sentence period is punctuation; a dot connecting token pieces
# extends a number, date or identifier.
return not (0 <= outward < len(text) and
(_token_character(text[outward]) or text[outward] in "./-"))
return True
def literal_annotation_matches(phrase, text):
return any(_literal_boundary(text, match.start() - 1, -1)
and _literal_boundary(text, match.end(), 1)
for match in re.finditer(re.escape(phrase), text))
def complete_support(case, rows, document_id):
# Each evidence group must occur together in one faithful chunk of the
# annotated original, including all numbers, conditions and exceptions.
return all(any(str(row["document_id"]) == str(document_id)
and all(literal_annotation_matches(phrase, row["text"]) for phrase in group)
for row in rows) for group in case["evidence_groups"])
def select_cutoff(cases, observations, bindings, profile):
validate_cases(cases)
if set(observations) != {c["id"] for c in cases}:
raise ValueError("Every case requires a completed retrieval observation")
if any(observations[c["id"]].get("status") == "error" for c in cases):
return dict(status="technical_error", cutoff=None, trials=[], cases=observations)
distances = {0.0}
for observation in observations.values():
if observation["retrieval_policy"] != RETRIEVAL_POLICY:
raise ValueError("Calibration retrieval policy changed")
for row in observation["candidates"]:
distance = row["cosine_distance"]
if type(distance) not in (int, float) or not math.isfinite(distance):
raise ValueError("Calibration requires finite measured distances")
if 0 <= distance <= 2:
distances.add(distance)
trials = []
best = None
for cutoff in sorted(distances):
results = []
for case in cases:
rows = admit_candidates(observations[case["id"]]["candidates"], cutoff)
passed = (complete_support(case, rows, bindings[case["original_sha256"]])
if case["answerable"] else not rows)
results.append(dict(id=case["id"], answerable=case["answerable"], passed=passed,
status="ok" if rows else "no_evidence", sources=rows))
coverage = sum(r["passed"] for r in results if r["answerable"])
false_positives = sum(not r["passed"] for r in results if not r["answerable"])
trials.append(dict(distance=cutoff, complete_support=coverage,
unsupported_false_positives=false_positives))
# Ascending cutoff traversal preserves the stricter cutoff on ties.
if false_positives == 0 and (best is None or coverage > best["complete_support"]):
best = dict(distance=cutoff, complete_support=coverage, results=results)
if best is None or best["complete_support"] == 0:
return dict(status="measured_failure", cutoff=None, trials=trials, cases=observations)
return dict(status="calibrated", cutoff=dict(profile=asdict(profile),
distance=best["distance"], retrieval_policy=RETRIEVAL_POLICY),
complete_support=best["complete_support"],
unsupported_false_positives=0, trials=trials, cases=best["results"])
def load_cutoff(report):
if report.get("status") != "calibrated" or not report.get("calibration_id"):
raise ValueError("Successful measured calibration report required")
return CalibratedCutoff(**report["cutoff"], calibration_id=report["calibration_id"])
+98
View File
@@ -0,0 +1,98 @@
"""Backend-owned evidence admission, ordering and execution source identities."""
from contextlib import contextmanager
from dataclasses import dataclass, field
import math
from threading import RLock
from uuid import UUID, uuid4
from app.modules.knowledge.lexical import LEXICAL_POLICY
MAX_BRANCH_CANDIDATES = 50
MAX_CHUNKS = 5
MAX_EVIDENCE_CHARACTERS = 12000
RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}"
def merge_candidates(semantic, exact):
by_id = {}
for row in semantic:
by_id[row["chunk_id"]] = dict(row, exact_match=False)
for row in exact:
by_id[row["chunk_id"]] = dict(row, exact_match=True)
return sorted(by_id.values(), key=lambda row: (
not row["exact_match"], row["cosine_distance"], str(row["chunk_id"])))
def admit_candidates(rows, cutoff=None):
admitted, used = [], 0
for row in rows:
if cutoff is not None and row["cosine_distance"] > cutoff:
continue
size = len(row["text"])
if size + used > MAX_EVIDENCE_CHARACTERS:
continue
admitted.append(row)
used += size
if len(admitted) == MAX_CHUNKS:
break
return admitted
@dataclass(frozen=True)
class CalibratedCutoff:
profile: dict
distance: float
calibration_id: str
retrieval_policy: str = RETRIEVAL_POLICY
def __post_init__(self):
if (type(self.distance) not in (int, float) or not math.isfinite(self.distance)
or not 0 <= self.distance <= 2 or not self.calibration_id):
raise ValueError("Measured finite cosine cutoff and calibration identity required")
@dataclass
class SearchExecution:
"""Created by the trusted caller, never populated from model arguments."""
user_id: UUID
request_id: str = field(default_factory=lambda: str(uuid4()))
_authority: dict | None = field(default=None, init=False, repr=False)
_epoch: int | None = field(default=None, init=False, repr=False)
_refs: dict = field(default_factory=dict, init=False, repr=False)
_lock: RLock = field(default_factory=RLock, init=False, repr=False)
def capture(self, current, epoch):
with self._lock:
if self._authority is None:
self._authority, self._epoch = dict(current), epoch
return self._authority == current and self._epoch == epoch
def matches(self, current, epoch):
with self._lock:
return self._authority is not None and self._authority == current and self._epoch == epoch
@contextmanager
def source_handoff(self):
"""Stage reference mappings; publish only after authorized commit."""
with self._lock:
prepared = dict(self._refs)
yield lambda rows: self._sources(rows, prepared)
self._refs = prepared
def sources(self, rows):
with self._lock:
return self._sources(rows, self._refs)
@staticmethod
def _sources(rows, refs):
sources = []
for row in rows:
key = (row["document_id"], row["chunk_id"])
if key not in refs:
refs[key] = f"S{len(refs) + 1}"
sources.append(dict(source_ref=refs[key],
document_id=str(row["document_id"]), chunk_id=str(row["chunk_id"]),
title=row["title"], text=row["text"],
location=dict(page=row["location"].get("page"),
section=row["location"].get("section"))))
return sources
+203
View File
@@ -0,0 +1,203 @@
"""Lazy LangChain boundary over the canonical search service."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
import math
from threading import Condition, Event
import time
from sqlalchemy.exc import SQLAlchemyError
from app.modules.knowledge.evidence import SearchExecution
from app.modules.knowledge.service import (
KnowledgeError, SearchInput, authority, sql_error, transaction,
)
@dataclass(frozen=True)
class ToolContext:
"""Backend-owned execution, absolute monotonic deadline and cancellation."""
execution: SearchExecution
deadline: float
cancelled: Event = field(default_factory=Event)
def __post_init__(self):
if not isinstance(self.execution, SearchExecution):
raise ValueError("Trusted SearchExecution required")
if type(self.deadline) not in (int, float) or not math.isfinite(self.deadline):
raise ValueError("Finite monotonic deadline required")
if not isinstance(self.cancelled, Event):
raise ValueError("Cancellation event required")
class SearchToolRunner:
"""Share one runner across tools to enforce process-wide admission limits."""
def __init__(self, *, running=4, waiting=8, timeout=75.0):
if type(running) is not int or running < 1 or type(waiting) is not int or waiting < 0:
raise ValueError("Positive running and nonnegative waiting limits required")
if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
raise ValueError("Finite positive timeout required")
self.running, self.waiting, self.timeout = running, waiting, timeout
self._lock = Condition()
self._admitted = self._active = 0
self._closed = False
self._pool = ThreadPoolExecutor(max_workers=running, thread_name_prefix="knowledge-search")
@staticmethod
def error(ctx, code, message, retryable=False):
return dict(status="error", sources=[], error=dict(
code=code, message=message, request_id=ctx.execution.request_id,
retryable=retryable))
def _stop(self, ctx, deadline, cancelled):
with self._lock:
if self._closed:
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled: runner closed")
if ctx.cancelled.is_set() or cancelled.is_set():
return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled")
if time.monotonic() >= deadline:
return self.error(ctx, "SEARCH_TIMEOUT", "Knowledge retrieval timed out", True)
def _admit(self):
with self._lock:
if self._closed or self._admitted >= self.running + self.waiting:
return False
self._admitted += 1
return True
def _release(self, *, active=False):
with self._lock:
self._admitted -= 1
if active:
self._active -= 1
self._lock.notify_all()
def _submit(self, service, ctx, query, context, deadline, cancelled):
with self._lock:
if self._active >= self.running or self._closed:
return None
self._active += 1
try:
future = self._pool.submit(
self._work, service, ctx, query, context, deadline, cancelled)
except BaseException:
self._active -= 1
raise
future.add_done_callback(lambda _: self._release(active=True))
return future
def _work(self, service, ctx, query, context, deadline, cancelled):
try:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
# Persisted authority is captured outside model input, on a worker.
with transaction(service.engine) as conn:
current, settings = authority(conn, ctx.execution.user_id)
if not ctx.execution.capture(current, settings["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
result = service.search(ctx.execution, query, context)
if result["status"] != "error":
# Recheck this delivery boundary after the service handoff.
with transaction(service.engine) as conn:
current, settings = authority(conn, ctx.execution.user_id)
if not ctx.execution.matches(current, settings["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed")
return self._stop(ctx, deadline, cancelled) or result
except KnowledgeError as exc:
code = "CONTEXT_REVOKED" if exc.code == "ACTOR_UNAVAILABLE" else exc.code
return self.error(ctx, code, str(exc), exc.retryable)
except SQLAlchemyError as exc:
error = sql_error(exc)
return self.error(ctx, error.code, str(error), error.retryable)
except Exception:
return self.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed")
def invoke(self, service, ctx, query, context=None):
SearchInput(query=query, context=context)
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
cancelled, future = Event(), None
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
if not self._admit():
return self._stop(ctx, deadline, cancelled) or self.error(
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
try:
while True:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
cancelled.set()
return stopped
if future is None:
future = self._submit(service, ctx, query, context, deadline, cancelled)
if future is not None and future.done():
return self._stop(ctx, deadline, cancelled) or future.result()
time.sleep(min(0.01, max(0, deadline - time.monotonic())))
finally:
if future is None:
self._release()
async def ainvoke(self, service, ctx, query, context=None):
SearchInput(query=query, context=context)
deadline = min(ctx.deadline, time.monotonic() + self.timeout)
cancelled, future = Event(), None
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
return stopped
if not self._admit():
return self._stop(ctx, deadline, cancelled) or self.error(
ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True)
try:
while True:
stopped = self._stop(ctx, deadline, cancelled)
if stopped:
cancelled.set()
return stopped
if future is None:
future = self._submit(service, ctx, query, context, deadline, cancelled)
if future is not None and future.done():
return self._stop(ctx, deadline, cancelled) or future.result()
await asyncio.sleep(min(0.01, max(0, deadline - time.monotonic())))
except asyncio.CancelledError:
cancelled.set()
raise
finally:
if future is None:
self._release()
def close(self):
"""Permanently cancel callers and join work/admissions; safe to repeat.
Closure and submission linearize under the same condition lock. Only
completion callbacks release submitted slots; queued callers release
their own admissions. Call from a control thread, outside the event
loop and this runner's worker pool, so callers can drain.
"""
with self._lock:
self._closed = True
self._pool.shutdown(wait=True)
with self._lock:
self._lock.wait_for(lambda: self._admitted == 0)
def create_search_tool(service, context, runner):
"""Build only on explicit opt-in; core imports do not require LangChain."""
from langchain_core.tools import StructuredTool
trusted = context
def search_knowledge(query: str, context: str | None = None):
return runner.invoke(service, trusted, query, context)
async def asearch_knowledge(query: str, context: str | None = None):
return await runner.ainvoke(service, trusted, query, context)
return StructuredTool.from_function(
func=search_knowledge, coroutine=asearch_knowledge,
name="search_knowledge",
description="Search authorized selected documents for evidence. Context is an untrusted retrieval hint.",
args_schema=SearchInput,
)
+40
View File
@@ -0,0 +1,40 @@
"""Lexical comparisons only: faithful evidence and embedding inputs stay unchanged."""
import re
import unicodedata
TRANSLATE_FROM = "۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩كيى"
TRANSLATE_TO = "01234567890123456789کیی"
TRANSLATION = str.maketrans(TRANSLATE_FROM, TRANSLATE_TO)
LEXICAL_POLICY = "nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
# Python split() and PostgreSQL locale whitespace classes differ for NBSP.
# Bind the complete Unicode whitespace set used by Python str.split().
WHITESPACE = "\t\n\v\f\r\x1c\x1d\x1e\x1f\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"
SQL_LEXICAL_PARAMS = dict(lexical_from=TRANSLATE_FROM + WHITESPACE,
lexical_to=TRANSLATE_TO + " " * len(WHITESPACE))
SQL_LEXICAL_TEXT = (
"regexp_replace(lower(translate(normalize(c.text, NFC), "
":lexical_from, :lexical_to)), ' +', ' ', 'g')"
)
_TOKEN = re.compile(r"(?<![\w./-])[\w]+(?:[./-][\w]+)*(?![\w/-]|\.(?=[\w./-]))")
_ARTICLE = re.compile(r"(?<!\w)(?:ماده|تبصره|article|clause)\s+[0-9]+(?:[./-][0-9]+)*(?![\w/-]|\.(?=[\w./-]))")
_DATE = re.compile(r"(?:[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}|[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4})\Z")
def lexical_text(value):
return " ".join(unicodedata.normalize("NFC", value).translate(TRANSLATION).lower().split())
def exact_patterns(query, context=None):
value = lexical_text(query + ("\n" + context if context else ""))
keys = {match.group() for match in _ARTICLE.finditer(value)}
for match in _TOKEN.finditer(value):
token = match.group()
# Dates or mixed letter/digit codes, never an isolated quantity.
if _DATE.fullmatch(token) or (any(c.isalpha() for c in token)
and any(c.isdigit() for c in token)):
keys.add(token)
# Query/context are already bounded to 4000 characters. No key is silently
# dropped, and regex syntax comes solely from these validated tokens.
return tuple("(^|[^[:alnum:]_./-])" +
re.sub(r"([.\\+*?\[\]^$(){}|])", r"\\\1", key) +
"($|[^[:alnum:]_./-]|\\.(?![[:alnum:]_./-]))" for key in sorted(keys))
+151 -29
View File
@@ -1,12 +1,13 @@
"""Trusted operator/application selection and uncalibrated search candidates."""
"""Trusted selection and one scoped retrieval core."""
from array import array
from contextlib import contextmanager
from contextlib import ExitStack, contextmanager
from dataclasses import asdict
import json
from uuid import UUID, uuid4
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError, DBAPIError, DisconnectionError, TimeoutError as SQLAlchemyTimeoutError
from app.infrastructure.database import check_compatibility, CompatibilityError
from app.modules.documents.embeddings import (
@@ -15,6 +16,12 @@ from app.modules.documents.embeddings import (
)
from app.modules.documents.normalization import normalize_search_text, NORMALIZATION_POLICY
from app.modules.knowledge.lexical import exact_patterns, SQL_LEXICAL_TEXT, SQL_LEXICAL_PARAMS
from app.modules.knowledge.evidence import (
CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY, MAX_BRANCH_CANDIDATES,
admit_candidates, merge_candidates,
)
class KnowledgeError(ValueError):
def __init__(self, code, message, *, status=409, details=None, retryable=False):
@@ -23,6 +30,27 @@ class KnowledgeError(ValueError):
self.details, self.retryable = details, retryable
# Retryability is a safe category, never a request to automatically replay work.
# These SQLSTATEs identify known serialization, connection, shutdown or
# connection-capacity failures. An absent state is retryable only with a
# confirmed disconnection; permanent and unknown states remain non-retryable.
_TRANSIENT_SQLSTATES = frozenset({
"40001", "40P01", "08000", "08001", "08003", "08006", "08007",
"57P01", "57P02", "57P03", "53300",
})
def sql_error(exc):
state = getattr(getattr(exc, "orig", None), "sqlstate", None)
if state in ("57014", "55P03") or isinstance(exc, SQLAlchemyTimeoutError):
return KnowledgeError("SEARCH_TIMEOUT", "Knowledge retrieval timed out", retryable=True)
return KnowledgeError("SEARCH_FAILED", "Knowledge database retrieval failed",
retryable=(state in _TRANSIENT_SQLSTATES
or isinstance(exc, DisconnectionError)
or (state is None and isinstance(exc, DBAPIError)
and exc.connection_invalidated)))
class SearchInput(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
query: str = Field(min_length=1, max_length=2000)
@@ -141,42 +169,129 @@ def selection_replace(engine, administrator_id, expected_revision, document_ids)
class SearchService:
"""One exact cosine core. Its output is diagnostic, not evidence admission."""
def __init__(self, engine, settings, provider, token_counter=None):
"""Shared bounded retrieval for diagnostics and calibrated model evidence."""
def __init__(self, engine, settings, provider, token_counter=None, *, cutoff=None):
self.engine, self.settings = engine, settings
self.provider, self.counter = provider, token_counter
self.cutoff = cutoff
def inspect(self, user_id, query, context=None):
result = self.candidates(SearchExecution(user_id), query, context)
result["candidates"] = admit_candidates(result["candidates"])
return result
def search(self, execution, query, context=None):
"""Canonical API 7.2 outcomes; missing calibration is a technical error."""
try:
SearchInput(query=query, context=context)
if not isinstance(self.cutoff, CalibratedCutoff):
raise KnowledgeError("CALIBRATION_REQUIRED", "Profile-specific calibration required")
if (self.cutoff.profile != asdict(self.settings.embedding_profile)
or self.cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise KnowledgeError("PROFILE_MISMATCH", "Calibration differs from search profile or policy")
result = self.candidates(execution, query, context)
return self._handoff(execution, result)
except KnowledgeError as exc:
error = exc
except ValidationError:
error = KnowledgeError("VALIDATION_ERROR", "Invalid search arguments", status=422)
except SQLAlchemyError as exc:
error = sql_error(exc)
except Exception:
error = KnowledgeError("SEARCH_FAILED", "Knowledge retrieval failed")
return dict(status="error", sources=[], error=dict(
code=error.code, message=str(error), request_id=execution.request_id,
retryable=error.retryable))
def _handoff(self, execution, result):
"""Service handoff linearizes at the successful final transaction commit.
Lock settings/actor before the reference guard. Admission and reference
preparation happen under database authorization locks; references become
durable in this execution only after commit. Later transport delivery
must perform its own authorization check.
"""
with ExitStack() as references:
with transaction(self.engine) as conn:
try:
current, settings = authority(conn, execution.user_id)
except KnowledgeError as exc:
if exc.code in ("ACTOR_UNAVAILABLE", "CONTEXT_REVOKED"):
raise KnowledgeError("CONTEXT_REVOKED", "Actor access changed before search handoff") from None
raise
if not execution.matches(current, settings["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed before search handoff")
rows = admit_candidates(result["candidates"], self.cutoff.distance)
allocate = references.enter_context(execution.source_handoff())
response = dict(status="ok" if rows else "no_evidence",
knowledge_revision=result["knowledge_revision"],
sources=allocate(rows),
warnings=[] if rows else ["insufficient_support"])
# Transaction commit above is the handoff boundary. ExitStack then
# publishes staged reference mappings, or discards them on failure.
return response
def candidates(self, execution, query, context=None):
"""At most 100 eligible merged rows for inspection/calibration, no verdict."""
try:
return self._retrieve(execution, query, context)
except KnowledgeError:
raise
except ValidationError:
raise KnowledgeError("VALIDATION_ERROR", "Invalid search arguments", status=422) from None
except TimeoutError:
raise KnowledgeError("SEARCH_TIMEOUT", "Knowledge retrieval timed out", retryable=True) from None
except SQLAlchemyError as exc:
raise sql_error(exc) from None
except EmbeddingError:
raise KnowledgeError("INVALID_CONFIGURATION", "Invalid embedding configuration or input limits") from None
except Exception:
raise KnowledgeError("SEARCH_FAILED", "Knowledge retrieval failed") from None
def _retrieve(self, execution, query, context):
request = SearchInput(query=query, context=context)
profile = self.settings.embedding_profile
policy = self.settings.processing_profile()["embedding_request"]
validate_embedding_profile(profile)
if profile.preprocessing_version != "v1" or self.settings.normalization_policy != NORMALIZATION_POLICY:
raise KnowledgeError("PROFILE_MISMATCH", "Unsupported embedding preprocessing")
def verify_provider():
if self.provider.profile != profile or self.provider.request_policy != policy:
raise KnowledgeError("PROFILE_MISMATCH", "Query adapter differs from configured embedding profile")
def compatibility(conn):
try:
check_compatibility(conn, profile, require_worker=True)
except CompatibilityError:
raise KnowledgeError("PROFILE_MISMATCH", "Database and embedding profile are incompatible") from None
verify_provider()
if not is_representable_timeout(policy["timeout_seconds"]):
raise KnowledgeError("INVALID_CONFIGURATION", "Finite embedding timeout required")
limits = validated_limits(policy["limits"])
value = request.query if request.context is None else request.query + "\n\n" + request.context
# Existing v1 embedding preprocessing is intentionally unchanged.
value = normalize_search_text(value, self.settings.normalization_policy)
limits.validate_batch([value], self.counter)
patterns = exact_patterns(request.query, request.context)
with transaction(self.engine) as conn:
current, snapshot = authority(conn, user_id)
try:
check_compatibility(conn, profile, require_worker=True)
except CompatibilityError:
raise KnowledgeError("PROFILE_MISMATCH", "Database and embedding profile are incompatible") from None
current, snapshot = authority(conn, execution.user_id)
if not execution.capture(current, snapshot["access_epoch"]):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed during execution")
compatibility(conn)
# No database connection or transaction is held during the remote call.
try:
vectors = self.provider.embed([value])
except EmbeddingProviderError as exc:
raise KnowledgeError("PROVIDER_UNAVAILABLE", "Query embedding provider failed",
retryable=exc.retryable) from None
except TimeoutError:
raise KnowledgeError("SEARCH_TIMEOUT", "Query embedding timed out", retryable=True) from None
except EmbeddingError:
raise KnowledgeError("INVALID_VECTOR", "Query embedding response is invalid") from None
except Exception:
raise KnowledgeError("PROVIDER_UNAVAILABLE", "Query embedding provider failed", retryable=True) from None
verify_provider()
if not isinstance(vectors, (list, tuple)) or len(vectors) != 1:
raise KnowledgeError("INVALID_VECTOR", "Exactly one query vector required")
@@ -186,14 +301,23 @@ class SearchService:
except EmbeddingError:
raise KnowledgeError("INVALID_VECTOR", "Query vector must have a valid float32 cosine norm") from None
with transaction(self.engine) as conn:
final, settings = authority(conn, user_id)
if final != current or settings["access_epoch"] != snapshot["access_epoch"]:
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed during search")
try:
check_compatibility(conn, profile, require_worker=True)
except CompatibilityError:
raise KnowledgeError("PROFILE_MISMATCH", "Database and embedding profile are incompatible") from None
rows = conn.execute(text("""
final, settings = authority(conn, execution.user_id)
except KnowledgeError as exc:
if exc.code == "ACTOR_UNAVAILABLE":
raise KnowledgeError("CONTEXT_REVOKED", "Actor access changed during execution") from None
raise
if (final != current or settings["access_epoch"] != snapshot["access_epoch"]
or not execution.capture(final, settings["access_epoch"])):
raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed during execution")
compatibility(conn)
params = dict(org=final["organization_id"], vector=json.dumps(list(vector)),
branch_limit=MAX_BRANCH_CANDIDATES,
profile=json.dumps(asdict(profile)), patterns=list(patterns))
params.update(SQL_LEXICAL_PARAMS)
# Every branch shares all eligibility joins/predicates, before
# ordering or LIMIT. Lexical normalization is comparison-only.
base = """
SELECT d.id AS document_id,c.id AS chunk_id,d.title,c.text,c.location,
c.embedding <=> CAST(:vector AS vector) AS cosine_distance
FROM document_chunks c
@@ -202,17 +326,15 @@ class SearchService:
AND d.status='ready' AND d.is_active
AND d.deleted_at IS NULL AND d.content_purged_at IS NULL
AND d.processing_profile->'embedding'=CAST(:profile AS jsonb)
ORDER BY cosine_distance,c.id LIMIT 50
"""), dict(org=final["organization_id"], vector=json.dumps(list(vector)),
profile=json.dumps(asdict(profile)))).mappings().all()
candidates, used = [], 0
for row in rows:
if used + len(row["text"]) > 12000:
continue
candidates.append(dict(row))
used += len(row["text"])
if len(candidates) == 5:
break
"""
semantic = conn.execute(text(base + " ORDER BY cosine_distance,c.id LIMIT :branch_limit"),
params).mappings().all()
exact = []
if patterns:
exact = conn.execute(text(base + " AND " + SQL_LEXICAL_TEXT +
" ~ ANY(CAST(:patterns AS text[])) ORDER BY cosine_distance,c.id LIMIT :branch_limit"),
params).mappings().all()
return dict(kind="uncalibrated_candidates", semantic_quality="not_assessed",
knowledge_revision=settings["knowledge_revision"],
access_epoch=settings["access_epoch"], candidates=candidates)
access_epoch=settings["access_epoch"],
candidates=merge_candidates(semantic, exact))