Enable replay-safe document deletion and public deployment model identifiers with the forward voice-model schema revision. Add GapGPT dialogue and ElevenLabs speech routing, strict extractive grounding, ten-source retrieval and regression coverage. Validation: 199 targeted provider-free tests passed. The full provider-free run stalled and was interrupted; PostgreSQL acceptance was not run because TEST_DATABASE_URL is unset.
188 lines
9.3 KiB
Python
188 lines
9.3 KiB
Python
"""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, 14)])) == 10
|
|
|
|
|
|
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"
|