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,228 @@
|
||||
"""Opt-in Persian retrieval evaluation. Run as a module, never ordinary pytest.
|
||||
|
||||
JSONL records are flushed after each case; each output path is exclusive.
|
||||
This evaluates retrieved evidence only, not generated answers or Live.
|
||||
"""
|
||||
import argparse
|
||||
from dataclasses import asdict
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.ingest import json_value
|
||||
from app.infrastructure.database import create_database
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.evidence import RETRIEVAL_POLICY, SearchExecution
|
||||
from app.modules.knowledge.service import SearchService, authority, selected, transaction
|
||||
from tests.phase4_gate import (
|
||||
EvaluationPreflightError, assess, gate, validate_manifest, validate_question_separation,
|
||||
)
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
class BudgetProvider:
|
||||
def __init__(self, provider, budget):
|
||||
self.provider, self.budget, self.calls = provider, budget, 0
|
||||
|
||||
@property
|
||||
def profile(self):
|
||||
return self.provider.profile
|
||||
|
||||
@property
|
||||
def request_policy(self):
|
||||
return self.provider.request_policy
|
||||
|
||||
def embed(self, texts):
|
||||
if self.calls >= self.budget:
|
||||
raise RuntimeError("Evaluation call budget exhausted")
|
||||
self.calls += 1
|
||||
return self.provider.embed(texts)
|
||||
|
||||
def snapshot(engine, settings, user_id, bindings, manifest):
|
||||
with transaction(engine) as conn:
|
||||
current, config = authority(conn, user_id)
|
||||
if {str(i) for i in selected(conn, current["organization_id"])} != set(bindings.values()):
|
||||
raise ValueError("Selection must exactly equal the approved evaluation corpus")
|
||||
for original in manifest["originals"].values():
|
||||
digest = original["sha256"]
|
||||
row = conn.execute(text("""
|
||||
SELECT processing_profile, extraction_state FROM documents
|
||||
WHERE id=:id AND organization_id=:org AND file_sha256=:digest
|
||||
AND status='ready' AND is_active AND deleted_at IS NULL
|
||||
AND content_purged_at IS NULL
|
||||
"""), dict(id=UUID(bindings[digest]), org=current["organization_id"],
|
||||
digest=digest)).mappings().one_or_none()
|
||||
if row is None or row["processing_profile"]["embedding"] != asdict(settings.embedding_profile):
|
||||
raise ValueError("Original binding is ineligible or incompatible")
|
||||
if Path(original["path"]).suffix.lower() == ".docx":
|
||||
inclusion = row["extraction_state"].get("factual_inclusion") or {}
|
||||
if inclusion.get("decision") != "approve" or not inclusion.get("reviewer"):
|
||||
raise ValueError("Persisted human factual DOCX approval required")
|
||||
return dict(actor=current, knowledge_revision=config["knowledge_revision"],
|
||||
access_epoch=config["access_epoch"])
|
||||
|
||||
def verify_sources(engine, sources, bindings):
|
||||
if len(sources) > 5 or sum(len(s["text"]) for s in sources) > 12000:
|
||||
return False
|
||||
if len({s["chunk_id"] for s in sources}) != len(sources):
|
||||
return False
|
||||
with transaction(engine) as conn:
|
||||
for source in sources:
|
||||
if source["document_id"] not in set(bindings.values()):
|
||||
return False
|
||||
row = conn.execute(text("""
|
||||
SELECT text, location FROM document_chunks
|
||||
WHERE id=:chunk AND document_id=:document
|
||||
"""), dict(chunk=UUID(source["chunk_id"]),
|
||||
document=UUID(source["document_id"]))).mappings().one_or_none()
|
||||
if row is None or row["text"] != source["text"]:
|
||||
return False
|
||||
if any(row["location"].get(k) != source["location"].get(k) for k in ("page", "section")):
|
||||
return False
|
||||
return True
|
||||
|
||||
def classification(result, passed, sources_valid):
|
||||
if not sources_valid:
|
||||
return dict(category="selection", responsible_phase="Fast-Track 1",
|
||||
provisional=False)
|
||||
if passed:
|
||||
return None
|
||||
code = (result.get("error") or {}).get("code", "")
|
||||
if result["status"] == "error":
|
||||
if code in ("CALIBRATION_REQUIRED", "EMBEDDING_PROFILE_MISMATCH", "PROFILE_MISMATCH"):
|
||||
category = "compatibility"
|
||||
elif code in ("CONTEXT_REVOKED", "ACTOR_UNAVAILABLE"):
|
||||
category = "selection"
|
||||
else:
|
||||
category = "technical provider/database errors"
|
||||
return dict(category=category, responsible_phase="Fast-Track 2", code=code,
|
||||
provisional=False)
|
||||
return dict(category="retrieval/ranking", responsible_phase="Fast-Track 2",
|
||||
provisional=True,
|
||||
required_triage="Inspect original -> retained extraction/review -> chunks -> "
|
||||
"publication -> selection/profile -> ranking -> whole-chunk admission. "
|
||||
"Reclassify to extraction/review, chunking, publication, selection, "
|
||||
"compatibility or evidence budgeting only with stage evidence.")
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--cases", type=Path, required=True)
|
||||
parser.add_argument("--bindings", type=Path, required=True)
|
||||
parser.add_argument("--calibration", type=Path, required=True)
|
||||
parser.add_argument("--user-id", type=UUID, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--allow-provider-calls", action="store_true", required=True)
|
||||
parser.add_argument("--provider-call-budget", type=int, choices=range(1, 27), required=True)
|
||||
args = parser.parse_args(argv)
|
||||
engine = None
|
||||
try:
|
||||
if args.output.exists() or not args.output.parent.is_dir():
|
||||
raise ValueError("New output path required")
|
||||
raw = args.cases.read_bytes()
|
||||
manifest = json.loads(raw)
|
||||
validate_manifest(manifest)
|
||||
try:
|
||||
calibration_raw = args.calibration.read_bytes()
|
||||
calibration = json.loads(calibration_raw)
|
||||
except (OSError, ValueError):
|
||||
raise EvaluationPreflightError(
|
||||
"CALIBRATION_ANNOTATIONS_INVALID",
|
||||
"Read a valid full Phase 2 calibration JSON report containing annotations.cases."
|
||||
) from None
|
||||
validate_question_separation(manifest["cases"], calibration)
|
||||
bindings = json.loads(args.bindings.read_bytes())
|
||||
expected = {o["sha256"] for o in manifest["originals"].values()}
|
||||
if set(bindings) != expected or len(set(bindings.values())) != len(bindings):
|
||||
raise ValueError("Exact one-to-one approved hash/document bindings required")
|
||||
for original in manifest["originals"].values():
|
||||
if hashlib.sha256((ROOT / original["path"]).read_bytes()).hexdigest() != original["sha256"]:
|
||||
raise ValueError("Original changed after annotation")
|
||||
UUID(bindings[original["sha256"]])
|
||||
cutoff = load_cutoff(calibration)
|
||||
if calibration.get("final_authorization_confirmed") is not True:
|
||||
raise ValueError("Finalized measured calibration required")
|
||||
settings = IngestionSettings()
|
||||
if cutoff.profile != asdict(settings.embedding_profile) or cutoff.retrieval_policy != RETRIEVAL_POLICY:
|
||||
raise ValueError("Pinned model/policy differs from frozen Phase 2 cutoff")
|
||||
engine = create_database(settings.database_url.get_secret_value())
|
||||
before = snapshot(engine, settings, args.user_id, bindings, manifest)
|
||||
from app.worker import factories
|
||||
_, provider_factory = factories(settings)
|
||||
provider, counter = provider_factory(settings.processing_profile())
|
||||
bounded = BudgetProvider(provider, args.provider_call_budget)
|
||||
service = SearchService(engine, settings, bounded, counter, cutoff=cutoff)
|
||||
execution = SearchExecution(args.user_id)
|
||||
execution.capture(before["actor"], before["access_epoch"])
|
||||
observations = {}
|
||||
stopped = False
|
||||
with args.output.open("x", encoding="utf-8") as output:
|
||||
def record(value):
|
||||
output.write(json.dumps(value, ensure_ascii=False, default=json_value,
|
||||
allow_nan=False) + "\n")
|
||||
output.flush()
|
||||
record(dict(type="run", status="started", annotations=manifest, bindings=bindings,
|
||||
annotations_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
calibration_sha256=hashlib.sha256(calibration_raw).hexdigest(),
|
||||
calibration_id=cutoff.calibration_id, cutoff=cutoff.distance,
|
||||
profile=asdict(settings.embedding_profile), retrieval_policy=RETRIEVAL_POLICY,
|
||||
embedding_request=settings.processing_profile()["embedding_request"],
|
||||
snapshot=before, provider_call_budget=args.provider_call_budget,
|
||||
usage="unavailable", billing="unavailable",
|
||||
assessment="independent literal evidence groups; no model judge"))
|
||||
for case in manifest["cases"]:
|
||||
if stopped or bounded.calls >= bounded.budget:
|
||||
observation = dict(status="not_run", passed=False, sources_valid=False,
|
||||
provider_calls=0, latency_seconds=None,
|
||||
reason="Stopped after technical failure or bounded call budget")
|
||||
else:
|
||||
started, calls_before = time.monotonic(), bounded.calls
|
||||
try:
|
||||
result = service.search(execution, case["query"], case.get("context"))
|
||||
valid = verify_sources(engine, result.get("sources", []), bindings)
|
||||
passed = valid and assess(case, result, bindings)
|
||||
observation = dict(status=result["status"], result=result, passed=passed,
|
||||
sources_valid=valid,
|
||||
failure=classification(result, passed, valid))
|
||||
stopped = result["status"] == "error" or not valid
|
||||
except Exception:
|
||||
stopped = True
|
||||
observation = dict(status="error", passed=False, sources_valid=False,
|
||||
failure=dict(category="technical provider/database errors",
|
||||
responsible_phase="Fast-Track 2",
|
||||
code="EVALUATION_TECHNICAL_ERROR"))
|
||||
observation.update(latency_seconds=time.monotonic()-started,
|
||||
provider_calls=bounded.calls-calls_before)
|
||||
observation.update(usage="unavailable", billing="unavailable")
|
||||
observations[case["id"]] = observation
|
||||
record(dict(type="case", id=case["id"], expected=case, **observation))
|
||||
try:
|
||||
confirmed = snapshot(engine, settings, args.user_id, bindings, manifest) == before
|
||||
except Exception:
|
||||
confirmed = False
|
||||
summary = gate(manifest["cases"], observations, authorization_confirmed=confirmed)
|
||||
record(dict(type="summary", **summary, provider_calls=bounded.calls,
|
||||
usage="unavailable", billing="unavailable",
|
||||
retrieval_quality="passed" if summary["passed"] else "failed",
|
||||
generated_answers="not_evaluated", live="not_evaluated"))
|
||||
print(json.dumps(dict(output=str(args.output), **summary)))
|
||||
return 0 if summary["passed"] else 1
|
||||
except EvaluationPreflightError as exc:
|
||||
print(json.dumps(dict(error=dict(code=exc.code, message=str(exc)))), file=sys.stderr)
|
||||
return 1
|
||||
except Exception:
|
||||
print("Evaluation not completed: verify frozen complete labels, approved originals, "
|
||||
"bindings, human review, model/cutoff, selection, database and new output path.",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if engine is not None:
|
||||
engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Phase 2 real PostgreSQL retrieval, revocation and publication acceptance."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from threading import Event
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import event, text
|
||||
|
||||
from app.modules.knowledge.evidence import CalibratedCutoff, SearchExecution, RETRIEVAL_POLICY
|
||||
from app.modules.knowledge.service import KnowledgeError, SearchService, selection_replace
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_phase6 import pipeline, upload, worker, snapshot
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import administrator, publish, EVIDENCE, QUERY
|
||||
|
||||
|
||||
def canonical(engine, settings, provider=None, *, distance=2):
|
||||
# This deliberately permissive cutoff exercises technical contracts ONLY.
|
||||
# It is never recorded as calibration or model-quality acceptance.
|
||||
return SearchService(engine, settings, provider or DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), distance, "test-only"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["کلید K-12", "ماده 2", "1403/07/01", "CAFÉ-12"])
|
||||
def test_normalized_exact_matching_preserves_evidence(search_path, tmp_path, query):
|
||||
engine, settings, org, admin, old = search_path
|
||||
evidence = "كليد K-١٢\nماده\t۲ در ۱۴۰۳/۰۷/۰۱: Cafe\u0301-12 فقط پس از بازرسی؛ باز نکنید مگر هنگام خاموشی."
|
||||
doc = publish(engine, settings, tmp_path / "lexical", admin, evidence)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
result = canonical(engine, settings).search(SearchExecution(admin), query)
|
||||
assert result["status"] == "ok"
|
||||
assert result["sources"][0]["text"] == evidence
|
||||
assert result["sources"][0]["document_id"] == str(doc)
|
||||
assert result["sources"][0]["location"] == dict(page=None, section="text/paragraph/1")
|
||||
rows = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, query)["candidates"]
|
||||
assert rows[0]["exact_match"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["K-1", "K-123", "K/12", "ماده 20", "1403/07/0", "25"])
|
||||
def test_boundary_and_quantity_queries_do_not_claim_exact_matches(search_path, tmp_path, query):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "boundaries", admin,
|
||||
"K-12 ماده 2 تاریخ 1403/07/01 مقدار 25 bar")
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
result = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(admin, query)
|
||||
assert len(result["candidates"]) == 1
|
||||
assert not result["candidates"][0]["exact_match"]
|
||||
|
||||
|
||||
def test_sql_payload_is_data_and_embedding_preprocessing_unchanged(search_path, tmp_path):
|
||||
engine, settings, org, admin, old = search_path
|
||||
source = "K-12 فقط پس از بازرسی"
|
||||
doc = publish(engine, settings, tmp_path / "data", admin, source)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
result = SearchService(engine, settings, provider).inspect(admin, "K-۱۲'); DROP TABLE users; --", "hint")
|
||||
assert provider.calls == [("K-۱۲'); DROP TABLE users; --\n\nhint",)]
|
||||
assert result["candidates"][0]["exact_match"]
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(text("SELECT count(*) FROM users")).scalar_one() == 1
|
||||
|
||||
|
||||
def test_exact_first_deduplicated_bounded_merge_with_eligibility_before_limits(search_path, tmp_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
other_org, other_admin = administrator(engine)
|
||||
foreign = publish(engine, settings, tmp_path / "foreign", other_admin, "K-12 foreign")
|
||||
selection_replace(engine, other_admin, 1, [foreign])
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
with engine.begin() as conn:
|
||||
# Stress data only; the end-to-end cases below use production publication.
|
||||
conn.execute(text("DELETE FROM document_chunks WHERE document_id=:doc"), dict(doc=doc))
|
||||
for i in range(120):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,:evidence,CAST(:location AS jsonb),CAST(:vector AS vector))"""),
|
||||
dict(id=UUID(int=i+1), org=org, doc=doc, ordinal=i,
|
||||
evidence="K-12 exact" if i >= 60 else "semantic",
|
||||
location=json.dumps(dict(page=None, section=f"row/{i}")),
|
||||
vector="[1,1,0]" if i >= 60 else "[1,0,0]"))
|
||||
for i in range(60):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,'K-12 foreign','{}', '[1,0,0]')"""),
|
||||
dict(id=uuid4(), org=other_org, doc=foreign, ordinal=i+1))
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
provider.embed = lambda _: [[1,0,0]]
|
||||
core = SearchService(engine, settings, provider)
|
||||
pool = core.candidates(SearchExecution(admin), "K-12")["candidates"]
|
||||
assert len(pool) == 100
|
||||
assert sum(r["exact_match"] for r in pool) == 50
|
||||
assert len({r["chunk_id"] for r in pool}) == 100
|
||||
assert all(r["document_id"] == doc for r in pool)
|
||||
assert [r["chunk_id"].int for r in pool[:50]] == list(range(61,111))
|
||||
result = core.inspect(admin, "K-12")
|
||||
assert [r["chunk_id"].int for r in result["candidates"]] == list(range(61,66))
|
||||
# Exact matches cannot bypass a measured admission cutoff.
|
||||
output = canonical(engine, settings, provider, distance=.1).search(SearchExecution(admin), "K-12")
|
||||
assert len(output["sources"]) == 5
|
||||
assert all(s["text"] == "semantic" for s in output["sources"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ineligible", ["inactive", "deleted", "purged", "failed", "queued", "processing"])
|
||||
def test_every_branch_excludes_ineligible_exact_evidence(search_path, tmp_path, ineligible):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "excluded", admin, "K-12 unavailable")
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
assignment = {"inactive":"is_active=false", "deleted":"is_active=false,deleted_at=now()",
|
||||
"purged":"is_active=false,content_purged_at=now()", "failed":"is_active=false,status='failed'",
|
||||
"queued":"is_active=false,status='queued'", "processing":"is_active=false,status='processing'"}[ineligible]
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE documents SET "+assignment+" WHERE id=:id"), dict(id=doc))
|
||||
result = canonical(engine, settings).search(SearchExecution(admin), "K-12")
|
||||
assert result["status"] == "no_evidence" and result["sources"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable"])
|
||||
def test_bounded_provider_barrier_revocation_suppresses_results(search_path, change):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
entered, release = Event(), Event()
|
||||
def paused(_):
|
||||
assert engine.pool.checkedout() == 0
|
||||
entered.set()
|
||||
assert release.wait(10), "provider barrier timed out"
|
||||
service = canonical(engine, settings, DeterministicEmbeddings(settings, observe=paused))
|
||||
execution = SearchExecution(admin)
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10), "search did not reach provider barrier"
|
||||
if change == "remove":
|
||||
selection_replace(engine, admin, 2, [])
|
||||
else:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), dict(id=admin))
|
||||
finally:
|
||||
release.set()
|
||||
result = future.result(timeout=15)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED"
|
||||
|
||||
|
||||
def test_execution_epoch_and_source_refs_span_multiple_searches(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
first = service.search(execution, QUERY)
|
||||
second = service.search(execution, "What are the conditions?")
|
||||
assert first["sources"][0]["source_ref"] == second["sources"][0]["source_ref"] == "S1"
|
||||
selection_replace(engine, admin, 2, [])
|
||||
assert service.search(execution, QUERY)["error"]["code"] == "CONTEXT_REVOKED"
|
||||
|
||||
|
||||
def test_sql_failure_and_timeout_are_canonical_errors(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
service = canonical(engine, settings)
|
||||
def fail(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" in statement:
|
||||
# Real PostgreSQL statement cancellation SQLSTATE 57014.
|
||||
conn.execute(text("SET LOCAL statement_timeout = '10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
event.listen(engine, "before_cursor_execute", fail)
|
||||
try:
|
||||
result = service.search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["error"]["code"] == "SEARCH_TIMEOUT"
|
||||
finally:
|
||||
event.remove(engine, "before_cursor_execute", fail)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("ALTER TABLE document_chunks RENAME TO broken_chunks"))
|
||||
result = service.search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["error"]["code"] == "SEARCH_FAILED"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", [".md", ".docx"])
|
||||
def test_ingestion_publication_selection_search_retains_literal_complete_evidence(pipeline, suffix):
|
||||
p = pipeline
|
||||
# The Phase 6 fixture has independent original paragraphs, not a chunker oracle.
|
||||
with p["engine"].begin() as conn:
|
||||
conn.execute(text("""INSERT INTO organization_settings(organization_id,assistant_name,instruction)
|
||||
SELECT organization_id,'Fixture','Answer from documents' FROM users WHERE id=:id"""), dict(id=p["actor"]))
|
||||
document = upload(p, suffix)
|
||||
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("phase2-e2e")
|
||||
service = canonical(p["engine"], p["settings"])
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
result = service.search(SearchExecution(p["actor"]), "Article 1 Article 2 Article 3")
|
||||
assert result["status"] == "ok" and len(result["sources"]) == 3
|
||||
rows = {s["location"]["section"]:s for s in result["sources"]}
|
||||
locator = "docx/paragraph/" if suffix == ".docx" else "text/paragraph/"
|
||||
required = [
|
||||
("25 bar", "only when temperature is below 60 C", "Do not open the bypass", "except during shutdown"),
|
||||
("40 liters per minute", "unless the inlet is blocked", "every 30 days"),
|
||||
("15 Nm", "Do not restart when leakage is present", "except after inspection"),
|
||||
]
|
||||
for i, phrases in enumerate(required, 1):
|
||||
matching = [s for key,s in rows.items() if key.endswith(locator+str(i))]
|
||||
assert len(matching) == 1
|
||||
assert matching[0]["document_id"] == str(document["id"])
|
||||
assert matching[0]["location"]["page"] is None
|
||||
assert all(phrase in matching[0]["text"] for phrase in phrases)
|
||||
assert len({s["source_ref"] for s in result["sources"]}) == 3
|
||||
assert len({s["chunk_id"] for s in result["sources"]}) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize("boundary", ["final_batch", "after_inserts", "after_completion_updates"])
|
||||
def test_partial_publication_never_becomes_searchable(pipeline, boundary):
|
||||
p = pipeline
|
||||
with p["engine"].begin() as conn:
|
||||
conn.execute(text("""INSERT INTO organization_settings(organization_id,assistant_name,instruction)
|
||||
SELECT organization_id,'Fixture','Answer from documents' FROM users WHERE id=:id"""), dict(id=p["actor"]))
|
||||
document = upload(p)
|
||||
entered, release = Event(), Event()
|
||||
p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=60, lease_seconds=120))
|
||||
p["repo"].settings = p["settings"]
|
||||
inserted = []
|
||||
def pause(conn, cursor, statement, parameters, context, executemany):
|
||||
if statement.lstrip().startswith("INSERT INTO document_chunks"):
|
||||
inserted.append(1)
|
||||
if boundary == "after_inserts" and len(inserted) == 3:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
if boundary == "after_completion_updates" and "UPDATE ingestion_jobs" in statement and "status='succeeded'" in statement:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
def embedding_barrier(batch):
|
||||
if boundary == "final_batch" and batch == 2:
|
||||
entered.set()
|
||||
assert release.wait(10)
|
||||
service = canonical(p["engine"], p["settings"])
|
||||
provider = DeterministicEmbeddings(p["settings"], observe=embedding_barrier,
|
||||
fail_at=2 if boundary=="final_batch" else None)
|
||||
event.listen(p["engine"], "after_cursor_execute", pause)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(worker(p, provider).run_once, "phase2-boundary")
|
||||
try:
|
||||
assert entered.wait(10)
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
partial = snapshot(p, document)
|
||||
assert partial["actual_count"] == partial["chunk_count"] == 0
|
||||
assert partial["status"] == partial["job_status"] == "processing"
|
||||
assert partial["ready_at"] is None and not partial["is_active"]
|
||||
# Do not block selection behind the intentionally paused publisher.
|
||||
finally:
|
||||
release.set()
|
||||
assert future.result(timeout=15)
|
||||
finally:
|
||||
release.set()
|
||||
event.remove(p["engine"], "after_cursor_execute", pause)
|
||||
if boundary == "final_batch":
|
||||
assert snapshot(p, document)["status"] == "failed"
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
with pytest.raises(KnowledgeError) as exc:
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
assert exc.value.code == "DOCUMENT_NOT_READY"
|
||||
else:
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "no_evidence"
|
||||
selection_replace(p["engine"], p["actor"], 1, [document["id"]])
|
||||
assert service.search(SearchExecution(p["actor"]), "Article 1")["status"] == "ok"
|
||||
|
||||
|
||||
def test_calibration_runner_uses_shared_core_frozen_bindings_and_bounded_calls(search_path, tmp_path):
|
||||
import hashlib
|
||||
from app.calibrate_search import CASES_PATH, run
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
with engine.connect() as conn:
|
||||
digest = conn.execute(text("SELECT file_sha256 FROM documents WHERE id=:id"), dict(id=doc)).scalar_one()
|
||||
assert digest == hashlib.sha256(original.read_bytes()).hexdigest() == annotations["original_sha256"]
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
report = run(engine, settings, provider, None, admin, annotations, {digest:str(doc)})
|
||||
assert len(provider.calls) == report["provider_calls"] == 10
|
||||
assert report["provider_call_budget"] == 10
|
||||
assert report["retrieval_policy"] == RETRIEVAL_POLICY
|
||||
assert report["profile"] == asdict(settings.embedding_profile)
|
||||
assert len(report["observations"]) == 10
|
||||
assert report["status"] in ("calibrated", "measured_failure")
|
||||
# Deterministic vectors do not establish semantic-quality acceptance.
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
with pytest.raises(KnowledgeError) as exc:
|
||||
run(engine, settings, provider, None, admin, annotations, {digest:str(uuid4())})
|
||||
assert exc.value.code == "CALIBRATION_BINDING_INVALID" and not provider.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code", [("provider", "PROVIDER_UNAVAILABLE"),
|
||||
("timeout", "SEARCH_TIMEOUT"),
|
||||
("vector", "INVALID_VECTOR")])
|
||||
def test_actual_provider_boundary_errors_never_report_no_evidence(search_path, failure, code):
|
||||
from app.modules.documents.embeddings import EmbeddingProviderError
|
||||
engine, settings, org, admin, doc = search_path
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
def broken(_):
|
||||
if failure == "provider":
|
||||
raise EmbeddingProviderError("secret raw response", retryable=False)
|
||||
if failure == "timeout":
|
||||
raise TimeoutError("secret raw timeout")
|
||||
return [[0,0,0]]
|
||||
provider.embed = broken
|
||||
result = canonical(engine, settings, provider).search(SearchExecution(admin), QUERY)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == code
|
||||
assert "secret" not in result["error"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("space", ["\u00a0", "\u202f", "\u2003", "\u3000"])
|
||||
def test_unicode_whitespace_is_equivalent_only_for_exact_comparison(search_path, tmp_path, space):
|
||||
engine, settings, org, admin, old = search_path
|
||||
evidence = "Article" + space + "2 faithful passage"
|
||||
doc = publish(engine, settings, tmp_path / "unicode-space", admin, evidence)
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
rows = SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(
|
||||
admin, "Article 2")["candidates"]
|
||||
assert rows[0]["exact_match"] and rows[0]["text"] == evidence
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Confirmed Psycopg disconnects in the existing isolated PostgreSQL core."""
|
||||
import json
|
||||
import pytest
|
||||
from sqlalchemy import event, text
|
||||
|
||||
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 SearchExecution
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_search_phase2 import canonical
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import publish, QUERY
|
||||
|
||||
def disconnect(engine, conn):
|
||||
assert conn.execute(text("SELECT pg_backend_pid()")).scalar_one() > 0
|
||||
# Close only this test's actual Psycopg connection. The next SQLAlchemy
|
||||
# execution wraps a SQLSTATE-less OperationalError and marks it invalid.
|
||||
conn.connection.driver_connection.close()
|
||||
conn.execute(text("SELECT 1"))
|
||||
|
||||
@pytest.mark.parametrize("boundary", ["candidate", "handoff"])
|
||||
def test_confirmed_real_disconnect_has_safe_retryability_and_no_replay(search_path, monkeypatch, boundary):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
service = canonical(engine, settings, provider=provider)
|
||||
execution = SearchExecution(admin)
|
||||
normalized = []
|
||||
mapper = core.sql_error
|
||||
def record(exc):
|
||||
normalized.append(exc)
|
||||
return mapper(exc)
|
||||
monkeypatch.setattr(core, "sql_error", record)
|
||||
attempts = []
|
||||
authorize = core.authority
|
||||
def fail_handoff(conn, *args, **kwargs):
|
||||
attempts.append(1)
|
||||
if len(attempts) == 3:
|
||||
disconnect(engine, conn)
|
||||
return authorize(conn, *args, **kwargs)
|
||||
def fail_candidate(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" in statement:
|
||||
attempts.append(1)
|
||||
disconnect(engine, conn)
|
||||
if boundary == "handoff":
|
||||
monkeypatch.setattr(core, "authority", fail_handoff)
|
||||
else:
|
||||
event.listen(engine, "before_cursor_execute", fail_candidate)
|
||||
try:
|
||||
result = service.search(execution, QUERY)
|
||||
finally:
|
||||
if boundary == "candidate":
|
||||
event.remove(engine, "before_cursor_execute", fail_candidate)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "SEARCH_FAILED" and result["error"]["retryable"]
|
||||
assert result["error"]["message"] == "Knowledge database retrieval failed"
|
||||
assert len(provider.calls) == 1
|
||||
assert len(attempts) == (3 if boundary == "handoff" else 1)
|
||||
assert len(normalized) == 1
|
||||
assert normalized[0].connection_invalidated and normalized[0].orig.sqlstate is None
|
||||
assert execution.sources([dict(chunk_id=doc, document_id=doc, title="test", text="later",
|
||||
location=dict(page=None, section=None))])[0]["source_ref"] == "S1"
|
||||
|
||||
def test_real_final_calibration_disconnect_retains_completed_observations(search_path, tmp_path, monkeypatch):
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
authorize = calibrate_search.authority
|
||||
attempts = []
|
||||
def fail_final(conn, *args, **kwargs):
|
||||
attempts.append(1)
|
||||
if len(attempts) == 2:
|
||||
assert len(provider.calls) == 10
|
||||
disconnect(engine, conn)
|
||||
return authorize(conn, *args, **kwargs)
|
||||
monkeypatch.setattr(calibrate_search, "authority", fail_final)
|
||||
report = calibrate_search.run(engine, settings, provider, None, admin, annotations,
|
||||
{annotations["original_sha256"]: str(doc)})
|
||||
assert report["status"] == "technical_error" and report["cutoff"] is None
|
||||
assert report["provider_calls"] == len(provider.calls) == 10
|
||||
assert len(attempts) == 2 and not report["final_authorization_confirmed"]
|
||||
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"] >= 0
|
||||
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 ("pg_backend_pid", "pg_terminate_backend", "SELECT 1"))
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Real PostgreSQL reproduction of Phase 2 handoff and exact recovery defects."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from threading import Event
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.modules.knowledge import service as core
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.integration.test_search_phase2 import canonical
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import publish, QUERY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable", "authority"])
|
||||
def test_revocation_after_candidates_before_service_handoff(search_path, monkeypatch, change):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
entered, release = Event(), Event()
|
||||
retrieve = service.candidates
|
||||
retained = []
|
||||
def paused(*args, **kwargs):
|
||||
result = retrieve(*args, **kwargs)
|
||||
retained.extend(result["candidates"])
|
||||
assert result["candidates"] and engine.pool.checkedout() == 0
|
||||
entered.set()
|
||||
assert release.wait(10), "candidate barrier timed out"
|
||||
return result
|
||||
monkeypatch.setattr(service, "candidates", paused)
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10), "retrieval did not reach pre-publication barrier"
|
||||
if change == "remove":
|
||||
core.selection_replace(engine, admin, 2, [])
|
||||
else:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET "+(
|
||||
"is_enabled=false" if change=="disable" else "role='user'")+" WHERE id=:id"),
|
||||
dict(id=admin))
|
||||
finally:
|
||||
release.set()
|
||||
result = future.result(timeout=15)
|
||||
assert result["status"] == "error" and result["sources"] == []
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED"
|
||||
# An independently formatted later row still receives S1: rejected evidence
|
||||
# cannot consume execution-wide references.
|
||||
different = dict(retained[0], chunk_id=uuid4())
|
||||
assert execution.sources([different])[0]["source_ref"] == "S1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query,context,evidence", [
|
||||
("K-12.", None, "Only valid with inspection. Identifier K-12."),
|
||||
("K-12", None, "Identifier K-12."),
|
||||
("Article 2", None, "Article 2."),
|
||||
("1403/07/01", None, "Issue date 1403/07/01."),
|
||||
("IR.12.", None, "Identifier IR.12."),
|
||||
("IR/12.", None, "Identifier IR/12."),
|
||||
("IR-12.", None, "Identifier IR-12."),
|
||||
("کلید-12.", None, "Required identifier كليد-١٢."),
|
||||
("Conditions?", "کلید-۱۲.", "Required identifier كليد-١٢."),
|
||||
("Article 2.", None, "Article 2."),
|
||||
("1403/07/01.", None, "Issue date 1403/07/01."),
|
||||
("Conditions?", "K-12.", "Only valid with inspection. Identifier K-12."),
|
||||
("Conditions?", "Article 2.", "Article 2."),
|
||||
("Conditions?", "1403/07/01.", "Issue date 1403/07/01."),
|
||||
("کد-12.", None, "Required identifier كد-١٢."),
|
||||
("ماده 2.", None, "ماده ۲."),
|
||||
("1403/07/01.", None, "Issue date ۱۴۰۳/۰۷/۰۱."),
|
||||
("Conditions?", "کد-۱۲.", "Required identifier كد-١٢."),
|
||||
])
|
||||
def test_exact_period_recovery_outside_first_fifty_semantic_candidates(
|
||||
search_path, tmp_path, query, context, evidence):
|
||||
engine, settings, org, admin, semantic_doc = search_path
|
||||
target = publish(engine, settings, tmp_path / "punctuation", admin, evidence)
|
||||
core.selection_replace(engine, admin, 1, [semantic_doc, target])
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("UPDATE document_chunks SET embedding='[1,1,0]' WHERE document_id=:id"),
|
||||
dict(id=target))
|
||||
conn.execute(text("UPDATE document_chunks SET embedding='[1,0,0]' WHERE document_id=:id"),
|
||||
dict(id=semantic_doc))
|
||||
# Stress distractors are test data; the relevant evidence was published
|
||||
# through the real intake/extraction/worker path above.
|
||||
for i in range(50):
|
||||
conn.execute(text("""INSERT INTO document_chunks
|
||||
(id,organization_id,document_id,ordinal,text,location,embedding)
|
||||
VALUES (:id,:org,:doc,:ordinal,'Unrelated eligible passage',
|
||||
jsonb_build_object('page',NULL,'section',NULL), '[1,0,0]')"""),
|
||||
dict(id=uuid4(), org=org, doc=semantic_doc, ordinal=i+1))
|
||||
semantic = conn.execute(text("""SELECT document_id FROM document_chunks
|
||||
WHERE organization_id=:org ORDER BY embedding <=> '[1,0,0]'::vector,id LIMIT 50"""),
|
||||
dict(org=org)).scalars().all()
|
||||
assert target not in semantic
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
provider.embed = lambda *args: [[1,0,0]]
|
||||
pool = core.SearchService(engine, settings, provider).candidates(
|
||||
SearchExecution(admin), query, context)["candidates"]
|
||||
assert pool[0]["document_id"] == target and pool[0]["exact_match"]
|
||||
assert len(pool) == 51 and len({r["chunk_id"] for r in pool}) == 51
|
||||
result = canonical(engine, settings, provider).search(SearchExecution(admin), query, context)
|
||||
assert result["status"] == "ok" and result["sources"][0]["document_id"] == str(target)
|
||||
assert result["sources"][0]["text"] == evidence
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query,evidence", [
|
||||
("K-1.", "Identifier K-12."),
|
||||
("K-12.", "Identifier K-12.foo."),
|
||||
("Article 2.", "Article 20."),
|
||||
("1403/07/01.", "Issue date 1403/07/010."),
|
||||
("IR.12.", "Identifier IR/12."),
|
||||
("IR/12.", "Identifier IR-12."),
|
||||
("IR-12.", "Identifier IR.12."),
|
||||
])
|
||||
def test_period_boundaries_do_not_admit_identifier_prefixes_or_other_separators(
|
||||
search_path, tmp_path, query, evidence):
|
||||
engine, settings, org, admin, old = search_path
|
||||
doc = publish(engine, settings, tmp_path / "prefix", admin, evidence)
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
rows = core.SearchService(engine, settings, DeterministicEmbeddings(settings)).inspect(
|
||||
admin, query)["candidates"]
|
||||
assert len(rows)==1 and not rows[0]["exact_match"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["remove", "disable"])
|
||||
def test_authorized_admission_is_locked_until_service_handoff(search_path, monkeypatch, change):
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
service = canonical(engine, settings)
|
||||
execution = SearchExecution(admin)
|
||||
entered, release = Event(), Event()
|
||||
admit = core.admit_candidates
|
||||
def paused(*args, **kwargs):
|
||||
# Retrieval has finished; this is guarded canonical finalization.
|
||||
entered.set()
|
||||
assert release.wait(10), "admission barrier timed out"
|
||||
return admit(*args, **kwargs)
|
||||
monkeypatch.setattr(core, "admit_candidates", paused)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
search = pool.submit(service.search, execution, QUERY)
|
||||
try:
|
||||
assert entered.wait(10)
|
||||
def remove_or_disable():
|
||||
if change == "remove":
|
||||
return core.selection_replace(engine, admin, 2, [])
|
||||
with core.transaction(engine) as conn:
|
||||
conn.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), dict(id=admin))
|
||||
mutation = pool.submit(remove_or_disable)
|
||||
with pytest.raises(SQLAlchemyError) as exc:
|
||||
mutation.result(timeout=5)
|
||||
assert exc.value.orig.sqlstate == "55P03"
|
||||
finally:
|
||||
release.set()
|
||||
result = search.result(timeout=15)
|
||||
assert result["status"] == "ok" and result["sources"][0]["source_ref"] == "S1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code,retryable", [
|
||||
("table", "SEARCH_FAILED", False),
|
||||
("permission", "SEARCH_FAILED", False),
|
||||
("syntax", "SEARCH_FAILED", False),
|
||||
("timeout", "SEARCH_TIMEOUT", True),
|
||||
("serialization", "SEARCH_FAILED", True),
|
||||
("deadlock", "SEARCH_FAILED", True),
|
||||
("unknown", "SEARCH_FAILED", False),
|
||||
])
|
||||
def test_real_sql_failures_have_safe_canonical_retryability(search_path, failure, code, retryable):
|
||||
from sqlalchemy import event
|
||||
engine, settings, org, admin, doc = search_path
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
with engine.connect() as conn:
|
||||
schema = conn.execute(text("SELECT current_schema()")).scalar_one()
|
||||
def fail(conn, cursor, statement, parameters, context, executemany):
|
||||
if "FROM document_chunks c" not in statement:
|
||||
return
|
||||
if failure == "table":
|
||||
conn.execute(text("SELECT * FROM nonexistent_private_table"))
|
||||
elif failure == "permission":
|
||||
conn.execute(text("SET LOCAL ROLE pg_read_all_settings"))
|
||||
conn.execute(text(f'SELECT * FROM "{schema}".document_chunks'))
|
||||
elif failure == "syntax":
|
||||
conn.execute(text("SELECT FROM"))
|
||||
elif failure == "timeout":
|
||||
conn.execute(text("SET LOCAL statement_timeout='10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
else:
|
||||
state = {"serialization":"40001", "deadlock":"40P01", "unknown":"XX000"}[failure]
|
||||
conn.execute(text("DO $$ BEGIN RAISE EXCEPTION USING ERRCODE='"+state+
|
||||
"',MESSAGE='private SQL payload postgresql://user:password@secret/db'; END $$"))
|
||||
event.listen(engine, "before_cursor_execute", fail)
|
||||
try:
|
||||
output = canonical(engine, settings).search(SearchExecution(admin), QUERY)
|
||||
finally:
|
||||
event.remove(engine, "before_cursor_execute", fail)
|
||||
assert output["status"] == "error" and output["sources"] == []
|
||||
assert (output["error"]["code"],output["error"]["retryable"]) == (code,retryable)
|
||||
assert all(token not in json.dumps(output) for token in
|
||||
("SELECT", "nonexistent_private_table", "password", "private SQL", schema))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code,retryable", [
|
||||
("timeout", "SEARCH_TIMEOUT", True), ("table", "SEARCH_FAILED", False),
|
||||
])
|
||||
def test_calibration_retains_completed_metrics_after_real_final_sql_failure(
|
||||
search_path, tmp_path, monkeypatch, failure, code, retryable):
|
||||
from app import calibrate_search
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
engine, settings, org, admin, old = search_path
|
||||
annotations = json.loads(calibrate_search.CASES_PATH.read_text(encoding="utf-8"))
|
||||
original = calibrate_search.CASES_PATH.parent / annotations["original_file"]
|
||||
doc = publish(engine, settings, tmp_path / "calibration", admin, original.read_text(encoding="utf-8"))
|
||||
core.selection_replace(engine, admin, 1, [doc])
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
authorize = calibrate_search.authority
|
||||
authorizations = []
|
||||
def fail_final(conn, *args, **kwargs):
|
||||
authorizations.append(1)
|
||||
if len(authorizations) == 2:
|
||||
assert len(provider.calls) == 10
|
||||
if failure == "timeout":
|
||||
conn.execute(text("SET LOCAL statement_timeout='10ms'"))
|
||||
conn.execute(text("SELECT pg_sleep(1)"))
|
||||
else:
|
||||
conn.execute(text("SELECT * FROM missing_private_relation"))
|
||||
return authorize(conn, *args, **kwargs)
|
||||
monkeypatch.setattr(calibrate_search, "authority", fail_final)
|
||||
report = calibrate_search.run(engine, settings, provider, None, admin, annotations,
|
||||
{annotations["original_sha256"]:str(doc)})
|
||||
assert report["status"] == "technical_error" and report["cutoff"] is None
|
||||
assert report["provider_calls"] == len(provider.calls) == 10
|
||||
assert (report["finalization_error"]["code"],report["finalization_error"]["retryable"]) == (code,retryable)
|
||||
assert not report["final_authorization_confirmed"]
|
||||
for observation in report["observations"].values():
|
||||
assert observation["retrieval_status"] == "completed"
|
||||
assert observation["provider_calls"] == 1 and observation["latency_seconds"] >= 0
|
||||
assert "candidates" not in observation and "sources" not in observation
|
||||
assert "missing_private_relation" not in json.dumps(report)
|
||||
with pytest.raises(ValueError):
|
||||
load_cutoff(report)
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Actual LangChain boundary over the same persisted PostgreSQL search service."""
|
||||
import asyncio
|
||||
from dataclasses import asdict
|
||||
import time
|
||||
|
||||
from app.modules.knowledge.evidence import CalibratedCutoff, SearchExecution
|
||||
from app.modules.knowledge.langchain_tool import SearchToolRunner, ToolContext, create_search_tool
|
||||
from app.modules.knowledge.service import SearchService, selection_replace
|
||||
from tests.integration.test_scoped_search import search_path
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.search import EVIDENCE, QUERY, administrator, publish
|
||||
|
||||
|
||||
def test_real_service_inspection_sync_async_equivalence(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
provider = DeterministicEmbeddings(settings)
|
||||
# Technical-only cutoff; not semantic calibration.
|
||||
service = SearchService(engine, settings, provider, cutoff=CalibratedCutoff(
|
||||
asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
inspected = service.inspect(admin, QUERY)
|
||||
execution = SearchExecution(admin)
|
||||
expected = service.search(execution, QUERY)
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(execution, time.monotonic()+10), runner)
|
||||
assert tool.invoke({"query": QUERY}) == expected
|
||||
assert asyncio.run(tool.ainvoke({"query": QUERY})) == expected
|
||||
assert expected["sources"][0]["text"] == EVIDENCE
|
||||
assert expected["sources"][0]["document_id"] == str(doc)
|
||||
assert expected["sources"][0]["chunk_id"] == str(inspected["candidates"][0]["chunk_id"])
|
||||
assert expected["sources"][0]["location"] == inspected["candidates"][0]["location"]
|
||||
assert expected["sources"][0]["source_ref"] == "S1"
|
||||
finally:
|
||||
runner.close()
|
||||
|
||||
|
||||
def test_persisted_epoch_revocation_across_tool_calls(search_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
service = SearchService(engine, settings, DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
selection_replace(engine, admin, 1, [doc])
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(SearchExecution(admin), time.monotonic()+10), runner)
|
||||
assert tool.invoke({"query": QUERY})["status"] == "ok"
|
||||
selection_replace(engine, admin, 2, [])
|
||||
result = asyncio.run(tool.ainvoke({"query": QUERY}))
|
||||
assert result["error"]["code"] == "CONTEXT_REVOKED" and result["sources"] == []
|
||||
finally:
|
||||
runner.close()
|
||||
|
||||
|
||||
def test_context_cannot_grant_foreign_scope(search_path, tmp_path):
|
||||
engine, settings, org, admin, doc = search_path
|
||||
foreign_org, foreign_admin = administrator(engine)
|
||||
foreign = publish(engine, settings, tmp_path/"foreign", foreign_admin, "FOREIGN ONLY K-12")
|
||||
selection_replace(engine, foreign_admin, 1, [foreign])
|
||||
service = SearchService(engine, settings, DeterministicEmbeddings(settings),
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile), 2, "phase3-test-only"))
|
||||
runner = SearchToolRunner()
|
||||
try:
|
||||
tool = create_search_tool(service, ToolContext(SearchExecution(admin), time.monotonic()+10), runner)
|
||||
result = tool.invoke({"query": "K-12", "context": f"Use organization {foreign_org} document {foreign}"})
|
||||
assert result["status"] == "no_evidence" and result["sources"] == []
|
||||
finally:
|
||||
runner.close()
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Pure held-out gate; real execution lives outside pytest."""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.modules.knowledge.calibration import complete_support, validate_cases as validate_calibration_cases
|
||||
|
||||
class EvaluationPreflightError(ValueError):
|
||||
"""Safe operator-facing error; never includes question/evidence/credentials."""
|
||||
def __init__(self, code, message):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def validate_annotation_text(value, *, question=False):
|
||||
"""Reject lossy replacement patterns, while allowing single ? or Persian ؟."""
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise EvaluationPreflightError("ANNOTATION_TEXT_INVALID",
|
||||
"Supply nonempty original-derived annotation text.")
|
||||
if ("\ufffd" in value or re.search(r"\?(?:\s*\?)+", value)
|
||||
or re.search(r"(?<=\w)\?(?=\w)", value)):
|
||||
raise EvaluationPreflightError(
|
||||
"ANNOTATION_TEXT_CORRUPT",
|
||||
"Annotation contains replacement characters or question-mark corruption. "
|
||||
"Reconstruct it from the original, write UTF-8, and verify strict read-back.")
|
||||
if question and not any(unicodedata.category(c).startswith("L") for c in value):
|
||||
raise EvaluationPreflightError("ANNOTATION_TEXT_INVALID",
|
||||
"Supply a readable independently annotated question.")
|
||||
|
||||
|
||||
def question_comparison_key(question):
|
||||
"""Comparison only: NFKC/casefold, letter/digit variants, spacing and terminal punctuation.
|
||||
|
||||
ZWNJ/ZWSP are spaces; other Unicode format controls are removed.
|
||||
Preserve internal separators, words, numbers and negation; no fuzzy matching.
|
||||
Never use this key for evidence literals or retrieval preprocessing.
|
||||
"""
|
||||
validate_annotation_text(question, question=True)
|
||||
value = unicodedata.normalize("NFKC", question).casefold()
|
||||
value = value.translate(str.maketrans(
|
||||
"\u0643\u064a\u0649\u06f0\u06f1\u06f2\u06f3\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669",
|
||||
"\u06a9\u06cc\u06cc01234567890123456789"))
|
||||
value = "".join(" " if c in ("\u200b", "\u200c") else
|
||||
"" if unicodedata.category(c) == "Cf" else c for c in value)
|
||||
return " ".join(value.split()).rstrip(".!?\u061f").rstrip()
|
||||
|
||||
|
||||
def validate_question_separation(held_out_cases, calibration_report):
|
||||
"""Fail closed on missing/malformed full Phase 2 annotations; compare queries only."""
|
||||
invalid = EvaluationPreflightError(
|
||||
"CALIBRATION_ANNOTATIONS_INVALID",
|
||||
"Independence cannot be verified. Supply the full Phase 2 calibration report "
|
||||
"with annotations.cases: six answerable and four unsupported original-bound cases.")
|
||||
try:
|
||||
annotations = calibration_report["annotations"]
|
||||
cases = annotations["cases"]
|
||||
if (not isinstance(annotations, dict) or not isinstance(cases, list)
|
||||
or any(not isinstance(c, dict)
|
||||
or not isinstance(c.get("id"), str) or not c["id"].strip()
|
||||
or type(c.get("answerable")) is not bool
|
||||
or not isinstance(c.get("query"), str)
|
||||
or not isinstance(c.get("original_sha256"), str)
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", c["original_sha256"])
|
||||
or not isinstance(c.get("evidence_groups"), list)
|
||||
or any(not isinstance(g, list)
|
||||
or any(not isinstance(p, str) for p in g)
|
||||
for g in c["evidence_groups"]) for c in cases)):
|
||||
raise invalid
|
||||
validate_calibration_cases(cases)
|
||||
for case in cases:
|
||||
validate_annotation_text(case["query"], question=True)
|
||||
for group in case["evidence_groups"]:
|
||||
for phrase in group:
|
||||
validate_annotation_text(phrase)
|
||||
keys = {question_comparison_key(c["query"]) for c in cases}
|
||||
if len(keys) != 10:
|
||||
raise invalid
|
||||
except (KeyError, TypeError, ValueError):
|
||||
raise invalid from None
|
||||
if any(question_comparison_key(c["query"]) in keys for c in held_out_cases):
|
||||
raise EvaluationPreflightError(
|
||||
"HELD_OUT_QUESTION_OVERLAP",
|
||||
"Held-out questions overlap Phase 2 calibration after comparison normalization. "
|
||||
"Annotate distinct held-out questions from originals before freezing; "
|
||||
"shared source documents are permitted.")
|
||||
|
||||
|
||||
def validate_manifest(manifest):
|
||||
cases = manifest["cases"]
|
||||
if (manifest.get("status") != "frozen" or len(cases) != 26
|
||||
or len({c["id"] for c in cases}) != 26
|
||||
or sum(c["answerable"] is True for c in cases) != 20
|
||||
or sum(c["answerable"] is False for c in cases) != 6
|
||||
or sum(c["answerable"] is True and c.get("unseen") is True for c in cases) < 4):
|
||||
raise ValueError("Frozen 20 answerable / 6 unsupported with four unseen cases required")
|
||||
for case in cases:
|
||||
validate_annotation_text(case["query"], question=True)
|
||||
if case.get("annotation_status") == "unresolved":
|
||||
raise EvaluationPreflightError("ANNOTATION_UNRESOLVED",
|
||||
"Reconstruct unresolved evidence from originals before freezing.")
|
||||
if (not isinstance(case["query"], str) or not case["query"].strip()
|
||||
or type(case["critical"]) is not bool
|
||||
or bool(case["evidence_groups"]) != case["answerable"]
|
||||
or any(not g or any(not isinstance(p, str) or not p.strip() for p in g)
|
||||
for g in case["evidence_groups"])):
|
||||
raise ValueError("Complete independent evidence groups and critical labels required")
|
||||
for group in case["evidence_groups"]:
|
||||
for phrase in group:
|
||||
validate_annotation_text(phrase)
|
||||
if case["answerable"]:
|
||||
section = case.get("locator", {}).get("section")
|
||||
if section is not None:
|
||||
validate_annotation_text(section)
|
||||
original = manifest["originals"][case["original"]]
|
||||
if case["original_sha256"] != original["sha256"]:
|
||||
raise ValueError("Annotation original identity differs")
|
||||
if any(o.get("approval") != "approved" for o in manifest["originals"].values()):
|
||||
raise ValueError("Explicit original approval required")
|
||||
|
||||
def assess(case, result, bindings):
|
||||
status = result.get("status")
|
||||
sources = result.get("sources", [])
|
||||
if not case["answerable"]:
|
||||
return status == "no_evidence" and sources == []
|
||||
return (status == "ok" and 1 <= len(sources) <= 5
|
||||
and sum(len(s["text"]) for s in sources) <= 12000
|
||||
and complete_support(case, sources, bindings[case["original_sha256"]]))
|
||||
|
||||
def gate(cases, observations, *, authorization_confirmed):
|
||||
ids = {c["id"] for c in cases}
|
||||
valid_counts = (len(cases) == len(ids) == 26
|
||||
and sum(c["answerable"] is True for c in cases) == 20
|
||||
and sum(c["answerable"] is False for c in cases) == 6)
|
||||
executed = set(observations) == ids and all(
|
||||
observations[c["id"]].get("status") in ("ok", "no_evidence", "error") for c in cases)
|
||||
def passed_case(case):
|
||||
observation = observations.get(case["id"], {})
|
||||
expected_status = "ok" if case["answerable"] else "no_evidence"
|
||||
return observation.get("passed") is True and observation.get("status") == expected_status
|
||||
answerable = sum(passed_case(c) for c in cases if c["answerable"])
|
||||
critical = all(passed_case(c) for c in cases if c["critical"])
|
||||
unsupported = sum(passed_case(c) for c in cases if not c["answerable"])
|
||||
sources_valid = all(o.get("sources_valid") is True for o in observations.values())
|
||||
passed = (valid_counts and executed and authorization_confirmed and sources_valid
|
||||
and answerable >= 18 and critical and unsupported == 6)
|
||||
return dict(passed=passed, answerable_passed=answerable, answerable_required=20,
|
||||
answerable_minimum=18, all_critical=critical,
|
||||
unsupported_passed=unsupported, unsupported_required=6,
|
||||
all_cases_executed=executed, sources_valid=sources_valid,
|
||||
final_authorization_confirmed=authorization_confirmed)
|
||||
@@ -37,7 +37,7 @@ def publish(engine, settings, root, user, evidence=EVIDENCE):
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
source = root / "pump.md"
|
||||
source.write_text(evidence, encoding="utf-8")
|
||||
source.write_text(evidence, encoding="utf-8", newline="\n")
|
||||
store = LocalFileStore(root / "originals")
|
||||
candidates = LocalExtractionCandidates(root / "extractions", original_directory=store.directory)
|
||||
document = import_document(SqlIntakeRepository(engine), store, settings, path=source,
|
||||
|
||||
@@ -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