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.
247 lines
12 KiB
Python
247 lines
12 KiB
Python
"""Phase 4 review repairs; provider-free safety and original-artifact regressions."""
|
||
from copy import deepcopy
|
||
import hashlib
|
||
import json
|
||
from pathlib import Path
|
||
import sys
|
||
from types import SimpleNamespace
|
||
from uuid import UUID
|
||
import zipfile
|
||
import xml.etree.ElementTree as ET
|
||
|
||
import pytest
|
||
|
||
from tests.phase4_gate import (
|
||
EvaluationPreflightError, question_comparison_key, validate_annotation_text,
|
||
validate_manifest, validate_question_separation,
|
||
)
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
|
||
|
||
def calibration():
|
||
# Actual separately authored Phase 2 annotations; no provider or retrieval output.
|
||
return {"annotations": json.loads(
|
||
(ROOT / "docs/calibration/phase2-cases.json").read_text(encoding="utf-8"))}
|
||
|
||
|
||
def held_out():
|
||
# Synthetic complete shape for preflight tests. No persisted human approvals.
|
||
digest = "1" * 64
|
||
cases = [dict(id=f"A{i}", answerable=True, critical=True,
|
||
unseen=i >= 16, original="synthetic", original_sha256=digest,
|
||
query=f"سؤال مستقل شماره {i} چیست؟", evidence_groups=[["شرط لازم"]])
|
||
for i in range(20)]
|
||
cases += [dict(id=f"U{i}", answerable=False, critical=False, unseen=False,
|
||
query=f"سؤال بدون شواهد شماره {i} چیست؟", evidence_groups=[])
|
||
for i in range(6)]
|
||
return dict(status="frozen", cases=cases,
|
||
originals={"synthetic": dict(sha256=digest, path="unused", approval="approved")})
|
||
|
||
|
||
@pytest.mark.parametrize("corrupted", [
|
||
"???? ??? ????", "شرط ؟ چیست \ufffd", "شرط ?? درصد چیست؟",
|
||
"ک?دام شرط لازم است؟", "? ? ?",
|
||
])
|
||
def test_lossy_text_is_rejected(corrupted):
|
||
with pytest.raises(EvaluationPreflightError):
|
||
validate_annotation_text(corrupted, question=True)
|
||
|
||
|
||
@pytest.mark.parametrize("valid", [
|
||
"شرط ماده ۵ چیست؟", "شرط ماده ۵ چیست?", "کدام شرط؟ کدام استثنا؟",
|
||
"میزان ۱۰٪ در بند (۱) چیست؟", "What is K-1403/07?", "Café?",
|
||
])
|
||
def test_legitimate_punctuation_and_letters_survive(valid):
|
||
validate_annotation_text(valid, question=True)
|
||
|
||
|
||
@pytest.mark.parametrize("field", ["query", "evidence", "section"])
|
||
def test_frozen_annotations_reject_corruption_in_each_evidence_field(field):
|
||
manifest = held_out()
|
||
if field == "query":
|
||
manifest["cases"][0]["query"] = "???? ??????"
|
||
elif field == "evidence":
|
||
manifest["cases"][0]["evidence_groups"] = [["?? ????"]]
|
||
else:
|
||
manifest["cases"][0]["locator"] = {"section": "???? ?"}
|
||
with pytest.raises(EvaluationPreflightError, match="corruption"):
|
||
validate_manifest(manifest)
|
||
|
||
|
||
def test_literal_evidence_keeps_its_original_unicode():
|
||
manifest = held_out()
|
||
manifest["cases"][0]["evidence_groups"] = [["بيش از ۷۵ درصد", "كاهش", "Café"]]
|
||
before = deepcopy(manifest)
|
||
validate_manifest(manifest)
|
||
validate_question_separation(manifest["cases"], calibration())
|
||
assert manifest == before
|
||
|
||
|
||
def test_persisted_original_annotations_and_status_are_readable_and_aligned():
|
||
draft = json.loads((ROOT / "docs/calibration/phase4-cases.draft.json")
|
||
.read_bytes().decode("utf-8", errors="strict"))
|
||
status = json.loads((ROOT / "docs/calibration/phase4-status.json")
|
||
.read_bytes().decode("utf-8", errors="strict"))
|
||
assert len(draft["cases"]) == 22
|
||
assert sum(c["answerable"] for c in draft["cases"]) == 16
|
||
assert draft["status"] == "incomplete_not_frozen"
|
||
assert draft["annotation_repair"]["unresolved"] == []
|
||
for case in draft["cases"]:
|
||
validate_annotation_text(case["query"], question=True)
|
||
# Artifact-specific Persian corpus check catches replacement by ASCII even
|
||
# when a generic query validator would permit an English question.
|
||
assert any("\u0600" <= c <= "\u06ff" and c.isalpha() for c in case["query"])
|
||
assert case["outcome"] == "not_run"
|
||
for group in case["evidence_groups"]:
|
||
for phrase in group:
|
||
validate_annotation_text(phrase)
|
||
if case["answerable"]:
|
||
validate_annotation_text(case["locator"]["section"]) if "section" in case["locator"] else None
|
||
expected = draft["cases"] + draft["pending_answerable_slots"]
|
||
assert [o["expected"] for o in status["observations"]] == expected
|
||
assert all(o["provider_calls"] == 0 and o["status"] == "not_run"
|
||
for o in status["observations"])
|
||
assert status["provider_calls"] == 0 and status["quality_gate"] == "not_run"
|
||
assert draft["required_gate"] == status["required_gate"]
|
||
slots = draft["pending_answerable_slots"]
|
||
assert [s["id"] for s in slots] == ["A17", "A18", "A19", "A20"]
|
||
assert all(s["query"] is None and s["evidence_groups"] is None and s["unseen"] for s in slots)
|
||
for original in draft["originals"].values():
|
||
assert original["approval"] == "pending" and original["document_id"] is None
|
||
assert hashlib.sha256((ROOT / original["path"]).read_bytes()).hexdigest() == original["sha256"]
|
||
|
||
|
||
def test_recovered_critical_conditions_and_original_docx_literals():
|
||
draft = json.loads((ROOT / "docs/calibration/phase4-cases.draft.json").read_text(encoding="utf-8"))
|
||
cases = {c["id"]: c for c in draft["cases"]}
|
||
assert "بیش از هفتاد و پنج درصد" in cases["A06"]["evidence_groups"][0]
|
||
assert "حداقل هفتاد و پنج درصد" in cases["A07"]["evidence_groups"][0]
|
||
assert "از تاریخ ابلاغ این مصوبه" in cases["A03"]["evidence_groups"][0]
|
||
assert "مشمول این مشوق نمی گردند" in cases["A04"]["evidence_groups"][0]
|
||
assert cases["A13"]["evidence_groups"] == [
|
||
["اتصال نظام جبران خدمت و پاداشها به", "نتایج واقعی ارزیابی عملکرد"]]
|
||
original = draft["originals"]["docx"]
|
||
with zipfile.ZipFile(ROOT / original["path"]) as source:
|
||
body = ET.fromstring(source.read("word/document.xml"))
|
||
ns = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
|
||
paragraphs = ["".join(t.text or "" for t in p.findall(".//w:t", ns))
|
||
for p in body.findall(".//w:p", ns)]
|
||
# Compare independent repaired literals to paragraphs in the original, not an index.
|
||
for case_id, paragraph_index in (("A14", 2), ("A15", 10), ("A16", 6)):
|
||
assert all(phrase in paragraphs[paragraph_index]
|
||
for group in cases[case_id]["evidence_groups"] for phrase in group)
|
||
|
||
|
||
def test_exact_calibration_overlap_rejected():
|
||
report, manifest = calibration(), held_out()
|
||
manifest["cases"][0]["query"] = report["annotations"]["cases"][0]["query"]
|
||
with pytest.raises(EvaluationPreflightError) as error:
|
||
validate_question_separation(manifest["cases"], report)
|
||
assert error.value.code == "HELD_OUT_QUESTION_OVERLAP"
|
||
|
||
|
||
@pytest.mark.parametrize("pair", [
|
||
("شرط ماده ۱ چیست؟", "\u200f شرط\tماده\u00a0١\nچيست ? "),
|
||
("شرط كاهش چیست؟", "شرط کاهش چیست؟"),
|
||
("بهرهبرداری چیست؟", "بهره برداری چیست ؟"),
|
||
("Café چیست؟", "Cafe\u0301 چیست?"),
|
||
("PUMP-7 چیست؟", "PUMP-7 چیست?"),
|
||
])
|
||
def test_formatting_equivalent_overlap_rejected(pair):
|
||
report, manifest = calibration(), held_out()
|
||
report["annotations"]["cases"][0]["query"] = pair[0]
|
||
manifest["cases"][0]["query"] = pair[1]
|
||
before = deepcopy(manifest)
|
||
with pytest.raises(EvaluationPreflightError) as error:
|
||
validate_question_separation(manifest["cases"], report)
|
||
assert error.value.code == "HELD_OUT_QUESTION_OVERLAP"
|
||
assert manifest == before
|
||
|
||
|
||
def test_distinct_questions_can_share_originals_and_preserve_meaningful_differences():
|
||
report, manifest = calibration(), held_out()
|
||
original = report["annotations"]["cases"][0]
|
||
manifest["cases"][0].update(
|
||
original_sha256=original["original_sha256"], query="شرط ماده ۲ چیست؟")
|
||
report["annotations"]["cases"][0]["query"] = "شرط ماده ۱ چیست؟"
|
||
validate_question_separation(manifest["cases"], report)
|
||
assert question_comparison_key("باز کنید؟") != question_comparison_key("باز نکنید؟")
|
||
assert question_comparison_key("K-1403/07 چیست؟") != question_comparison_key("K-1403/08 چیست؟")
|
||
|
||
|
||
@pytest.mark.parametrize("malformation", [
|
||
"missing_annotations", "null_annotations", "missing_cases", "wrong_cases_type",
|
||
"empty_cases", "missing_query", "blank_query", "wrong_query_type",
|
||
"corrupted_query", "duplicate_question", "missing_evidence", "malformed_evidence",
|
||
"missing_hash", "wrong_label",
|
||
])
|
||
def test_missing_or_malformed_calibration_annotations_rejected(malformation):
|
||
report = calibration()
|
||
if malformation == "missing_annotations":
|
||
report = {}
|
||
elif malformation == "null_annotations":
|
||
report["annotations"] = None
|
||
elif malformation == "missing_cases":
|
||
report["annotations"] = {}
|
||
elif malformation == "wrong_cases_type":
|
||
report["annotations"]["cases"] = {}
|
||
elif malformation == "empty_cases":
|
||
report["annotations"]["cases"] = []
|
||
else:
|
||
cases = report["annotations"]["cases"]
|
||
if malformation == "missing_query":
|
||
del cases[0]["query"]
|
||
elif malformation == "blank_query":
|
||
cases[0]["query"] = " \t "
|
||
elif malformation == "wrong_query_type":
|
||
cases[0]["query"] = 5
|
||
elif malformation == "corrupted_query":
|
||
cases[0]["query"] = "???? ????"
|
||
elif malformation == "duplicate_question":
|
||
cases[1]["query"] = cases[0]["query"]
|
||
elif malformation == "missing_evidence":
|
||
del cases[0]["evidence_groups"]
|
||
elif malformation == "malformed_evidence":
|
||
cases[0]["evidence_groups"] = "not groups"
|
||
elif malformation == "missing_hash":
|
||
del cases[0]["original_sha256"]
|
||
elif malformation == "wrong_label":
|
||
cases[0]["answerable"] = 1
|
||
with pytest.raises(EvaluationPreflightError) as error:
|
||
validate_question_separation(held_out()["cases"], report)
|
||
assert error.value.code == "CALIBRATION_ANNOTATIONS_INVALID"
|
||
|
||
|
||
@pytest.mark.parametrize("problem", ["overlap", "equivalent", "missing", "malformed_json"])
|
||
def test_cli_independence_rejection_precedes_database_settings_and_provider(
|
||
tmp_path, monkeypatch, capsys, problem):
|
||
import tests.evaluate_search as evaluator
|
||
manifest, report = held_out(), calibration()
|
||
if problem in ("overlap", "equivalent"):
|
||
manifest["cases"][0]["query"] = report["annotations"]["cases"][0]["query"]
|
||
if problem == "equivalent":
|
||
manifest["cases"][0]["query"] = "\u200f \t " + manifest["cases"][0]["query"].replace(" ", "\u00a0") + "\n"
|
||
elif problem == "missing":
|
||
report = {"status": "calibrated", "calibration_id": "synthetic"}
|
||
cases_path, calibration_path = tmp_path / "cases.json", tmp_path / "report.json"
|
||
cases_path.write_text(json.dumps(manifest, ensure_ascii=False), encoding="utf-8")
|
||
calibration_path.write_text("{" if problem == "malformed_json" else
|
||
json.dumps(report, ensure_ascii=False), encoding="utf-8")
|
||
def forbidden(*args, **kwargs):
|
||
pytest.fail("Independence failure reached database/settings/provider setup")
|
||
monkeypatch.setattr(evaluator, "create_database", forbidden)
|
||
monkeypatch.setattr(evaluator, "IngestionSettings", forbidden)
|
||
monkeypatch.setitem(sys.modules, "app.worker", SimpleNamespace(factories=forbidden))
|
||
output = tmp_path / "new.jsonl"
|
||
assert evaluator.main(["--cases", str(cases_path), "--bindings", str(tmp_path / "missing"),
|
||
"--calibration", str(calibration_path),
|
||
"--user-id", str(UUID(int=1)), "--output", str(output),
|
||
"--allow-provider-calls", "--provider-call-budget", "26"]) == 1
|
||
diagnostic = json.loads(capsys.readouterr().err)["error"]
|
||
expected_code = "HELD_OUT_QUESTION_OVERLAP" if problem in ("overlap", "equivalent") else "CALIBRATION_ANNOTATIONS_INVALID"
|
||
assert diagnostic["code"] == expected_code
|
||
assert manifest["cases"][0]["query"] not in diagnostic["message"]
|
||
assert str(tmp_path) not in diagnostic["message"]
|
||
assert not output.exists()
|