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:
amirhosein mazaheri
2026-10-08 12:58:59 +03:30
parent 4d36f2ba35
commit fef381c41b
36 changed files with 6679 additions and 45 deletions
+157
View File
@@ -0,0 +1,157 @@
"""Literal frozen-annotation and confirmed-disconnect regressions."""
from dataclasses import asdict
import json
from uuid import uuid4
import psycopg
import pytest
from sqlalchemy.exc import DBAPIError
from app import calibrate_search
from app.modules.knowledge import service as core
from app.modules.knowledge.calibration import complete_support, select_cutoff, load_cutoff
from app.modules.knowledge.evidence import SearchExecution, CalibratedCutoff, RETRIEVAL_POLICY
from tests.unit.test_search_phase2_repairs import calibration_environment, evidence
def disconnected(state=None, invalidated=True):
original = psycopg.OperationalError("private postgresql://user:password@secret/db")
if state is not None:
class StatedError(psycopg.OperationalError):
sqlstate = state
original = StatedError("private SQL payload")
return DBAPIError("SELECT private", {"password": "private"}, original,
connection_invalidated=invalidated)
@pytest.fixture
def frozen():
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
return annotations["cases"], original.read_text(encoding="utf-8"), uuid4()
def annotated_row(doc, text, distance=.1):
return dict(evidence(), document_id=doc, text=text, cosine_distance=distance)
@pytest.mark.parametrize("index", range(6))
def test_unchanged_frozen_annotations_pass_with_binding_and_whole_group(frozen, index):
cases, original, doc = frozen
case = cases[index]
assert complete_support(case, [annotated_row(doc, original)], doc)
assert not complete_support(case, [annotated_row(uuid4(), original)], doc)
for phrase in case["evidence_groups"][0]:
assert not complete_support(case, [annotated_row(doc, original.replace(phrase, ""))], doc)
# Required facts cannot be assembled from separate chunks.
rows = [annotated_row(doc, phrase) for phrase in case["evidence_groups"][0]]
assert not complete_support(case, rows, doc)
@pytest.mark.parametrize("index,replacement", [
(0, "۱۲۵ بار"), (1, "۱۴۰ لیتر در دقیقه"), (2, "۱۱۵ نیوتن‌متر"),
(3, "۱۴۰۳/۰۷/۰۱/۲"), (3, "۱۴۰۳/۰۷/۰۱۰"),
(4, "۱۱۲ درصد"), (5, "PUMP-70"), (5, "XPUMP-7"),
(5, "PUMP-7/2"), (5, "PUMP-7.2"), (5, "PUMP-7-A"),
(5, "PUMP-7۲"), (5, "PUMP-7\u0301"), (5, "PUMP-7\u200cپسوند"),
])
def test_frozen_annotation_extensions_fail_and_do_not_inflate_coverage(settings, frozen, index, replacement):
cases, original, doc = frozen
phrase = cases[index]["evidence_groups"][0][0]
corrupted = original.replace(phrase, replacement)
assert phrase != replacement
assert not complete_support(cases[index], [annotated_row(doc, corrupted)], doc)
observations = {c["id"]: dict(status="completed", retrieval_policy=RETRIEVAL_POLICY,
candidates=[annotated_row(doc, corrupted if i==index else original)] if c["answerable"] else [])
for i,c in enumerate(cases)}
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]: str(doc)},
settings.embedding_profile)
assert report["complete_support"] == 5
assert report["unsupported_false_positives"] == 0
assert report["cutoff"]["distance"] == .1
assert max(t["complete_support"] for t in report["trials"]) == 5
def test_frozen_ten_days_numeric_prefix_fails(frozen):
cases, original, doc = frozen
assert not complete_support(cases[3], [annotated_row(doc, original.replace("۱۰ روز", "۱۱۰ روز"))], doc)
def test_all_corrupted_frozen_cases_cannot_produce_six_of_six(settings, frozen):
cases, original, doc = frozen
observations = {}
for case in cases:
if case["answerable"]:
phrase = case["evidence_groups"][0][0]
# Independent mutation, retaining every other condition/exception.
corrupt = original.replace(phrase, ("X" if phrase=="PUMP-7" else "۱")+phrase)
rows = [annotated_row(doc, corrupt)]
else:
rows = []
observations[case["id"]] = dict(status="completed", retrieval_policy=RETRIEVAL_POLICY, candidates=rows)
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]:str(doc)}, settings.embedding_profile)
assert report["status"] == "measured_failure" and report["cutoff"] is None
assert max(t["complete_support"] for t in report["trials"]) == 0
assert all(t["unsupported_false_positives"] == 0 for t in report["trials"])
@pytest.mark.parametrize("state,invalidated,retryable", [
(None, True, True), (None, False, False),
("42P01", True, False), ("42501", True, False), ("42601", True, False),
("XX000", True, False), ("08006", False, True),
])
def test_confirmed_disconnect_candidate_normalization_without_retries(settings, monkeypatch, state, invalidated, retryable):
service = core.SearchService(None, settings, None)
attempts = []
def fail(*args):
attempts.append(1)
raise disconnected(state, invalidated)
monkeypatch.setattr(service, "_retrieve", fail)
with pytest.raises(core.KnowledgeError) as exc:
service.candidates(SearchExecution(uuid4()), "query")
assert exc.value.code == "SEARCH_FAILED" and exc.value.retryable is retryable
assert str(exc.value) == "Knowledge database retrieval failed"
assert len(attempts) == 1
def test_confirmed_disconnect_handoff_discards_sources_without_retries(settings, monkeypatch):
from contextlib import contextmanager
user = uuid4()
current = dict(id=user, organization_id=uuid4(), role="user")
execution = SearchExecution(user)
execution.capture(current, 1)
service = core.SearchService(None, settings, None,
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), .2, "test-only"))
monkeypatch.setattr(service, "candidates", lambda *args: dict(
knowledge_revision=2, access_epoch=1, candidates=[evidence()]))
monkeypatch.setattr(core, "authority", lambda *args: (current, dict(access_epoch=1)))
attempts = []
@contextmanager
def failed_commit(*args):
attempts.append(1)
yield None
raise disconnected()
monkeypatch.setattr(core, "transaction", failed_commit)
result = service.search(execution, "query")
assert result["sources"] == [] and result["error"]["retryable"]
assert result["error"]["message"] == "Knowledge database retrieval failed"
assert execution.sources([evidence(2)])[0]["source_ref"] == "S1"
assert len(attempts) == 1
def test_confirmed_disconnect_final_calibration_retains_metrics(calibration_environment):
env = calibration_environment
env["failure"].append(disconnected())
report = calibrate_search.run(*env["args"])
assert report["status"] == "technical_error" and report["cutoff"] is None
assert report["provider_calls"] == len(env["provider"].calls) == 10
assert len(env["authority_calls"]) == 2
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"] == 1
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 ("password", "SELECT private", "secret/db"))
with pytest.raises(ValueError):
load_cutoff(report)
def test_frozen_cutoff_preserves_six_support_zero_false_positives_and_stricter_ties(settings, frozen):
cases, original, doc = frozen
observations = {c["id"]: dict(status="completed", retrieval_policy=RETRIEVAL_POLICY,
candidates=[annotated_row(doc, original, .1 if c["answerable"] else .3)]) for c in cases}
observations[cases[0]["id"]]["candidates"].append(dict(annotated_row(doc, "irrelevant", .25), chunk_id=uuid4()))
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]:str(doc)}, settings.embedding_profile)
assert report["complete_support"] == 6 and report["unsupported_false_positives"] == 0
assert report["cutoff"]["distance"] == .1
assert any(t["unsupported_false_positives"] == 4 for t in report["trials"])