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:
@@ -0,0 +1,320 @@
|
||||
"""Phase 2 real PostgreSQL retrieval, revocation and publication acceptance."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from threading import Event
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import event, text
|
||||
|
||||
from app.modules.knowledge.evidence import CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY
|
||||
from app.modules.knowledge.service import KnowledgeError, SearchService, selection_replace
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_phase6 import pipeline, upload, worker, snapshot
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import administrator, publish, EVIDENCE, QUERY
|
||||
|
||||
|
||||
def canonical(engine, settings, provider=None, *, distance=2):
|
||||
# This deliberately permissive cutoff exercises technical contracts ONLY.
|
||||
# It is never recorded as calibration or model-quality acceptance.
|
||||
return SearchService(engine, settings, provider or DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), distance, "test-only"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["کلید K-12", "ماده 2", "1403/07/01", "CAFÉ-12"])
|
||||
def test_normalized_exact_matching_preserves_evidence(search_path, tmp_path, query):
|
||||
engine, settings, org, admin, old = search_path
|
||||
evidence = "كليد K-١٢\nماده\t۲ در ۱۴۰۳/۰۷/۰۱: Cafe\u0301-12 فقط پس از بازرسی؛ باز نکنید مگر هنگام خاموشی."
|
||||
doc = publish(engine, settings, tmp_path / "lexical", admin, evidence)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
result = canonical(engine, settings).search(SearchExecution(admin), query)
|
||||
assert result["status"] == "ok"
|
||||
assert result["sources"][0]["text"] == evidence
|
||||
assert result["sources"][0]["document_id"] == str(doc)
|
||||
assert result["sources"][0]["location"] == dict(page=None, section="text/paragraph/1")
|
||||
rows = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, query)["candidates"]
|
||||
assert rows[0]["exact_match"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["K-1", "K-123", "K/12", "ماده 20", "1403/07/0", "25"])
|
||||
def test_boundary_and_quantity_queries_do_not_claim_exact_matches(search_path, tmp_path, query):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "boundaries", admin,
|
||||
"K-12 ماده 2 تاریخ 1403/07/01 مقدار 25 bar")
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
result = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, query)
|
||||
assert len(result["candidates"]) == 1
|
||||
assert not result["candidates"][0]["exact_match"]
|
||||
|
||||
|
||||
def test_sql_payload_is_data_and_embedding_preprocessing_unchanged(search_path, tmp_path):
|
||||
engine, settings, org, admin, old = search_path
|
||||
source = "K-12 فقط پس از بازرسی"
|
||||
doc = publish(engine, settings, tmp_path / "data", admin, source)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
result = SearchService(engine, settings, provider).inspect(admin, "K-۱۲'); DROP TABLE users; --", "hint")
|
||||
assert provider.calls == [("K-۱۲'); DROP TABLE users; --\n\nhint",)]
|
||||
assert result["candidates"][0]["exact_match"]
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(text("SELECT count(*) FROM users")).scalar_one() == 1
|
||||
|
||||
|
||||
def test_exact_first_deduplicated_bounded_merge_with_eligibility_before_limits(search_path, tmp_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
other_org, other_admin = administrator(engine)
|
||||
foreign = publish(engine, settings, tmp_path / "foreign", other_admin, "K-12 foreign")
|
||||
selection_replace(engine, other_admin, 1, [foreign])
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
with engine.begin() as conn:
|
||||
# Stress data only; the end-to-end cases below use production publication.
|
||||
conn.execute(text("DELETE FROM document_chunks WHERE document_id=:doc"), dict(doc=doc))
|
||||
for i in range(120):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,:evidence,CAST(:location AS jsonb),CAST(:vector AS vector))"""),
|
||||
dict(id=UUID(int=i+1), org=org, doc=doc, ordinal=i,
|
||||
evidence="K-12 exact" if i >= 60 else "semantic",
|
||||
location=json.dumps(dict(page=None, section=f"row/{i}")),
|
||||
vector="[1,1,0]" if i >= 60 else "[1,0,0]"))
|
||||
for i in range(60):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,'K-12 foreign','{}', '[1,0,0]')"""),
|
||||
dict(id=uuid4(), org=other_org, doc=foreign, ordinal=i+1))
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
provider.embed = lambda _: [[1,0,0]]
|
||||
core = SearchService(engine, settings, provider)
|
||||
pool = core.candidates(SearchExecution(admin), "K-12")["candidates"]
|
||||
assert len(pool) == 100
|
||||
assert sum(r["exact_match"] for r in pool) == 50
|
||||
assert len({r["chunk_id"] for r in pool}) == 100
|
||||
assert all(r["document_id"] == doc for r in pool)
|
||||
assert [r["chunk_id"].int for r in pool[:50]] == list(range(61,111))
|
||||
result = core.inspect(admin, "K-12")
|
||||
assert [r["chunk_id"].int for r in result["candidates"]] == list(range(61,66))
|
||||
# Exact matches cannot bypass a measured admission cutoff.
|
||||
output = canonical(engine, settings, provider, distance=.1).search(SearchExecution(admin), "K-12")
|
||||
assert len(output["sources"]) == 5
|
||||
assert all(s["text"] == "semantic" for s in output["sources"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ineligible", ["inactive", "deleted", "purged", "failed", "queued", "processing"])
|
||||
def test_every_branch_excludes_ineligible_exact_evidence(search_path, tmp_path, ineligible):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "excluded", admin, "K-12 unavailable")
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
assignment = {"inactive":"is_active=false", "deleted":"is_active=false,deleted_at=now()",
|
||||
"purged":"is_active=false,content_purged_at=now()", "failed":"is_active=false,status='failed'",
|
||||
"queued":"is_active=false,status='queued'", "processing":"is_active=false,status='processing'"}[ineligible]
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE documents SET "+assignment+" WHERE id=:id"), dict(id=doc))
|
||||
result = canonical(engine, settings).search(SearchExecution(admin), "K-12")
|
||||
assert result["status"] == "no_evidence" and result["sources"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable"])
|
||||
def test_bounded_provider_barrier_revocation_suppresses_results(search_path, change):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
entered, release = Event(), Event()
|
||||
def paused(_):
|
||||
assert engine.pool.checkedout() == 0
|
||||
entered.set()
|
||||
assert release.wait(10), "provider barrier timed out"
|
||||
service = canonical(engine, settings, DeterministicEmbeddings(settings, observe=paused))
|
||||
execution = SearchExecution(admin)
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10), "search did not reach provider barrier"
|
||||
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))
|
||||
finally:
|
||||
release.set()
|
||||
result = future.result(timeout=15)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED"
|
||||
|
||||
|
||||
def test_execution_epoch_and_source_refs_span_multiple_searches(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
first = service.search(execution, QUERY)
|
||||
second = service.search(execution, "What are the conditions?")
|
||||
assert first["sources"][0]["source_ref"] == second["sources"][0]["source_ref"] == "S1"
|
||||
selection_replace(engine, admin, 2, [])
|
||||
assert service.search(execution, QUERY)["error"]["code"] == "CONTEXT_REVOKED"
|
||||
|
||||
|
||||
def test_sql_failure_and_timeout_are_canonical_errors(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
service = canonical(engine, settings)
|
||||
def fail(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" in statement:
|
||||
# Real PostgreSQL statement cancellation SQLSTATE 57014.
|
||||
conn.execute(text("SET LOCAL statement_timeout = '10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
event.listen(engine, "before_cursor_execute", fail)
|
||||
try:
|
||||
result = service.search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["error"]["code"] == "SEARCH_TIMEOUT"
|
||||
finally:
|
||||
event.remove(engine, "before_cursor_execute", fail)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE document_chunks RENAME TO broken_chunks"))
|
||||
result = service.search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["error"]["code"] == "SEARCH_FAILED"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".md", ".docx"])
|
||||
def test_ingestion_publication_selection_search_retains_literal_complete_evidence(pipeline, suffix):
|
||||
p = pipeline
|
||||
# The Phase 6 fixture has independent original paragraphs, not a chunker oracle.
|
||||
with p["engine"].begin() as conn:
|
||||
conn.execute(text("""INSERT INTO organization_settings(organization_id,assistant_name,instruction)
|
||||
SELECT organization_id,'Fixture','Answer from documents' FROM users WHERE id=:id"""), dict(id=p["actor"]))
|
||||
document = upload(p, suffix)
|
||||
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("phase2-e2e")
|
||||
service = canonical(p["engine"], p["settings"])
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
result = service.search(SearchExecution(p["actor"]), "Article 1 Article 2 Article 3")
|
||||
assert result["status"] == "ok" and len(result["sources"]) == 3
|
||||
rows = {s["location"]["section"]:s for s in result["sources"]}
|
||||
locator = "docx/paragraph/" if suffix == ".docx" else "text/paragraph/"
|
||||
required = [
|
||||
("25 bar", "only when temperature is below 60 C", "Do not open the bypass", "except during shutdown"),
|
||||
("40 liters per minute", "unless the inlet is blocked", "every 30 days"),
|
||||
("15 Nm", "Do not restart when leakage is present", "except after inspection"),
|
||||
]
|
||||
for i, phrases in enumerate(required, 1):
|
||||
matching = [s for key,s in rows.items() if key.endswith(locator+str(i))]
|
||||
assert len(matching) == 1
|
||||
assert matching[0]["document_id"] == str(document["id"])
|
||||
assert matching[0]["location"]["page"] is None
|
||||
assert all(phrase in matching[0]["text"] for phrase in phrases)
|
||||
assert len({s["source_ref"] for s in result["sources"]}) == 3
|
||||
assert len({s["chunk_id"] for s in result["sources"]}) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("boundary", ["final_batch", "after_inserts", "after_completion_updates"])
|
||||
def test_partial_publication_never_becomes_searchable(pipeline, boundary):
|
||||
p = pipeline
|
||||
with p["engine"].begin() as conn:
|
||||
conn.execute(text("""INSERT INTO organization_settings(organization_id,assistant_name,instruction)
|
||||
SELECT organization_id,'Fixture','Answer from documents' FROM users WHERE id=:id"""), dict(id=p["actor"]))
|
||||
document = upload(p)
|
||||
entered, release = Event(), Event()
|
||||
p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=60, lease_seconds=120))
|
||||
p["repo"].settings = p["settings"]
|
||||
inserted = []
|
||||
def pause(conn, cursor, statement, parameters, context, executemany):
|
||||
if statement.lstrip().startswith("INSERT INTO document_chunks"):
|
||||
inserted.append(1)
|
||||
if boundary == "after_inserts" and len(inserted) == 3:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
if boundary == "after_completion_updates" and "UPDATE ingestion_jobs" in statement and "status='succeeded'" in statement:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
def embedding_barrier(batch):
|
||||
if boundary == "final_batch" and batch == 2:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
service = canonical(p["engine"], p["settings"])
|
||||
provider = DeterministicEmbeddings(p["settings"], observe=embedding_barrier,
|
||||
fail_at=2 if boundary=="final_batch" else None)
|
||||
event.listen(p["engine"], "after_cursor_execute", pause)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(worker(p, provider).run_once, "phase2-boundary")
|
||||
try:
|
||||
assert entered.wait(10)
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
partial = snapshot(p, document)
|
||||
assert partial["actual_count"] == partial["chunk_count"] == 0
|
||||
assert partial["status"] == partial["job_status"] == "processing"
|
||||
assert partial["ready_at"] is None and not partial["is_active"]
|
||||
# Do not block selection behind the intentionally paused publisher.
|
||||
finally:
|
||||
release.set()
|
||||
assert future.result(timeout=15)
|
||||
finally:
|
||||
release.set()
|
||||
event.remove(p["engine"], "after_cursor_execute", pause)
|
||||
if boundary == "final_batch":
|
||||
assert snapshot(p, document)["status"] == "failed"
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
with pytest.raises(KnowledgeError) as exc:
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
assert exc.value.code == "DOCUMENT_NOT_READY"
|
||||
else:
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "ok"
|
||||
|
||||
|
||||
def test_calibration_runner_uses_shared_core_frozen_bindings_and_bounded_calls(search_path, tmp_path):
|
||||
import hashlib
|
||||
from app.calibrate_search import CASES_PATH, run
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
with engine.connect() as conn:
|
||||
digest = conn.execute(text("SELECT file_sha256 FROM documents WHERE id=:id"), dict(id=doc)).scalar_one()
|
||||
assert digest == hashlib.sha256(original.read_bytes()).hexdigest() == annotations["original_sha256"]
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
report = run(engine, settings, provider, None, admin, annotations, {digest:str(doc)})
|
||||
assert len(provider.calls) == report["provider_calls"] == 10
|
||||
assert report["provider_call_budget"] == 10
|
||||
assert report["retrieval_policy"] == RETRIEVAL_POLICY
|
||||
assert report["profile"] == asdict(settings.embedding_profile)
|
||||
assert len(report["observations"]) == 10
|
||||
assert report["status"] in ("calibrated", "measured_failure")
|
||||
# Deterministic vectors do not establish semantic-quality acceptance.
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
with pytest.raises(KnowledgeError) as exc:
|
||||
run(engine, settings, provider, None, admin, annotations, {digest:str(uuid4())})
|
||||
assert exc.value.code == "CALIBRATION_BINDING_INVALID" and not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code", [("provider", "PROVIDER_UNAVAILABLE"),
|
||||
("timeout", "SEARCH_TIMEOUT"),
|
||||
("vector", "INVALID_VECTOR")])
|
||||
def test_actual_provider_boundary_errors_never_report_no_evidence(search_path, failure, code):
|
||||
from app.modules.documents.embeddings import EmbeddingProviderError
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
def broken(_):
|
||||
if failure == "provider":
|
||||
raise EmbeddingProviderError("secret raw response", retryable=False)
|
||||
if failure == "timeout":
|
||||
raise TimeoutError("secret raw timeout")
|
||||
return [[0,0,0]]
|
||||
provider.embed = broken
|
||||
result = canonical(engine, settings, provider).search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == code
|
||||
assert "secret" not in result["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("space", ["\u00a0", "\u202f", "\u2003", "\u3000"])
|
||||
def test_unicode_whitespace_is_equivalent_only_for_exact_comparison(search_path, tmp_path, space):
|
||||
engine, settings, org, admin, old = search_path
|
||||
evidence = "Article" + space + "2 faithful passage"
|
||||
doc = publish(engine, settings, tmp_path / "unicode-space", admin, evidence)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
rows = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(
|
||||
admin, "Article 2")["candidates"]
|
||||
assert rows[0]["exact_match"] and rows[0]["text"] == evidence
|
||||
Reference in New Issue
Block a user