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.
222 lines
11 KiB
Python
222 lines
11 KiB
Python
"""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"])
|