Files
rag-technical-docs-assistant/app/modules/knowledge/service.py
T
11linear11 996435d2ae feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations,
tool completion/replay fencing, revocation, and startup reconciliation.
Introduce forward lifecycle/owner-chain migrations and the temporary Gemini
adapter while preserving the existing OpenAI Realtime adapter.

Include the executable audio client, regression coverage, configuration,
API/database documentation, and recorded acceptance evidence.

Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript
syntax, and whitespace checks passed. Full PostgreSQL/provider-free results
are recorded in the repair report; real-provider/browser acceptance is unrun.

Follow-up work remains for configurable OpenAI/Gemini selection, transport
admission, authority diagnostics, playback message bounds, and client replay
identity after ambiguous creation responses.
2026-10-09 07:59:02 -04:00

353 lines
19 KiB
Python

"""Trusted selection and one scoped retrieval core."""
from array import array
from contextlib import ExitStack, contextmanager
from dataclasses import asdict
import json
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,
)
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)))
class SearchInput(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
query: str = Field(min_length=1, max_length=2000)
context: str | None = Field(default=None, max_length=2000)
@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" and 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_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, 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")
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
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)
"""
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=merge_candidates(semantic, exact))