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,149 @@
|
||||
"""Pure held-out gate; real execution lives outside pytest."""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.modules.knowledge.calibration import complete_support, validate_cases as validate_calibration_cases
|
||||
|
||||
class EvaluationPreflightError(ValueError):
|
||||
"""Safe operator-facing error; never includes question/evidence/credentials."""
|
||||
def __init__(self, code, message):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def validate_annotation_text(value, *, question=False):
|
||||
"""Reject lossy replacement patterns, while allowing single ? or Persian ؟."""
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise EvaluationPreflightError("ANNOTATION_TEXT_INVALID",
|
||||
"Supply nonempty original-derived annotation text.")
|
||||
if ("\ufffd" in value or re.search(r"\?(?:\s*\?)+", value)
|
||||
or re.search(r"(?<=\w)\?(?=\w)", value)):
|
||||
raise EvaluationPreflightError(
|
||||
"ANNOTATION_TEXT_CORRUPT",
|
||||
"Annotation contains replacement characters or question-mark corruption. "
|
||||
"Reconstruct it from the original, write UTF-8, and verify strict read-back.")
|
||||
if question and not any(unicodedata.category(c).startswith("L") for c in value):
|
||||
raise EvaluationPreflightError("ANNOTATION_TEXT_INVALID",
|
||||
"Supply a readable independently annotated question.")
|
||||
|
||||
|
||||
def question_comparison_key(question):
|
||||
"""Comparison only: NFKC/casefold, letter/digit variants, spacing and terminal punctuation.
|
||||
|
||||
ZWNJ/ZWSP are spaces; other Unicode format controls are removed.
|
||||
Preserve internal separators, words, numbers and negation; no fuzzy matching.
|
||||
Never use this key for evidence literals or retrieval preprocessing.
|
||||
"""
|
||||
validate_annotation_text(question, question=True)
|
||||
value = unicodedata.normalize("NFKC", question).casefold()
|
||||
value = value.translate(str.maketrans(
|
||||
"\u0643\u064a\u0649\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669",
|
||||
"\u06a9\u06cc\u06cc01234567890123456789"))
|
||||
value = "".join(" " if c in ("\u200b", "\u200c") else
|
||||
"" if unicodedata.category(c) == "Cf" else c for c in value)
|
||||
return " ".join(value.split()).rstrip(".!?\u061f").rstrip()
|
||||
|
||||
|
||||
def validate_question_separation(held_out_cases, calibration_report):
|
||||
"""Fail closed on missing/malformed full Phase 2 annotations; compare queries only."""
|
||||
invalid = EvaluationPreflightError(
|
||||
"CALIBRATION_ANNOTATIONS_INVALID",
|
||||
"Independence cannot be verified. Supply the full Phase 2 calibration report "
|
||||
"with annotations.cases: six answerable and four unsupported original-bound cases.")
|
||||
try:
|
||||
annotations = calibration_report["annotations"]
|
||||
cases = annotations["cases"]
|
||||
if (not isinstance(annotations, dict) or not isinstance(cases, list)
|
||||
or any(not isinstance(c, dict)
|
||||
or not isinstance(c.get("id"), str) or not c["id"].strip()
|
||||
or type(c.get("answerable")) is not bool
|
||||
or not isinstance(c.get("query"), str)
|
||||
or not isinstance(c.get("original_sha256"), str)
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", c["original_sha256"])
|
||||
or not isinstance(c.get("evidence_groups"), list)
|
||||
or any(not isinstance(g, list)
|
||||
or any(not isinstance(p, str) for p in g)
|
||||
for g in c["evidence_groups"]) for c in cases)):
|
||||
raise invalid
|
||||
validate_calibration_cases(cases)
|
||||
for case in cases:
|
||||
validate_annotation_text(case["query"], question=True)
|
||||
for group in case["evidence_groups"]:
|
||||
for phrase in group:
|
||||
validate_annotation_text(phrase)
|
||||
keys = {question_comparison_key(c["query"]) for c in cases}
|
||||
if len(keys) != 10:
|
||||
raise invalid
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise invalid from None
|
||||
if any(question_comparison_key(c["query"]) in keys for c in held_out_cases):
|
||||
raise EvaluationPreflightError(
|
||||
"HELD_OUT_QUESTION_OVERLAP",
|
||||
"Held-out questions overlap Phase 2 calibration after comparison normalization. "
|
||||
"Annotate distinct held-out questions from originals before freezing; "
|
||||
"shared source documents are permitted.")
|
||||
|
||||
|
||||
def validate_manifest(manifest):
|
||||
cases = manifest["cases"]
|
||||
if (manifest.get("status") != "frozen" or len(cases) != 26
|
||||
or len({c["id"] for c in cases}) != 26
|
||||
or sum(c["answerable"] is True for c in cases) != 20
|
||||
or sum(c["answerable"] is False for c in cases) != 6
|
||||
or sum(c["answerable"] is True and c.get("unseen") is True for c in cases) < 4):
|
||||
raise ValueError("Frozen 20 answerable / 6 unsupported with four unseen cases required")
|
||||
for case in cases:
|
||||
validate_annotation_text(case["query"], question=True)
|
||||
if case.get("annotation_status") == "unresolved":
|
||||
raise EvaluationPreflightError("ANNOTATION_UNRESOLVED",
|
||||
"Reconstruct unresolved evidence from originals before freezing.")
|
||||
if (not isinstance(case["query"], str) or not case["query"].strip()
|
||||
or type(case["critical"]) is not bool
|
||||
or bool(case["evidence_groups"]) != case["answerable"]
|
||||
or any(not g or any(not isinstance(p, str) or not p.strip() for p in g)
|
||||
for g in case["evidence_groups"])):
|
||||
raise ValueError("Complete independent evidence groups and critical labels required")
|
||||
for group in case["evidence_groups"]:
|
||||
for phrase in group:
|
||||
validate_annotation_text(phrase)
|
||||
if case["answerable"]:
|
||||
section = case.get("locator", {}).get("section")
|
||||
if section is not None:
|
||||
validate_annotation_text(section)
|
||||
original = manifest["originals"][case["original"]]
|
||||
if case["original_sha256"] != original["sha256"]:
|
||||
raise ValueError("Annotation original identity differs")
|
||||
if any(o.get("approval") != "approved" for o in manifest["originals"].values()):
|
||||
raise ValueError("Explicit original approval required")
|
||||
|
||||
def assess(case, result, bindings):
|
||||
status = result.get("status")
|
||||
sources = result.get("sources", [])
|
||||
if not case["answerable"]:
|
||||
return status == "no_evidence" and sources == []
|
||||
return (status == "ok" and 1 <= len(sources) <= 5
|
||||
and sum(len(s["text"]) for s in sources) <= 12000
|
||||
and complete_support(case, sources, bindings[case["original_sha256"]]))
|
||||
|
||||
def gate(cases, observations, *, authorization_confirmed):
|
||||
ids = {c["id"] for c in cases}
|
||||
valid_counts = (len(cases) == len(ids) == 26
|
||||
and sum(c["answerable"] is True for c in cases) == 20
|
||||
and sum(c["answerable"] is False for c in cases) == 6)
|
||||
executed = set(observations) == ids and all(
|
||||
observations[c["id"]].get("status") in ("ok", "no_evidence", "error") for c in cases)
|
||||
def passed_case(case):
|
||||
observation = observations.get(case["id"], {})
|
||||
expected_status = "ok" if case["answerable"] else "no_evidence"
|
||||
return observation.get("passed") is True and observation.get("status") == expected_status
|
||||
answerable = sum(passed_case(c) for c in cases if c["answerable"])
|
||||
critical = all(passed_case(c) for c in cases if c["critical"])
|
||||
unsupported = sum(passed_case(c) for c in cases if not c["answerable"])
|
||||
sources_valid = all(o.get("sources_valid") is True for o in observations.values())
|
||||
passed = (valid_counts and executed and authorization_confirmed and sources_valid
|
||||
and answerable >= 18 and critical and unsupported == 6)
|
||||
return dict(passed=passed, answerable_passed=answerable, answerable_required=20,
|
||||
answerable_minimum=18, all_critical=critical,
|
||||
unsupported_passed=unsupported, unsupported_required=6,
|
||||
all_cases_executed=executed, sources_valid=sources_valid,
|
||||
final_authorization_confirmed=authorization_confirmed)
|
||||
Reference in New Issue
Block a user