Files
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

229 lines
12 KiB
Python

"""Opt-in Persian retrieval evaluation. Run as a module, never ordinary pytest.
JSONL records are flushed after each case; each output path is exclusive.
This evaluates retrieved evidence only, not generated answers or Live.
"""
import argparse
from dataclasses import asdict
import hashlib
import json
from pathlib import Path
import sys
import time
from uuid import UUID
from sqlalchemy import text
from app.ingest import json_value
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY, SearchExecution
from app.modules.knowledge.service import SearchService, authority, selected, transaction
from tests.phase4_gate import (
EvaluationPreflightError, assess, gate, validate_manifest, validate_question_separation,
)
ROOT = Path(__file__).resolve().parents[1]
class BudgetProvider:
def __init__(self, provider, budget):
self.provider, self.budget, self.calls = provider, budget, 0
@property
def profile(self):
return self.provider.profile
@property
def request_policy(self):
return self.provider.request_policy
def embed(self, texts):
if self.calls >= self.budget:
raise RuntimeError("Evaluation call budget exhausted")
self.calls += 1
return self.provider.embed(texts)
def snapshot(engine, settings, user_id, bindings, manifest):
with transaction(engine) as conn:
current, config = authority(conn, user_id)
if {str(i) for i in selected(conn, current["organization_id"])} != set(bindings.values()):
raise ValueError("Selection must exactly equal the approved evaluation corpus")
for original in manifest["originals"].values():
digest = original["sha256"]
row = conn.execute(text("""
SELECT processing_profile, extraction_state FROM documents
WHERE id=:id AND organization_id=:org AND file_sha256=:digest
AND status='ready' AND is_active AND deleted_at IS NULL
AND content_purged_at IS NULL
"""), dict(id=UUID(bindings[digest]), org=current["organization_id"],
digest=digest)).mappings().one_or_none()
if row is None or row["processing_profile"]["embedding"] != asdict(settings.embedding_profile):
raise ValueError("Original binding is ineligible or incompatible")
if Path(original["path"]).suffix.lower() == ".docx":
inclusion = row["extraction_state"].get("factual_inclusion") or {}
if inclusion.get("decision") != "approve" or not inclusion.get("reviewer"):
raise ValueError("Persisted human factual DOCX approval required")
return dict(actor=current, knowledge_revision=config["knowledge_revision"],
access_epoch=config["access_epoch"])
def verify_sources(engine, sources, bindings):
if len(sources) > 5 or sum(len(s["text"]) for s in sources) > 12000:
return False
if len({s["chunk_id"] for s in sources}) != len(sources):
return False
with transaction(engine) as conn:
for source in sources:
if source["document_id"] not in set(bindings.values()):
return False
row = conn.execute(text("""
SELECT text, location FROM document_chunks
WHERE id=:chunk AND document_id=:document
"""), dict(chunk=UUID(source["chunk_id"]),
document=UUID(source["document_id"]))).mappings().one_or_none()
if row is None or row["text"] != source["text"]:
return False
if any(row["location"].get(k) != source["location"].get(k) for k in ("page", "section")):
return False
return True
def classification(result, passed, sources_valid):
if not sources_valid:
return dict(category="selection", responsible_phase="Fast-Track 1",
provisional=False)
if passed:
return None
code = (result.get("error") or {}).get("code", "")
if result["status"] == "error":
if code in ("CALIBRATION_REQUIRED", "EMBEDDING_PROFILE_MISMATCH", "PROFILE_MISMATCH"):
category = "compatibility"
elif code in ("CONTEXT_REVOKED", "ACTOR_UNAVAILABLE"):
category = "selection"
else:
category = "technical provider/database errors"
return dict(category=category, responsible_phase="Fast-Track 2", code=code,
provisional=False)
return dict(category="retrieval/ranking", responsible_phase="Fast-Track 2",
provisional=True,
required_triage="Inspect original -> retained extraction/review -> chunks -> "
"publication -> selection/profile -> ranking -> whole-chunk admission. "
"Reclassify to extraction/review, chunking, publication, selection, "
"compatibility or evidence budgeting only with stage evidence.")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cases", type=Path, required=True)
parser.add_argument("--bindings", type=Path, required=True)
parser.add_argument("--calibration", type=Path, required=True)
parser.add_argument("--user-id", type=UUID, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--allow-provider-calls", action="store_true", required=True)
parser.add_argument("--provider-call-budget", type=int, choices=range(1, 27), required=True)
args = parser.parse_args(argv)
engine = None
try:
if args.output.exists() or not args.output.parent.is_dir():
raise ValueError("New output path required")
raw = args.cases.read_bytes()
manifest = json.loads(raw)
validate_manifest(manifest)
try:
calibration_raw = args.calibration.read_bytes()
calibration = json.loads(calibration_raw)
except (OSError, ValueError):
raise EvaluationPreflightError(
"CALIBRATION_ANNOTATIONS_INVALID",
"Read a valid full Phase 2 calibration JSON report containing annotations.cases."
) from None
validate_question_separation(manifest["cases"], calibration)
bindings = json.loads(args.bindings.read_bytes())
expected = {o["sha256"] for o in manifest["originals"].values()}
if set(bindings) != expected or len(set(bindings.values())) != len(bindings):
raise ValueError("Exact one-to-one approved hash/document bindings required")
for original in manifest["originals"].values():
if hashlib.sha256((ROOT / original["path"]).read_bytes()).hexdigest() != original["sha256"]:
raise ValueError("Original changed after annotation")
UUID(bindings[original["sha256"]])
cutoff = load_cutoff(calibration)
if calibration.get("final_authorization_confirmed") is not True:
raise ValueError("Finalized measured calibration required")
settings = IngestionSettings()
if cutoff.profile != asdict(settings.embedding_profile) or cutoff.retrieval_policy != RETRIEVAL_POLICY:
raise ValueError("Pinned model/policy differs from frozen Phase 2 cutoff")
engine = create_database(settings.database_url.get_secret_value())
before = snapshot(engine, settings, args.user_id, bindings, manifest)
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
bounded = BudgetProvider(provider, args.provider_call_budget)
service = SearchService(engine, settings, bounded, counter, cutoff=cutoff)
execution = SearchExecution(args.user_id)
execution.capture(before["actor"], before["access_epoch"])
observations = {}
stopped = False
with args.output.open("x", encoding="utf-8") as output:
def record(value):
output.write(json.dumps(value, ensure_ascii=False, default=json_value,
allow_nan=False) + "\n")
output.flush()
record(dict(type="run", status="started", annotations=manifest, bindings=bindings,
annotations_sha256=hashlib.sha256(raw).hexdigest(),
calibration_sha256=hashlib.sha256(calibration_raw).hexdigest(),
calibration_id=cutoff.calibration_id, cutoff=cutoff.distance,
profile=asdict(settings.embedding_profile), retrieval_policy=RETRIEVAL_POLICY,
embedding_request=settings.processing_profile()["embedding_request"],
snapshot=before, provider_call_budget=args.provider_call_budget,
usage="unavailable", billing="unavailable",
assessment="independent literal evidence groups; no model judge"))
for case in manifest["cases"]:
if stopped or bounded.calls >= bounded.budget:
observation = dict(status="not_run", passed=False, sources_valid=False,
provider_calls=0, latency_seconds=None,
reason="Stopped after technical failure or bounded call budget")
else:
started, calls_before = time.monotonic(), bounded.calls
try:
result = service.search(execution, case["query"], case.get("context"))
valid = verify_sources(engine, result.get("sources", []), bindings)
passed = valid and assess(case, result, bindings)
observation = dict(status=result["status"], result=result, passed=passed,
sources_valid=valid,
failure=classification(result, passed, valid))
stopped = result["status"] == "error" or not valid
except Exception:
stopped = True
observation = dict(status="error", passed=False, sources_valid=False,
failure=dict(category="technical provider/database errors",
responsible_phase="Fast-Track 2",
code="EVALUATION_TECHNICAL_ERROR"))
observation.update(latency_seconds=time.monotonic()-started,
provider_calls=bounded.calls-calls_before)
observation.update(usage="unavailable", billing="unavailable")
observations[case["id"]] = observation
record(dict(type="case", id=case["id"], expected=case, **observation))
try:
confirmed = snapshot(engine, settings, args.user_id, bindings, manifest) == before
except Exception:
confirmed = False
summary = gate(manifest["cases"], observations, authorization_confirmed=confirmed)
record(dict(type="summary", **summary, provider_calls=bounded.calls,
usage="unavailable", billing="unavailable",
retrieval_quality="passed" if summary["passed"] else "failed",
generated_answers="not_evaluated", live="not_evaluated"))
print(json.dumps(dict(output=str(args.output), **summary)))
return 0 if summary["passed"] else 1
except EvaluationPreflightError as exc:
print(json.dumps(dict(error=dict(code=exc.code, message=str(exc)))), file=sys.stderr)
return 1
except Exception:
print("Evaluation not completed: verify frozen complete labels, approved originals, "
"bindings, human review, model/cutoff, selection, database and new output path.",
file=sys.stderr)
return 1
finally:
if engine is not None:
engine.dispose()
if __name__ == "__main__":
raise SystemExit(main())