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:
@@ -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