Files
rag-technical-docs-assistant/tests/integration/test_search_phase2_repairs.py
amirhosein mazaheri fef381c41b 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.
2026-10-08 12:58:59 +03:30

245 lines
12 KiB
Python

"""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)