feat(search): implement Phase 1 scoped search vertical slice

Resolve persisted enabled actors and atomically replace knowledge selection with revision checks, removal epochs, stable locking and audit updates.

Reuse compatible query embeddings for scoped pgvector cosine retrieval, revalidate authority after remote work, and expose opt-in operator inspection with uncalibrated candidates.

Validation: 37 targeted tests passed (14 unit, 23 PostgreSQL); provider-free inactive-to-active demonstration passed. Real-provider demonstration remains pending ingestion database connectivity. Applied migrations are unchanged.
This commit is contained in:
amirhosein mazaheri
2026-10-07 17:31:59 +03:30
parent ff9c32823c
commit 7fa1c2dcc1
11 changed files with 798 additions and 2 deletions
+50
View File
@@ -0,0 +1,50 @@
"""Trusted operator knowledge selection. User UUIDs are not HTTP authentication."""
import argparse
import json
import sys
from uuid import UUID
from app.ingest import json_value
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.service import KnowledgeError, selection_get, selection_replace
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
selection = commands.add_parser("selection")
actions = selection.add_subparsers(dest="action", required=True)
get = actions.add_parser("get")
get.add_argument("--administrator-id", type=UUID, required=True)
replace = actions.add_parser("replace")
replace.add_argument("--administrator-id", type=UUID, required=True)
replace.add_argument("--expected-revision", type=int, required=True)
choice = replace.add_mutually_exclusive_group(required=True)
choice.add_argument("--document-id", type=UUID, action="append")
choice.add_argument("--clear", action="store_true")
args = parser.parse_args(argv)
engine = None
try:
settings = IngestionSettings()
engine = create_database(settings.database_url.get_secret_value())
result = (selection_get(engine, args.administrator_id) if args.action == "get"
else selection_replace(engine, args.administrator_id, args.expected_revision,
args.document_id or []))
print(json.dumps(result, default=json_value))
return 0
except KnowledgeError as exc:
print(json.dumps(dict(error=dict(code=exc.code, message=str(exc), details=exc.details))),
file=sys.stderr)
return 1
except Exception:
print(json.dumps(dict(error=dict(code="SELECTION_FAILED",
message="Verify actor, configuration and database availability"))), file=sys.stderr)
return 1
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
"""Shared selection and search; no prototype or provider I/O on import."""
+218
View File
@@ -0,0 +1,218 @@
"""Trusted operator/application selection and uncalibrated search candidates."""
from array import array
from contextlib import contextmanager
from dataclasses import asdict
import json
from uuid import UUID, uuid4
from pydantic import BaseModel, ConfigDict, Field, field_validator
from sqlalchemy import text
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
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
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))
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)]))))
return result
class SearchService:
"""One exact cosine core. Its output is diagnostic, not evidence admission."""
def __init__(self, engine, settings, provider, token_counter=None):
self.engine, self.settings = engine, settings
self.provider, self.counter = provider, token_counter
def inspect(self, user_id, query, context=None):
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")
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
value = normalize_search_text(value, self.settings.normalization_policy)
limits.validate_batch([value], self.counter)
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
# 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 EmbeddingError:
raise KnowledgeError("INVALID_VECTOR", "Query embedding response is invalid") 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:
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("""
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)
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
return dict(kind="uncalibrated_candidates", semantic_quality="not_assessed",
knowledge_revision=settings["knowledge_revision"],
access_epoch=settings["access_epoch"], candidates=candidates)
+49
View File
@@ -0,0 +1,49 @@
"""Single-query operator inspection; candidates are uncalibrated, not certified evidence."""
import argparse
import json
import sys
from uuid import UUID
from app.ingest import json_value
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.service import KnowledgeError, SearchInput, SearchService
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inspect", action="store_true", required=True)
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--query", required=True)
parser.add_argument("--context")
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize exactly one query embedding call")
args = parser.parse_args(argv)
engine = None
try:
SearchInput(query=args.query, context=args.context)
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())
result = SearchService(engine, settings, provider, counter).inspect(
args.user_id, args.query, args.context)
print(json.dumps(result, default=json_value, ensure_ascii=True, allow_nan=False))
return 0
except KnowledgeError as exc:
print(json.dumps(dict(error=dict(code=exc.code, message=str(exc),
retryable=exc.retryable))), file=sys.stderr)
return 1
except Exception:
print(json.dumps(dict(error=dict(code="SEARCH_FAILED",
message="Verify input, actor, embedding configuration and database availability"))),
file=sys.stderr)
return 1
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
sys.exit(main())
+41 -1
View File
@@ -68,7 +68,7 @@ Prototype runtime prerequisites remain unverified: configured credentials, appro
## Gaps and decisions
- Required document content is available under `specifications/`; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, scoped pgvector search, HTTP identity/upload, LangChain integration, native Live and UI. Full durable text turns/history are deferred; no component test certifies this integration.
- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, calibrated search/exact identifiers, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration.
- Open validations: exact format/size caps, funded model profiles/vector dimension, Gemini Live WSS/tool/transcript and Persian speech proof, hosting/connectivity, account/session/retention policy, quality target and delivery date. Direct Gemini Live, LangChain, new browser uploads, existing embedding reuse and all supplied example structures are confirmed MVP direction. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
- The 2026-10-06 MVP supersedes provisional SDP/WebRTC with backend-managed direct Gemini Live WSS; see API Section 7. Current-session provider answer transcripts/sources are displayed when available; durable full voice history remains deferred. Broader features do not authorize model selectors or CTI.
- Project documentation now lives under `docs/`; sample corpus files remain under `data/documents/`. A future default corpus rebuild excludes the moved specifications and reference map. Existing vector indexes are not rebuilt or cleaned by this reorganization and may retain previously indexed project documentation. Use an approved corpus for real-provider evaluation.
@@ -1323,3 +1323,43 @@ Affected repair files (all other baseline files are unchanged):
- docs/specifications/RAG-Phase1-Implementation-Guide.md
- tests/integration/test_phase6.py
- tests/unit/test_phase6.py
## Fast-Track Search Phase 1 first-result checkpoint (2026-10-07)
Current inventory supersedes historical statements that scoped search and
selection are still entirely absent. [Shared selection/search core](../app/modules/knowledge/service.py),
[selection CLI](../app/knowledge.py), [inspection CLI](../app/search.py),
[targeted PostgreSQL tests](../tests/integration/test_scoped_search.py),
[input/CLI tests](../tests/unit/test_scoped_search.py), and
[provider-free demonstration](../tests/search_demo.py) now exist.
See the [operator checkpoint guide](guides/scoped-search-checkpoint.md)
for setup, commands, exact observed source IDs/text and limitations.
Implemented: persisted enabled actor/organization resolution; full-set selection
with expected knowledge revision, settings-first document locks in UUID order,
no-op counter preservation, knowledge revision increments, removal epochs and
atomic change audit; compatible bounded one-input query embeddings outside
transactions; exact pgvector cosine eligibility joins; actor/epoch revalidation;
whole-chunk diagnostic results (five chunks, 12000 text characters).
No migration, dependency, prototype retriever, HTTP search or framework was added.
The inspection format is uncalibrated_candidates, not the model-tool contract.
Actual checks:
- PostgreSQL prerequisite probe passed: PostgreSQL 16.15 / pgvector 0.8.7 in a
fresh dedicated container/database on 127.0.0.1:54938.
- `.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/integration/test_scoped_search.py --require-postgres -q --tb=short`:
**37 passed** (14 unit, 23 PostgreSQL), zero skips, 28.46 seconds.
- `.venv/Scripts/python -m tests.search_demo` with isolated TEST_DATABASE_URL:
inactive=0 candidates; after legitimate selection revision=2/epoch=1,
one faithful pump-limit candidate with document/chunk IDs and actual locator.
- Selection/search CLI help verified; tracked and new-file whitespace passed;
all applied migration files compared byte-for-byte with HEAD and preserved.
The available operator URL was rejected by the isolated-test guard because its
database name was not suffixed _test; it was not used for test writes.
The deployment ingestion database connection failed with OperationalError.
Credentials/configuration were present but no hosted call was attempted;
approved ready real-document/provider demonstration remains pending a reachable
compatible ingestion database. This is provider-free database validation, not
semantic-quality acceptance. Full regressions/calibration/LangChain/UI/Live/ANN
were not run or built; Fast-Track phases 2-4 remain pending.
+88
View File
@@ -0,0 +1,88 @@
# Fast-Track Search Phase 1 checkpoint
This checkpoint provides atomic selected-knowledge replacement and one scoped
pgvector cosine search through a trusted operator CLI. User UUID arguments are
operator authority inputs, not HTTP authentication. Search resolves enabled
actors and their organization from persisted users. Administrators manage
selection; enabled users and administrators can inspect candidates.
Reuse the ingestion setup and worker to publish a ready document. Configure
the existing INGEST_DATABASE_URL and complete compatible embedding identity,
input limits/tokenizer and credentials. No new dependency or migration is needed.
```powershell
.venv/Scripts/python -m app.knowledge selection get --administrator-id <admin-id>
.venv/Scripts/python -m app.knowledge selection replace --administrator-id <admin-id> --expected-revision <knowledge-revision> --document-id <ready-document-id>
.venv/Scripts/python -m app.search --inspect --user-id <user-id> --query "<question>" --allow-provider-calls
```
Repeat --document-id for a full selected set. --clear explicitly replaces it
with an empty set and cannot accompany document IDs. A no-op preserves all
counters and creates no change audit. Additions increment knowledge revision;
removals also increment access epoch. Configuration revision is preserved.
Flags, counters and change audit commit atomically, with settings locked before
documents in UUID order. A stale expected revision fails; read selection again.
Inspection performs exactly one query embedding call, outside database
transactions. It uses the existing adapter, preprocessing, limits/tokenizer,
float32 validation and database compatibility checks. SQL statement/lock
timeouts are 5/2 seconds; the provider uses the finite configured timeout.
Before retrieval it rechecks enabled actor, organization/role and access epoch.
Search joins document/chunk organization identities and excludes inactive,
unready, deleted and purged content. It retrieves at most 50 cosine candidates,
returning at most five whole chunks within 12,000 text characters.
JSON on stdout labels results as uncalibrated_candidates with
semantic_quality=not_assessed. Candidates contain faithful text, title,
document_id, chunk_id, actual location and cosine distance. This is a diagnostic
format, not a model tool response, evidence-sufficiency verdict or semantic
quality certification. Failures go to stderr and return a nonzero exit code.
## Observed demonstration, 2026-10-07
The configured ingestion database could not connect (OperationalError). Hosted
embedding credentials/configuration were present but were not exercised, and
no processed approved real document could be verified. The missing prerequisite
for the real demonstration is a reachable compatible ingestion database with
an approved ready document. No deployment data was changed.
A dedicated local test container ran PostgreSQL 16.15 and pgvector 0.8.7.
The exact provider-free demonstration command was:
```powershell
$env:TEST_DATABASE_URL = 'postgresql+psycopg://postgres:search-test-only@127.0.0.1:54938/rag_scoped_search_test'
.venv/Scripts/python -m tests.search_demo
```
The demo used actual intake, extraction, embedding staging and worker publication
in a disposable schema, with deterministic embeddings and no provider calls.
Question: "When is pump pressure 25 bar?"
Observed: inactive_candidate_count=0; selection revision=2, access_epoch=1;
one uncalibrated candidate after selection. Title: "Pump operating limits".
Text: "Pump pressure is 25 bar only when temperature is below 60 C. Do not open
the bypass except during shutdown." Location: page=null,
section="text/paragraph/1". Observed document ID:
568e01ca-cacb-4a0b-bff8-1e6b071dac3d; chunk ID:
1404092e-d8cf-4cc2-a72a-dda898baa625; cosine distance:
0.35838125217767736. IDs are disposable and change on each run.
Targeted checks:
```powershell
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/integration/test_scoped_search.py --require-postgres -q --tb=short
```
The final targeted run passed 37 tests (14 unit, 23 PostgreSQL), with zero skips.
The dedicated container was stopped after validation and retained for reuse;
restart it with docker start rag-scoped-search-20261007 before repeating the
command above. A fresh environment can create it with:
```powershell
docker run --name rag-scoped-search-20261007 -e POSTGRES_PASSWORD=search-test-only -e POSTGRES_DB=rag_scoped_search_test -p 127.0.0.1:54938:5432 -d pgvector/pgvector:pg16
```
Wait for PostgreSQL readiness and rerun the prerequisite probe first. Applied migration
files were preserved. Full regression and real-provider semantic-quality
acceptance are outside this checkpoint; phases 2-4 remain pending.
@@ -2,7 +2,7 @@
**Date:** 2026-10-07
**Target file:** `docs/plans/scoped-search-implementation-plan.md`
**Status:** Approved planning direction; implementation and acceptance remain pending. This four-phase plan replaces the earlier seven-phase proposal.
**Status:** Phase 1 first-result checkpoint implemented with provider-free PostgreSQL acceptance (2026-10-07); real-provider demonstration is pending ingestion database connectivity. Phases 2-4 remain pending. This four-phase plan replaces the earlier seven-phase proposal.
## 1. Delivery Strategy
+221
View File
@@ -0,0 +1,221 @@
"""Real PostgreSQL acceptance for the first search result."""
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
import json
from uuid import uuid4
import pytest
from sqlalchemy import text
from app.modules.knowledge.service import KnowledgeError, SearchService, selection_get, selection_replace
from tests.support.embedding import DeterministicEmbeddings
from tests.support.search import administrator, configure, publish, EVIDENCE, QUERY
@pytest.fixture
def search_path(migrated_db, settings, tmp_path):
engine, _ = migrated_db
settings = configure(settings)
org, admin = administrator(engine)
doc = publish(engine, settings, tmp_path, admin)
return engine, settings, org, admin, doc
def test_inactive_to_active(search_path):
engine, settings, org, admin, doc = search_path
provider = DeterministicEmbeddings(settings, observe=lambda _: (
pytest.fail("Remote call holds a connection") if engine.pool.checkedout() else None))
service = SearchService(engine, settings, provider)
assert service.inspect(admin, QUERY)["candidates"] == []
assert selection_replace(engine, admin, 1, [doc]) == dict(
revision=2, access_epoch=1, document_ids=[doc], conversations_invalidated=False)
result = service.inspect(admin, QUERY)
assert result["kind"] == "uncalibrated_candidates"
assert result["semantic_quality"] == "not_assessed"
assert len(result["candidates"]) == 1
row = result["candidates"][0]
assert row["document_id"] == doc and row["title"] == "Pump operating limits"
assert row["text"] == EVIDENCE
assert row["location"] == {"page": None, "section": "text/paragraph/1"}
with engine.connect() as conn:
assert row["chunk_id"] == conn.execute(text(
"SELECT id FROM document_chunks WHERE document_id=:id"), dict(id=doc)).scalar_one()
def test_selection_counters_atomicity_and_authority(search_path):
engine, settings, org, admin, doc = search_path
assert selection_get(engine, admin) == dict(revision=1, access_epoch=1, document_ids=[])
with pytest.raises(KnowledgeError, match="Duplicate"):
selection_replace(engine, admin, 1, [doc, doc])
with pytest.raises(KnowledgeError) as error:
selection_replace(engine, admin, 1, [doc, uuid4()])
assert error.value.status == 404
assert selection_get(engine, admin)["document_ids"] == []
selection_replace(engine, admin, 1, [doc])
no_op = selection_replace(engine, admin, 2, [doc])
assert no_op["revision"] == 2 and no_op["access_epoch"] == 1
with pytest.raises(KnowledgeError) as error:
selection_replace(engine, admin, 1, [])
assert error.value.code == "REVISION_CONFLICT"
removed = selection_replace(engine, admin, 2, [])
assert removed["revision"] == 3 and removed["access_epoch"] == 2
assert removed["conversations_invalidated"]
with engine.begin() as conn:
assert conn.execute(text("SELECT revision FROM organization_settings WHERE organization_id=:org"),
dict(org=org)).scalar_one() == 1
audits = conn.execute(text("SELECT metadata FROM audit_events WHERE action='selection_changed' ORDER BY created_at")).scalars().all()
assert len(audits) == 2
assert audits[1]["removed_document_ids"] == [str(doc)]
conn.execute(text("UPDATE users SET role='user' WHERE id=:id"), dict(id=admin))
with pytest.raises(KnowledgeError) as error:
selection_get(engine, admin)
assert error.value.code == "FORBIDDEN"
assert SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, QUERY)["candidates"] == []
with engine.begin() as conn:
conn.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), dict(id=admin))
provider = DeterministicEmbeddings(settings)
with pytest.raises(KnowledgeError):
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert provider.calls == []
def test_concurrent_selection_only_one_revision_wins(search_path):
engine, settings, org, admin, doc = search_path
def select():
try:
return selection_replace(engine, admin, 1, [doc])["revision"]
except KnowledgeError as error:
return error.code
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _: select(), range(2)))
assert sorted(results, key=str) == sorted([2, "REVISION_CONFLICT"], key=str)
with engine.connect() as conn:
assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='selection_changed'")).scalar_one() == 1
@pytest.mark.parametrize("ineligible", ["inactive", "deleted", "purged", "failed", "queued", "processing"])
def test_organization_and_eligibility(search_path, tmp_path, ineligible):
engine, settings, org, admin, doc = search_path
other_org, other_admin = administrator(engine)
foreign = publish(engine, settings, tmp_path / "foreign", other_admin, "Foreign organization secret")
selection_replace(engine, other_admin, 1, [foreign])
with pytest.raises(KnowledgeError) as error:
selection_replace(engine, admin, 1, [foreign])
assert error.value.status == 404
selection_replace(engine, admin, 1, [doc])
# Deliberately retained chunks prove eligibility joins exclude stale data.
assignments = {"inactive": "", "deleted": ",deleted_at=now()",
"purged": ",content_purged_at=now()", "failed": ",status='failed'",
"queued": ",status='queued'", "processing": ",status='processing'"}
with engine.begin() as conn:
conn.execute(text("UPDATE documents SET is_active=false" + assignments[ineligible] + " WHERE id=:id"),
dict(id=doc))
assert SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, QUERY)["candidates"] == []
if ineligible in ("failed", "queued", "processing", "deleted", "purged"):
with pytest.raises(KnowledgeError) as error:
selection_replace(engine, admin, 2, [doc])
assert error.value.code == ("DOCUMENT_NOT_READY" if ineligible in ("failed", "queued", "processing") else "NOT_FOUND")
def test_profile_mismatch_fails_before_remote(search_path):
engine, settings, org, admin, doc = search_path
provider = DeterministicEmbeddings(settings)
provider.profile = replace(provider.profile, model="different")
with pytest.raises(KnowledgeError) as error:
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert error.value.code == "PROFILE_MISMATCH" and not provider.calls
bad = settings.model_copy(update={"embedding_model": "different"})
provider = DeterministicEmbeddings(bad)
with pytest.raises(KnowledgeError) as error:
SearchService(engine, bad, provider).inspect(admin, QUERY)
assert error.value.code == "PROFILE_MISMATCH" and not provider.calls
with engine.begin() as conn:
conn.execute(text("UPDATE documents SET processing_profile=jsonb_set(processing_profile,'{embedding,model}',:model) WHERE id=:id"),
dict(id=doc, model=json.dumps("different")))
provider = DeterministicEmbeddings(settings)
with pytest.raises(KnowledgeError) as error:
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert error.value.code == "PROFILE_MISMATCH" and not provider.calls
@pytest.mark.parametrize("vector", [[0, 0, 0], [1, 2], [float("nan"), 1, 1],
[float("inf"), 1, 1], [1e30, 1, 1], [1e-30, 0, 0], [True, 1, 1]])
def test_invalid_query_vectors_are_errors(search_path, vector):
engine, settings, org, admin, doc = search_path
selection_replace(engine, admin, 1, [doc])
provider = DeterministicEmbeddings(settings)
provider.embed = lambda _: [vector]
with pytest.raises(KnowledgeError) as error:
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert error.value.code == "INVALID_VECTOR"
@pytest.mark.parametrize("change", ["remove", "disable"])
def test_revalidation_after_provider(search_path, change):
engine, settings, org, admin, doc = search_path
selection_replace(engine, admin, 1, [doc])
def revoke(_):
if change == "remove":
selection_replace(engine, admin, 2, [])
else:
with engine.begin() as conn:
conn.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), dict(id=admin))
provider = DeterministicEmbeddings(settings, observe=revoke)
with pytest.raises(KnowledgeError) as error:
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert error.value.code in ("CONTEXT_REVOKED", "ACTOR_UNAVAILABLE")
def test_audit_failure_rolls_back_flags_and_counters(search_path):
engine, settings, org, admin, doc = search_path
with engine.begin() as conn:
conn.execute(text("""CREATE FUNCTION reject_selection_audit() RETURNS trigger LANGUAGE plpgsql AS
'BEGIN IF NEW.action = ''selection_changed'' THEN RAISE EXCEPTION ''fixture failure''; END IF; RETURN NEW; END'"""))
conn.execute(text("CREATE TRIGGER fail_audit BEFORE INSERT ON audit_events FOR EACH ROW EXECUTE FUNCTION reject_selection_audit()"))
with pytest.raises(Exception):
selection_replace(engine, admin, 1, [doc])
assert selection_get(engine, admin) == dict(revision=1, access_epoch=1, document_ids=[])
def test_query_limits_normalization_and_provider_policy(search_path):
engine, settings, org, admin, doc = search_path
provider = DeterministicEmbeddings(settings)
service = SearchService(engine, settings, provider)
service.inspect(admin, "Cafe\u0301\r\nquestion", "hint")
assert provider.calls == [("Caf\u00e9\nquestion\n\nhint",)]
provider.request_policy["send_dimensions"] = True
with pytest.raises(KnowledgeError) as error:
service.inspect(admin, QUERY)
assert error.value.code == "PROFILE_MISMATCH"
assert len(provider.calls) == 1
def test_provider_failure_is_not_empty_candidates(search_path):
from app.modules.documents.embeddings import EmbeddingProviderError
engine, settings, org, admin, doc = search_path
provider = DeterministicEmbeddings(settings)
def fail(_):
raise EmbeddingProviderError("secret provider body", retryable=True)
provider.embed = fail
with pytest.raises(KnowledgeError) as error:
SearchService(engine, settings, provider).inspect(admin, QUERY)
assert error.value.code == "PROVIDER_UNAVAILABLE" and error.value.retryable
assert "secret" not in str(error.value)
def test_whole_chunk_budget_and_five_candidate_limit(search_path, tmp_path):
from app.modules.documents.embeddings import EmbeddingLimits
engine, settings, org, admin, doc = search_path
documents = [doc]
for i in range(6):
documents.append(publish(engine, settings, tmp_path / str(i), admin,
"Eligible complete passage " + str(i)))
large_settings = settings.model_copy(update=dict(chunk_size_characters=15000,
embedding_limits=EmbeddingLimits(unit="utf8_bytes", max_input_units=20000,
max_batch_units=40000, max_batch_inputs=2)))
documents.append(publish(engine, large_settings, tmp_path / "large", admin, "a" * 12001))
selection_replace(engine, admin, 1, documents)
result = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, QUERY)
assert len(result["candidates"]) == 5
assert sum(len(row["text"]) for row in result["candidates"]) <= 12000
assert all(row["document_id"] != documents[-1] for row in result["candidates"])
+35
View File
@@ -0,0 +1,35 @@
"""Provider-free first-result demonstration in a disposable PostgreSQL schema."""
import json
import os
from tempfile import TemporaryDirectory
from app.ingest import json_value
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.service import SearchService, selection_replace
from tests.support.embedding import DeterministicEmbeddings
from tests.support.postgres import disposable_database
from tests.support.search import administrator, configure, publish, QUERY
def main():
url = os.environ.get("TEST_DATABASE_URL")
if not url:
raise SystemExit("TEST_DATABASE_URL is required; use an isolated _test database")
settings = configure(IngestionSettings(_env_file=None, database_url=url,
embedding_provider="test", embedding_endpoint="https://test.invalid/v1",
embedding_model="deterministic-test", embedding_dimensions=3))
with disposable_database(url, settings) as (engine, _), TemporaryDirectory() as root:
_, admin = administrator(engine)
doc = publish(engine, settings, root, admin)
service = SearchService(engine, settings, DeterministicEmbeddings(settings))
before = service.inspect(admin, QUERY)
selection = selection_replace(engine, admin, 1, [doc])
after = service.inspect(admin, QUERY)
print(json.dumps(dict(validation="provider_free_database", query=QUERY,
inactive_candidate_count=len(before["candidates"]), selection=selection,
result=after), default=json_value))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+52
View File
@@ -0,0 +1,52 @@
"""Provider-free search pipeline fixtures on an isolated migrated database."""
from pathlib import Path
from uuid import uuid4
from sqlalchemy import text
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.infrastructure.file_store import LocalFileStore
from app.infrastructure.intake_repository import SqlIntakeRepository
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.modules.documents.embeddings import EmbeddingLimits
from app.modules.documents.extraction import PageBlockExtractor
from app.modules.documents.intake import import_document
from app.modules.documents.worker import Worker
from tests.support.embedding import DeterministicEmbeddings
EVIDENCE = "Pump pressure is 25 bar only when temperature is below 60 C. Do not open the bypass except during shutdown."
QUERY = "When is pump pressure 25 bar?"
def configure(settings):
return settings.model_copy(update=dict(embedding_limits=EmbeddingLimits(
unit="utf8_bytes", max_input_units=4096, max_batch_units=8192, max_batch_inputs=2)))
def administrator(engine):
org, user = uuid4(), uuid4()
with engine.begin() as conn:
conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'search fixture')"), dict(id=org))
conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role)
VALUES (:id,:org,:name,'test-only','admin')"""), dict(id=user, org=org, name=str(user)))
conn.execute(text("""INSERT INTO organization_settings(organization_id,assistant_name,instruction)
VALUES (:org,'Fixture','Answer from documents')"""), dict(org=org))
return org, user
def publish(engine, settings, root, user, evidence=EVIDENCE):
root = Path(root)
root.mkdir(parents=True, exist_ok=True)
source = root / "pump.md"
source.write_text(evidence, encoding="utf-8")
store = LocalFileStore(root / "originals")
candidates = LocalExtractionCandidates(root / "extractions", original_directory=store.directory)
document = import_document(SqlIntakeRepository(engine), store, settings, path=source,
administrator_id=user, request_id=uuid4(), title="Pump operating limits")["document"]
provider = DeterministicEmbeddings(settings)
worker = Worker(SqlWorkerRepository(engine, settings), store, candidates,
lambda _: PageBlockExtractor(), lambda _: (provider, None), settings)
worker.run_once(str(uuid4()))
with engine.connect() as conn:
assert conn.execute(text("SELECT status FROM documents WHERE id=:id"),
dict(id=document["id"])).scalar_one() == "ready"
return document["id"]
+42
View File
@@ -0,0 +1,42 @@
"""Input/CLI validation is deterministic and never accesses providers."""
import pytest
from pydantic import ValidationError
from app.modules.knowledge.service import SearchInput, KnowledgeError, selection_replace
from app import search, knowledge
@pytest.mark.parametrize("payload", [
{"query": " "}, {"query": ""}, {"query": "q" * 2001},
{"query": "q", "context": "c" * 2001}, {"query": "q", "organization_id": "forged"},
{"query": "q", "context": "bad\x00text"}, {"query": 123},
])
def test_input_rejects_untrusted_or_invalid_fields(payload):
with pytest.raises((ValidationError, ValueError)):
SearchInput(**payload)
def test_opt_in_required_before_any_initialization():
with pytest.raises(SystemExit) as error:
search.main(["--inspect", "--user-id", "10000000-0000-4000-8000-000000000001", "--query", "q"])
assert error.value.code == 2
def test_selection_clear_is_explicit_and_exclusive():
with pytest.raises(SystemExit):
knowledge.main(["selection", "replace", "--administrator-id",
"10000000-0000-4000-8000-000000000001", "--expected-revision", "1"])
with pytest.raises(SystemExit):
knowledge.main(["selection", "replace", "--administrator-id",
"10000000-0000-4000-8000-000000000001", "--expected-revision", "1",
"--clear", "--document-id", "10000000-0000-4000-8000-000000000002"])
@pytest.mark.parametrize("revision", [0, -1, True, "1"])
def test_invalid_revision_before_database(revision):
with pytest.raises(KnowledgeError):
selection_replace(None, None, revision, [])
def test_empty_optional_context_is_allowed():
assert SearchInput(query="q", context="").context == ""