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,187 @@
|
||||
"""Phase 2 provider-free lexical, admission, canonical and calibration checks."""
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import asdict
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app import calibrate_search
|
||||
from app.modules.knowledge import service as core
|
||||
from app.modules.knowledge.calibration import select_cutoff, load_cutoff
|
||||
from app.modules.knowledge.evidence import (
|
||||
CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY, admit_candidates, merge_candidates,
|
||||
)
|
||||
from app.modules.knowledge.lexical import exact_patterns, lexical_text
|
||||
from app.modules.knowledge.service import KnowledgeError, SearchService
|
||||
|
||||
|
||||
def row(number=1, *, distance=0.2, exact=False, text="Complete evidence", doc=None):
|
||||
return dict(chunk_id=UUID(int=number), document_id=doc or UUID(int=100), title="Title",
|
||||
text=text, location=dict(page=None, section=None),
|
||||
cosine_distance=distance, exact_match=exact)
|
||||
|
||||
|
||||
def test_lexical_normalization_leaves_embedding_policy_separate():
|
||||
assert lexical_text("Cafe\u0301\t كليد ۱۲٣\nABC-4") == "café کلید 123 abc-4"
|
||||
assert exact_patterns("25 bar 60 C 30 days") == ()
|
||||
assert exact_patterns("ماده ۲ و K-۱۲/٠٧ در ۱۴۰۳/۰۷/۰۱") == exact_patterns(
|
||||
"ماده 2 و k-12/07 در 1403/07/01")
|
||||
assert exact_patterns("ARTICLE\n 2 CAFÉ-12") == exact_patterns("article 2 cafe\u0301-12")
|
||||
assert exact_patterns("query", "تبصره ۳") == exact_patterns("تبصره 3")
|
||||
|
||||
|
||||
def test_identifiers_keep_separators_and_sql_metacharacters_are_not_authority():
|
||||
patterns = exact_patterns("IR-12 IR/12 IR.12 '); DROP TABLE users; --")
|
||||
assert len(patterns) == 3
|
||||
assert any("ir\\.12" in p for p in patterns)
|
||||
assert exact_patterns("IR-12") != exact_patterns("IR/12")
|
||||
assert all("DROP" not in p for p in patterns)
|
||||
|
||||
|
||||
def test_merge_deduplicates_and_orders_exact_distance_id():
|
||||
semantic = [row(2, distance=.1), row(1, distance=.1), row(3, distance=.8)]
|
||||
exact = [row(3, distance=.8), row(2, distance=.1)]
|
||||
results = merge_candidates(semantic, exact)
|
||||
assert [r["chunk_id"].int for r in results] == [2, 3, 1]
|
||||
assert [r["exact_match"] for r in results] == [True, True, False]
|
||||
|
||||
|
||||
def test_exact_match_cannot_bypass_admission_or_whole_chunk_budget():
|
||||
rows = [row(1, exact=True, distance=.8), row(2, text="x"*12001),
|
||||
row(3, text="x"*11980)] + [row(i, text="1234567890") for i in range(4, 10)]
|
||||
accepted = admit_candidates(rows, .2)
|
||||
assert [r["chunk_id"].int for r in accepted] == [3, 4, 5]
|
||||
assert sum(len(r["text"]) for r in accepted) == 12000
|
||||
assert len(admit_candidates([row(i) for i in range(1, 10)])) == 5
|
||||
|
||||
|
||||
def test_execution_reuses_refs_and_never_rebinds_across_searches():
|
||||
execution = SearchExecution(uuid4())
|
||||
first = execution.sources([row(1), row(2)])
|
||||
second = execution.sources([row(2), row(3)])
|
||||
assert [s["source_ref"] for s in first] == ["S1", "S2"]
|
||||
assert [s["source_ref"] for s in second] == ["S2", "S3"]
|
||||
assert first[0]["location"] == dict(page=None, section=None)
|
||||
assert set(first[0]) == {"source_ref", "document_id", "chunk_id", "title", "text", "location"}
|
||||
|
||||
|
||||
def service(settings, monkeypatch, candidates):
|
||||
cutoff = CalibratedCutoff(asdict(settings.embedding_profile), .2, "unit-only-measurement")
|
||||
result = SearchService(None, settings, None, cutoff=cutoff)
|
||||
def current(user):
|
||||
return dict(id=user, organization_id="fixture", role="user")
|
||||
def completed(execution, *args):
|
||||
execution.capture(current(execution.user_id), 1)
|
||||
return dict(knowledge_revision=7, candidates=candidates)
|
||||
monkeypatch.setattr(result, "candidates", completed)
|
||||
monkeypatch.setattr(core, "transaction", lambda *args: nullcontext(None))
|
||||
monkeypatch.setattr(core, "authority", lambda conn, user: (
|
||||
current(user), dict(knowledge_revision=7, access_epoch=1)))
|
||||
return result
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence"),
|
||||
([row(distance=.9, exact=True)], "no_evidence")])
|
||||
def test_canonical_outcomes(settings, monkeypatch, rows, status):
|
||||
result = service(settings, monkeypatch, rows).search(SearchExecution(uuid4()), "q")
|
||||
assert result["status"] == status and result["knowledge_revision"] == 7
|
||||
assert result["warnings"] == ([] if status == "ok" else ["insufficient_support"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", ["PROVIDER_UNAVAILABLE", "SEARCH_FAILED", "SEARCH_TIMEOUT",
|
||||
"PROFILE_MISMATCH", "CONTEXT_REVOKED"])
|
||||
def test_technical_failures_never_become_no_evidence(settings, monkeypatch, code):
|
||||
result = service(settings, monkeypatch, [])
|
||||
def fail(*_):
|
||||
raise KnowledgeError(code, "Safe error", retryable=True)
|
||||
monkeypatch.setattr(result, "candidates", fail)
|
||||
execution = SearchExecution(uuid4(), request_id="bounded-test-request")
|
||||
output = result.search(execution, "q")
|
||||
assert output == dict(status="error", sources=[], error=dict(code=code, message="Safe error",
|
||||
request_id="bounded-test-request", retryable=True))
|
||||
|
||||
|
||||
def test_missing_or_incompatible_calibration_is_error_before_work(settings, monkeypatch):
|
||||
result = SearchService(None, settings, None)
|
||||
assert result.search(SearchExecution(uuid4()), "q")["error"]["code"] == "CALIBRATION_REQUIRED"
|
||||
result.cutoff = CalibratedCutoff(dict(model="other"), .2, "measurement")
|
||||
assert result.search(SearchExecution(uuid4()), "q")["error"]["code"] == "PROFILE_MISMATCH"
|
||||
|
||||
|
||||
def test_invalid_model_inputs_are_canonical_errors(settings, monkeypatch):
|
||||
result = service(settings, monkeypatch, [])
|
||||
assert result.search(SearchExecution(uuid4()), " ")["error"]["code"] == "VALIDATION_ERROR"
|
||||
|
||||
|
||||
def calibration_data():
|
||||
cases, observations = [], {}
|
||||
for i in range(10):
|
||||
answerable = i < 6
|
||||
case = dict(id=str(i), answerable=answerable, query=f"Question {i}",
|
||||
original_sha256="hash", evidence_groups=[[f"fact-{i}", "unless closed"]] if answerable else [])
|
||||
cases.append(case)
|
||||
observations[str(i)] = dict(status="completed", retrieval_policy=RETRIEVAL_POLICY,
|
||||
candidates=[row(i+1, text=f"fact-{i} unless closed",
|
||||
distance=.1 if i < 3 else .2 if i < 6 else .3)])
|
||||
return cases, observations, {"hash": str(UUID(int=100))}
|
||||
|
||||
|
||||
def test_cutoff_maximizes_complete_support_zero_false_positives_and_stricter_tie(settings):
|
||||
cases, observations, bindings = calibration_data()
|
||||
# Adds a non-supporting candidate with a later distance; coverage ties,
|
||||
# so it must not relax the selected cutoff to .25.
|
||||
observations["0"]["candidates"].append(row(15, distance=.25, text="irrelevant"))
|
||||
report = select_cutoff(cases, observations, bindings, settings.embedding_profile)
|
||||
assert report["status"] == "calibrated"
|
||||
assert report["cutoff"]["distance"] == .2
|
||||
assert report["complete_support"] == 6 and report["unsupported_false_positives"] == 0
|
||||
report["calibration_id"] = "unit-measurement"
|
||||
assert load_cutoff(report).distance == .2
|
||||
|
||||
|
||||
def test_calibration_preserves_qualifiers_and_failures(settings):
|
||||
cases, observations, bindings = calibration_data()
|
||||
observations["0"]["candidates"][0]["text"] = "fact-0" # exception lost
|
||||
result = select_cutoff(cases, observations, bindings, settings.embedding_profile)
|
||||
assert result["complete_support"] == 5
|
||||
assert not result["cases"][0]["passed"]
|
||||
observations["9"] = dict(status="error", error=dict(code="SEARCH_TIMEOUT"))
|
||||
assert select_cutoff(cases, observations, bindings, settings.embedding_profile)["status"] == "technical_error"
|
||||
|
||||
|
||||
def test_no_working_cutoff_records_measured_failure(settings):
|
||||
cases, observations, bindings = calibration_data()
|
||||
for i in range(6, 10):
|
||||
observations[str(i)]["candidates"][0]["cosine_distance"] = 0
|
||||
report = select_cutoff(cases, observations, bindings, settings.embedding_profile)
|
||||
assert report["status"] == "measured_failure" and report["cutoff"] is None
|
||||
|
||||
|
||||
def test_calibration_requires_explicit_provider_authorization():
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
calibrate_search.main(["--user-id", str(uuid4()), "--bindings", "unused.json", "--output", "unused.json"])
|
||||
assert exc.value.code == 2
|
||||
|
||||
|
||||
def test_frozen_case_set_is_independent_and_complete():
|
||||
import hashlib
|
||||
import json
|
||||
from app.modules.knowledge.calibration import validate_cases
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
validate_cases(annotations["cases"])
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
assert hashlib.sha256(original.read_bytes()).hexdigest() == annotations["original_sha256"]
|
||||
for case in annotations["cases"]:
|
||||
for group in case["evidence_groups"]:
|
||||
assert all(p in original.read_text(encoding="utf-8") for p in group)
|
||||
|
||||
|
||||
def test_calibration_existing_output_fails_before_provider_initialization(tmp_path, monkeypatch):
|
||||
output = tmp_path / "retained-report.json"
|
||||
output.write_text("retained", encoding="utf-8")
|
||||
def unexpected():
|
||||
pytest.fail("Existing output must be rejected before configuration/provider work")
|
||||
monkeypatch.setattr(calibrate_search, "IngestionSettings", unexpected)
|
||||
result = calibrate_search.main(["--user-id", str(uuid4()), "--bindings", "unused.json",
|
||||
"--output", str(output), "--allow-provider-calls"])
|
||||
assert result == 1 and output.read_text(encoding="utf-8") == "retained"
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Literal frozen-annotation and confirmed-disconnect regressions."""
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from app import calibrate_search
|
||||
from app.modules.knowledge import service as core
|
||||
from app.modules.knowledge.calibration import complete_support, select_cutoff, load_cutoff
|
||||
from app.modules.knowledge.evidence import SearchExecution, CalibratedCutoff, RETRIEVAL_POLICY
|
||||
from tests.unit.test_search_phase2_repairs import calibration_environment, evidence
|
||||
|
||||
def disconnected(state=None, invalidated=True):
|
||||
original = psycopg.OperationalError("private postgresql://user:password@secret/db")
|
||||
if state is not None:
|
||||
class StatedError(psycopg.OperationalError):
|
||||
sqlstate = state
|
||||
original = StatedError("private SQL payload")
|
||||
return DBAPIError("SELECT private", {"password": "private"}, original,
|
||||
connection_invalidated=invalidated)
|
||||
|
||||
@pytest.fixture
|
||||
def frozen():
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
return annotations["cases"], original.read_text(encoding="utf-8"), uuid4()
|
||||
|
||||
def annotated_row(doc, text, distance=.1):
|
||||
return dict(evidence(), document_id=doc, text=text, cosine_distance=distance)
|
||||
|
||||
@pytest.mark.parametrize("index", range(6))
|
||||
def test_unchanged_frozen_annotations_pass_with_binding_and_whole_group(frozen, index):
|
||||
cases, original, doc = frozen
|
||||
case = cases[index]
|
||||
assert complete_support(case, [annotated_row(doc, original)], doc)
|
||||
assert not complete_support(case, [annotated_row(uuid4(), original)], doc)
|
||||
for phrase in case["evidence_groups"][0]:
|
||||
assert not complete_support(case, [annotated_row(doc, original.replace(phrase, ""))], doc)
|
||||
# Required facts cannot be assembled from separate chunks.
|
||||
rows = [annotated_row(doc, phrase) for phrase in case["evidence_groups"][0]]
|
||||
assert not complete_support(case, rows, doc)
|
||||
|
||||
@pytest.mark.parametrize("index,replacement", [
|
||||
(0, "۱۲۵ بار"), (1, "۱۴۰ لیتر در دقیقه"), (2, "۱۱۵ نیوتنمتر"),
|
||||
(3, "۱۴۰۳/۰۷/۰۱/۲"), (3, "۱۴۰۳/۰۷/۰۱۰"),
|
||||
(4, "۱۱۲ درصد"), (5, "PUMP-70"), (5, "XPUMP-7"),
|
||||
(5, "PUMP-7/2"), (5, "PUMP-7.2"), (5, "PUMP-7-A"),
|
||||
(5, "PUMP-7۲"), (5, "PUMP-7\u0301"), (5, "PUMP-7\u200cپسوند"),
|
||||
])
|
||||
def test_frozen_annotation_extensions_fail_and_do_not_inflate_coverage(settings, frozen, index, replacement):
|
||||
cases, original, doc = frozen
|
||||
phrase = cases[index]["evidence_groups"][0][0]
|
||||
corrupted = original.replace(phrase, replacement)
|
||||
assert phrase != replacement
|
||||
assert not complete_support(cases[index], [annotated_row(doc, corrupted)], doc)
|
||||
observations = {c["id"]: dict(status="completed", retrieval_policy=RETRIEVAL_POLICY,
|
||||
candidates=[annotated_row(doc, corrupted if i==index else original)] if c["answerable"] else [])
|
||||
for i,c in enumerate(cases)}
|
||||
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]: str(doc)},
|
||||
settings.embedding_profile)
|
||||
assert report["complete_support"] == 5
|
||||
assert report["unsupported_false_positives"] == 0
|
||||
assert report["cutoff"]["distance"] == .1
|
||||
assert max(t["complete_support"] for t in report["trials"]) == 5
|
||||
|
||||
def test_frozen_ten_days_numeric_prefix_fails(frozen):
|
||||
cases, original, doc = frozen
|
||||
assert not complete_support(cases[3], [annotated_row(doc, original.replace("۱۰ روز", "۱۱۰ روز"))], doc)
|
||||
|
||||
def test_all_corrupted_frozen_cases_cannot_produce_six_of_six(settings, frozen):
|
||||
cases, original, doc = frozen
|
||||
observations = {}
|
||||
for case in cases:
|
||||
if case["answerable"]:
|
||||
phrase = case["evidence_groups"][0][0]
|
||||
# Independent mutation, retaining every other condition/exception.
|
||||
corrupt = original.replace(phrase, ("X" if phrase=="PUMP-7" else "۱")+phrase)
|
||||
rows = [annotated_row(doc, corrupt)]
|
||||
else:
|
||||
rows = []
|
||||
observations[case["id"]] = dict(status="completed", retrieval_policy=RETRIEVAL_POLICY, candidates=rows)
|
||||
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]:str(doc)}, settings.embedding_profile)
|
||||
assert report["status"] == "measured_failure" and report["cutoff"] is None
|
||||
assert max(t["complete_support"] for t in report["trials"]) == 0
|
||||
assert all(t["unsupported_false_positives"] == 0 for t in report["trials"])
|
||||
|
||||
@pytest.mark.parametrize("state,invalidated,retryable", [
|
||||
(None, True, True), (None, False, False),
|
||||
("42P01", True, False), ("42501", True, False), ("42601", True, False),
|
||||
("XX000", True, False), ("08006", False, True),
|
||||
])
|
||||
def test_confirmed_disconnect_candidate_normalization_without_retries(settings, monkeypatch, state, invalidated, retryable):
|
||||
service = core.SearchService(None, settings, None)
|
||||
attempts = []
|
||||
def fail(*args):
|
||||
attempts.append(1)
|
||||
raise disconnected(state, invalidated)
|
||||
monkeypatch.setattr(service, "_retrieve", fail)
|
||||
with pytest.raises(core.KnowledgeError) as exc:
|
||||
service.candidates(SearchExecution(uuid4()), "query")
|
||||
assert exc.value.code == "SEARCH_FAILED" and exc.value.retryable is retryable
|
||||
assert str(exc.value) == "Knowledge database retrieval failed"
|
||||
assert len(attempts) == 1
|
||||
|
||||
def test_confirmed_disconnect_handoff_discards_sources_without_retries(settings, monkeypatch):
|
||||
from contextlib import contextmanager
|
||||
user = uuid4()
|
||||
current = dict(id=user, organization_id=uuid4(), role="user")
|
||||
execution = SearchExecution(user)
|
||||
execution.capture(current, 1)
|
||||
service = core.SearchService(None, settings, None,
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), .2, "test-only"))
|
||||
monkeypatch.setattr(service, "candidates", lambda *args: dict(
|
||||
knowledge_revision=2, access_epoch=1, candidates=[evidence()]))
|
||||
monkeypatch.setattr(core, "authority", lambda *args: (current, dict(access_epoch=1)))
|
||||
attempts = []
|
||||
@contextmanager
|
||||
def failed_commit(*args):
|
||||
attempts.append(1)
|
||||
yield None
|
||||
raise disconnected()
|
||||
monkeypatch.setattr(core, "transaction", failed_commit)
|
||||
result = service.search(execution, "query")
|
||||
assert result["sources"] == [] and result["error"]["retryable"]
|
||||
assert result["error"]["message"] == "Knowledge database retrieval failed"
|
||||
assert execution.sources([evidence(2)])[0]["source_ref"] == "S1"
|
||||
assert len(attempts) == 1
|
||||
|
||||
def test_confirmed_disconnect_final_calibration_retains_metrics(calibration_environment):
|
||||
env = calibration_environment
|
||||
env["failure"].append(disconnected())
|
||||
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 len(env["authority_calls"]) == 2
|
||||
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"] == 1
|
||||
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 ("password", "SELECT private", "secret/db"))
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
|
||||
def test_frozen_cutoff_preserves_six_support_zero_false_positives_and_stricter_ties(settings, frozen):
|
||||
cases, original, doc = frozen
|
||||
observations = {c["id"]: dict(status="completed", retrieval_policy=RETRIEVAL_POLICY,
|
||||
candidates=[annotated_row(doc, original, .1 if c["answerable"] else .3)]) for c in cases}
|
||||
observations[cases[0]["id"]]["candidates"].append(dict(annotated_row(doc, "irrelevant", .25), chunk_id=uuid4()))
|
||||
report = select_cutoff(cases, observations, {cases[0]["original_sha256"]:str(doc)}, settings.embedding_profile)
|
||||
assert report["complete_support"] == 6 and report["unsupported_false_positives"] == 0
|
||||
assert report["cutoff"]["distance"] == .1
|
||||
assert any(t["unsupported_false_positives"] == 4 for t in report["trials"])
|
||||
@@ -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
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Actual LangChain adapter acceptance; install .[search,test], never skip."""
|
||||
import asyncio
|
||||
from contextlib import nullcontext
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event, get_ident
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.modules.knowledge import langchain_tool as adapter
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from app.modules.knowledge.service import KnowledgeError
|
||||
from tests.unit.test_search_phase2 import service as canonical_service, row
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runner():
|
||||
value = adapter.SearchToolRunner(running=1, waiting=1, timeout=2)
|
||||
yield value
|
||||
value.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def authority(monkeypatch):
|
||||
state = dict(epoch=1, enabled=True)
|
||||
def persisted(conn, user):
|
||||
if not state["enabled"]:
|
||||
raise KnowledgeError("ACTOR_UNAVAILABLE", "Enabled actor required")
|
||||
return dict(id=user, organization_id="fixture", role="user"), dict(access_epoch=state["epoch"])
|
||||
monkeypatch.setattr(adapter, "transaction", lambda _: nullcontext(None))
|
||||
monkeypatch.setattr(adapter, "authority", persisted)
|
||||
return state
|
||||
|
||||
|
||||
def context(seconds=2):
|
||||
return adapter.ToolContext(SearchExecution(uuid4()), time.monotonic() + seconds)
|
||||
|
||||
|
||||
def tool(service, ctx, runner):
|
||||
return adapter.create_search_tool(service, ctx, runner)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{}, {"query": ""}, {"query": " "}, {"query": 1}, {"query": "x"*2001},
|
||||
{"query": "q", "context": "x"*2001}, {"query": "q", "context": 3},
|
||||
*[dict(query="q", **{key: "forged"}) for key in (
|
||||
"user_id", "organization_id", "document_id", "top_k", "deadline",
|
||||
"access_epoch", "source_ref", "request_id", "path", "unknown")],
|
||||
])
|
||||
def test_strict_model_arguments_rejected_before_work(payload, runner, authority):
|
||||
fake = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("No work allowed"))
|
||||
value = tool(fake, context(), runner)
|
||||
with pytest.raises(ValidationError):
|
||||
value.invoke(payload)
|
||||
async def check():
|
||||
with pytest.raises(ValidationError):
|
||||
await value.ainvoke(payload)
|
||||
asyncio.run(check())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
|
||||
def test_canonical_service_equivalence_and_stable_refs(settings, monkeypatch, runner, authority, rows, status):
|
||||
service = canonical_service(settings, monkeypatch, rows)
|
||||
ctx = context()
|
||||
value = tool(service, ctx, runner)
|
||||
expected = service.search(ctx.execution, "q", "hint")
|
||||
assert value.invoke({"query": "q", "context": "hint"}) == expected
|
||||
assert asyncio.run(value.ainvoke({"query": "q", "context": "hint"})) == expected
|
||||
assert expected["status"] == status
|
||||
schema = value.args_schema.model_json_schema()
|
||||
assert set(schema["properties"]) == {"query", "context"}
|
||||
assert schema["required"] == ["query"]
|
||||
assert schema["additionalProperties"] is False
|
||||
|
||||
|
||||
def test_cli_and_tool_use_same_candidates(settings, monkeypatch, runner, authority, capsys):
|
||||
from app import search
|
||||
from app import worker
|
||||
service = canonical_service(settings, monkeypatch, [row()])
|
||||
service.engine = SimpleNamespace(dispose=lambda: None)
|
||||
monkeypatch.setattr(search, "IngestionSettings", lambda: settings)
|
||||
monkeypatch.setattr(search, "create_database", lambda _: service.engine)
|
||||
monkeypatch.setattr(search, "SearchService", lambda *_: service)
|
||||
monkeypatch.setattr(worker, "factories", lambda _: (None, lambda _: (None, None)))
|
||||
ctx = context()
|
||||
assert search.main(["--inspect", "--user-id", str(ctx.execution.user_id),
|
||||
"--query", "q", "--context", "hint", "--allow-provider-calls"]) == 0
|
||||
diagnostic = json.loads(capsys.readouterr().out)
|
||||
canonical = tool(service, ctx, runner).invoke({"query": "q", "context": "hint"})
|
||||
source = canonical["sources"][0]
|
||||
candidate = diagnostic["candidates"][0]
|
||||
assert source["source_ref"] == "S1"
|
||||
assert all(source[key] == candidate[key] for key in ("document_id", "chunk_id", "text", "title", "location"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", ["PROVIDER_UNAVAILABLE", "PROFILE_MISMATCH", "SEARCH_TIMEOUT",
|
||||
"CALIBRATION_REQUIRED", "SEARCH_FAILED"])
|
||||
def test_canonical_errors_unchanged(code, runner, authority):
|
||||
ctx = context()
|
||||
expected = runner.error(ctx, code, "Safe failure", True)
|
||||
fake = SimpleNamespace(engine=None, search=lambda *_: expected)
|
||||
assert tool(fake, ctx, runner).invoke({"query": "q"}) == expected
|
||||
|
||||
|
||||
def test_epoch_and_disabled_actor_suppress_success(runner, authority):
|
||||
for disabled in (False, True):
|
||||
ctx = context()
|
||||
def search(*_):
|
||||
if disabled:
|
||||
authority["enabled"] = False
|
||||
else:
|
||||
authority["epoch"] += 1
|
||||
return dict(status="ok", sources=[{"text": "must not escape"}])
|
||||
result = tool(SimpleNamespace(engine=None, search=search), ctx, runner).invoke({"query": "q"})
|
||||
assert result["status"] == "error" and not result["sources"]
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED"
|
||||
|
||||
|
||||
async def until(predicate):
|
||||
deadline = time.monotonic() + 2
|
||||
while not predicate():
|
||||
assert time.monotonic() < deadline, "Bounded barrier did not arrive"
|
||||
await asyncio.sleep(.001)
|
||||
|
||||
|
||||
def test_async_responsive_saturation_and_cancelled_slot_retention(runner, authority):
|
||||
entered, release = Event(), Event()
|
||||
loop_thread = get_ident()
|
||||
calls = []
|
||||
def search(*args):
|
||||
calls.append(get_ident())
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return dict(status="no_evidence", sources=[], warnings=["insufficient_support"], knowledge_revision=1)
|
||||
fake = SimpleNamespace(engine=None, search=search)
|
||||
async def scenario():
|
||||
first = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
|
||||
second = None
|
||||
try:
|
||||
await until(entered.is_set)
|
||||
second = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
|
||||
await until(lambda: runner._admitted == 2)
|
||||
full = await tool(fake, context(), runner).ainvoke({"query": "q"})
|
||||
assert full["error"]["code"] == "SEARCH_SATURATED"
|
||||
first.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await first
|
||||
assert calls == [calls[0]] and calls[0] != loop_thread
|
||||
assert runner._active == 1
|
||||
second.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await second
|
||||
# Running cancelled work still owns capacity.
|
||||
assert runner._admitted == 1
|
||||
release.set()
|
||||
await until(lambda: runner._admitted == 0)
|
||||
finally:
|
||||
release.set()
|
||||
for task in (first, second):
|
||||
if task and not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*[t for t in (first, second) if t], return_exceptions=True)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_queued_timeout_and_external_cancellation_do_not_start_work(runner, authority):
|
||||
entered, release = Event(), Event()
|
||||
calls = []
|
||||
def search(*_):
|
||||
calls.append(1)
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return dict(status="no_evidence", sources=[])
|
||||
fake = SimpleNamespace(engine=None, search=search)
|
||||
async def scenario():
|
||||
first = asyncio.create_task(tool(fake, context(), runner).ainvoke({"query": "q"}))
|
||||
try:
|
||||
await until(entered.is_set)
|
||||
expired = await tool(fake, context(.04), runner).ainvoke({"query": "q"})
|
||||
assert expired["error"]["code"] == "SEARCH_TIMEOUT"
|
||||
assert len(calls) == 1
|
||||
ctx = context()
|
||||
waiting = asyncio.create_task(tool(fake, ctx, runner).ainvoke({"query": "q"}))
|
||||
await until(lambda: runner._admitted == 2)
|
||||
ctx.cancelled.set()
|
||||
assert (await waiting)["error"]["code"] == "SEARCH_CANCELLED"
|
||||
assert len(calls) == 1
|
||||
finally:
|
||||
release.set()
|
||||
await first
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_call", [False, True])
|
||||
def test_running_timeout_retains_slot_and_suppresses_late_result(async_call, runner, authority):
|
||||
entered, release = Event(), Event()
|
||||
def search(*_):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return dict(status="ok", sources=[{"text": "late"}])
|
||||
fake = SimpleNamespace(engine=None, search=search)
|
||||
ctx = context(.05)
|
||||
try:
|
||||
value = tool(fake, ctx, runner)
|
||||
result = asyncio.run(value.ainvoke({"query": "q"})) if async_call else value.invoke({"query": "q"})
|
||||
assert entered.is_set()
|
||||
assert result["error"]["code"] == "SEARCH_TIMEOUT" and not result["sources"]
|
||||
assert runner._active == 1
|
||||
saturated_ctx = context()
|
||||
saturated_ctx.cancelled.set()
|
||||
assert tool(fake, saturated_ctx, runner).invoke({"query": "q"})["error"]["code"] == "SEARCH_CANCELLED"
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs", [
|
||||
dict(running=0), dict(running=True), dict(waiting=-1), dict(waiting=1.5),
|
||||
dict(timeout=0), dict(timeout=float("nan")), dict(timeout=float("inf")), dict(timeout=True),
|
||||
])
|
||||
def test_invalid_limits(kwargs):
|
||||
with pytest.raises(ValueError):
|
||||
adapter.SearchToolRunner(**kwargs)
|
||||
|
||||
|
||||
def test_lazy_imports_without_framework():
|
||||
script = """
|
||||
import importlib.abc, sys
|
||||
class Reject(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, *args):
|
||||
if fullname.startswith(('langchain', 'langgraph')):
|
||||
raise ModuleNotFoundError('Framework deliberately absent')
|
||||
sys.meta_path.insert(0, Reject())
|
||||
import app.modules.knowledge.service
|
||||
import app.modules.knowledge.langchain_tool
|
||||
import app.ingest, app.worker, app.search
|
||||
assert not any(n.startswith(('langchain', 'langgraph')) for n in sys.modules)
|
||||
from app.modules.knowledge.langchain_tool import create_search_tool
|
||||
try:
|
||||
create_search_tool(None, None, None)
|
||||
except ModuleNotFoundError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Explicit construction must require declared extra')
|
||||
"""
|
||||
result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=15)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
def test_default_four_running_eight_waiting_limits(authority):
|
||||
runner = adapter.SearchToolRunner()
|
||||
release = Event()
|
||||
started = []
|
||||
def search(*_):
|
||||
started.append(get_ident())
|
||||
assert release.wait(4)
|
||||
return dict(status="no_evidence", sources=[])
|
||||
fake = SimpleNamespace(engine=None, search=search)
|
||||
async def scenario():
|
||||
tasks = [asyncio.create_task(tool(fake, context(3), runner).ainvoke({"query": "q"}))
|
||||
for _ in range(12)]
|
||||
try:
|
||||
await until(lambda: len(started) == 4 and runner._admitted == 12)
|
||||
result = await tool(fake, context(), runner).ainvoke({"query": "q"})
|
||||
assert result["error"]["code"] == "SEARCH_SATURATED"
|
||||
assert len(set(started)) == 4
|
||||
release.set()
|
||||
assert all(r["status"] == "no_evidence" for r in await asyncio.gather(*tasks))
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
try:
|
||||
asyncio.run(scenario())
|
||||
finally:
|
||||
runner.close()
|
||||
|
||||
|
||||
def test_external_running_cancellation_suppresses_result(runner, authority):
|
||||
entered, release = Event(), Event()
|
||||
def search(*_):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return dict(status="ok", sources=[{"text": "cancelled"}])
|
||||
fake = SimpleNamespace(engine=None, search=search)
|
||||
async def scenario():
|
||||
ctx = context()
|
||||
task = asyncio.create_task(tool(fake, ctx, runner).ainvoke({"query": "q"}))
|
||||
try:
|
||||
await until(entered.is_set)
|
||||
ctx.cancelled.set()
|
||||
result = await task
|
||||
assert result["error"]["code"] == "SEARCH_CANCELLED" and not result["sources"]
|
||||
assert runner._active == 1
|
||||
release.set()
|
||||
await until(lambda: runner._active == 0)
|
||||
assert result["sources"] == []
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Deterministic shutdown races through actual LangChain sync/async entrypoints."""
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.knowledge import langchain_tool as adapter
|
||||
from tests.unit.test_search_phase3 import authority, context, tool
|
||||
|
||||
|
||||
def invoke(value, asynchronous):
|
||||
return asyncio.run(value.ainvoke({"query": "q"})) if asynchronous else value.invoke({"query": "q"})
|
||||
|
||||
|
||||
def assert_cancelled(result):
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "SEARCH_CANCELLED"
|
||||
assert result["error"]["retryable"] is False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runner():
|
||||
value = adapter.SearchToolRunner(running=1, waiting=1, timeout=10)
|
||||
yield value
|
||||
value.close()
|
||||
|
||||
|
||||
def shutdown_barrier(monkeypatch, runner):
|
||||
"""Signal after close has set closure but before executor join."""
|
||||
entered = Event()
|
||||
original = runner._pool.shutdown
|
||||
def shutdown(*args, **kwargs):
|
||||
entered.set()
|
||||
return original(*args, **kwargs)
|
||||
monkeypatch.setattr(runner._pool, "shutdown", shutdown)
|
||||
return entered
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_shutdown_drains_queued_call_and_retains_running_slot(
|
||||
asynchronous, runner, authority, monkeypatch):
|
||||
started, release, queued = Event(), Event(), Event()
|
||||
calls, releases = [], []
|
||||
original_submit, original_release = runner._submit, runner._release
|
||||
def submit(*args):
|
||||
future = original_submit(*args)
|
||||
if future is None:
|
||||
queued.set()
|
||||
return future
|
||||
def record_release(*, active=False):
|
||||
releases.append(active)
|
||||
original_release(active=active)
|
||||
monkeypatch.setattr(runner, "_submit", submit)
|
||||
monkeypatch.setattr(runner, "_release", record_release)
|
||||
closing = shutdown_barrier(monkeypatch, runner)
|
||||
def search(*_):
|
||||
calls.append("running")
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return dict(status="ok", sources=[dict(text="late")])
|
||||
service = SimpleNamespace(engine=None, search=search)
|
||||
running_ctx, queued_ctx = context(10), context(10)
|
||||
with ThreadPoolExecutor(max_workers=4) as callers:
|
||||
first = callers.submit(invoke, tool(service, running_ctx, runner), asynchronous)
|
||||
second = close = repeated = None
|
||||
try:
|
||||
assert started.wait(2)
|
||||
second = callers.submit(invoke, tool(service, queued_ctx, runner), asynchronous)
|
||||
assert queued.wait(2)
|
||||
assert (runner._active, runner._admitted) == (1, 2)
|
||||
close = callers.submit(runner.close)
|
||||
assert closing.wait(2)
|
||||
assert_cancelled(second.result(timeout=2))
|
||||
assert_cancelled(first.result(timeout=2))
|
||||
# The running provider is still blocked, despite caller cancellation.
|
||||
assert (runner._active, runner._admitted) == (1, 1)
|
||||
assert not close.done()
|
||||
repeated = callers.submit(runner.close)
|
||||
assert_cancelled(invoke(tool(service, context(10), runner), asynchronous))
|
||||
assert calls == ["running"]
|
||||
release.set()
|
||||
close.result(timeout=2)
|
||||
repeated.result(timeout=2)
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
assert sorted(releases) == [False, True]
|
||||
assert calls == ["running"]
|
||||
finally:
|
||||
running_ctx.cancelled.set()
|
||||
queued_ctx.cancelled.set()
|
||||
release.set()
|
||||
for future in (first, second, close, repeated):
|
||||
if future:
|
||||
future.result(timeout=3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("expired", [False, True])
|
||||
def test_invocation_after_repeated_close_is_nonretryable_cancellation(
|
||||
asynchronous, expired, runner, authority):
|
||||
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
||||
runner.close()
|
||||
runner.close()
|
||||
result = invoke(tool(service, context(-1 if expired else 10), runner), asynchronous)
|
||||
assert_cancelled(result)
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_close_between_initial_stop_check_and_admission(
|
||||
asynchronous, runner, authority, monkeypatch):
|
||||
entered, proceed = Event(), Event()
|
||||
original = runner._admit
|
||||
def admit():
|
||||
entered.set()
|
||||
assert proceed.wait(5)
|
||||
return original()
|
||||
monkeypatch.setattr(runner, "_admit", admit)
|
||||
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
||||
ctx = context(10)
|
||||
with ThreadPoolExecutor(max_workers=1) as callers:
|
||||
call = callers.submit(invoke, tool(service, ctx, runner), asynchronous)
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
# No admission yet, so close must finish without waiting for this call.
|
||||
runner.close()
|
||||
proceed.set()
|
||||
assert_cancelled(call.result(timeout=2))
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
finally:
|
||||
ctx.cancelled.set()
|
||||
proceed.set()
|
||||
call.result(timeout=3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_submission_wins_lock_but_closed_worker_starts_no_io(
|
||||
asynchronous, runner, authority, monkeypatch):
|
||||
submitting, submit_allowed, worker_entered, work_allowed = (Event() for _ in range(4))
|
||||
attempted = Event()
|
||||
closing = shutdown_barrier(monkeypatch, runner)
|
||||
original_submit, original_work = runner._pool.submit, runner._work
|
||||
def submit(*args, **kwargs):
|
||||
submitting.set() # _submit owns the runner lock here.
|
||||
assert submit_allowed.wait(5)
|
||||
return original_submit(*args, **kwargs)
|
||||
def work(*args):
|
||||
worker_entered.set()
|
||||
assert work_allowed.wait(5)
|
||||
return original_work(*args)
|
||||
def close():
|
||||
attempted.set()
|
||||
runner.close()
|
||||
monkeypatch.setattr(runner._pool, "submit", submit)
|
||||
monkeypatch.setattr(runner, "_work", work)
|
||||
monkeypatch.setattr(adapter, "transaction", lambda *_: pytest.fail("Closed worker database work"))
|
||||
service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail("Closed provider work"))
|
||||
ctx = context(10)
|
||||
with ThreadPoolExecutor(max_workers=2) as callers:
|
||||
call = callers.submit(invoke, tool(service, ctx, runner), asynchronous)
|
||||
shutdown = None
|
||||
try:
|
||||
assert submitting.wait(2)
|
||||
shutdown = callers.submit(close)
|
||||
assert attempted.wait(2)
|
||||
submit_allowed.set()
|
||||
assert worker_entered.wait(2)
|
||||
assert closing.wait(2)
|
||||
assert_cancelled(call.result(timeout=2))
|
||||
assert (runner._active, runner._admitted) == (1, 1)
|
||||
assert not shutdown.done()
|
||||
work_allowed.set()
|
||||
shutdown.result(timeout=2)
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
finally:
|
||||
ctx.cancelled.set()
|
||||
submit_allowed.set()
|
||||
work_allowed.set()
|
||||
call.result(timeout=3)
|
||||
if shutdown:
|
||||
shutdown.result(timeout=3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("closure_first", [False, True])
|
||||
def test_close_racing_worker_completion_and_callback(
|
||||
closure_first, runner, authority, monkeypatch):
|
||||
computed, finish, callback_entered, release_callback = (Event() for _ in range(4))
|
||||
closing = shutdown_barrier(monkeypatch, runner)
|
||||
original_work, original_release = runner._work, runner._release
|
||||
releases = []
|
||||
def work(*args):
|
||||
result = original_work(*args)
|
||||
computed.set()
|
||||
assert finish.wait(5)
|
||||
return result
|
||||
def callback(*, active=False):
|
||||
if active:
|
||||
callback_entered.set()
|
||||
assert release_callback.wait(5)
|
||||
releases.append(active)
|
||||
original_release(active=active)
|
||||
monkeypatch.setattr(runner, "_work", work)
|
||||
monkeypatch.setattr(runner, "_release", callback)
|
||||
service = SimpleNamespace(engine=None, search=lambda *_: dict(status="ok", sources=[]))
|
||||
ctx = context(10)
|
||||
with ThreadPoolExecutor(max_workers=2) as callers:
|
||||
call = callers.submit(invoke, tool(service, ctx, runner), False)
|
||||
shutdown = None
|
||||
try:
|
||||
assert computed.wait(2)
|
||||
if closure_first:
|
||||
shutdown = callers.submit(runner.close)
|
||||
assert closing.wait(2)
|
||||
assert_cancelled(call.result(timeout=2))
|
||||
finish.set()
|
||||
else:
|
||||
finish.set()
|
||||
assert callback_entered.wait(2)
|
||||
assert call.result(timeout=2)["status"] == "ok"
|
||||
shutdown = callers.submit(runner.close)
|
||||
assert closing.wait(2)
|
||||
assert callback_entered.wait(2)
|
||||
assert (runner._active, runner._admitted) == (1, 1)
|
||||
assert not shutdown.done()
|
||||
release_callback.set()
|
||||
shutdown.result(timeout=2)
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
assert releases == [True]
|
||||
runner.close()
|
||||
finally:
|
||||
ctx.cancelled.set()
|
||||
finish.set()
|
||||
release_callback.set()
|
||||
call.result(timeout=3)
|
||||
if shutdown:
|
||||
shutdown.result(timeout=3)
|
||||
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
def test_close_waits_for_queued_release_after_worker_has_finished(
|
||||
asynchronous, runner, authority, monkeypatch):
|
||||
started, release_work, queued, releasing_queue = (Event() for _ in range(4))
|
||||
allow_queue_release, worker_released = Event(), Event()
|
||||
closing = shutdown_barrier(monkeypatch, runner)
|
||||
original_submit, original_release = runner._submit, runner._release
|
||||
releases = []
|
||||
def submit(*args):
|
||||
future = original_submit(*args)
|
||||
if future is None:
|
||||
queued.set()
|
||||
return future
|
||||
def release(*, active=False):
|
||||
if not active:
|
||||
releasing_queue.set()
|
||||
assert allow_queue_release.wait(5)
|
||||
releases.append(active)
|
||||
original_release(active=active)
|
||||
if active:
|
||||
worker_released.set()
|
||||
monkeypatch.setattr(runner, "_submit", submit)
|
||||
monkeypatch.setattr(runner, "_release", release)
|
||||
def search(*_):
|
||||
started.set()
|
||||
assert release_work.wait(5)
|
||||
return dict(status="ok", sources=[])
|
||||
service = SimpleNamespace(engine=None, search=search)
|
||||
running_ctx, queued_ctx = context(10), context(10)
|
||||
with ThreadPoolExecutor(max_workers=3) as callers:
|
||||
first = callers.submit(invoke, tool(service, running_ctx, runner), asynchronous)
|
||||
second = shutdown = None
|
||||
try:
|
||||
assert started.wait(2)
|
||||
second = callers.submit(invoke, tool(service, queued_ctx, runner), asynchronous)
|
||||
assert queued.wait(2)
|
||||
shutdown = callers.submit(runner.close)
|
||||
assert closing.wait(2)
|
||||
assert releasing_queue.wait(2)
|
||||
release_work.set()
|
||||
assert worker_released.wait(2)
|
||||
assert (runner._active, runner._admitted) == (0, 1)
|
||||
assert not shutdown.done()
|
||||
allow_queue_release.set()
|
||||
assert_cancelled(second.result(timeout=2))
|
||||
assert_cancelled(first.result(timeout=2))
|
||||
shutdown.result(timeout=2)
|
||||
assert (runner._active, runner._admitted) == (0, 0)
|
||||
assert sorted(releases) == [False, True]
|
||||
finally:
|
||||
running_ctx.cancelled.set()
|
||||
queued_ctx.cancelled.set()
|
||||
release_work.set()
|
||||
allow_queue_release.set()
|
||||
for future in (first, second, shutdown):
|
||||
if future:
|
||||
future.result(timeout=3)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Gate regressions; synthetic outcomes prove scoring only, not model quality."""
|
||||
import pytest
|
||||
from tests.phase4_gate import assess, gate, validate_manifest
|
||||
|
||||
def fixture():
|
||||
cases = [dict(id=str(i), answerable=i < 20, critical=i == 0) for i in range(26)]
|
||||
observations = {c["id"]: dict(status="ok" if c["answerable"] else "no_evidence",
|
||||
passed=True, sources_valid=True) for c in cases}
|
||||
return cases, observations
|
||||
|
||||
def test_exact_18_with_all_critical_and_unsupported_passes():
|
||||
cases, rows = fixture()
|
||||
rows["18"]["passed"] = rows["19"]["passed"] = False
|
||||
assert gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
rows["17"]["passed"] = False
|
||||
assert not gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
|
||||
@pytest.mark.parametrize("failed", ["0", "20"])
|
||||
def test_critical_or_unsupported_failure_vetoes_score(failed):
|
||||
cases, rows = fixture()
|
||||
rows[failed]["passed"] = False
|
||||
assert not gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
|
||||
def test_incomplete_or_unauthorized_run_cannot_pass():
|
||||
cases, rows = fixture()
|
||||
assert not gate(cases, rows, authorization_confirmed=False)["passed"]
|
||||
rows["4"]["sources_valid"] = False
|
||||
assert not gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
del rows["4"]
|
||||
assert not gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
assert not gate(cases[:-1], rows, authorization_confirmed=True)["passed"]
|
||||
|
||||
def test_error_never_counts_as_unsupported_success():
|
||||
case = dict(answerable=False)
|
||||
assert not assess(case, dict(status="error", sources=[]), {})
|
||||
assert not assess(case, dict(status="no_evidence", sources=[dict(text="x")]), {})
|
||||
|
||||
def test_qualifiers_must_share_the_bound_original_chunk():
|
||||
case = dict(answerable=True, original_sha256="hash",
|
||||
evidence_groups=[["75%", "more than", "25 units"]])
|
||||
source = dict(document_id="doc", text="more than 75% with 25 units")
|
||||
assert assess(case, dict(status="ok", sources=[source]), {"hash": "doc"})
|
||||
for changed in [dict(source, document_id="foreign"), dict(source, text="at least 75% with 25 units")]:
|
||||
assert not assess(case, dict(status="ok", sources=[changed]), {"hash": "doc"})
|
||||
|
||||
def test_draft_cannot_run():
|
||||
with pytest.raises(ValueError, match="Frozen"):
|
||||
validate_manifest(dict(status="incomplete_not_frozen", cases=[]))
|
||||
|
||||
|
||||
def test_gate_rejects_error_even_if_assessment_flag_is_incorrect():
|
||||
cases, rows = fixture()
|
||||
rows["20"]["status"] = "error"
|
||||
assert not gate(cases, rows, authorization_confirmed=True)["passed"]
|
||||
|
||||
def test_provider_budget_counts_failed_calls_and_prevents_extra_transport():
|
||||
from tests.evaluate_search import BudgetProvider
|
||||
class Provider:
|
||||
calls = 0
|
||||
def embed(self, texts):
|
||||
self.calls += 1
|
||||
raise RuntimeError("provider unavailable")
|
||||
provider = Provider()
|
||||
bounded = BudgetProvider(provider, 1)
|
||||
with pytest.raises(RuntimeError, match="unavailable"):
|
||||
bounded.embed(["query"])
|
||||
with pytest.raises(RuntimeError, match="budget"):
|
||||
bounded.embed(["query"])
|
||||
assert bounded.calls == provider.calls == 1
|
||||
|
||||
def test_incomplete_annotations_fail_before_database_or_provider(tmp_path, monkeypatch):
|
||||
import json
|
||||
import tests.evaluate_search as evaluator
|
||||
draft = tmp_path / "draft.json"
|
||||
draft.write_text(json.dumps(dict(status="incomplete_not_frozen", cases=[])), encoding="utf-8")
|
||||
def forbidden(*args, **kwargs):
|
||||
pytest.fail("Incomplete annotations reached database/provider setup")
|
||||
monkeypatch.setattr(evaluator, "create_database", forbidden)
|
||||
output = tmp_path / "new.jsonl"
|
||||
assert evaluator.main(["--cases", str(draft), "--bindings", str(tmp_path / "missing"),
|
||||
"--calibration", str(tmp_path / "missing"),
|
||||
"--user-id", "00000000-0000-0000-0000-000000000001",
|
||||
"--output", str(output), "--allow-provider-calls",
|
||||
"--provider-call-budget", "26"]) == 1
|
||||
assert not output.exists()
|
||||
@@ -0,0 +1,246 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user