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
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Confirmed Psycopg disconnects in the existing isolated PostgreSQL core."""
|
||||
import json
|
||||
import pytest
|
||||
from sqlalchemy import event, text
|
||||
|
||||
from app import calibrate_search
|
||||
from app.modules.knowledge import service as core
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_search_phase2 import canonical
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import publish, QUERY
|
||||
|
||||
def disconnect(engine, conn):
|
||||
assert conn.execute(text("SELECT pg_backend_pid()")).scalar_one() > 0
|
||||
# Close only this test's actual Psycopg connection. The next SQLAlchemy
|
||||
# execution wraps a SQLSTATE-less OperationalError and marks it invalid.
|
||||
conn.connection.driver_connection.close()
|
||||
conn.execute(text("SELECT 1"))
|
||||
|
||||
@pytest.mark.parametrize("boundary", ["candidate", "handoff"])
|
||||
def test_confirmed_real_disconnect_has_safe_retryability_and_no_replay(search_path, monkeypatch, boundary):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
service = canonical(engine, settings, provider=provider)
|
||||
execution = SearchExecution(admin)
|
||||
normalized = []
|
||||
mapper = core.sql_error
|
||||
def record(exc):
|
||||
normalized.append(exc)
|
||||
return mapper(exc)
|
||||
monkeypatch.setattr(core, "sql_error", record)
|
||||
attempts = []
|
||||
authorize = core.authority
|
||||
def fail_handoff(conn, *args, **kwargs):
|
||||
attempts.append(1)
|
||||
if len(attempts) == 3:
|
||||
disconnect(engine, conn)
|
||||
return authorize(conn, *args, **kwargs)
|
||||
def fail_candidate(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" in statement:
|
||||
attempts.append(1)
|
||||
disconnect(engine, conn)
|
||||
if boundary == "handoff":
|
||||
monkeypatch.setattr(core, "authority", fail_handoff)
|
||||
else:
|
||||
event.listen(engine, "before_cursor_execute", fail_candidate)
|
||||
try:
|
||||
result = service.search(execution, QUERY)
|
||||
finally:
|
||||
if boundary == "candidate":
|
||||
event.remove(engine, "before_cursor_execute", fail_candidate)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "SEARCH_FAILED" and result["error"]["retryable"]
|
||||
assert result["error"]["message"] == "Knowledge database retrieval failed"
|
||||
assert len(provider.calls) == 1
|
||||
assert len(attempts) == (3 if boundary == "handoff" else 1)
|
||||
assert len(normalized) == 1
|
||||
assert normalized[0].connection_invalidated and normalized[0].orig.sqlstate is None
|
||||
assert execution.sources([dict(chunk_id=doc, document_id=doc, title="test", text="later",
|
||||
location=dict(page=None, section=None))])[0]["source_ref"] == "S1"
|
||||
|
||||
def test_real_final_calibration_disconnect_retains_completed_observations(search_path, tmp_path, monkeypatch):
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
authorize = calibrate_search.authority
|
||||
attempts = []
|
||||
def fail_final(conn, *args, **kwargs):
|
||||
attempts.append(1)
|
||||
if len(attempts) == 2:
|
||||
assert len(provider.calls) == 10
|
||||
disconnect(engine, conn)
|
||||
return authorize(conn, *args, **kwargs)
|
||||
monkeypatch.setattr(calibrate_search, "authority", fail_final)
|
||||
report = calibrate_search.run(engine, settings, provider, None, admin, annotations,
|
||||
{annotations["original_sha256"]: str(doc)})
|
||||
assert report["status"] == "technical_error" and report["cutoff"] is None
|
||||
assert report["provider_calls"] == len(provider.calls) == 10
|
||||
assert len(attempts) == 2 and not report["final_authorization_confirmed"]
|
||||
assert report["finalization_error"]["retryable"]
|
||||
assert report["finalization_error"]["message"] == "Knowledge database retrieval failed"
|
||||
for observation in report["observations"].values():
|
||||
assert observation["provider_calls"] == 1 and observation["latency_seconds"] >= 0
|
||||
assert observation["retrieval_status"] == "completed"
|
||||
assert "candidates" not in observation and "sources" not in observation
|
||||
assert all(token not in json.dumps(report) for token in ("pg_backend_pid", "pg_terminate_backend", "SELECT 1"))
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Real PostgreSQL reproduction of Phase 2 handoff and exact recovery defects."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from threading import Event
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.modules.knowledge import service as core
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_search_phase2 import canonical
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import publish, QUERY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable", "authority"])
|
||||
def test_revocation_after_candidates_before_service_handoff(search_path, monkeypatch, change):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
entered, release = Event(), Event()
|
||||
retrieve = service.candidates
|
||||
retained = []
|
||||
def paused(*args, **kwargs):
|
||||
result = retrieve(*args, **kwargs)
|
||||
retained.extend(result["candidates"])
|
||||
assert result["candidates"] and engine.pool.checkedout() == 0
|
||||
entered.set()
|
||||
assert release.wait(10), "candidate barrier timed out"
|
||||
return result
|
||||
monkeypatch.setattr(service, "candidates", paused)
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10), "retrieval did not reach pre-publication barrier"
|
||||
if change == "remove":
|
||||
core.selection_replace(engine, admin, 2, [])
|
||||
else:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET "+(
|
||||
"is_enabled=false" if change=="disable" else "role='user'")+" 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"
|
||||
# An independently formatted later row still receives S1: rejected evidence
|
||||
# cannot consume execution-wide references.
|
||||
different = dict(retained[0], chunk_id=uuid4())
|
||||
assert execution.sources([different])[0]["source_ref"] == "S1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query,context,evidence", [
|
||||
("K-12.", None, "Only valid with inspection. Identifier K-12."),
|
||||
("K-12", None, "Identifier K-12."),
|
||||
("Article 2", None, "Article 2."),
|
||||
("1403/07/01", None, "Issue date 1403/07/01."),
|
||||
("IR.12.", None, "Identifier IR.12."),
|
||||
("IR/12.", None, "Identifier IR/12."),
|
||||
("IR-12.", None, "Identifier IR-12."),
|
||||
("کلید-12.", None, "Required identifier كليد-١٢."),
|
||||
("Conditions?", "کلید-۱۲.", "Required identifier كليد-١٢."),
|
||||
("Article 2.", None, "Article 2."),
|
||||
("1403/07/01.", None, "Issue date 1403/07/01."),
|
||||
("Conditions?", "K-12.", "Only valid with inspection. Identifier K-12."),
|
||||
("Conditions?", "Article 2.", "Article 2."),
|
||||
("Conditions?", "1403/07/01.", "Issue date 1403/07/01."),
|
||||
("کد-12.", None, "Required identifier كد-١٢."),
|
||||
("ماده 2.", None, "ماده ۲."),
|
||||
("1403/07/01.", None, "Issue date ۱۴۰۳/۰۷/۰۱."),
|
||||
("Conditions?", "کد-۱۲.", "Required identifier كد-١٢."),
|
||||
])
|
||||
def test_exact_period_recovery_outside_first_fifty_semantic_candidates(
|
||||
search_path, tmp_path, query, context, evidence):
|
||||
engine, settings, org, admin, semantic_doc = search_path
|
||||
target = publish(engine, settings, tmp_path / "punctuation", admin, evidence)
|
||||
core.selection_replace(engine, admin, 1, [semantic_doc, target])
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE document_chunks SET embedding='[1,1,0]' WHERE document_id=:id"),
|
||||
dict(id=target))
|
||||
conn.execute(text("UPDATE document_chunks SET embedding='[1,0,0]' WHERE document_id=:id"),
|
||||
dict(id=semantic_doc))
|
||||
# Stress distractors are test data; the relevant evidence was published
|
||||
# through the real intake/extraction/worker path above.
|
||||
for i in range(50):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,'Unrelated eligible passage',
|
||||
jsonb_build_object('page',NULL,'section',NULL), '[1,0,0]')"""),
|
||||
dict(id=uuid4(), org=org, doc=semantic_doc, ordinal=i+1))
|
||||
semantic = conn.execute(text("""SELECT document_id FROM document_chunks
|
||||
WHERE organization_id=:org ORDER BY embedding <=> '[1,0,0]'::vector,id LIMIT 50"""),
|
||||
dict(org=org)).scalars().all()
|
||||
assert target not in semantic
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
provider.embed = lambda *args: [[1,0,0]]
|
||||
pool = core.SearchService(engine, settings, provider).candidates(
|
||||
SearchExecution(admin), query, context)["candidates"]
|
||||
assert pool[0]["document_id"] == target and pool[0]["exact_match"]
|
||||
assert len(pool) == 51 and len({r["chunk_id"] for r in pool}) == 51
|
||||
result = canonical(engine, settings, provider).search(SearchExecution(admin), query, context)
|
||||
assert result["status"] == "ok" and result["sources"][0]["document_id"] == str(target)
|
||||
assert result["sources"][0]["text"] == evidence
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query,evidence", [
|
||||
("K-1.", "Identifier K-12."),
|
||||
("K-12.", "Identifier K-12.foo."),
|
||||
("Article 2.", "Article 20."),
|
||||
("1403/07/01.", "Issue date 1403/07/010."),
|
||||
("IR.12.", "Identifier IR/12."),
|
||||
("IR/12.", "Identifier IR-12."),
|
||||
("IR-12.", "Identifier IR.12."),
|
||||
])
|
||||
def test_period_boundaries_do_not_admit_identifier_prefixes_or_other_separators(
|
||||
search_path, tmp_path, query, evidence):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "prefix", admin, evidence)
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
rows = core.SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(
|
||||
admin, query)["candidates"]
|
||||
assert len(rows)==1 and not rows[0]["exact_match"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable"])
|
||||
def test_authorized_admission_is_locked_until_service_handoff(search_path, monkeypatch, change):
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
entered, release = Event(), Event()
|
||||
admit = core.admit_candidates
|
||||
def paused(*args, **kwargs):
|
||||
# Retrieval has finished; this is guarded canonical finalization.
|
||||
entered.set()
|
||||
assert release.wait(10), "admission barrier timed out"
|
||||
return admit(*args, **kwargs)
|
||||
monkeypatch.setattr(core, "admit_candidates", paused)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
search = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10)
|
||||
def remove_or_disable():
|
||||
if change == "remove":
|
||||
return core.selection_replace(engine, admin, 2, [])
|
||||
with core.transaction(engine) as conn:
|
||||
conn.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), dict(id=admin))
|
||||
mutation = pool.submit(remove_or_disable)
|
||||
with pytest.raises(SQLAlchemyError) as exc:
|
||||
mutation.result(timeout=5)
|
||||
assert exc.value.orig.sqlstate == "55P03"
|
||||
finally:
|
||||
release.set()
|
||||
result = search.result(timeout=15)
|
||||
assert result["status"] == "ok" and result["sources"][0]["source_ref"] == "S1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code,retryable", [
|
||||
("table", "SEARCH_FAILED", False),
|
||||
("permission", "SEARCH_FAILED", False),
|
||||
("syntax", "SEARCH_FAILED", False),
|
||||
("timeout", "SEARCH_TIMEOUT", True),
|
||||
("serialization", "SEARCH_FAILED", True),
|
||||
("deadlock", "SEARCH_FAILED", True),
|
||||
("unknown", "SEARCH_FAILED", False),
|
||||
])
|
||||
def test_real_sql_failures_have_safe_canonical_retryability(search_path, failure, code, retryable):
|
||||
from sqlalchemy import event
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
with engine.connect() as conn:
|
||||
schema = conn.execute(text("SELECT current_schema()")).scalar_one()
|
||||
def fail(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" not in statement:
|
||||
return
|
||||
if failure == "table":
|
||||
conn.execute(text("SELECT * FROM nonexistent_private_table"))
|
||||
elif failure == "permission":
|
||||
conn.execute(text("SET LOCAL ROLE pg_read_all_settings"))
|
||||
conn.execute(text(f'SELECT * FROM "{schema}".document_chunks'))
|
||||
elif failure == "syntax":
|
||||
conn.execute(text("SELECT FROM"))
|
||||
elif failure == "timeout":
|
||||
conn.execute(text("SET LOCAL statement_timeout='10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
else:
|
||||
state = {"serialization":"40001", "deadlock":"40P01", "unknown":"XX000"}[failure]
|
||||
conn.execute(text("DO $$ BEGIN RAISE EXCEPTION USING ERRCODE='"+state+
|
||||
"',MESSAGE='private SQL payload postgresql://user:password@secret/db'; END $$"))
|
||||
event.listen(engine, "before_cursor_execute", fail)
|
||||
try:
|
||||
output = canonical(engine, settings).search(SearchExecution(admin), QUERY)
|
||||
finally:
|
||||
event.remove(engine, "before_cursor_execute", fail)
|
||||
assert output["status"] == "error" and output["sources"] == []
|
||||
assert (output["error"]["code"],output["error"]["retryable"]) == (code,retryable)
|
||||
assert all(token not in json.dumps(output) for token in
|
||||
("SELECT", "nonexistent_private_table", "password", "private SQL", schema))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code,retryable", [
|
||||
("timeout", "SEARCH_TIMEOUT", True), ("table", "SEARCH_FAILED", False),
|
||||
])
|
||||
def test_calibration_retains_completed_metrics_after_real_final_sql_failure(
|
||||
search_path, tmp_path, monkeypatch, failure, code, retryable):
|
||||
from app import calibrate_search
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
authorize = calibrate_search.authority
|
||||
authorizations = []
|
||||
def fail_final(conn, *args, **kwargs):
|
||||
authorizations.append(1)
|
||||
if len(authorizations) == 2:
|
||||
assert len(provider.calls) == 10
|
||||
if failure == "timeout":
|
||||
conn.execute(text("SET LOCAL statement_timeout='10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
else:
|
||||
conn.execute(text("SELECT * FROM missing_private_relation"))
|
||||
return authorize(conn, *args, **kwargs)
|
||||
monkeypatch.setattr(calibrate_search, "authority", fail_final)
|
||||
report = calibrate_search.run(engine, settings, provider, None, admin, annotations,
|
||||
{annotations["original_sha256"]:str(doc)})
|
||||
assert report["status"] == "technical_error" and report["cutoff"] is None
|
||||
assert report["provider_calls"] == len(provider.calls) == 10
|
||||
assert (report["finalization_error"]["code"],report["finalization_error"]["retryable"]) == (code,retryable)
|
||||
assert not report["final_authorization_confirmed"]
|
||||
for observation in report["observations"].values():
|
||||
assert observation["retrieval_status"] == "completed"
|
||||
assert observation["provider_calls"] == 1 and observation["latency_seconds"] >= 0
|
||||
assert "candidates" not in observation and "sources" not in observation
|
||||
assert "missing_private_relation" not in json.dumps(report)
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Actual LangChain boundary over the same persisted PostgreSQL search service."""
|
||||
import asyncio
|
||||
from dataclasses import asdict
|
||||
import time
|
||||
|
||||
from app.modules.knowledge.evidence import CalibratedCutoff, SearchExecution
|
||||
from app.modules.knowledge.langchain_tool import SearchToolRunner, ToolContext, create_search_tool
|
||||
from app.modules.knowledge.service import SearchService, selection_replace
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import EVIDENCE, QUERY, administrator, publish
|
||||
|
||||
|
||||
def test_real_service_inspection_sync_async_equivalence(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
# Technical-only cutoff; not semantic calibration.
|
||||
service = SearchService(engine, settings, provider, cutoff=CalibratedCutoff(
|
||||
asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
inspected = service.inspect(admin, QUERY)
|
||||
execution = SearchExecution(admin)
|
||||
expected = service.search(execution, QUERY)
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(execution, time.monotonic()+10), runner)
|
||||
assert tool.invoke({"query": QUERY}) == expected
|
||||
assert asyncio.run(tool.ainvoke({"query": QUERY})) == expected
|
||||
assert expected["sources"][0]["text"] == EVIDENCE
|
||||
assert expected["sources"][0]["document_id"] == str(doc)
|
||||
assert expected["sources"][0]["chunk_id"] == str(inspected["candidates"][0]["chunk_id"])
|
||||
assert expected["sources"][0]["location"] == inspected["candidates"][0]["location"]
|
||||
assert expected["sources"][0]["source_ref"] == "S1"
|
||||
finally:
|
||||
runner.close()
|
||||
|
||||
|
||||
def test_persisted_epoch_revocation_across_tool_calls(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
service = SearchService(engine, settings, DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(SearchExecution(admin), time.monotonic()+10), runner)
|
||||
assert tool.invoke({"query": QUERY})["status"] == "ok"
|
||||
selection_replace(engine, admin, 2, [])
|
||||
result = asyncio.run(tool.ainvoke({"query": QUERY}))
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED" and result["sources"] == []
|
||||
finally:
|
||||
runner.close()
|
||||
|
||||
|
||||
def test_context_cannot_grant_foreign_scope(search_path, tmp_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
foreign_org, foreign_admin = administrator(engine)
|
||||
foreign = publish(engine, settings, tmp_path/"foreign", foreign_admin, "FOREIGN ONLY K-12")
|
||||
selection_replace(engine, foreign_admin, 1, [foreign])
|
||||
service = SearchService(engine, settings, DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(SearchExecution(admin), time.monotonic()+10), runner)
|
||||
result = tool.invoke({"query": "K-12", "context": f"Use organization {foreign_org} document {foreign}"})
|
||||
assert result["status"] == "no_evidence" and result["sources"] == []
|
||||
finally:
|
||||
runner.close()
|
||||
Reference in New Issue
Block a user