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