Files
rag-technical-docs-assistant/app/modules/knowledge/service.py
T
amirhosein mazaheri 42400495af feat(backend): integrate document deletion and grounded speech providers
Enable replay-safe document deletion and public deployment model identifiers with the forward voice-model schema revision.

Add GapGPT dialogue and ElevenLabs speech routing, strict extractive grounding, ten-source retrieval and regression coverage.

Validation: 199 targeted provider-free tests passed. The full provider-free run stalled and was interrupted; PostgreSQL acceptance was not run because TEST_DATABASE_URL is unset.
2026-10-20 09:00:37 +03:30

444 lines
23 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Trusted selection and one scoped retrieval core."""
from array import array
from contextlib import ExitStack, contextmanager
from dataclasses import asdict
import json
import re
from uuid import UUID, uuid4
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 (
EmbeddingError, EmbeddingProviderError, packed_vector, validated_limits,
validate_database_string, validate_embedding_profile, is_representable_timeout,
)
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,
)
import logging
import sys
import time
logger = logging.getLogger("app.search.trace")
logger.setLevel(logging.INFO)
if not logger.handlers and not any(h for h in logging.getLogger("app").handlers):
_trace_handler = logging.StreamHandler(sys.stderr)
_trace_handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
)
logger.addHandler(_trace_handler)
def _trace(execution, stage, **details):
elapsed_ms = 0.0
event = None
if hasattr(execution, "record_trace"):
event = execution.record_trace(stage, **details)
elapsed_ms = event.get("elapsed_ms", 0.0)
details_str = " | ".join(f"{k}={v!r}" for k, v in details.items()) if details else ""
logger.info("[%s] (+%.1fms) %s", stage, elapsed_ms, details_str)
return event
class KnowledgeError(ValueError):
def __init__(self, code, message, *, status=409, details=None, retryable=False):
super().__init__(message)
self.code, self.status = code, status
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)))
def clean_search_query(text: str) -> str:
cleaned = text
patterns = [
r"شرکت\s+شهرک[‌\s]*های\s+صنعتی\s+(?:استان\s+)?اصفهان",
r"شهرک[‌\s]*های\s+صنعتی\s+(?:استان\s+)?اصفهان",
r"شرکت\s+شهرک[‌\s]*های\s+صنعتی",
]
for pat in patterns:
sub = re.sub(pat, "", cleaned, flags=re.IGNORECASE).strip()
sub = re.sub(r"^(در|از|به|برای)\s+", "", sub).strip()
sub = re.sub(r"\s+(در|از|به|برای)$", "", sub).strip()
if len(sub) >= 3:
cleaned = sub
return re.sub(r"\s+", " ", cleaned).strip()
class SearchInput(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
query: str = Field(
min_length=1,
max_length=2000,
description="Clean, concise search terms or entity names only (e.g. 'آقای دانش' or 'معاون برنامه ریزی'). Do NOT include conversational filler, meta-narration, or 'کاربر می‌پرسد'. Never append 'شهرک‌های صنعتی اصفهان' or expand 'شرکت'."
)
context: str | None = Field(
default=None,
max_length=2000,
description="Leave null unless referencing a specific formal document identifier. Never use for conversational commentary or explanations."
)
@field_validator("query", "context")
@classmethod
def database_text(cls, value, info):
if value is not None:
validate_database_string(value)
if info.field_name == "query":
value = clean_search_query(value)
if not value.strip():
raise ValueError("Search text cannot be blank")
return value
@contextmanager
def transaction(engine):
with engine.begin() as conn:
conn.execute(text("SET LOCAL statement_timeout = '5s'"))
conn.execute(text("SET LOCAL lock_timeout = '2s'"))
yield conn
def actor(conn, user_id, *, administrator=False, lock=False):
row = conn.execute(text("""
SELECT id, organization_id, role FROM users
WHERE id=:id AND is_enabled
""" + (" FOR SHARE" if lock else "")), {"id": user_id}).mappings().one_or_none()
if row is None:
raise KnowledgeError("ACTOR_UNAVAILABLE", "Enabled actor required", status=403)
if administrator and row["role"] != "admin":
raise KnowledgeError("FORBIDDEN", "Administrator required", status=403)
return dict(row)
def authority(conn, user_id, *, administrator=False, exclusive=False):
initial = actor(conn, user_id, administrator=administrator)
settings = conn.execute(text("""
SELECT * FROM organization_settings WHERE organization_id=:org
""" + (" FOR UPDATE" if exclusive else " FOR SHARE")),
{"org": initial["organization_id"]}).mappings().one_or_none()
if settings is None:
raise KnowledgeError("SETTINGS_UNAVAILABLE", "Organization settings required")
current = actor(conn, user_id, administrator=administrator, lock=True)
if current != initial:
raise KnowledgeError("CONTEXT_REVOKED", "Actor authority changed")
return current, dict(settings)
def selected(conn, org):
return conn.execute(text("""
SELECT id FROM documents WHERE organization_id=:org AND is_active ORDER BY id
"""), {"org": org}).scalars().all()
def selection_get(engine, administrator_id):
with transaction(engine) as conn:
current, settings = authority(conn, administrator_id, administrator=True)
return dict(revision=settings["knowledge_revision"], access_epoch=settings["access_epoch"],
document_ids=selected(conn, current["organization_id"]))
def selection_replace(engine, administrator_id, expected_revision, document_ids):
ids = list(document_ids)
if (type(expected_revision) is not int or expected_revision < 1
or any(not isinstance(value, UUID) for value in ids)):
raise KnowledgeError("INVALID_SELECTION", "Positive revision and UUID document IDs required", status=422)
if len(set(ids)) != len(ids):
raise KnowledgeError("INVALID_SELECTION", "Duplicate document IDs", status=422)
wanted = set(ids)
with transaction(engine) as conn:
current, settings = authority(conn, administrator_id, administrator=True, exclusive=True)
org = current["organization_id"]
if expected_revision != settings["knowledge_revision"]:
raise KnowledgeError("REVISION_CONFLICT", "Read the current selection before replacing it")
old = set(selected(conn, org))
# Settings first, then every affected document in stable UUID order.
rows = {}
for document_id in sorted(old | wanted):
row = conn.execute(text("""
SELECT id,status,deleted_at,content_purged_at FROM documents
WHERE organization_id=:org AND id=:id FOR UPDATE
"""), {"org": org, "id": document_id}).mappings().one_or_none()
if row is not None:
rows[document_id] = row
if any(value not in rows or rows[value]["deleted_at"] is not None
or rows[value]["content_purged_at"] is not None for value in wanted):
raise KnowledgeError("NOT_FOUND", "Selected document is unavailable", status=404)
rejected = sorted(value for value in wanted if rows[value]["status"] != "ready")
if rejected:
raise KnowledgeError("DOCUMENT_NOT_READY", "Every selected document must be ready",
details={"document_ids": [str(value) for value in rejected]})
changed, removed = old != wanted, bool(old - wanted)
revision = settings["knowledge_revision"] + int(changed)
epoch = settings["access_epoch"] + int(removed)
result = dict(revision=revision, access_epoch=epoch, document_ids=sorted(wanted),
conversations_invalidated=removed)
if changed:
for document_id in sorted(old | wanted):
conn.execute(text("""
UPDATE documents SET is_active=:active,updated_at=now()
WHERE organization_id=:org AND id=:id
"""), {"org": org, "id": document_id, "active": document_id in wanted})
conn.execute(text("""
UPDATE organization_settings SET knowledge_revision=:revision,access_epoch=:epoch,
updated_by=:actor,updated_at=now() WHERE organization_id=:org
"""), dict(org=org, actor=current["id"], revision=revision, epoch=epoch))
if removed:
conn.execute(text("""UPDATE conversations SET status='stale',updated_at=now() WHERE organization_id=:org AND access_epoch<:epoch AND status='active'"""), {'org': org, 'epoch': epoch})
conn.execute(text("""
UPDATE live_sessions
SET status = 'closed', closed_at = now(), close_reason = 'epoch_invalidated', updated_at = now()
WHERE organization_id = :org AND access_epoch < :epoch AND status IN ('creating', 'connecting', 'connected')
"""), {"org": org, "epoch": epoch})
conn.execute(text("""UPDATE tool_calls SET status='failed',completed_at=now(),error_code='CONTEXT_REVOKED'
WHERE organization_id=:org AND access_epoch<:epoch AND status='running'"""), {'org': org, 'epoch': epoch})
conn.execute(text("""
INSERT INTO audit_events(id,organization_id,actor_user_id,action,metadata)
VALUES (:id,:org,:actor,'selection_changed',CAST(:metadata AS jsonb))
"""), dict(id=uuid4(), org=org, actor=current["id"],
metadata=json.dumps(dict(knowledge_revision=revision, access_epoch=epoch,
added_document_ids=[str(v) for v in sorted(wanted - old)],
removed_document_ids=[str(v) for v in sorted(old - wanted)]))))
if changed and removed:
from app.modules.voice.registry import notify
notify(organization_id=org, new_epoch=epoch)
return result
class SearchService:
"""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_or_execution, query, context=None):
if isinstance(user_or_execution, SearchExecution):
execution = user_or_execution
else:
execution = SearchExecution(user_or_execution)
_trace(execution, "INSPECT_START", query=query, context=context)
result = self.candidates(execution, query, context)
result["candidates"] = admit_candidates(result["candidates"])
_trace(execution, "INSPECT_COMPLETE", candidates_count=len(result["candidates"]))
return result
def search(self, execution, query, context=None):
"""Canonical API 7.2 outcomes; missing calibration is a technical error."""
_trace(execution, "SEARCH_START", query=query, context=context, user_id=str(execution.user_id))
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)
response = self._handoff(execution, result)
_trace(execution, "SEARCH_COMPLETE", status=response.get("status"), sources_count=len(response.get("sources", [])))
return response
except KnowledgeError as exc:
error = exc
_trace(execution, "SEARCH_ERROR", code=exc.code, message=str(exc))
except ValidationError:
error = KnowledgeError("VALIDATION_ERROR", "Invalid search arguments", status=422)
_trace(execution, "SEARCH_ERROR", code="VALIDATION_ERROR", message=str(error))
except SQLAlchemyError as exc:
error = sql_error(exc)
_trace(execution, "SEARCH_ERROR", code=error.code, message=str(error))
except Exception:
error = KnowledgeError("SEARCH_FAILED", "Knowledge retrieval failed")
_trace(execution, "SEARCH_ERROR", code="SEARCH_FAILED", message=str(error))
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())
sources = allocate(rows)
_trace(execution, "CUTOFF_ADMISSION",
cutoff_distance=self.cutoff.distance,
evaluated_count=len(result["candidates"]),
admitted_count=len(rows),
status="ok" if rows else "no_evidence")
response = dict(status="ok" if rows else "no_evidence",
knowledge_revision=result["knowledge_revision"],
sources=sources,
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)
_trace(execution, "QUERY_PREPROCESSED",
policy=self.settings.normalization_policy,
normalized_query=value,
patterns=list(patterns))
with transaction(self.engine) as conn:
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.
embed_start = time.monotonic()
_trace(execution, "EMBEDDING_DISPATCH", provider=profile.provider, model=profile.model, dimensions=profile.dimensions)
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
embed_latency_ms = round((time.monotonic() - embed_start) * 1000, 2)
verify_provider()
if not isinstance(vectors, (list, tuple)) or len(vectors) != 1:
raise KnowledgeError("INVALID_VECTOR", "Exactly one query vector required")
try:
vector = array("f")
vector.frombytes(packed_vector(vectors[0], profile.dimensions))
except EmbeddingError:
raise KnowledgeError("INVALID_VECTOR", "Query vector must have a valid float32 cosine norm") from None
_trace(execution, "EMBEDDING_RECEIVED",
latency_ms=embed_latency_ms,
dimensions=len(vector),
sample_components=[round(float(x), 4) for x in vector[:5]])
with transaction(self.engine) as conn:
try:
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
JOIN documents d ON d.id=c.document_id AND d.organization_id=c.organization_id
WHERE d.organization_id=:org AND c.organization_id=:org
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)
"""
db_start = time.monotonic()
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()
db_latency_ms = round((time.monotonic() - db_start) * 1000, 2)
merged = merge_candidates(semantic, exact)
_trace(execution, "DATABASE_QUERY_DONE",
latency_ms=db_latency_ms,
semantic_count=len(semantic),
exact_count=len(exact),
merged_count=len(merged),
top_3=[{"doc_id": str(r["document_id"]), "title": r["title"], "distance": round(float(r["cosine_distance"]), 4), "exact": r["exact_match"]} for r in merged[:3]])
return dict(kind="uncalibrated_candidates", semantic_quality="not_assessed",
knowledge_revision=settings["knowledge_revision"],
access_epoch=settings["access_epoch"],
candidates=merged)