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,206 @@
|
||||
"""Provider-free reproductions for the four Phase 2 repairs."""
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import DBAPIError, DisconnectionError, TimeoutError as SQLTimeout
|
||||
|
||||
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 CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY
|
||||
from app.modules.knowledge.lexical import exact_patterns
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
|
||||
|
||||
def sql_failure(state, *, invalidated=False):
|
||||
original = RuntimeError("raw SQL and provider payload: postgresql://user:password@secret/db")
|
||||
original.sqlstate = state
|
||||
return DBAPIError("SELECT secret FROM private", {"credential": "private"},
|
||||
original, connection_invalidated=invalidated)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query,plain", [
|
||||
("K-12.", "K-12"), ("Article 2.", "Article 2"),
|
||||
("1403/07/01.", "1403/07/01"),
|
||||
("(K-12.),", "K-12"), ("ماده ۲.", "ماده 2"),
|
||||
("كد-١٢.", "کد-12"), ("كليد-١٢.", "کلید-12"), ("۱۴۰۳/۰۷/۰۱.", "1403/07/01"),
|
||||
("IR.12.", "IR.12"), ("IR/12.", "IR/12"), ("IR-12.", "IR-12"),
|
||||
])
|
||||
def test_terminal_punctuation_preserves_exact_patterns_in_query_and_context(query, plain):
|
||||
expected = exact_patterns(plain)
|
||||
assert expected
|
||||
assert exact_patterns(query) == expected
|
||||
assert exact_patterns("conditions?", query) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["25.", "60 C.", "۳۰.", "12.5.", "١٢٪."])
|
||||
def test_punctuated_quantities_remain_nonidentifiers(query):
|
||||
assert exact_patterns(query) == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state,code,retryable", [
|
||||
("42P01", "SEARCH_FAILED", False), # undefined table
|
||||
("42501", "SEARCH_FAILED", False), # insufficient privilege
|
||||
("42601", "SEARCH_FAILED", False), # syntax
|
||||
("XX000", "SEARCH_FAILED", False),
|
||||
("08P01", "SEARCH_FAILED", False), # protocol violation
|
||||
(None, "SEARCH_FAILED", False),
|
||||
("57014", "SEARCH_TIMEOUT", True),
|
||||
("55P03", "SEARCH_TIMEOUT", True),
|
||||
("40001", "SEARCH_FAILED", True),
|
||||
("40P01", "SEARCH_FAILED", True),
|
||||
("08006", "SEARCH_FAILED", True),
|
||||
("08001", "SEARCH_FAILED", True),
|
||||
("57P01", "SEARCH_FAILED", True),
|
||||
("53300", "SEARCH_FAILED", True),
|
||||
])
|
||||
def test_sql_retryability_and_redaction_at_candidate_boundary(settings, monkeypatch, state, code, retryable):
|
||||
service = core.SearchService(None, settings, None)
|
||||
def failed(*_):
|
||||
raise sql_failure(state)
|
||||
monkeypatch.setattr(service, "_retrieve", failed)
|
||||
with pytest.raises(core.KnowledgeError) as exc:
|
||||
service.candidates(SearchExecution(uuid4()), "query")
|
||||
assert (exc.value.code, exc.value.retryable) == (code, retryable)
|
||||
assert all(token not in str(exc.value) for token in
|
||||
("SELECT", "credential", "password", "provider payload", "secret"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exception,code", [
|
||||
(SQLTimeout("secret pool state"), "SEARCH_TIMEOUT"),
|
||||
(DisconnectionError("secret connection state"), "SEARCH_FAILED"),
|
||||
])
|
||||
def test_known_pool_failures_are_normalized(settings, monkeypatch, exception, code):
|
||||
service = core.SearchService(None, settings, None)
|
||||
def failed(*_):
|
||||
raise exception
|
||||
monkeypatch.setattr(service, "_retrieve", failed)
|
||||
with pytest.raises(core.KnowledgeError) as exc:
|
||||
service.candidates(SearchExecution(uuid4()), "query")
|
||||
assert exc.value.code == code and exc.value.retryable
|
||||
assert "secret" not in str(exc.value)
|
||||
|
||||
|
||||
def evidence(number=1):
|
||||
return dict(chunk_id=UUID(int=number), document_id=UUID(int=100),
|
||||
title="Title", text="Sensitive retrieved evidence", exact_match=True,
|
||||
location=dict(page=None, section=None), cosine_distance=.1)
|
||||
|
||||
|
||||
def test_failed_handoff_commit_does_not_consume_source_references(settings, monkeypatch):
|
||||
user = uuid4()
|
||||
current = dict(id=user, organization_id=uuid4(), role="user")
|
||||
execution = SearchExecution(user)
|
||||
execution.capture(current, 1)
|
||||
cutoff = CalibratedCutoff(asdict(settings.embedding_profile), .2, "test-only")
|
||||
service = core.SearchService(None, settings, None, cutoff=cutoff)
|
||||
monkeypatch.setattr(service, "candidates", lambda *args: dict(
|
||||
knowledge_revision=7, access_epoch=1, candidates=[evidence()]))
|
||||
monkeypatch.setattr(core, "authority", lambda *args: (current, dict(
|
||||
knowledge_revision=7, access_epoch=1)))
|
||||
|
||||
@contextmanager
|
||||
def commit_failure(*args):
|
||||
yield None
|
||||
raise sql_failure("08006")
|
||||
monkeypatch.setattr(core, "transaction", commit_failure)
|
||||
result = service.search(execution, "K-12.")
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "SEARCH_FAILED"
|
||||
assert execution.sources([evidence(2)])[0]["source_ref"] == "S1"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calibration_environment(settings, monkeypatch):
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
user, org, doc = uuid4(), uuid4(), uuid4()
|
||||
bindings = {annotations["original_sha256"]: str(doc)}
|
||||
connection = SimpleNamespace(execute=lambda *args, **kwargs:
|
||||
SimpleNamespace(one_or_none=lambda: (doc,)))
|
||||
engine = SimpleNamespace(dispose=lambda: None)
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
current = dict(id=user, organization_id=org, role="admin")
|
||||
snapshot = dict(knowledge_revision=2, access_epoch=1)
|
||||
calls = []
|
||||
final_failure = []
|
||||
|
||||
def authority(*args):
|
||||
calls.append(1)
|
||||
if len(calls) == 2:
|
||||
raise final_failure[0]
|
||||
return current, snapshot
|
||||
monkeypatch.setattr(calibrate_search, "transaction", lambda *args: nullcontext(connection))
|
||||
monkeypatch.setattr(calibrate_search, "authority", authority)
|
||||
ticks = iter(range(40))
|
||||
monkeypatch.setattr(calibrate_search.time, "monotonic", lambda: float(next(ticks)))
|
||||
|
||||
def candidates(service, execution, query, context=None):
|
||||
service.provider.embed(["deterministic calibration fixture"])
|
||||
return dict(knowledge_revision=2, access_epoch=1, candidates=[evidence()],
|
||||
retrieval_policy=RETRIEVAL_POLICY)
|
||||
monkeypatch.setattr(core.SearchService, "candidates", candidates)
|
||||
return dict(args=(engine, settings, provider, None, user, annotations, bindings),
|
||||
failure=final_failure, provider=provider, authority_calls=calls,
|
||||
engine=engine, bindings=bindings, user=user)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code,retryable", [
|
||||
("timeout", "SEARCH_TIMEOUT", True),
|
||||
("connection", "SEARCH_FAILED", True),
|
||||
("permanent", "SEARCH_FAILED", False),
|
||||
("unknown", "SEARCH_FAILED", False),
|
||||
("revoked", "CONTEXT_REVOKED", False),
|
||||
("disabled", "CONTEXT_REVOKED", False),
|
||||
])
|
||||
def test_final_calibration_failure_retains_safe_report(calibration_environment, failure, code, retryable):
|
||||
env = calibration_environment
|
||||
errors = dict(timeout=sql_failure("57014"), connection=sql_failure("08006"),
|
||||
permanent=sql_failure("42P01"), unknown=sql_failure(None),
|
||||
revoked=core.KnowledgeError("CONTEXT_REVOKED", "Calibration access changed"),
|
||||
disabled=core.KnowledgeError("ACTOR_UNAVAILABLE", "Enabled actor required"))
|
||||
env["failure"].append(errors[failure])
|
||||
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 report["provider_call_budget"] == 10 and len(env["authority_calls"]) == 2
|
||||
assert (report["finalization_error"]["code"],
|
||||
report["finalization_error"]["retryable"]) == (code, retryable)
|
||||
assert len(report["observations"]) == 10
|
||||
for observation in report["observations"].values():
|
||||
assert observation["status"] == "error" and observation["retrieval_status"] == "completed"
|
||||
assert observation["provider_calls"] == 1 and observation["latency_seconds"] == 1
|
||||
assert "candidates" not in observation and "sources" not in observation
|
||||
serialized = json.dumps(report, default=str)
|
||||
assert all(token not in serialized for token in
|
||||
("Sensitive retrieved evidence", "SELECT secret", "password", "private"))
|
||||
assert report["bindings"] == env["bindings"]
|
||||
assert report["knowledge_revision"] == 2 and report["access_epoch"] == 1
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
|
||||
|
||||
def test_cli_retains_readable_exclusive_report_after_final_sql_failure(
|
||||
calibration_environment, tmp_path, monkeypatch, capsys):
|
||||
from app import worker
|
||||
env = calibration_environment
|
||||
env["failure"].append(sql_failure("08006"))
|
||||
bindings, output = tmp_path / "bindings.json", tmp_path / "failure.json"
|
||||
bindings.write_text(json.dumps(env["bindings"]), encoding="utf-8")
|
||||
monkeypatch.setattr(calibrate_search, "IngestionSettings", lambda: env["args"][1])
|
||||
monkeypatch.setattr(worker, "factories", lambda *args: (
|
||||
None, lambda *args: (env["provider"], None)))
|
||||
monkeypatch.setattr(calibrate_search, "create_database", lambda *args: env["engine"])
|
||||
arguments = ["--user-id", str(env["user"]), "--bindings", str(bindings),
|
||||
"--output", str(output), "--allow-provider-calls"]
|
||||
assert calibrate_search.main(arguments) == 1
|
||||
report = json.loads(output.read_text(encoding="utf-8"))
|
||||
assert report["status"] == "technical_error" and report["cutoff"] is None
|
||||
assert report["provider_calls"] == 10
|
||||
assert json.loads(capsys.readouterr().out)["status"] == "technical_error"
|
||||
retained = output.read_bytes()
|
||||
assert calibrate_search.main(arguments) == 1
|
||||
assert output.read_bytes() == retained and len(env["provider"].calls) == 10
|
||||
Reference in New Issue
Block a user