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,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)
|
||||
Reference in New Issue
Block a user