From fef381c41b78bcc69c4f6253bf0d7a5d90ee5841 Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Thu, 8 Oct 2026 12:58:59 +0330 Subject: [PATCH] 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. --- .gitattributes | 4 + app/calibrate_search.py | 176 +++ app/modules/knowledge/calibration.py | 104 ++ app/modules/knowledge/evidence.py | 98 ++ app/modules/knowledge/langchain_tool.py | 203 +++ app/modules/knowledge/lexical.py | 40 + app/modules/knowledge/service.py | 180 ++- data/calibration/phase2-source.md | 12 + docs/README.md | 6 +- docs/agent-reference-map.md | 265 +++- docs/calibration/phase2-cases.json | 115 ++ docs/calibration/phase2-status.json | 39 + docs/calibration/phase4-cases.draft.json | 741 +++++++++ docs/calibration/phase4-status.json | 1318 +++++++++++++++++ docs/guides/scoped-search-phase2-repairs.md | 99 ++ docs/guides/scoped-search-phase2.md | 170 +++ docs/guides/scoped-search-phase3.md | 206 +++ docs/guides/scoped-search-phase4.md | 253 ++++ docs/plans/live-document-mvp-todo.md | 39 +- .../scoped-search-implementation-plan.md | 70 +- docs/specifications/RAG-Phase1-API-Catalog.md | 2 +- pyproject.toml | 1 + tests/evaluate_search.py | 228 +++ tests/integration/test_search_phase2.py | 320 ++++ .../test_search_phase2_remaining.py | 94 ++ .../integration/test_search_phase2_repairs.py | 244 +++ tests/integration/test_search_phase3.py | 67 + tests/phase4_gate.py | 149 ++ tests/support/search.py | 2 +- tests/unit/test_search_phase2.py | 187 +++ tests/unit/test_search_phase2_remaining.py | 157 ++ tests/unit/test_search_phase2_repairs.py | 206 +++ tests/unit/test_search_phase3.py | 303 ++++ tests/unit/test_search_phase3_shutdown.py | 295 ++++ tests/unit/test_search_phase4_gate.py | 85 ++ tests/unit/test_search_phase4_repairs.py | 246 +++ 36 files changed, 6679 insertions(+), 45 deletions(-) create mode 100644 app/calibrate_search.py create mode 100644 app/modules/knowledge/calibration.py create mode 100644 app/modules/knowledge/evidence.py create mode 100644 app/modules/knowledge/langchain_tool.py create mode 100644 app/modules/knowledge/lexical.py create mode 100644 data/calibration/phase2-source.md create mode 100644 docs/calibration/phase2-cases.json create mode 100644 docs/calibration/phase2-status.json create mode 100644 docs/calibration/phase4-cases.draft.json create mode 100644 docs/calibration/phase4-status.json create mode 100644 docs/guides/scoped-search-phase2-repairs.md create mode 100644 docs/guides/scoped-search-phase2.md create mode 100644 docs/guides/scoped-search-phase3.md create mode 100644 docs/guides/scoped-search-phase4.md create mode 100644 tests/evaluate_search.py create mode 100644 tests/integration/test_search_phase2.py create mode 100644 tests/integration/test_search_phase2_remaining.py create mode 100644 tests/integration/test_search_phase2_repairs.py create mode 100644 tests/integration/test_search_phase3.py create mode 100644 tests/phase4_gate.py create mode 100644 tests/unit/test_search_phase2.py create mode 100644 tests/unit/test_search_phase2_remaining.py create mode 100644 tests/unit/test_search_phase2_repairs.py create mode 100644 tests/unit/test_search_phase3.py create mode 100644 tests/unit/test_search_phase3_shutdown.py create mode 100644 tests/unit/test_search_phase4_gate.py create mode 100644 tests/unit/test_search_phase4_repairs.py diff --git a/.gitattributes b/.gitattributes index 3f07983..fb50bfc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,6 @@ # Preserve immutable migration snapshots byte-for-byte across platforms. /migrations/versions/*.py -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol + +# Preserve calibration original bytes used by independently annotated hashes. +/data/calibration/phase2-source.md -text +/docs/calibration/phase2-cases.json text eol=lf diff --git a/app/calibrate_search.py b/app/calibrate_search.py new file mode 100644 index 0000000..0b4aa61 --- /dev/null +++ b/app/calibrate_search.py @@ -0,0 +1,176 @@ +"""Opt-in ten-query calibration against operator-bound approved originals.""" +import argparse +from dataclasses import asdict +import hashlib +import json +from pathlib import Path +import sys +import time +from uuid import UUID, uuid4 + +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError + +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 select_cutoff, validate_cases +from app.modules.knowledge.evidence import RETRIEVAL_POLICY, SearchExecution +from app.modules.knowledge.service import KnowledgeError, SearchService, authority, transaction, sql_error + +CASES_PATH = Path(__file__).resolve().parents[1] / "docs/calibration/phase2-cases.json" + + +class CountingProvider: + """Count actual adapter invocations without hiding dynamic adapter identity.""" + def __init__(self, provider): + self.provider = provider + self.calls = 0 + + @property + def profile(self): + return self.provider.profile + + @property + def request_policy(self): + return self.provider.request_policy + + def embed(self, texts): + self.calls += 1 + return self.provider.embed(texts) + + +def run(engine, settings, provider, counter, user_id, annotations, bindings): + cases = annotations["cases"] + validate_cases(cases) + execution = SearchExecution(user_id) + measured_provider = CountingProvider(provider) + service = SearchService(engine, settings, measured_provider, counter) + with transaction(engine) as conn: + current, snapshot = authority(conn, user_id) + execution.capture(current, snapshot["access_epoch"]) + for digest in {c["original_sha256"] for c in cases}: + document_id = UUID(bindings[digest]) + row = conn.execute(text(""" + SELECT id 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 + AND processing_profile->'embedding'=CAST(:profile AS jsonb) + """), dict(id=document_id, org=current["organization_id"], digest=digest, + profile=json.dumps(asdict(settings.embedding_profile)))).one_or_none() + if row is None: + raise KnowledgeError("CALIBRATION_BINDING_INVALID", "Approved original binding is not eligible") + observations = {} + for case in cases: + calls_before = measured_provider.calls + started = time.monotonic() + try: + result = service.candidates(execution, case["query"]) + if result["knowledge_revision"] != snapshot["knowledge_revision"]: + raise KnowledgeError("CONTEXT_REVOKED", "Calibration selection changed") + observations[case["id"]] = dict(status="completed", candidates=result["candidates"], + retrieval_policy=RETRIEVAL_POLICY, latency_seconds=time.monotonic() - started) + observations[case["id"]]["provider_calls"] = measured_provider.calls - calls_before + except KnowledgeError as exc: + observations[case["id"]] = dict(status="error", + error=dict(code=exc.code, message=str(exc), retryable=exc.retryable), + latency_seconds=time.monotonic() - started) + observations[case["id"]]["provider_calls"] = measured_provider.calls - calls_before + # An error is never counted as an unsupported success; stop remote work. + for remaining in cases: + observations.setdefault(remaining["id"], dict(status="error", + error=dict(code="NOT_RUN", message="Calibration stopped after technical error"))) + break + # Freeze/revalidate the full execution and selected corpus even after the last call. + finalization_error = None + try: + with transaction(engine) as conn: + final, settings_row = authority(conn, user_id) + if (not execution.capture(final, settings_row["access_epoch"]) + or settings_row["knowledge_revision"] != snapshot["knowledge_revision"]): + raise KnowledgeError("CONTEXT_REVOKED", "Calibration access or selection changed") + except KnowledgeError as exc: + if exc.code == "ACTOR_UNAVAILABLE": + exc = KnowledgeError("CONTEXT_REVOKED", "Actor access changed before calibration handoff") + finalization_error = dict(code=exc.code, message=str(exc), retryable=exc.retryable) + except SQLAlchemyError as exc: + failure = sql_error(exc) + finalization_error = dict(code=failure.code, message=str(failure), retryable=failure.retryable) + if finalization_error is not None: + # Keep completed observations' safe metrics/status, without any evidence + # whose final authorization could not be confirmed. + observations = {case["id"]: dict( + {key: value for key, value in observations[case["id"]].items() + if key in ("provider_calls", "latency_seconds", "retrieval_policy")}, + status="error", retrieval_status=observations[case["id"]]["status"], + error=dict(finalization_error), + **({"retrieval_error": observations[case["id"]]["error"]} + if "error" in observations[case["id"]] else {})) + for case in cases} + report = select_cutoff(cases, observations, bindings, settings.embedding_profile) + report.update(calibration_id=str(uuid4()), knowledge_revision=snapshot["knowledge_revision"], + access_epoch=snapshot["access_epoch"], organization_id=str(current["organization_id"]), + profile=asdict(settings.embedding_profile), retrieval_policy=RETRIEVAL_POLICY, + embedding_request=settings.processing_profile()["embedding_request"], + bindings=bindings, annotations=annotations, observations=observations, + provider_calls=measured_provider.calls, provider_call_budget=10, usage="unavailable", billing="unavailable") + report["final_authorization_confirmed"] = finalization_error is None + if finalization_error is not None: + report["finalization_error"] = finalization_error + # Preserve the frozen labels and original identity, not literal evidence. + report["annotations"] = dict( + original_file=annotations["original_file"], + original_sha256=annotations["original_sha256"], + cases=[{key: case[key] for key in ("id", "answerable", "original_sha256")} + for case in cases]) + return report + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--user-id", type=UUID, required=True) + parser.add_argument("--bindings", type=Path, required=True, + help="JSON original SHA-256 to selected document UUID mapping") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--allow-provider-calls", action="store_true", required=True, + help="Authorize at most ten configured compatible query embedding calls") + args = parser.parse_args(argv) + engine = None + try: + if args.output.exists() or not args.output.parent.is_dir(): + raise ValueError("A new report path in an existing directory is required") + annotation_bytes = CASES_PATH.read_bytes() + annotations = json.loads(annotation_bytes) + validate_cases(annotations["cases"]) + original = CASES_PATH.parent / annotations["original_file"] + if hashlib.sha256(original.read_bytes()).hexdigest() != annotations["original_sha256"]: + raise ValueError("Calibration original differs from frozen annotations") + bindings = json.loads(args.bindings.read_text(encoding="utf-8")) + settings = IngestionSettings() + from app.worker import factories + _, provider_factory = factories(settings) + provider, counter = provider_factory(settings.processing_profile()) + engine = create_database(settings.database_url.get_secret_value()) + report = run(engine, settings, provider, counter, args.user_id, annotations, bindings) + report["annotations_sha256"] = hashlib.sha256(annotation_bytes).hexdigest() + # Refuse overwrite: each real run retains its independent measurements. + with args.output.open("x", encoding="utf-8") as output: + json.dump(report, output, default=json_value, ensure_ascii=False, allow_nan=False, indent=2) + output.write("\n") + print(json.dumps(dict(status=report["status"], output=str(args.output), + complete_support=report.get("complete_support")), ensure_ascii=True)) + return 0 if report["status"] == "calibrated" else 1 + except KnowledgeError as exc: + print(json.dumps(dict(status="error", error=dict(code=exc.code, message=str(exc)))), file=sys.stderr) + return 1 + except Exception: + print(json.dumps(dict(status="error", error=dict(code="CALIBRATION_FAILED", + message="Verify approved original bindings, profile, database and output path"))), file=sys.stderr) + return 1 + finally: + if engine is not None: + engine.dispose() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/modules/knowledge/calibration.py b/app/modules/knowledge/calibration.py new file mode 100644 index 0000000..a9e4b48 --- /dev/null +++ b/app/modules/knowledge/calibration.py @@ -0,0 +1,104 @@ +"""Ten-case profile-specific cutoff selection, separate from held-out evaluation.""" +from dataclasses import asdict +import math +import re +import unicodedata + +from app.modules.knowledge.evidence import RETRIEVAL_POLICY, admit_candidates, CalibratedCutoff + + +def validate_cases(cases): + if (len(cases) != 10 or len({c["id"] for c in cases}) != 10 + or sum(c["answerable"] is True for c in cases) != 6 + or sum(c["answerable"] is False for c in cases) != 4): + raise ValueError("Exactly six answerable and four unsupported separate cases required") + for case in cases: + groups = case["evidence_groups"] + if (not case["query"].strip() or not case["original_sha256"] + or bool(groups) != case["answerable"] + or any(not g or any(not p.strip() for p in g) for g in groups)): + raise ValueError("Original-bound independent evidence annotations required") + + +def _token_character(character): + # Python's \w omits combining marks and format joiners used inside + # Unicode words. Treat those as continuations too, without normalizing + # or rewriting independently annotated literal evidence. + category = unicodedata.category(character) + return category[0] in "LNM" or category in ("Pc", "Cf") + + +def _literal_boundary(text, index, direction): + if not 0 <= index < len(text): + return True + character = text[index] + if _token_character(character) or character in "/-+\u066b\u066c": + return False + if character == ".": + outward = index + direction + # A sentence period is punctuation; a dot connecting token pieces + # extends a number, date or identifier. + return not (0 <= outward < len(text) and + (_token_character(text[outward]) or text[outward] in "./-")) + return True + + +def literal_annotation_matches(phrase, text): + return any(_literal_boundary(text, match.start() - 1, -1) + and _literal_boundary(text, match.end(), 1) + for match in re.finditer(re.escape(phrase), text)) + + +def complete_support(case, rows, document_id): + # Each evidence group must occur together in one faithful chunk of the + # annotated original, including all numbers, conditions and exceptions. + return all(any(str(row["document_id"]) == str(document_id) + and all(literal_annotation_matches(phrase, row["text"]) for phrase in group) + for row in rows) for group in case["evidence_groups"]) + + +def select_cutoff(cases, observations, bindings, profile): + validate_cases(cases) + if set(observations) != {c["id"] for c in cases}: + raise ValueError("Every case requires a completed retrieval observation") + if any(observations[c["id"]].get("status") == "error" for c in cases): + return dict(status="technical_error", cutoff=None, trials=[], cases=observations) + distances = {0.0} + for observation in observations.values(): + if observation["retrieval_policy"] != RETRIEVAL_POLICY: + raise ValueError("Calibration retrieval policy changed") + for row in observation["candidates"]: + distance = row["cosine_distance"] + if type(distance) not in (int, float) or not math.isfinite(distance): + raise ValueError("Calibration requires finite measured distances") + if 0 <= distance <= 2: + distances.add(distance) + trials = [] + best = None + for cutoff in sorted(distances): + results = [] + for case in cases: + rows = admit_candidates(observations[case["id"]]["candidates"], cutoff) + passed = (complete_support(case, rows, bindings[case["original_sha256"]]) + if case["answerable"] else not rows) + results.append(dict(id=case["id"], answerable=case["answerable"], passed=passed, + status="ok" if rows else "no_evidence", sources=rows)) + coverage = sum(r["passed"] for r in results if r["answerable"]) + false_positives = sum(not r["passed"] for r in results if not r["answerable"]) + trials.append(dict(distance=cutoff, complete_support=coverage, + unsupported_false_positives=false_positives)) + # Ascending cutoff traversal preserves the stricter cutoff on ties. + if false_positives == 0 and (best is None or coverage > best["complete_support"]): + best = dict(distance=cutoff, complete_support=coverage, results=results) + if best is None or best["complete_support"] == 0: + return dict(status="measured_failure", cutoff=None, trials=trials, cases=observations) + return dict(status="calibrated", cutoff=dict(profile=asdict(profile), + distance=best["distance"], retrieval_policy=RETRIEVAL_POLICY), + complete_support=best["complete_support"], + unsupported_false_positives=0, trials=trials, cases=best["results"]) + + +def load_cutoff(report): + if report.get("status") != "calibrated" or not report.get("calibration_id"): + raise ValueError("Successful measured calibration report required") + return CalibratedCutoff(**report["cutoff"], calibration_id=report["calibration_id"]) diff --git a/app/modules/knowledge/evidence.py b/app/modules/knowledge/evidence.py new file mode 100644 index 0000000..ed5b798 --- /dev/null +++ b/app/modules/knowledge/evidence.py @@ -0,0 +1,98 @@ +"""Backend-owned evidence admission, ordering and execution source identities.""" +from contextlib import contextmanager +from dataclasses import dataclass, field +import math +from threading import RLock +from uuid import UUID, uuid4 + +from app.modules.knowledge.lexical import LEXICAL_POLICY + +MAX_BRANCH_CANDIDATES = 50 +MAX_CHUNKS = 5 +MAX_EVIDENCE_CHARACTERS = 12000 +RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}" + + +def merge_candidates(semantic, exact): + by_id = {} + for row in semantic: + by_id[row["chunk_id"]] = dict(row, exact_match=False) + for row in exact: + by_id[row["chunk_id"]] = dict(row, exact_match=True) + return sorted(by_id.values(), key=lambda row: ( + not row["exact_match"], row["cosine_distance"], str(row["chunk_id"]))) + + +def admit_candidates(rows, cutoff=None): + admitted, used = [], 0 + for row in rows: + if cutoff is not None and row["cosine_distance"] > cutoff: + continue + size = len(row["text"]) + if size + used > MAX_EVIDENCE_CHARACTERS: + continue + admitted.append(row) + used += size + if len(admitted) == MAX_CHUNKS: + break + return admitted + + +@dataclass(frozen=True) +class CalibratedCutoff: + profile: dict + distance: float + calibration_id: str + retrieval_policy: str = RETRIEVAL_POLICY + + def __post_init__(self): + if (type(self.distance) not in (int, float) or not math.isfinite(self.distance) + or not 0 <= self.distance <= 2 or not self.calibration_id): + raise ValueError("Measured finite cosine cutoff and calibration identity required") + + +@dataclass +class SearchExecution: + """Created by the trusted caller, never populated from model arguments.""" + user_id: UUID + request_id: str = field(default_factory=lambda: str(uuid4())) + _authority: dict | None = field(default=None, init=False, repr=False) + _epoch: int | None = field(default=None, init=False, repr=False) + _refs: dict = field(default_factory=dict, init=False, repr=False) + _lock: RLock = field(default_factory=RLock, init=False, repr=False) + + def capture(self, current, epoch): + with self._lock: + if self._authority is None: + self._authority, self._epoch = dict(current), epoch + return self._authority == current and self._epoch == epoch + + def matches(self, current, epoch): + with self._lock: + return self._authority is not None and self._authority == current and self._epoch == epoch + + @contextmanager + def source_handoff(self): + """Stage reference mappings; publish only after authorized commit.""" + with self._lock: + prepared = dict(self._refs) + yield lambda rows: self._sources(rows, prepared) + self._refs = prepared + + def sources(self, rows): + with self._lock: + return self._sources(rows, self._refs) + + @staticmethod + def _sources(rows, refs): + sources = [] + for row in rows: + key = (row["document_id"], row["chunk_id"]) + if key not in refs: + refs[key] = f"S{len(refs) + 1}" + sources.append(dict(source_ref=refs[key], + document_id=str(row["document_id"]), chunk_id=str(row["chunk_id"]), + title=row["title"], text=row["text"], + location=dict(page=row["location"].get("page"), + section=row["location"].get("section")))) + return sources diff --git a/app/modules/knowledge/langchain_tool.py b/app/modules/knowledge/langchain_tool.py new file mode 100644 index 0000000..33951ef --- /dev/null +++ b/app/modules/knowledge/langchain_tool.py @@ -0,0 +1,203 @@ +"""Lazy LangChain boundary over the canonical search service.""" +import asyncio +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +import math +from threading import Condition, Event +import time + +from sqlalchemy.exc import SQLAlchemyError +from app.modules.knowledge.evidence import SearchExecution +from app.modules.knowledge.service import ( + KnowledgeError, SearchInput, authority, sql_error, transaction, +) + + +@dataclass(frozen=True) +class ToolContext: + """Backend-owned execution, absolute monotonic deadline and cancellation.""" + execution: SearchExecution + deadline: float + cancelled: Event = field(default_factory=Event) + + def __post_init__(self): + if not isinstance(self.execution, SearchExecution): + raise ValueError("Trusted SearchExecution required") + if type(self.deadline) not in (int, float) or not math.isfinite(self.deadline): + raise ValueError("Finite monotonic deadline required") + if not isinstance(self.cancelled, Event): + raise ValueError("Cancellation event required") + + +class SearchToolRunner: + """Share one runner across tools to enforce process-wide admission limits.""" + def __init__(self, *, running=4, waiting=8, timeout=75.0): + if type(running) is not int or running < 1 or type(waiting) is not int or waiting < 0: + raise ValueError("Positive running and nonnegative waiting limits required") + if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0: + raise ValueError("Finite positive timeout required") + self.running, self.waiting, self.timeout = running, waiting, timeout + self._lock = Condition() + self._admitted = self._active = 0 + self._closed = False + self._pool = ThreadPoolExecutor(max_workers=running, thread_name_prefix="knowledge-search") + + @staticmethod + def error(ctx, code, message, retryable=False): + return dict(status="error", sources=[], error=dict( + code=code, message=message, request_id=ctx.execution.request_id, + retryable=retryable)) + + def _stop(self, ctx, deadline, cancelled): + with self._lock: + if self._closed: + return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled: runner closed") + if ctx.cancelled.is_set() or cancelled.is_set(): + return self.error(ctx, "SEARCH_CANCELLED", "Knowledge retrieval cancelled") + if time.monotonic() >= deadline: + return self.error(ctx, "SEARCH_TIMEOUT", "Knowledge retrieval timed out", True) + + def _admit(self): + with self._lock: + if self._closed or self._admitted >= self.running + self.waiting: + return False + self._admitted += 1 + return True + + def _release(self, *, active=False): + with self._lock: + self._admitted -= 1 + if active: + self._active -= 1 + self._lock.notify_all() + + def _submit(self, service, ctx, query, context, deadline, cancelled): + with self._lock: + if self._active >= self.running or self._closed: + return None + self._active += 1 + try: + future = self._pool.submit( + self._work, service, ctx, query, context, deadline, cancelled) + except BaseException: + self._active -= 1 + raise + future.add_done_callback(lambda _: self._release(active=True)) + return future + + def _work(self, service, ctx, query, context, deadline, cancelled): + try: + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + return stopped + # Persisted authority is captured outside model input, on a worker. + with transaction(service.engine) as conn: + current, settings = authority(conn, ctx.execution.user_id) + if not ctx.execution.capture(current, settings["access_epoch"]): + raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed") + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + return stopped + result = service.search(ctx.execution, query, context) + if result["status"] != "error": + # Recheck this delivery boundary after the service handoff. + with transaction(service.engine) as conn: + current, settings = authority(conn, ctx.execution.user_id) + if not ctx.execution.matches(current, settings["access_epoch"]): + raise KnowledgeError("CONTEXT_REVOKED", "Knowledge access changed") + return self._stop(ctx, deadline, cancelled) or result + except KnowledgeError as exc: + code = "CONTEXT_REVOKED" if exc.code == "ACTOR_UNAVAILABLE" else exc.code + return self.error(ctx, code, str(exc), exc.retryable) + except SQLAlchemyError as exc: + error = sql_error(exc) + return self.error(ctx, error.code, str(error), error.retryable) + except Exception: + return self.error(ctx, "SEARCH_FAILED", "Knowledge retrieval failed") + + def invoke(self, service, ctx, query, context=None): + SearchInput(query=query, context=context) + deadline = min(ctx.deadline, time.monotonic() + self.timeout) + cancelled, future = Event(), None + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + return stopped + if not self._admit(): + return self._stop(ctx, deadline, cancelled) or self.error( + ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True) + try: + while True: + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + cancelled.set() + return stopped + if future is None: + future = self._submit(service, ctx, query, context, deadline, cancelled) + if future is not None and future.done(): + return self._stop(ctx, deadline, cancelled) or future.result() + time.sleep(min(0.01, max(0, deadline - time.monotonic()))) + finally: + if future is None: + self._release() + + async def ainvoke(self, service, ctx, query, context=None): + SearchInput(query=query, context=context) + deadline = min(ctx.deadline, time.monotonic() + self.timeout) + cancelled, future = Event(), None + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + return stopped + if not self._admit(): + return self._stop(ctx, deadline, cancelled) or self.error( + ctx, "SEARCH_SATURATED", "Knowledge retrieval capacity exhausted", True) + try: + while True: + stopped = self._stop(ctx, deadline, cancelled) + if stopped: + cancelled.set() + return stopped + if future is None: + future = self._submit(service, ctx, query, context, deadline, cancelled) + if future is not None and future.done(): + return self._stop(ctx, deadline, cancelled) or future.result() + await asyncio.sleep(min(0.01, max(0, deadline - time.monotonic()))) + except asyncio.CancelledError: + cancelled.set() + raise + finally: + if future is None: + self._release() + + def close(self): + """Permanently cancel callers and join work/admissions; safe to repeat. + + Closure and submission linearize under the same condition lock. Only + completion callbacks release submitted slots; queued callers release + their own admissions. Call from a control thread, outside the event + loop and this runner's worker pool, so callers can drain. + """ + with self._lock: + self._closed = True + self._pool.shutdown(wait=True) + with self._lock: + self._lock.wait_for(lambda: self._admitted == 0) + + +def create_search_tool(service, context, runner): + """Build only on explicit opt-in; core imports do not require LangChain.""" + from langchain_core.tools import StructuredTool + + trusted = context + + def search_knowledge(query: str, context: str | None = None): + return runner.invoke(service, trusted, query, context) + + async def asearch_knowledge(query: str, context: str | None = None): + return await runner.ainvoke(service, trusted, query, context) + + return StructuredTool.from_function( + func=search_knowledge, coroutine=asearch_knowledge, + name="search_knowledge", + description="Search authorized selected documents for evidence. Context is an untrusted retrieval hint.", + args_schema=SearchInput, + ) diff --git a/app/modules/knowledge/lexical.py b/app/modules/knowledge/lexical.py new file mode 100644 index 0000000..fdbd8ea --- /dev/null +++ b/app/modules/knowledge/lexical.py @@ -0,0 +1,40 @@ +"""Lexical comparisons only: faithful evidence and embedding inputs stay unchanged.""" +import re +import unicodedata + +TRANSLATE_FROM = "۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩كيى" +TRANSLATE_TO = "01234567890123456789کیی" +TRANSLATION = str.maketrans(TRANSLATE_FROM, TRANSLATE_TO) +LEXICAL_POLICY = "nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2" +# Python split() and PostgreSQL locale whitespace classes differ for NBSP. +# Bind the complete Unicode whitespace set used by Python str.split(). +WHITESPACE = "\t\n\v\f\r\x1c\x1d\x1e\x1f\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" +SQL_LEXICAL_PARAMS = dict(lexical_from=TRANSLATE_FROM + WHITESPACE, + lexical_to=TRANSLATE_TO + " " * len(WHITESPACE)) +SQL_LEXICAL_TEXT = ( + "regexp_replace(lower(translate(normalize(c.text, NFC), " + ":lexical_from, :lexical_to)), ' +', ' ', 'g')" +) +_TOKEN = re.compile(r"(? CAST(:vector AS vector) AS cosine_distance FROM document_chunks c @@ -202,17 +326,15 @@ class SearchService: AND d.status='ready' AND d.is_active AND d.deleted_at IS NULL AND d.content_purged_at IS NULL AND d.processing_profile->'embedding'=CAST(:profile AS jsonb) - ORDER BY cosine_distance,c.id LIMIT 50 - """), dict(org=final["organization_id"], vector=json.dumps(list(vector)), - profile=json.dumps(asdict(profile)))).mappings().all() - candidates, used = [], 0 - for row in rows: - if used + len(row["text"]) > 12000: - continue - candidates.append(dict(row)) - used += len(row["text"]) - if len(candidates) == 5: - break + """ + semantic = conn.execute(text(base + " ORDER BY cosine_distance,c.id LIMIT :branch_limit"), + params).mappings().all() + exact = [] + if patterns: + exact = conn.execute(text(base + " AND " + SQL_LEXICAL_TEXT + + " ~ ANY(CAST(:patterns AS text[])) ORDER BY cosine_distance,c.id LIMIT :branch_limit"), + params).mappings().all() return dict(kind="uncalibrated_candidates", semantic_quality="not_assessed", knowledge_revision=settings["knowledge_revision"], - access_epoch=settings["access_epoch"], candidates=candidates) + access_epoch=settings["access_epoch"], + candidates=merge_candidates(semantic, exact)) diff --git a/data/calibration/phase2-source.md b/data/calibration/phase2-source.md new file mode 100644 index 0000000..cce1700 --- /dev/null +++ b/data/calibration/phase2-source.md @@ -0,0 +1,12 @@ +ماده ۱: فشار پمپ ۲۵ بار است فقط وقتی دما کمتر از ۶۰ درجه باشد. شیر کنارگذر را باز نکنید مگر هنگام خاموشی. + +ماده ۲: دبی ۴۰ لیتر در دقیقه است مگر ورودی مسدود باشد. آب‌بندها را هر ۳۰ روز بازرسی کنید. + +ماده ۳: گشتاور ۱۵ نیوتن‌متر است. در صورت نشتی دستگاه را راه‌اندازی نکنید مگر پس از بازرسی. + +بخشنامه ۱۴۰۳/۰۷: شناسه K-1403/07 است و در تاریخ ۱۴۰۳/۰۷/۰۱ صادر شد. مهلت درخواست ۱۰ روز است فقط برای متقاضی دارای مجوز معتبر. + +ماده ۴: تخفیف ۱۲ درصد است برای درخواست‌های ثبت‌شده تا ۱۴۰۳/۰۸/۰۱. درخواست بدون مجوز مشمول نیست. + +ماده ۵: نگهداری تجهیز. +تبصره ۲: شناسه تجهیز PUMP-7 است. تعویض فیلتر فقط پس از قطع برق مجاز است؛ تجهیزات دارای نشتی مستثنا هستند. diff --git a/docs/README.md b/docs/README.md index ff6a34e..1959eeb 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,8 +31,10 @@ Implementation progress is tracked in the [Live document MVP TODO](plans/live-do Phase 5 worker/publication/retry and retained review/resume backend services are implemented; [Phase 6 operator handoff](guides/ingestion-operator-handoff.md) records integration acceptance and the separate opt-in provider smoke command. -Authenticated D06/D07 transport, scoped pgvector search/selection, HTTP -identity/upload, browser integration, Live and UI remain pending. Real-provider +Scoped pgvector search/selection and Fast-Track Search Phase 2 technical +correctness are implemented; [Phase 2 results and calibration prerequisites](guides/scoped-search-phase2.md) +record actual acceptance. Real-model cutoff calibration, LangChain, authenticated +D06/D07 transport, HTTP identity/upload, browser integration, Live and UI remain pending. Real-provider compatibility and Persian extraction/semantic quality are not certified by mocks. The [root README](../README.md) retains prototype startup instructions. diff --git a/docs/agent-reference-map.md b/docs/agent-reference-map.md index f8028f6..5d6f9c7 100644 --- a/docs/agent-reference-map.md +++ b/docs/agent-reference-map.md @@ -68,7 +68,7 @@ Prototype runtime prerequisites remain unverified: configured credentials, appro ## Gaps and decisions - Required document content is available under `specifications/`; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it. -- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, calibrated search/exact identifiers, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration. +- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, real-model search calibration, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration. - Open validations: exact format/size caps, funded model profiles/vector dimension, Gemini Live WSS/tool/transcript and Persian speech proof, hosting/connectivity, account/session/retention policy, quality target and delivery date. Direct Gemini Live, LangChain, new browser uploads, existing embedding reuse and all supplied example structures are confirmed MVP direction. See guide 13 and plan 2. Do not turn proposals into recorded approvals. - The 2026-10-06 MVP supersedes provisional SDP/WebRTC with backend-managed direct Gemini Live WSS; see API Section 7. Current-session provider answer transcripts/sources are displayed when available; durable full voice history remains deferred. Broader features do not authorize model selectors or CTI. - Project documentation now lives under `docs/`; sample corpus files remain under `data/documents/`. A future default corpus rebuild excludes the moved specifications and reference map. Existing vector indexes are not rebuilt or cleaned by this reorganization and may retain previously indexed project documentation. Use an approved corpus for real-provider evaluation. @@ -1363,3 +1363,266 @@ approved ready real-document/provider demonstration remains pending a reachable compatible ingestion database. This is provider-free database validation, not semantic-quality acceptance. Full regressions/calibration/LangChain/UI/Live/ANN were not run or built; Fast-Track phases 2-4 remain pending. + +## Fast-Track Search Phase 2 technical acceptance (2026-10-08) + +Current inventory supersedes the Phase 1 checkpoint's pending exact-matching and +canonical-outcome statements. [Shared core](../app/modules/knowledge/service.py) +now uses [comparison-only lexical normalization](../app/modules/knowledge/lexical.py), +[bounded merge/admission and execution references](../app/modules/knowledge/evidence.py), +[cutoff selection](../app/modules/knowledge/calibration.py) and an +[opt-in calibration CLI](../app/calibrate_search.py). The existing inspection CLI, +selection service, embedding preprocessing/provider adapter, publication path, +dependencies and all applied migrations remain preserved. + +See [Phase 2 operator guide](guides/scoped-search-phase2.md) for the actual +commands, boundaries, [ten independent annotations](calibration/phase2-cases.json), +[original fixture](../data/calibration/phase2-source.md) and +[pending real-model status](calibration/phase2-status.json). +Exact candidates cannot bypass calibrated admission. Canonical search refuses +an absent measured cutoff rather than inventing a universal threshold. +One SearchExecution pins actor/access epoch across calls and owns stable S +references. Remote embedding work holds no database connection. Every matching +branch applies all eligibility predicates before ranking/limits. + +Actual checks, with no real providers: +- Affected [unit](../tests/unit/test_search_phase2.py) and + [PostgreSQL](../tests/integration/test_search_phase2.py) tests plus the Phase 1 + scoped-search tests: **93 passed** (35 unit / 58 PostgreSQL), zero skips. +- Full provider-free suite: **1121 passed, 3 skipped, 266 deselected**. + Existing Windows symlink privilege cases account for the skips. +- Affected ingestion/publication PostgreSQL suites (test_phase5/test_phase6): + **91 passed**, zero skips. +- PostgreSQL **16.15** / pgvector **0.8.7**, existing isolated + rag-scoped-search-20261007 container, rag_scoped_search_test database, + 127.0.0.1:54938. Only disposable schemas were written. +- Dependency check, inspection/calibration CLI help, tracked diff and separate + AST/new-file whitespace/local-link inspection passed. All three migration + files compare byte-for-byte with HEAD. + +Bounded provider barriers prove removal and actor disablement suppress results. +Real Markdown/DOCX ingestion-to-search tests assert independent literal numbers, +conditions, negation, exceptions and actual locators. Publication barriers and +a failed final batch remain invisible/unselectable/unsearchable. Calibration +runner/bindings, actual ten-call bounds, complete-group coverage, zero unsupported +false positives and stricter-cutoff tie selection are covered provider-free. + +Phase 2 technical implementation is complete; its real-model calibration gate +is **pending**. No provider-call authorization or approved original/document +bindings were available. The configured Ollama bge-m3 / 1024 / v1 profile was +observed without invoking it. No cutoff or semantic-quality certification is +claimed. Phases 3/4, LangChain, full PostgreSQL regression and held-out quality +acceptance remain separate. + +## Current Phase 2 repair acceptance (2026-10-08) + +[Repair report](guides/scoped-search-phase2-repairs.md) supersedes the earlier +Phase 2 counts for current acceptance. Canonical service handoff now guards +admission and staged reference allocation at transaction commit; provider work +remains outside transactions. Terminal punctuation exact matching, retained +calibration finalization failures and explicit SQL retryability are repaired. +[Unit regressions](../tests/unit/test_search_phase2_repairs.py) and +[PostgreSQL regressions](../tests/integration/test_search_phase2_repairs.py) include +bounded candidate/admission barriers and exact recovery beyond 50 semantic rows. + +Actual results: 75 affected unit tests; 97 affected isolated PostgreSQL tests +with --require-postgres, zero skips; 1161 provider-free tests, three existing +Windows symlink skips and 305 deselected. pip check, both CLI help commands, +whitespace/new-file checks and migration byte-preservation passed. Unrelated +changes were preserved. No real provider calls or production cutoff: approved +bindings, explicit call authorization and real compatibility remain pending. +Future transport delivery and Phases 3/4 are outside this acceptance. + +## Current remaining Phase 2 repair acceptance (2026-10-08) + +[Current repair report](guides/scoped-search-phase2-repairs.md#remaining-two-repairs-current-acceptance-2026-10-08) +supersedes earlier test counts. Literal frozen-annotation matching rejects +numeric/date/identifier extensions while retaining whole-group and bound-document +checks. Confirmed SQLSTATE-less DBAPI connection invalidation is retryable; +permanent and unknown errors retain safe nonretryable classifications. No +automatic retries were added. + +[Unit regressions](../tests/unit/test_search_phase2_remaining.py) and +[real PostgreSQL disconnect regressions](../tests/integration/test_search_phase2_remaining.py) +cover candidate retrieval, canonical handoff and retained calibration failure +reports. Actual acceptance: 107 affected unit tests; 100 affected PostgreSQL +tests with --require-postgres and zero skips; 1193 provider-free tests, three +existing symlink skips and 308 deselected. pip check, CLI help, whitespace, +AST/local links, migration byte comparisons and unrelated/frozen baseline +preservation passed. The four earlier repairs and Phase 1 inspection path remain +intact. No real model calls or production cutoff; calibration prerequisites +and Phases 3/4 remain pending. + +## Fast-Track Search Phase 3 technical acceptance (2026-10-08) + +[Lazy LangChain adapter](../app/modules/knowledge/langchain_tool.py) delegates +directly to the canonical Phase 2 service. The dedicated `search` extra declares +only `langchain-core>=1,<2`; actual acceptance installed 1.6.7. +[Operator guide](guides/scoped-search-phase3.md) records schema, trusted context, +invocation, cancellation/deadline semantics and exact executed commands. + +Only query and optional context are model inputs, using the existing strict +SearchInput schema. ToolContext captures backend-owned execution/reference +state, absolute monotonic deadline and cancellation; persisted actor/epoch +capture/revalidation runs in the worker, outside model input. One shared runner +allows four running/eight waiting calls with a 75-second total deadline. +Queue waiting consumes the deadline; async waiting uses no executor thread. +Running work holds its slot until actual completion after timeout/cancellation. +Saturation/deadline/cancellation remain canonical technical errors. +No new retrieval, provider pipeline, text agent, Live dispatch or schema +migration was introduced; the diagnostic CLI remains uncalibrated. + +Executed checks: +- Search extra installation and pip check passed. +- [41 new unit tests](../tests/unit/test_search_phase3.py) plus affected search + unit regressions: **148 passed**, zero skips. +- [Three new PostgreSQL tests](../tests/integration/test_search_phase3.py) plus + affected scoped/Phase 2/repair acceptance: **103 passed**, zero skips, + with --require-postgres. +- Fresh isolated rag-search-phase3-20261008 container, rag_phase3_test database, + 127.0.0.1:54939; prerequisite probe: PostgreSQL **16.15**, pgvector **0.8.7**. + Only disposable test schemas were written. +- Sync/async actual StructuredTool invocation produced the same faithful pump + evidence/document/chunk/locator and stable S1 as the shared canonical service; + inspection candidate identities agreed. Foreign hints granted no scope; + persisted selection removal revoked subsequent pinned-execution calls. +- Event-loop responsiveness, default four/eight saturation, queued/running + timeout/cancellation, retained running slots, strict forged/unknown fields, + canonical results and framework-blocked fresh-process lazy imports passed. +- Tracked diff, new-file AST/whitespace, local guide links and applied-migration + byte-preservation checks passed; unrelated work was preserved. + +No real providers were called. Phase 3 technical integration is complete. +Phase 2 real-model calibration and Phase 4 frozen Persian held-out quality +acceptance remain pending approved bindings/access/explicit call authorization. +Full provider-free and mandatory isolated PostgreSQL regression acceptance +remains part of the final Phase 4 checkpoint, not a Phase 3 readiness claim. + +## Phase 3 runner shutdown repair acceptance (2026-10-08) + +This checkpoint supersedes the initial Phase 3 shutdown behavior only. +[Runner](../app/modules/knowledge/langchain_tool.py) now recognizes permanent +closure in stop checks and after rejected admissions, returning existing +canonical SEARCH_CANCELLED with empty sources and retryable:false. +[Operator guide](guides/scoped-search-phase3.md#shutdown-repair-acceptance-2026-10-08) +documents shutdown priority, races and the blocking close lifecycle. + +Closure/admission/submission share a condition lock. Closure prevents queued +submission; already submitted work owns its running/admission slots until the +actual completion callback releases them. Queued callers promptly cancel and +release their own admissions once. After executor join, close waits for queued +admissions to drain; it returns with active/admitted zero and is safe to repeat, +including concurrently. A submitted worker observing closure before I/O starts +performs no provider/database work. Previously delivered results cannot be +recalled; final delivery checks suppress results when closure wins. +Call blocking close from a control thread outside active event loops and this +runner's worker pool, keeping queued callers schedulable until they drain. + +[Fourteen event-barrier regressions](../tests/unit/test_search_phase3_shutdown.py) +cover sync/async queued shutdown, post-close/expired invocations, concurrent +repeat close, admission/submission and completion/callback races, exact releases, +no queued I/O and retention of actual running work. All waits are bounded; +there are no sleep-based ordering assertions in the new tests. + +Actual checks: +- Before repair, six selected reproduction cases failed (six deselected in + the initial test set): queued calls stayed pending and closed calls returned + SEARCH_SATURATED/SEARCH_TIMEOUT. +- Actual LangChain tests with installed declared extra (1.6.7): **55 passed**, + zero skips. Existing cancellation/deadline/lazy import/schema/delegation + acceptance remains intact. +- Affected search unit regressions: **162 passed**, zero skips. +- Affected search PostgreSQL acceptance with --require-postgres: + **103 passed**, zero skips. +- Fresh rag-phase3-shutdown-20261008 container, rag_shutdown_test database, + 127.0.0.1:54939; prerequisite probe passed PostgreSQL **16.15** / + pgvector **0.8.7**. Only disposable schemas were written. +- pip check, tracked/new-file whitespace, AST, local documentation links and + byte-for-byte comparison of all applied migrations passed. +- Unrelated changes were left untouched. Baseline comparison observed a + concurrent change to scripts/live_voice_server.py; this repair did not edit it. + +Only runner shutdown, its new unit tests, the operator guide, this reference +record and the plan were changed by the repair. No real providers, calibration, +Phase 4, Live or HTTP work was performed. Blocking shutdown still waits for +actual blocking work and needs active queued caller loops to progress. +Full repository regressions and real-model/held-out quality gates remain +separate unrun acceptance. + +Shutdown test cleanup: zero disposable schemas and zero public tables remained. +The verified rag-phase3-shutdown-20261008 container and its anonymous volume +were removed; all pre-existing containers were preserved. + + +## Historical Fast-Track Search Phase 4 preparatory acceptance (2026-10-08) + +[Phase 4 operator guide](guides/scoped-search-phase4.md) and +[status](calibration/phase4-status.json) retain the historical preparatory technical +regressions: 1258 provider-free tests passed, three existing Windows symlink +skips, and 311 isolated PostgreSQL tests passed with --require-postgres and zero +skips. The fresh rag-phase4-acceptance-20261008 container used rag_phase4_test on +127.0.0.1:54940, PostgreSQL 16.15 / pgvector 0.8.7. No deployment database writes. +pip check, tracked/new-file whitespace, AST/JSON and byte-preservation of all +three applied migrations passed. + +[Draft independent annotations](calibration/phase4-cases.draft.json) cover both +original PDFs, the visually inspected infographic and factual DOCX candidates: +16 answerable, six unsupported, and four unseen slots without invented evidence. +Approval, DOCX human inclusion and actual hash/document bindings are pending. +The [opt-in evaluator](../tests/evaluate_search.py) is outside pytest and +delegates to the existing canonical service with a measured Phase 2 cutoff, +bounded calls, checked bindings/sources, flushed per-case records and the exact +18/20 + all-critical + 6/6-unsupported gate. +[Ten deterministic regressions](../tests/unit/test_search_phase4_gate.py) test +scoring/preflight/budget safety only; they do not establish model quality. + +Real evaluation: zero cases, zero provider calls. The local Phase 2 cutoff is +still null; funded-profile approval, explicit call opt-in/budget, unseen +originals, required human review and actual eligible bindings are unavailable. +Quality acceptance remains not run. No production defects were silently fixed. +No retrieval, generated-answer or Live readiness is certified. + +Cleanup confirmed zero disposable schemas and zero public tables. The created +Phase 4 test container and its anonymous volume were removed; existing containers +were preserved. Temporary original-page renderings were removed. Baseline +comparison found a concurrent change to scripts/live_voice_server.py, which this +evaluation did not edit. All other unrelated baseline files were unchanged. + + +## Current Phase 4 annotation/independence repair checks (2026-10-08) + +[Repair guide](guides/scoped-search-phase4.md) and +[current status](calibration/phase4-status.json) supersede the preparatory +checkpoint for current repair validation. All 22 populated draft annotations +(16 answerable / six unsupported) were reconstructed from actual originals, +persisted as UTF-8, strictly read back and synchronized with status expected +records. Zero unresolved annotations. Hashes, approvals, null bindings and four +empty unseen slots remain unchanged. + +[Evaluator](../tests/evaluate_search.py) now checks question separation using +[comparison-only validation](../tests/phase4_gate.py) against the supplied full +Phase 2 calibration annotations before settings/database/provider setup. +Missing/malformed annotations and exact/Unicode-formatting-equivalent overlap +fail closed with safe actionable diagnostics. Different questions may share +documents; evidence literals/retrieval preprocessing and all gate thresholds +remain unchanged. +[Repair regressions](../tests/unit/test_search_phase4_repairs.py) include original +DOCX literal/source checks, persisted corruption detection, legitimate punctuation, +exact/equivalent overlaps, distinct shared-source questions and setup barriers. + +Executed: **52 targeted passed**, zero skips; **1300 provider-free passed**, +three existing Windows symlink skips, 311 deselected; pip check, whitespace, +AST/JSON, UTF-8 read-back and all three applied migration comparisons passed. +Mandatory isolated PostgreSQL **not run** because TEST_DATABASE_URL is absent; +previous database acceptance remains historical. No providers were run. + +Phase 4 quality acceptance is still not_run. Measured cutoff, approved funded +profile/call budget, approved original/FAQ decisions, actual eligible bindings +and four unseen annotations remain pending. No retrieval, generated-answer or +Live readiness is claimed. + +Final preservation inspection observed a change to scripts/live_voice_server.py +outside this repair. It was left untouched; all other unrelated baseline files +were unchanged. All three applied migrations match HEAD byte-for-byte. Local +documentation links and new-file inspection passed. Existing intentional Markdown +hard breaks were preserved. Temporary original-image inspection files were removed. diff --git a/docs/calibration/phase2-cases.json b/docs/calibration/phase2-cases.json new file mode 100644 index 0000000..9241680 --- /dev/null +++ b/docs/calibration/phase2-cases.json @@ -0,0 +1,115 @@ +{ + "original_file": "../../data/calibration/phase2-source.md", + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f", + "annotation_basis": "Literal original paragraphs authored before retrieval; quantities and all qualifiers independently marked. Calibration only, separate from Phase 4.", + "cases": [ + { + "id": "A1", + "answerable": true, + "query": "شرط فشار پمپ در ماده ۱ و استثنای شیر کنارگذر چیست؟", + "evidence_groups": [ + [ + "۲۵ بار", + "فقط وقتی دما کمتر از ۶۰ درجه", + "باز نکنید", + "مگر هنگام خاموشی" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "A2", + "answerable": true, + "query": "ماده ۲ درباره دبی و زمان بازرسی آب‌بندها چه می‌گوید؟", + "evidence_groups": [ + [ + "۴۰ لیتر در دقیقه", + "مگر ورودی مسدود باشد", + "هر ۳۰ روز" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "A3", + "answerable": true, + "query": "گشتاور و ممنوعیت راه‌اندازی در ماده ۳ چیست؟", + "evidence_groups": [ + [ + "۱۵ نیوتن‌متر", + "در صورت نشتی", + "راه‌اندازی نکنید", + "مگر پس از بازرسی" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "A4", + "answerable": true, + "query": "تاریخ و مهلت درخواست بخشنامه K-1403/07 با شرط آن چیست؟", + "evidence_groups": [ + [ + "۱۴۰۳/۰۷/۰۱", + "۱۰ روز", + "فقط برای متقاضی دارای مجوز معتبر" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "A5", + "answerable": true, + "query": "در ماده ۴ میزان تخفیف، تاریخ و استثنا چیست؟", + "evidence_groups": [ + [ + "۱۲ درصد", + "تا ۱۴۰۳/۰۸/۰۱", + "درخواست بدون مجوز مشمول نیست" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "A6", + "answerable": true, + "query": "تعویض فیلتر PUMP-7 در تبصره ۲ چه شرط و استثنایی دارد؟", + "evidence_groups": [ + [ + "PUMP-7", + "فقط پس از قطع برق", + "تجهیزات دارای نشتی مستثنا هستند" + ] + ], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "U1", + "answerable": false, + "query": "قیمت فعلی زمین صنعتی چقدر است؟", + "evidence_groups": [], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "U2", + "answerable": false, + "query": "موجودی حساب مشتری با شناسه ACCOUNT-99 چقدر است؟", + "evidence_groups": [], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "U3", + "answerable": false, + "query": "استثنای تمدید در ماده ۹۹ چیست؟", + "evidence_groups": [], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + }, + { + "id": "U4", + "answerable": false, + "query": "نرخ ارز در تاریخ ۱۴۰۴/۰۱/۰۱ چقدر است؟", + "evidence_groups": [], + "original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f" + } + ] +} diff --git a/docs/calibration/phase2-status.json b/docs/calibration/phase2-status.json new file mode 100644 index 0000000..03d52b4 --- /dev/null +++ b/docs/calibration/phase2-status.json @@ -0,0 +1,39 @@ +{ + "status": "pending", + "date": "2026-10-08", + "cutoff": null, + "provider_calls": 0, + "configured_profile": { + "provider": "ollama", + "endpoint": "http://localhost:11434/v1", + "model": "bge-m3", + "dimensions": 1024, + "preprocessing_version": "v1" + }, + "calibration_cases": { + "answerable": 6, + "unsupported": 4, + "annotations": "docs/calibration/phase2-cases.json", + "original": "data/calibration/phase2-source.md" + }, + "missing_prerequisites": [ + "explicit_authorization_for_real_provider_calls", + "approved_original_to_selected_document_bindings", + "verified_compatible_real_ingestion_database_and_provider" + ], + "selection_rule": "Maximize complete-support coverage with zero unsupported false positives; stricter cutoff on ties.", + "model_quality_acceptance": "pending", + "technical_tests": "provider-free; current repairs recorded in docs/guides/scoped-search-phase2-repairs.md", + "technical_repair_status": "verified", + "technical_repair_results": { + "affected_unit_passed": 107, + "affected_postgres_passed": 100, + "provider_free_passed": 1193, + "provider_free_skipped": 3, + "provider_free_deselected": 308 + }, + "latest_repairs": [ + "literal_frozen_annotation_boundaries", + "confirmed_sqlstate_less_connection_invalidation" + ] +} diff --git a/docs/calibration/phase4-cases.draft.json b/docs/calibration/phase4-cases.draft.json new file mode 100644 index 0000000..79abdd0 --- /dev/null +++ b/docs/calibration/phase4-cases.draft.json @@ -0,0 +1,741 @@ +{ + "status": "incomplete_not_frozen", + "date": "2026-10-08", + "originals": { + "letter": { + "path": "data/documents/5905170444656189186_13450510740952.pdf", + "sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "document_id": null, + "approval": "pending" + }, + "regulation": { + "path": "data/documents/7364346504113364738_13450847753183.pdf", + "sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "document_id": null, + "approval": "pending" + }, + "infographic": { + "path": "data/documents/photo_1_2026-10-06_09-05-11.jpg", + "sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "document_id": null, + "approval": "pending" + }, + "docx": { + "path": "data/documents/-2348240626507047168_13449360743721.docx", + "sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "document_id": null, + "approval": "pending" + } + }, + "cases": [ + { + "id": "A01", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "مشوق دهه فجر کدام بخش قرارداد واگذاری حق بهره‌برداری زمین را کاهش می‌دهد و میزان کاهش چقدر است؟", + "evidence_groups": [ + [ + "کاهش بخش نقدی", + "پیش دریافت", + "قراردادهای واگذاری حق بهره برداری زمین", + "۱۰", + "درصد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Reduction of cash advance only; no total-price discount inferred.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A02", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "برای برخورداری از مشوق دهه فجر، قرارداد واگذاری باید در چه بازه زمانی منعقد شود؟", + "evidence_groups": [ + [ + "از تاریخ", + "۱۲", + "بهمن تا پایان بهمن سال", + "۱۴۰۴", + "منعقد گردد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Contract conclusion within the stated window; not upload date.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A03", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "آیا قراردادهای انصرافی مشمول مشوق دهه فجر هستند و قید زمانی استثنا چیست؟", + "evidence_groups": [ + [ + "قراردادهای انصرافی", + "از تاریخ ابلاغ این مصوبه", + "مشمول این مشوق نمی گردند" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Exclusion applies from notification date.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A04", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "آیا اراضی و مستحدثات واگذارشده به شیوه مزایده از مشوق دهه فجر برخوردارند؟", + "evidence_groups": [ + [ + "اراضی و مستحدثاتی", + "وفق مصوبه هیات مدیره شرکت استانی", + "به شیوه مزایده واگذار می شوند", + "مشمول این مشوق نمی گردند" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Preserve provincial board resolution qualifier and negation.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A05", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "قیمت و بازپرداخت اقساط قراردادهای مشمول مشوق دهه فجر تابع کدام ماده و مصوبه معتبر است؟", + "evidence_groups": [ + [ + "قیمت و بازپرداخت اقساط", + "ماده", + "۸", + "دستورالعمل بهره برداری" + ], + [ + "مصوبه هیات مدیره شرکت استانی", + "در شش ماه دوم سال جاری معتبر میباشد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Both article and valid provincial resolution; not a new instalment rate.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A06", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۵ چه حد نصابی برای واگذاری زمین و تعداد واحدهای بهره‌بردار شهرک صنعتی و ناحیه صنعتی روستایی تعیین کرده است؟", + "evidence_groups": [ + [ + "بیش از هفتاد و پنج درصد", + "زمین های قابل واگذاری", + "فاز عملیاتی", + "واگذار" + ], + [ + "حداقل تعداد واحدهای به بهره برداری رسیده", + "در شهرک صنعتی به بیست و پنج واحد", + "در ناحیه صنعتی روستایی به پانزده واحد" + ], + [ + "بر اساس شرایط مندرج در اساسنامه نمونه", + "تشکیل شرکت خدماتی" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Strictly greater than 75%; 25 industrial-town/15 rural-area operating units.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A07", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۶ در چه شرایطی شرکت را موظف به تشکیل شرکت خدماتی می‌کند؟", + "evidence_groups": [ + [ + "حداقل هفتاد و پنج درصد", + "زمین های قابل واگذاری", + "واگذار" + ], + [ + "حداقل پنجاه درصد", + "واحدهای مستقر", + "با هر تعداد به بهره برداری رسیده باشد", + "موظف به تشکیل شرکت خدماتی" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۶ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "At least 75% land and at least 50% resident units operating; any unit count.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A08", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "طبق تبصره ماده ۵، پیش از تشکیل شرکت خدماتی چه کسی امور شهرک و ناحیه صنعتی را اداره می‌کند؟", + "evidence_groups": [ + [ + "تا قبل از تشکیل شرکت خدماتی", + "اداره امور شهرک و ناحیه صنعتی", + "توسط شرکت صورت می گیرد" + ] + ], + "locator": { + "page": 3, + "section": "تبصره ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Before service company formation only.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A09", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۸ پرداخت هزینه شرکت خدماتی را تا چه مدت مجاز می‌داند و کسر هزینه پس از تشکیل شرکت چگونه است؟", + "evidence_groups": [ + [ + "می توانند حداکثر دو ماه", + "هزینه های شرکت خدماتی" + ], + [ + "پس از تشکیل شرکت خدماتی", + "منطبق با اساسنامه شرکت", + "از هزینه های مشترک قابل پرداخت توسط شرکت کسر نمایند" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۸ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Maximum two months, permissible rather than mandatory.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A10", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "اگر ساخت‌وساز غیرمجاز مالک یا متصرف قانونی به مشاعات خسارت بزند، ماده ۴ چه تکلیفی در حالت توافق و عدم توافق مقرر می‌کند؟", + "evidence_groups": [ + [ + "ساخت و ساز غیرمجاز مالک یا متصرف قانونی", + "قسمتی از مشاعات", + "از بین رفته و یا تخریب گردد" + ], + [ + "از طریق توافق", + "جبران خسارت وارده", + "اعاده وضع به حال سابق" + ], + [ + "در صورت عدم توافق", + "جبران خسارت و اعاده وضع به حال سابق", + "مطابق قوانین و مقررات مربوط" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۴" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Keep negotiated remedy and fallback legal process.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A11", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "شش محور اصلاح نظام اداری دولت چهاردهم در تصویر کدام‌اند؟", + "evidence_groups": [ + [ + "چابک‌سازی و تمرکززدایی ساختاری" + ], + [ + "مدیریت شایسته محور سرمایه انسانی" + ], + [ + "ارتقای سلامت اداری و مقابله با فساد" + ], + [ + "استقرار دولت هوشمند و داده‌محور" + ], + [ + "مدیریت عملکرد نتیجه گرا" + ], + [ + "ارتقای بهره‌وری ملی و انرژی" + ] + ], + "locator": { + "page": null, + "section": "شش محور؛ دو ستون تحول در ساختار و سرمایه انسانی و هوشمندسازی و ارتقای بهره‌وری" + }, + "critical": false, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Six axes across both image columns; no invented numerical target.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A12", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "محور ارتقای سلامت اداری و مقابله با فساد چه اقداماتی را درباره تعارض منافع مطرح می‌کند؟", + "evidence_groups": [ + [ + "شفافیت", + "پاسخگویی", + "پیشگیری از وقوع موقعیت" + ], + [ + "تعارض منافع", + "دستگاه‌های اجرایی" + ] + ], + "locator": { + "page": null, + "section": "ارتقای سلامت اداری و مقابله با فساد؛ پایین ستون چپ" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Prevention of conflict-of-interest situations; not a guarantee of elimination.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A13", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "در محور مدیریت عملکرد نتیجه‌گرا، نظام جبران خدمت و پاداش‌ها به چه چیزی متصل می‌شود؟", + "evidence_groups": [ + [ + "اتصال نظام جبران خدمت و پاداش‌ها به", + "نتایج واقعی ارزیابی عملکرد" + ] + ], + "locator": { + "page": null, + "section": "مدیریت عملکرد نتیجه گرا؛ میانه ستون راست" + }, + "critical": false, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Original infographic states connection of compensation and rewards to actual performance-evaluation results; no claim about a redesigned measurement system.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A14", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "در فایل اصلی ساعت کاری شنبه تا چهارشنبه و پنجشنبه چیست و هنگام تعطیلی یا تغییر ساعات اداری چه ملاکی حاکم است؟", + "evidence_groups": [ + [ + "از شنبه تا چهارشنبه از ساعت 8 صبح الي 13", + "در روزپنجشنبه از 8 صبح الي 12" + ], + [ + "در روزهای تعطیل یا تغییر ساعات اداری، آخرین ابلاغ شرکت ملاک است." + ] + ], + "locator": { + "page": null, + "section": "سؤال ساعت کاری؛ پاسخ در بند ۳ فایل اصلی" + }, + "critical": true, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; human authority/inclusion approval absent. Latest official notice governs.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A15", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "برای پیگیری امور انفورماتیک در فایل اصلی نام مخاطب و شماره داخلی چیست؟", + "evidence_groups": [ + [ + "سرکار خانم آذری، داخلی ۲۹۰" + ] + ], + "locator": { + "page": null, + "section": "سؤال امور انفورماتیک؛ پاسخ در بند ۱۱ فایل اصلی" + }, + "critical": true, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; not approved for publication.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "A16", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "نشانی شرکت در پاسخ مربوط به آدرس در فایل اصلی چیست؟", + "evidence_groups": [ + [ + "خ 22 بهمن ، مجموعه اداري امير كبير (غدير)" + ] + ], + "locator": { + "page": null, + "section": "سؤال آدرس شرکت؛ پاسخ در بند ۷ فایل اصلی" + }, + "critical": false, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; not independently verified as current address.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U01", + "answerable": false, + "query": "قیمت روز هر متر زمین محمودآباد چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No approved current tariff; DOCX demands current data, gives no price.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U02", + "answerable": false, + "query": "موجودی لحظه‌ای زمین محمودآباد چند مترمربع است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No live inventory in supplied originals.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U03", + "answerable": false, + "query": "بدهی فعلی شرکت فلان در پرونده صنعتی چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No authorized case database/evidence; never use behavioral DOCX replies as factual case data.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U04", + "answerable": false, + "query": "در تصویر اصلاح نظام اداری، هدف عددی کاهش مصرف انرژی چند درصد است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "Infographic gives an axis, not a numeric energy target.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U05", + "answerable": false, + "query": "شماره موبایل مدیرعامل فلان کارخانه چیست؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No approved personal contact evidence.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + { + "id": "U06", + "answerable": false, + "query": "میزان مشوق قراردادهای منعقدشده پس از پایان بهمن ۱۴۰۴ چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "Letter concerns 1404 conclusion window; no 1406 percentage.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + } + ], + "pending_answerable_slots": [ + { + "id": "A17", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + { + "id": "A18", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + { + "id": "A19", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + { + "id": "A20", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + } + ], + "required_gate": { + "answerable_total": 20, + "answerable_minimum": 18, + "all_critical": true, + "unsupported_total": 6, + "all_unsupported": true, + "no_ineligible_sources": true + }, + "annotation_caveat": "Original-derived draft transcriptions, not search output. Resolve literal rendering differences against originals before freezing; never weaken labels after retrieval. DOCX facts are pending human factual-corpus approval. Unsupported labels must be rechecked against complete approved unseen corpus before freeze.", + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "annotation_repair": { + "status": "reconstructed_from_originals", + "answerable_reconstructed": 16, + "unsupported_reconstructed": 6, + "unresolved": [], + "persisted_encoding": "UTF-8", + "human_approvals_changed": false + } +} diff --git a/docs/calibration/phase4-status.json b/docs/calibration/phase4-status.json new file mode 100644 index 0000000..4e4e388 --- /dev/null +++ b/docs/calibration/phase4-status.json @@ -0,0 +1,1318 @@ +{ + "date": "2026-10-08", + "status": "quality_not_run", + "technical_gate": "provider_free_repairs_passed_postgres_not_run", + "quality_gate": "not_run", + "retrieval_ready": false, + "generated_answer_readiness": "not_evaluated", + "live_readiness": "not_evaluated", + "executed_cases": 0, + "answerable_executed": 0, + "unsupported_executed": 0, + "answerable_annotated": 16, + "unseen_pending": 4, + "unsupported_draft": 6, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "cutoff": null, + "approved_original_document_bindings": null, + "annotations": "docs/calibration/phase4-cases.draft.json", + "operator_guide": "docs/guides/scoped-search-phase4.md", + "missing_prerequisites": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ], + "observations": [ + { + "id": "A01", + "status": "not_run", + "passed": null, + "expected": { + "id": "A01", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "مشوق دهه فجر کدام بخش قرارداد واگذاری حق بهره‌برداری زمین را کاهش می‌دهد و میزان کاهش چقدر است؟", + "evidence_groups": [ + [ + "کاهش بخش نقدی", + "پیش دریافت", + "قراردادهای واگذاری حق بهره برداری زمین", + "۱۰", + "درصد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Reduction of cash advance only; no total-price discount inferred.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A02", + "status": "not_run", + "passed": null, + "expected": { + "id": "A02", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "برای برخورداری از مشوق دهه فجر، قرارداد واگذاری باید در چه بازه زمانی منعقد شود؟", + "evidence_groups": [ + [ + "از تاریخ", + "۱۲", + "بهمن تا پایان بهمن سال", + "۱۴۰۴", + "منعقد گردد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Contract conclusion within the stated window; not upload date.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A03", + "status": "not_run", + "passed": null, + "expected": { + "id": "A03", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "آیا قراردادهای انصرافی مشمول مشوق دهه فجر هستند و قید زمانی استثنا چیست؟", + "evidence_groups": [ + [ + "قراردادهای انصرافی", + "از تاریخ ابلاغ این مصوبه", + "مشمول این مشوق نمی گردند" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Exclusion applies from notification date.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A04", + "status": "not_run", + "passed": null, + "expected": { + "id": "A04", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "آیا اراضی و مستحدثات واگذارشده به شیوه مزایده از مشوق دهه فجر برخوردارند؟", + "evidence_groups": [ + [ + "اراضی و مستحدثاتی", + "وفق مصوبه هیات مدیره شرکت استانی", + "به شیوه مزایده واگذار می شوند", + "مشمول این مشوق نمی گردند" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Preserve provincial board resolution qualifier and negation.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A05", + "status": "not_run", + "passed": null, + "expected": { + "id": "A05", + "answerable": true, + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "query": "قیمت و بازپرداخت اقساط قراردادهای مشمول مشوق دهه فجر تابع کدام ماده و مصوبه معتبر است؟", + "evidence_groups": [ + [ + "قیمت و بازپرداخت اقساط", + "ماده", + "۸", + "دستورالعمل بهره برداری" + ], + [ + "مصوبه هیات مدیره شرکت استانی", + "در شش ماه دوم سال جاری معتبر میباشد" + ] + ], + "locator": { + "page": 1 + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Both article and valid provincial resolution; not a new instalment rate.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A06", + "status": "not_run", + "passed": null, + "expected": { + "id": "A06", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۵ چه حد نصابی برای واگذاری زمین و تعداد واحدهای بهره‌بردار شهرک صنعتی و ناحیه صنعتی روستایی تعیین کرده است؟", + "evidence_groups": [ + [ + "بیش از هفتاد و پنج درصد", + "زمین های قابل واگذاری", + "فاز عملیاتی", + "واگذار" + ], + [ + "حداقل تعداد واحدهای به بهره برداری رسیده", + "در شهرک صنعتی به بیست و پنج واحد", + "در ناحیه صنعتی روستایی به پانزده واحد" + ], + [ + "بر اساس شرایط مندرج در اساسنامه نمونه", + "تشکیل شرکت خدماتی" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Strictly greater than 75%; 25 industrial-town/15 rural-area operating units.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A07", + "status": "not_run", + "passed": null, + "expected": { + "id": "A07", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۶ در چه شرایطی شرکت را موظف به تشکیل شرکت خدماتی می‌کند؟", + "evidence_groups": [ + [ + "حداقل هفتاد و پنج درصد", + "زمین های قابل واگذاری", + "واگذار" + ], + [ + "حداقل پنجاه درصد", + "واحدهای مستقر", + "با هر تعداد به بهره برداری رسیده باشد", + "موظف به تشکیل شرکت خدماتی" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۶ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "At least 75% land and at least 50% resident units operating; any unit count.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A08", + "status": "not_run", + "passed": null, + "expected": { + "id": "A08", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "طبق تبصره ماده ۵، پیش از تشکیل شرکت خدماتی چه کسی امور شهرک و ناحیه صنعتی را اداره می‌کند؟", + "evidence_groups": [ + [ + "تا قبل از تشکیل شرکت خدماتی", + "اداره امور شهرک و ناحیه صنعتی", + "توسط شرکت صورت می گیرد" + ] + ], + "locator": { + "page": 3, + "section": "تبصره ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Before service company formation only.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A09", + "status": "not_run", + "passed": null, + "expected": { + "id": "A09", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "ماده ۸ پرداخت هزینه شرکت خدماتی را تا چه مدت مجاز می‌داند و کسر هزینه پس از تشکیل شرکت چگونه است؟", + "evidence_groups": [ + [ + "می توانند حداکثر دو ماه", + "هزینه های شرکت خدماتی" + ], + [ + "پس از تشکیل شرکت خدماتی", + "منطبق با اساسنامه شرکت", + "از هزینه های مشترک قابل پرداخت توسط شرکت کسر نمایند" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۸ (اصلاحی ۱۳۹۶/۰۴/۱۸)" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Maximum two months, permissible rather than mandatory.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A10", + "status": "not_run", + "passed": null, + "expected": { + "id": "A10", + "answerable": true, + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "query": "اگر ساخت‌وساز غیرمجاز مالک یا متصرف قانونی به مشاعات خسارت بزند، ماده ۴ چه تکلیفی در حالت توافق و عدم توافق مقرر می‌کند؟", + "evidence_groups": [ + [ + "ساخت و ساز غیرمجاز مالک یا متصرف قانونی", + "قسمتی از مشاعات", + "از بین رفته و یا تخریب گردد" + ], + [ + "از طریق توافق", + "جبران خسارت وارده", + "اعاده وضع به حال سابق" + ], + [ + "در صورت عدم توافق", + "جبران خسارت و اعاده وضع به حال سابق", + "مطابق قوانین و مقررات مربوط" + ] + ], + "locator": { + "page": 3, + "section": "ماده ۴" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Keep negotiated remedy and fallback legal process.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A11", + "status": "not_run", + "passed": null, + "expected": { + "id": "A11", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "شش محور اصلاح نظام اداری دولت چهاردهم در تصویر کدام‌اند؟", + "evidence_groups": [ + [ + "چابک‌سازی و تمرکززدایی ساختاری" + ], + [ + "مدیریت شایسته محور سرمایه انسانی" + ], + [ + "ارتقای سلامت اداری و مقابله با فساد" + ], + [ + "استقرار دولت هوشمند و داده‌محور" + ], + [ + "مدیریت عملکرد نتیجه گرا" + ], + [ + "ارتقای بهره‌وری ملی و انرژی" + ] + ], + "locator": { + "page": null, + "section": "شش محور؛ دو ستون تحول در ساختار و سرمایه انسانی و هوشمندسازی و ارتقای بهره‌وری" + }, + "critical": false, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Six axes across both image columns; no invented numerical target.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A12", + "status": "not_run", + "passed": null, + "expected": { + "id": "A12", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "محور ارتقای سلامت اداری و مقابله با فساد چه اقداماتی را درباره تعارض منافع مطرح می‌کند؟", + "evidence_groups": [ + [ + "شفافیت", + "پاسخگویی", + "پیشگیری از وقوع موقعیت" + ], + [ + "تعارض منافع", + "دستگاه‌های اجرایی" + ] + ], + "locator": { + "page": null, + "section": "ارتقای سلامت اداری و مقابله با فساد؛ پایین ستون چپ" + }, + "critical": true, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Prevention of conflict-of-interest situations; not a guarantee of elimination.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A13", + "status": "not_run", + "passed": null, + "expected": { + "id": "A13", + "answerable": true, + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "query": "در محور مدیریت عملکرد نتیجه‌گرا، نظام جبران خدمت و پاداش‌ها به چه چیزی متصل می‌شود؟", + "evidence_groups": [ + [ + "اتصال نظام جبران خدمت و پاداش‌ها به", + "نتایج واقعی ارزیابی عملکرد" + ] + ], + "locator": { + "page": null, + "section": "مدیریت عملکرد نتیجه گرا؛ میانه ستون راست" + }, + "critical": false, + "unseen": false, + "annotation_method": "original visual reconstruction", + "qualifiers": "Original infographic states connection of compensation and rewards to actual performance-evaluation results; no claim about a redesigned measurement system.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A14", + "status": "not_run", + "passed": null, + "expected": { + "id": "A14", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "در فایل اصلی ساعت کاری شنبه تا چهارشنبه و پنجشنبه چیست و هنگام تعطیلی یا تغییر ساعات اداری چه ملاکی حاکم است؟", + "evidence_groups": [ + [ + "از شنبه تا چهارشنبه از ساعت 8 صبح الي 13", + "در روزپنجشنبه از 8 صبح الي 12" + ], + [ + "در روزهای تعطیل یا تغییر ساعات اداری، آخرین ابلاغ شرکت ملاک است." + ] + ], + "locator": { + "page": null, + "section": "سؤال ساعت کاری؛ پاسخ در بند ۳ فایل اصلی" + }, + "critical": true, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; human authority/inclusion approval absent. Latest official notice governs.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A15", + "status": "not_run", + "passed": null, + "expected": { + "id": "A15", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "برای پیگیری امور انفورماتیک در فایل اصلی نام مخاطب و شماره داخلی چیست؟", + "evidence_groups": [ + [ + "سرکار خانم آذری، داخلی ۲۹۰" + ] + ], + "locator": { + "page": null, + "section": "سؤال امور انفورماتیک؛ پاسخ در بند ۱۱ فایل اصلی" + }, + "critical": true, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; not approved for publication.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A16", + "status": "not_run", + "passed": null, + "expected": { + "id": "A16", + "answerable": true, + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "query": "نشانی شرکت در پاسخ مربوط به آدرس در فایل اصلی چیست؟", + "evidence_groups": [ + [ + "خ 22 بهمن ، مجموعه اداري امير كبير (غدير)" + ] + ], + "locator": { + "page": null, + "section": "سؤال آدرس شرکت؛ پاسخ در بند ۷ فایل اصلی" + }, + "critical": false, + "unseen": false, + "annotation_method": "original DOCX OOXML paragraph reconstruction", + "qualifiers": "Candidate factual group; not independently verified as current address.", + "annotation_status": "draft_original_annotated", + "outcome": "not_run", + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U01", + "status": "not_run", + "passed": null, + "expected": { + "id": "U01", + "answerable": false, + "query": "قیمت روز هر متر زمین محمودآباد چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No approved current tariff; DOCX demands current data, gives no price.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U02", + "status": "not_run", + "passed": null, + "expected": { + "id": "U02", + "answerable": false, + "query": "موجودی لحظه‌ای زمین محمودآباد چند مترمربع است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No live inventory in supplied originals.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U03", + "status": "not_run", + "passed": null, + "expected": { + "id": "U03", + "answerable": false, + "query": "بدهی فعلی شرکت فلان در پرونده صنعتی چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No authorized case database/evidence; never use behavioral DOCX replies as factual case data.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U04", + "status": "not_run", + "passed": null, + "expected": { + "id": "U04", + "answerable": false, + "query": "در تصویر اصلاح نظام اداری، هدف عددی کاهش مصرف انرژی چند درصد است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "Infographic gives an axis, not a numeric energy target.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U05", + "status": "not_run", + "passed": null, + "expected": { + "id": "U05", + "answerable": false, + "query": "شماره موبایل مدیرعامل فلان کارخانه چیست؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "No approved personal contact evidence.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "U06", + "status": "not_run", + "passed": null, + "expected": { + "id": "U06", + "answerable": false, + "query": "میزان مشوق قراردادهای منعقدشده پس از پایان بهمن ۱۴۰۴ چقدر است؟", + "evidence_groups": [], + "critical": false, + "unseen": false, + "annotation_status": "draft_absence_review", + "absence_basis": "Letter concerns 1404 conclusion window; no 1406 percentage.", + "outcome": "not_run", + "annotation_method": "original corpus absence review; no retrieved or generated output", + "absence_sources": [ + { + "original": "letter", + "original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99", + "scope": "entire supplied original" + }, + { + "original": "regulation", + "original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096", + "scope": "entire supplied original" + }, + { + "original": "infographic", + "original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935", + "scope": "entire supplied original" + }, + { + "original": "docx", + "original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23", + "scope": "entire supplied original" + } + ], + "repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A17", + "status": "not_run", + "passed": null, + "expected": { + "id": "A17", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A18", + "status": "not_run", + "passed": null, + "expected": { + "id": "A18", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A19", + "status": "not_run", + "passed": null, + "expected": { + "id": "A19", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + }, + { + "id": "A20", + "status": "not_run", + "passed": null, + "expected": { + "id": "A20", + "unseen": true, + "query": null, + "evidence_groups": null, + "reason": "Approved unseen original unavailable; cannot invent original-bound evidence." + }, + "sources": [], + "outcome": null, + "latency_seconds": null, + "provider_calls": 0, + "usage": "unavailable", + "billing": "unavailable", + "failure_category": null, + "blocking_reasons": [ + "Phase 2 measured finalized cutoff is absent (local cutoff:null).", + "Pinned funded provider/profile approval and explicit call authorization/budget absent.", + "Actual approved original hash/document bindings and ready selected corpus unavailable.", + "Required human exact-output / factual DOCX inclusion decisions unavailable.", + "Four independently annotated unseen-document cases unavailable." + ] + } + ], + "required_gate": { + "answerable_total": 20, + "answerable_minimum": 18, + "all_critical": true, + "unsupported_total": 6, + "all_unsupported": true, + "no_ineligible_sources": true + }, + "responsible_phase_for_unrun_gate": "Fast-Track 4 depends on Phase 2 real calibration and approved ingestion corpus/review", + "production_defects_exposed": [], + "notes": "No real provider calls; no quality scores inferred from synthetic tests. Every not-run slot retained. Original approval is not inferred from presence on disk.", + "annotation_repair": { + "status": "reconstructed_from_originals", + "answerable_reconstructed": 16, + "unsupported_reconstructed": 6, + "unresolved": [], + "persisted_encoding": "UTF-8", + "human_approvals_changed": false + }, + "historical_checks": { + "provider_free": { + "command": ".venv/Scripts/python -m pytest -m \"not postgres\" -q --tb=short", + "passed": 1258, + "skipped": 3, + "deselected": 311, + "seconds": 71.74 + }, + "postgres": { + "command": ".venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short", + "passed": 311, + "skipped": 0, + "deselected": 1251, + "seconds": 326.9, + "container": "rag-phase4-acceptance-20261008", + "host": "127.0.0.1", + "port": 54940, + "database": "rag_phase4_test", + "server": "16.15", + "pgvector": "0.8.7", + "deployment_database_written": false, + "cleanup": "Zero leftover disposable schemas and zero public tables; created test container and anonymous volume removed; pre-existing containers preserved." + }, + "pip_check": "passed", + "tracked_whitespace": "passed", + "new_file_whitespace": "passed", + "new_python_ast": "passed", + "json_parse": "passed", + "applied_migrations_preserved": 3, + "preservation": { + "applied_migrations": "all three byte-for-byte preserved", + "unrelated_files": "all baseline files except externally changed scripts/live_voice_server.py preserved", + "concurrent_change": "scripts/live_voice_server.py changed during this task; not edited by this evaluation" + }, + "local_guide_links": "passed" + }, + "checks": { + "targeted": { + "command": ".venv/Scripts/python -m pytest tests/unit/test_search_phase4_gate.py tests/unit/test_search_phase4_repairs.py -q --tb=short", + "passed": 52, + "skipped": 0, + "seconds": 1.82 + }, + "provider_free": { + "command": ".venv/Scripts/python -m pytest -m \"not postgres\" -q --tb=short", + "passed": 1300, + "skipped": 3, + "deselected": 311, + "seconds": 78.88 + }, + "postgres": { + "status": "not_run", + "reason": "TEST_DATABASE_URL is not configured; no isolated PostgreSQL acceptance was run for this repair." + }, + "pip_check": "passed", + "tracked_whitespace": "passed", + "new_file_whitespace": "passed", + "new_python_ast": "passed", + "json_parse": "passed", + "utf8_strict_readback": "passed", + "applied_migrations_preserved": 3, + "draft_question_comparison": "22 populated questions distinct from local Phase 2 annotations; four empty unseen slots remain pending; full future report revalidation is mandatory", + "local_guide_links": "passed", + "preservation": { + "applied_migrations": "all three byte-for-byte preserved", + "unrelated_files": "All baseline files outside the repair are unchanged except an observed change to scripts/live_voice_server.py, which this repair did not edit or revert." + }, + "markdown_hardbreaks": "Existing intentional two-space Markdown line endings on plan lines 3-4 retained; tracked diff and new-file whitespace passed." + }, + "review_repairs": { + "responsible_phase": "Fast-Track Search 4", + "corruption_confirmed": { + "populated_questions": 22, + "status_expected_annotations_duplicated_corruption": true, + "previous_draft_sha256": "01df5a4b76175d9419f0768e92d31da6bb2f50220e595ab08627f43d30b5b3d7", + "previous_status_sha256": "530b116fd60d8c9627fb5832b658882d14bd42d36720158eb7f79ed558b0da96" + }, + "annotations_reconstructed": { + "answerable": 16, + "unsupported": 6, + "unresolved": [] + }, + "separation": "Reject overlap and missing/malformed Phase 2 annotations before settings/database/provider setup. Shared source documents allowed.", + "question_comparison": "NFKC + casefold + Persian/Arabic kaf/yeh/digit equivalence + collapsed Unicode whitespace; ZWNJ/ZWSP become spaces; other format controls removed; terminal . ! ? and Persian question mark ignored. Internal separators, numbers, words and negation remain significant. No fuzzy/paraphrase detector.", + "provider_calls": 0, + "quality_acceptance": "not_run" + } +} diff --git a/docs/guides/scoped-search-phase2-repairs.md b/docs/guides/scoped-search-phase2-repairs.md new file mode 100644 index 0000000..bd5a8cc --- /dev/null +++ b/docs/guides/scoped-search-phase2-repairs.md @@ -0,0 +1,99 @@ +# Phase 2 repair acceptance (2026-10-08) + +These repairs extend the existing shared retrieval core. Real-model quality acceptance remains pending; no real provider calls were made and no cutoff was invented. + +Current acceptance for the two additional repairs is recorded in the +[remaining-repairs section](#remaining-two-repairs-current-acceptance-2026-10-08). +Earlier counts below are historical. + +## Reproductions and corrections + +| Defect | Reproduction before repair | Correction and regression evidence | +| --- | --- | --- | +| Canonical handoff after unlocked retrieval | Three PostgreSQL barriers returned ok after removal, actor disablement or authority change committed between candidate retrieval and publication. A unit commit-failure case also published references. | Finalization takes settings-first persisted authority locks, checks enabled actor and the execution's pinned epoch, admits evidence and stages references inside a short transaction. Successful commit is the service handoff boundary; failed/revoked finalization publishes no references. Bounded candidate barriers cover all three mutations; admission barriers prove removal/disablement cannot commit while finalization holds locks. Existing provider barriers and execution-wide reference tests pass. | +| Terminal punctuation destroys exact patterns | Ten unit punctuation cases failed; ten corrected PostgreSQL recovery cases failed with the target outside the first 50 semantic candidates. | Python extraction and parameterized PostgreSQL boundaries accept terminal periods while retaining internal separators. Regressions cover query, context and source punctuation, Persian/Arabic digits and kaf/yeh, article/date/identifier patterns, separator distinctions, partial-match rejection and quantities. Eighteen real PostgreSQL recovery cases exercise the exact branch beyond the semantic limit. Comparison policy is v2; embedding preprocessing is unchanged. | +| Final calibration failures discard reports | Final SQL revalidation exceptions escaped after completed observations; revoked reports lost timings, and the CLI produced no retained report. | SQL and authority failures retain a technical_error report with cutoff=null, actual call counts, completed timings and safe categories. Unconfirmed evidence/query annotations are suppressed, safe binding/profile metadata remains, and cutoff loading rejects failed reports. Six deterministic final-failure cases, two real SQL final-failure cases and CLI readability/exclusive-output tests pass without extra calls. | +| SQL errors are indiscriminately retryable | Permanent/unknown SQL failures were retryable; pool timeout normalization was missing. | Timeout normalization remains. Only explicit transient SQLSTATEs and disconnection errors are retryable; permanent and unknown errors default false. Unit and real PostgreSQL cases cover undefined table, permission, syntax, timeout, serialization/deadlock and unknown errors, with safe constant messages. | + +Before production changes, the new unit regressions reported **25 failed, 14 passed** (1.51 seconds). The corrected exact-recovery PostgreSQL reproduction reported **10 failed, 10 deselected** (15.53 seconds). An initial test fixture SQL literal was corrected before that reproduction; it was not a product defect. + +The service boundary protects canonical result handoff at transaction commit. Future transport delivery has no implemented guard and is not certified by these tests. Provider calls remain outside database transactions. Eligibility before ranking/limits, deterministic chunk-ID merge, five whole chunks within 12,000 evidence-text characters, faithful text and actual nullable locators remain unchanged. + +## Executed checks + +All PostgreSQL commands used this existing isolated test database, with disposable schemas only: + +```powershell +$env:TEST_DATABASE_URL = 'postgresql+psycopg://postgres:search-test-only@127.0.0.1:54938/rag_scoped_search_test' +.venv/Scripts/python -m tests.postgres_prerequisites +.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/unit/test_search_phase2_repairs.py -q --tb=short +.venv/Scripts/python -m pytest tests/integration/test_scoped_search.py tests/integration/test_search_phase2.py tests/integration/test_search_phase2_repairs.py --require-postgres -q --tb=short +.venv/Scripts/python -m pytest -m 'not postgres' -q --tb=short +.venv/Scripts/python -m pip check +.venv/Scripts/python -B -m app.search --help +.venv/Scripts/python -B -m app.calibrate_search --help +git diff --check +``` + +- Prerequisite probe: PostgreSQL **16.15**, pgvector **0.8.7**. +- Affected unit tests: **75 passed**, 0.91 seconds. +- Affected isolated PostgreSQL tests: **97 passed**, zero skips, 128.65 seconds. +- Full provider-free regression: **1161 passed, 3 skipped, 305 deselected**, 58.59 seconds. Skips are existing Windows symlink privilege cases. +- pip check: **No broken requirements found**. +- Both CLI help commands passed. AST, new-file whitespace, local documentation links and tracked diff whitespace passed. +- Applied migrations were compared byte-for-byte with HEAD. Unrelated baseline files, dependencies, annotation/original bytes and Phase 1 inspection CLI were preserved. +- Cleanup probe found zero leftover test schemas and zero public tables. The existing test container was restored to its original stopped state. + +The affected PostgreSQL suite includes the existing ingestion/publication-through-selection/search tests with independent literal expected numbers, conditions, negations, exceptions, partial-publication barriers and failed-batch invisibility. This is affected PostgreSQL acceptance, not a claim that the entire PostgreSQL suite ran. + +## Remaining calibration prerequisites + +[Current model-quality status](../calibration/phase2-status.json) remains pending. Real calibration requires separate explicit provider-call authorization, approved original-to-selected-document bindings, and verified compatibility of the configured real model, ingestion database and retained profile. The six-answerable/four-unsupported annotations and original are unchanged. The ten-call budget and exclusive output creation remain enforced. + +Selection still maximizes complete-support coverage with zero unsupported false positives and chooses the stricter cutoff on ties. A successful measured report is required; deterministic tests supply no production threshold. Phases 3/4 remain outside this repair. + +## Remaining two repairs: current acceptance (2026-10-08) + +This section supersedes the earlier test counts for current Phase 2 technical acceptance. It preserves the four repairs above and adds only literal calibration boundaries and confirmed-disconnection classification. + +### Reproduction and correction + +- **Calibration evidence:** unrestricted substring membership accepted independently annotated ۲۵ بار inside ۱۲۵ بار, ۱۰ روز inside ۱۱۰ روز, and PUMP-7 inside PUMP-70. Frozen-original regressions also reproduced numeric/date/identifier extensions and an incorrect six-of-six cutoff result. Literal annotation matching now checks Unicode letters, numbers, combining marks, connector characters and format joiners, plus date/identifier/numeric separators. Internal extensions fail; terminal sentence periods remain punctuation. No evidence normalization or expected-fact derivation was added. Every phrase in a required group must still occur together in one whole admitted chunk bound to the approved document. +- **Confirmed disconnection:** a Psycopg OperationalError wrapped by SQLAlchemy with SQLSTATE absent and connection_invalidated=true was normalized as nonretryable at candidate retrieval, handoff and calibration finalization. The shared mapper now recognizes that confirmed disconnect. Permanent and unknown SQLSTATEs remain nonretryable, and genuinely unknown failures without invalidation remain nonretryable. Messages stay constant and safe; no retry loop or additional provider work was introduced. + +Before production changes: +```powershell +.venv/Scripts/python -m pytest tests/unit/test_search_phase2_remaining.py -q --tb=short +``` +**19 failed, 12 passed**, 0.99 seconds: 16 annotation/coverage regressions and three confirmed-disconnect boundaries failed. + +[New unit regressions](../../tests/unit/test_search_phase2_remaining.py) use the frozen six-answerable/four-unsupported annotations and original. All unchanged groups pass; independently corrupted groups fail, incomplete/split groups fail, and wrong document bindings fail. Corruption cannot inflate coverage to six-of-six; corruption of all six yields measured_failure with no cutoff. The unchanged fixture retains six complete-support cases, zero unsupported false positives and the stricter cutoff on ties. No annotation/original bytes or labels changed. + +[New PostgreSQL regressions](../../tests/integration/test_search_phase2_remaining.py) close only the test's own actual Psycopg connection before the next SQLAlchemy execution. They verify SQLSTATE-less, connection-invalidated errors at retrieval and handoff, empty sources, no consumed reference and exactly one deterministic embedding call. Final calibration disconnection retains ten completed timings/call counts, technical_error with null cutoff, safe messages and suppressed evidence, with no additional calls. Initial administrative backend termination produced SQLSTATE 57P01; the fixture was corrected to exercise the requested SQLSTATE-less case. + +### Exact final commands and results + +```powershell +$env:TEST_DATABASE_URL = 'postgresql+psycopg://postgres:search-test-only@127.0.0.1:54938/rag_scoped_search_test' +.venv/Scripts/python -m tests.postgres_prerequisites +.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/unit/test_search_phase2_repairs.py tests/unit/test_search_phase2_remaining.py -q --tb=short +.venv/Scripts/python -m pytest tests/integration/test_scoped_search.py tests/integration/test_search_phase2.py tests/integration/test_search_phase2_repairs.py tests/integration/test_search_phase2_remaining.py --require-postgres -q --tb=short +.venv/Scripts/python -m pytest -m 'not postgres' -q --tb=short +.venv/Scripts/python -m pip check +.venv/Scripts/python -B -m app.search --help +.venv/Scripts/python -B -m app.calibrate_search --help +git diff --check +``` + +- Prerequisites: PostgreSQL **16.15**, pgvector **0.8.7**, passed. +- Affected unit acceptance: **107 passed**, 1.26 seconds. +- Affected isolated PostgreSQL acceptance: **100 passed**, zero skips, 138.82 seconds. +- Provider-free regression: **1193 passed, 3 skipped, 308 deselected**, 59.67 seconds. Skips remain Windows symlink privilege cases. +- pip check: **No broken requirements found**. Both CLI help commands passed. +- Tracked diff whitespace, separate new-file whitespace, AST and local documentation link checks passed. +- All three applied migration files compare byte-for-byte with HEAD. SHA-256 baseline comparisons preserve unrelated tracked/untracked files, dependencies, frozen original/annotations, lexical/evidence modules, calibration/inspection CLIs and previous regression files. +- Database cleanup probe: **0 leftover test schemas / 0 public tables**. Existing test container restored to its original stopped state. + +Only calibration.py, sql_error() in service.py, two new regression files and current status documentation changed in this repair. Retrieval SQL, admission budgets, settings-first locks and commit-time staged source publication are unchanged. Full PostgreSQL regression and real-provider calibration were not run; affected PostgreSQL acceptance is complete. + +Real-model quality acceptance still requires explicit separate provider-call authorization, approved original/document bindings and verified model/database/profile compatibility. No real provider calls were made, no production cutoff was invented, and Phases 3/4 remain pending. diff --git a/docs/guides/scoped-search-phase2.md b/docs/guides/scoped-search-phase2.md new file mode 100644 index 0000000..e3e54e4 --- /dev/null +++ b/docs/guides/scoped-search-phase2.md @@ -0,0 +1,170 @@ +# Fast-Track Search Phase 2 + +The existing inspection CLI and one retrieval core now combine at most 50 +eligible cosine candidates and 50 eligible exact candidates. Exact comparison +normalizes NFC, Persian/Arabic digits, kaf/yeh, case and Unicode whitespace. +Terminal sentence periods are accepted in queries, context and source passages; +internal date and identifier separators remain distinct. Isolated quantities do not +become identifiers. Every branch applies organization, ready, active, +undeleted, unpurged and compatible-profile predicates before sorting and limits. + +Merge deduplicates chunk IDs and orders exact matches first, then cosine +distance and chunk UUID. Admission applies the measured cosine cutoff to every +candidate, including exact matches. Results contain up to five whole chunks +and 12,000 evidence-text characters; a chunk that cannot fit is skipped. +Evidence and existing embedding preprocessing are unchanged. + +`SearchService.search(SearchExecution(user_id), query, context)` returns the +API 7.2 `ok`, `no_evidence` or normalized `error` envelope. Reuse one trusted +SearchExecution for all searches in an execution; the same chunk keeps its S +reference and new chunks receive new references. Identity, scope, cutoff, +budgets and execution metadata never come from model arguments. Actual nullable +page/section locators come from retained chunks. + +Actor and access epoch are captured and rechecked with settings-first locks. +No connection is held during embedding calls. Retrieval uses statement/lock +timeouts of 5/2 seconds and the existing finite provider timeout. An execution +cannot continue across knowledge removal or changed actor authority. +Canonical admission and staged reference allocation use a short settings-first +authorized transaction. Successful commit is the service handoff boundary: +removal or actor disablement committed before it returns CONTEXT_REVOKED with +empty sources and consumes no references. Future transport delivery is outside +this implemented boundary. Provider, SQL, invalid-vector, compatibility and +timeout failures remain errors. SQL retryability uses explicit transient +classifications; permanent and unknown failures default to false. +A missing calibration returns CALIBRATION_REQUIRED with empty sources. + +## Calibration prerequisites and command + +[Annotations](../calibration/phase2-cases.json) contain six answerable and four +unsupported Persian questions. Expected evidence groups are literal independent +annotations from the [separate original](../../data/calibration/phase2-source.md), +including every marked number, condition, negation and exception. This is a +calibration fixture, separate from Phase 4's required examples and held-out gate. +Its original bytes/hash are frozen; changing it requires new annotations. +The fixture's headings follow the existing ingestion grammar. + +An operator must approve the fixture, import it through existing intake/worker +publication with the configured compatible real model, then activate it through +the selection service. Do not set ready/active flags using raw SQL. Record its +actual document UUID in an external bindings JSON object: +`{"":""}`. +Keep the full selected corpus and knowledge revision fixed for the run. + +The real-provider command is available only with explicit opt-in: + +```powershell +.venv/Scripts/python -m app.calibrate_search --user-id --bindings --output --allow-provider-calls +``` + +The command authorizes at most ten compatible query-embedding calls. It checks +original bytes, database hash/identity, eligibility and profile, uses the same +retrieval core and records actual call counts, timings, profile/request policy, +bindings, annotations, candidate evidence and each trial. Usage and billing are marked unavailable because the existing adapter does +not expose those measurements. Existing reports cannot be overwritten. +Failures are retained as technical failures, never unsupported successes. Final +authorization SQL/timeout failures retain technical_error reports with null +cutoff, actual call counts and completed timings, suppressing unconfirmed +evidence. Revocation retains safe metadata. + +Cutoff selection maximizes complete-support coverage with zero unsupported +false positives, choosing the lower (stricter) distance on ties. Every required +evidence group must occur intact in a chunk of its bound original. If no +nonzero coverage can satisfy zero false positives, the report records +measured_failure with no cutoff. Repair the measured baseline without changing +the pinned embedding profile or weakening expected evidence. + +Load a successful measured report using +`app.modules.knowledge.calibration.load_cutoff(report)` and supply the returned +CalibratedCutoff to the SearchService constructor. Profile and retrieval policy +must match. There is no default production distance threshold. + +[Current quality status](../calibration/phase2-status.json) is pending: +no real provider calls were authorized or made, and approved original/document +bindings are unavailable. The observed configured profile was Ollama bge-m3, +1024 dimensions, preprocessing v1. Its actual database/provider compatibility +and model quality have not been certified by deterministic tests. + +## Inspection and technical acceptance + +The existing command remains available and uses this same core: + +```powershell +.venv/Scripts/python -m app.search --inspect --user-id --query "" --allow-provider-calls +``` + +It labels output uncalibrated_candidates / semantic_quality=not_assessed. +It returns five whole diagnostic chunks and preserves exact-match markers and +cosine distances. It does not require or claim calibrated evidence admission. + +Technical checks use deterministic embeddings and disposable schemas in a +dedicated PostgreSQL/pgvector test database. Tests cover both matching branches, +eligibility before limits, stable merge/deduplication, bounded evidence, source +identity, real SQL errors/timeouts, provider errors, and bounded removal/actor +disablement barriers. Markdown/DOCX cases run intake, extraction, staging, +publication, selection and search, asserting independent literal 25 bar / 60 C, +40 liters per minute / 30 days, and 15 Nm with all conditions, negations and +exceptions. Publication barriers verify no rows are visible before commit; +failed final batches cannot be selected or searched. + +```powershell +$env:TEST_DATABASE_URL = 'postgresql+psycopg://postgres:search-test-only@127.0.0.1:54938/rag_scoped_search_test' +.venv/Scripts/python -m tests.postgres_prerequisites +.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/integration/test_scoped_search.py tests/integration/test_search_phase2.py --require-postgres -q --tb=short +``` + +The existing isolated container is rag-scoped-search-20261007. No deployment +database was written. Applied migrations and the prototype path are unchanged. +LangChain and the held-out Persian quality gate remain Phases 3 and 4. + +## Current repair acceptance (2026-10-08) + +See [current repair report](scoped-search-phase2-repairs.md) for reproductions, +corrections, exact commands and results: 107 affected unit tests, 100 affected +PostgreSQL tests, and 1193 provider-free regression tests passed. Literal +annotation boundaries now reject numeric/date/identifier extensions; confirmed +SQLSTATE-less invalidated connections are retryable without automatic replay. Model-quality +acceptance remains pending. The following results describe the earlier baseline. + +## Earlier Phase 2 technical acceptance (2026-10-08) + +- Affected retrieval/calibration command above: **93 passed** (35 unit, + 58 real PostgreSQL), zero skips, 99.78 seconds. +- `.venv/Scripts/python -m pytest -m 'not postgres' -q --tb=short`: + **1121 passed, 3 skipped, 266 deselected**, 83.90 seconds. The skips are + existing Windows symlink privileges; no real providers were called. +- `.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py --require-postgres -q --tb=short` + with the isolated TEST_DATABASE_URL above: **91 passed**, zero skips, + 147.93 seconds. +- PostgreSQL prerequisite probe passed: **16.15**, pgvector **0.8.7**. +- `.venv/Scripts/python -m pip check`: no broken requirements. +- CLI help for inspection/calibration, tracked diff whitespace and separate + AST/new-file whitespace/local-link inspection passed. +- All three applied migrations compare byte-for-byte with HEAD. + +These results prove technical behavior with deterministic embeddings. Real-model +cutoff calibration and model-quality acceptance remain **pending**. The full +PostgreSQL suite and Phase 4 held-out evaluation were not run for this phase. + +## Affected files + +Retrieval: [service.py](../../app/modules/knowledge/service.py), +[lexical.py](../../app/modules/knowledge/lexical.py), +[evidence.py](../../app/modules/knowledge/evidence.py). + +Calibration: [calibration.py](../../app/modules/knowledge/calibration.py), +[CLI](../../app/calibrate_search.py), [original](../../data/calibration/phase2-source.md), +[cases](../calibration/phase2-cases.json), [pending status](../calibration/phase2-status.json). + +Validation: [unit tests](../../tests/unit/test_search_phase2.py), +[PostgreSQL tests](../../tests/integration/test_search_phase2.py), +[source-byte fixture helper](../../tests/support/search.py), +[Git byte-preservation rules](../../.gitattributes). + +Documentation: [index](../README.md), [reference map](../agent-reference-map.md), +[plan](../plans/scoped-search-implementation-plan.md), +[API catalog](../specifications/RAG-Phase1-API-Catalog.md), and this guide. + +Post-test inspection found zero leftover disposable schemas and zero public +tables. The existing test container was restored to its original stopped state; +all unrelated containers were preserved. diff --git a/docs/guides/scoped-search-phase3.md b/docs/guides/scoped-search-phase3.md new file mode 100644 index 0000000..22fbff1 --- /dev/null +++ b/docs/guides/scoped-search-phase3.md @@ -0,0 +1,206 @@ +# Phase 3: LangChain search boundary + +Phase 3 technical integration is implemented on 2026-10-08. This does not +certify semantic quality, generated answers, browser authentication or Live. + +Install from the repository root: + +~~~powershell +.venv/Scripts/python -m pip install -e ".[search,test]" +~~~ + +The dedicated extra declares only `langchain-core>=1,<2`. Acceptance installed +langchain-core 1.6.7. Ingestion and the search service do not import LangChain; +even importing the adapter does not import it. Explicit tool construction +requires the extra. Tests deliberately block framework imports in a fresh +process to verify the core/ingestion import boundary. + +## Backend invocation + +The trusted caller supplies the existing Phase 2 `SearchService`, its +`SearchExecution`, an absolute monotonic deadline, and a cancellation event. +Reuse the execution within a turn to preserve pinned persisted authority, +access epoch and source references. If authority has not already been pinned +by the trusted parent, the worker captures it from persisted enabled actor +and organization settings before calling the service. These objects never +come from model arguments. + +~~~python +import time +from app.modules.knowledge.evidence import SearchExecution +from app.modules.knowledge.langchain_tool import ( + SearchToolRunner, ToolContext, create_search_tool, +) + +# service is the existing SearchService with compatible provider and measured +# CalibratedCutoff; authenticated_user_id comes from the trusted backend. +runner = SearchToolRunner() # one shared runner per process +execution = SearchExecution(authenticated_user_id) +trusted = ToolContext(execution, time.monotonic() + 75) +tool = create_search_tool(service, trusted, runner) +result = tool.invoke({"query": "When is pump pressure 25 bar?"}) +# In an async caller: +result = await tool.ainvoke({"query": "When is pump pressure 25 bar?"}) +# On parent interruption: +trusted.cancelled.set() +# At process shutdown, outside the event loop: +runner.close() +~~~ + +The adapter uses the documented [StructuredTool.from_function](https://reference.langchain.com/python/langchain-core/tools/structured/StructuredTool/from_function) +boundary with explicit `SearchInput` and both entrypoints. No alternate +retrieval, embedding pipeline, vector store, text agent or Live dispatcher +was introduced. + +## Tool schema and outcomes + +Name: `search_knowledge`. + +~~~json +{ + "type": "object", + "additionalProperties": false, + "required": ["query"], + "properties": { + "query": {"type": "string", "minLength": 1, "maxLength": 2000}, + "context": { + "anyOf": [{"type": "string", "maxLength": 2000}, {"type": "null"}], + "default": null + } + } +} +~~~ + +Validation also rejects whitespace-only queries, non-string coercions and +invalid database text. Unknown fields, including forged user/organization IDs, +scope, limits, epochs, deadlines and source references, raise Pydantic +ValidationError before any provider/database work. Context is an untrusted +retrieval hint. + +Canonical Phase 2 results pass through: `ok`, `no_evidence`, or `error`. +Source fields remain source_ref/document_id/chunk_id/title/text/location; +actual nullable page/section locators and faithful whole chunks are preserved. +A missing measured cutoff remains `CALIBRATION_REQUIRED`. +The CLI retains its distinct `uncalibrated_candidates` diagnostic format. + +The default runner allows four running and eight waiting calls; the total +deadline is the earlier of the trusted deadline and admission time plus +75 seconds. Queue time consumes that deadline. Waiting async callers do not +occupy executor threads, and work is submitted only after acquiring a running +slot. All database/provider work, including persisted authority checks, runs +in the bounded pool. Existing five-second SQL statement, two-second lock and +explicit finite provider timeout policies remain in force. + +Saturation returns canonical `SEARCH_SATURATED` (retryable); deadline expiry +returns `SEARCH_TIMEOUT` (retryable); explicit parent cancellation or runner closure returns +`SEARCH_CANCELLED` (nonretryable). Async task cancellation propagates +CancelledError and suppresses delivery. Blocking work cannot be recalled; +its running/admission slot remains held until actual completion, even after +caller timeout/cancellation. No automatic provider retries were added. +Successful service results receive a fresh persisted actor/epoch check at +this adapter delivery boundary, followed by deadline/cancellation checks. + +## Executed acceptance + +Actual LangChain tests have no missing-dependency skip path. The new tests +cover strict schemas, canonical results, stable references, actual CLI +invocation and candidate equivalence, both tool entrypoints, event-loop +responsiveness, four/eight default bounds, saturation, queue and running +timeouts, queued/running cancellation, epoch/actor invalidation and lazy imports. + +~~~powershell +.venv/Scripts/python -m pytest tests/unit/test_search_phase3.py tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/unit/test_search_phase2_repairs.py tests/unit/test_search_phase2_remaining.py -q --tb=short +# 148 passed, including 41 Phase 3 tests; no skips. + +$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:phase3-test-only@127.0.0.1:54939/rag_phase3_test" +.venv/Scripts/python -m tests.postgres_prerequisites +# PostgreSQL 16.15 / pgvector 0.8.7. +.venv/Scripts/python -m pytest tests/integration/test_search_phase3.py tests/integration/test_scoped_search.py tests/integration/test_search_phase2.py tests/integration/test_search_phase2_repairs.py tests/integration/test_search_phase2_remaining.py --require-postgres -q --tb=short +~~~ + +Database acceptance: **103 passed**, including three Phase 3 tests, zero skips. +The reference-map Phase 3 entry records this checkpoint. +The new real-database tests invoke both entrypoints on published/selected +documents, compare literal evidence and identities with inspection, reject +foreign scope hints and invalidate pinned executions after persisted removal. +Their permissive cutoff is explicitly test-only, never production calibration. + +`pip check`, `git diff --check`, new Python AST/whitespace, local documentation +links and byte-for-byte comparison of all applied migrations passed. +Unrelated working-tree changes were preserved. + +## Shutdown repair acceptance (2026-10-08) + +This repair supersedes the initial Phase 3 shutdown behavior. Closure reuses +the existing canonical `SEARCH_CANCELLED` outcome, with empty sources, +the execution request ID and `retryable:false`. The safe message is +`Knowledge retrieval cancelled: runner closed`. Closure takes precedence +over deadline expiry, including on new calls to a permanently closed runner. +Input validation still precedes execution. + +`close()` is idempotent, including concurrent calls. It sets permanent closure +under the same condition lock used by admission and executor submission. +If closure wins that lock, no queued work is submitted. If submission wins, +the completion callback owns its running/admission slots until actual work +finishes. A submitted worker that observes closure before starting its I/O +returns cancellation without starting database/provider work. + +Sync and async waiting callers observe closure on their next existing bounded +poll and release their own queued admissions exactly once. Running callers +suppress results after observing closure; cancellation cannot recall their +blocking I/O. Completion callbacks release submitted slots and notify drain +waiters. After joining executor work, `close()` waits for all queued admissions +to drain, so it returns with both counters zero. Repeated closure never releases +a slot a second time. A result whose final stop check precedes closure may +already have been delivered; closure cannot recall it. + +Run `close()` in a control thread, outside active event loops and this runner's +worker pool, so queued callers can progress. Its duration depends on actual +blocking work finishing; shutdown does not forcibly terminate provider/database +operations. Four-running/eight-waiting defaults, queue-inclusive deadlines, +parent/task cancellation, lazy imports, schema and canonical delegation remain +unchanged. + +[Shutdown regressions](../../tests/unit/test_search_phase3_shutdown.py) use +bounded event barriers, without sleep-based ordering assertions. Fourteen cases +cover sync/async queued shutdown, closed/expired new invocations, repeated and +concurrent close, admission/submission races, worker completion/callback races, +no post-closure I/O, exact releases and running-slot retention. + +Executed reproduction before repair: +~~~powershell +.venv/Scripts/python -m pytest tests/unit/test_search_phase3_shutdown.py -k "after_repeated_close or drains_queued" -q --tb=short +# 6 failed, 6 deselected with the initial regression set. +~~~ + +Executed acceptance with the declared search extra installed (langchain-core +1.6.7), no real providers: +~~~powershell +.venv/Scripts/python -m pytest tests/unit/test_search_phase3_shutdown.py tests/unit/test_search_phase3.py -q --tb=short +# 55 passed, zero skips. +.venv/Scripts/python -m pytest tests/unit/test_search_phase3_shutdown.py tests/unit/test_search_phase3.py tests/unit/test_scoped_search.py tests/unit/test_search_phase2.py tests/unit/test_search_phase2_repairs.py tests/unit/test_search_phase2_remaining.py -q --tb=short +# 162 passed, zero skips. + +$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:shutdown-test-only@127.0.0.1:54939/rag_shutdown_test" +.venv/Scripts/python -m tests.postgres_prerequisites +# PostgreSQL 16.15 / pgvector 0.8.7. +.venv/Scripts/python -m pytest tests/integration/test_search_phase3.py tests/integration/test_scoped_search.py tests/integration/test_search_phase2.py tests/integration/test_search_phase2_repairs.py tests/integration/test_search_phase2_remaining.py --require-postgres -q --tb=short +~~~ + +Database acceptance: **103 passed**, zero skips. Only disposable schemas in +the fresh isolated rag_shutdown_test database were used. Cleanup is recorded +in the reference-map shutdown repair entry. Dependency, diff/new-file AST/whitespace, local-link and applied-migration +preservation checks passed. Unrelated edits were left untouched; a concurrent change to +scripts/live_voice_server.py was observed during baseline comparison. Full repository regression and +real-model/quality acceptance were not run by this shutdown-only repair. + +## Remaining final gate + +Phase 2 real-model calibration still needs approved original/document bindings, +compatible funded provider access and explicit bounded call authorization. +Phase 4 remains pending: frozen held-out Persian evaluation with twenty +answerable cases (at least four unseen-document cases) and six unsupported +cases; at least 18/20 answerable, every critical qualifier case, all unsupported, +and no unauthorized evidence must pass. Technical errors count as failures. +Full provider-free and mandatory isolated PostgreSQL regression acceptance +belongs to that final checkpoint. No real providers were called in Phase 3. diff --git a/docs/guides/scoped-search-phase4.md b/docs/guides/scoped-search-phase4.md new file mode 100644 index 0000000..874cf8e --- /dev/null +++ b/docs/guides/scoped-search-phase4.md @@ -0,0 +1,253 @@ +# Persian retrieval acceptance: Phase 4 checkpoint (2026-10-08) + +The two Phase 4 review findings are repaired. Current provider-free checks passed; +mandatory PostgreSQL acceptance is **not run** for this repair. The real quality +gate remains **not run**. +Retrieval readiness is not established. Generated answers and Live are not +evaluated. No production code, applied migration, provider profile or Phase 2 +cutoff was changed. + +## Historical setup and results (before the review repairs) + +From the repository root, the existing .venv and installed pyproject dependencies +were used. A new local pgvector/pgvector:pg16 container named +rag-phase4-acceptance-20261008 was created on 127.0.0.1:54940 with the dedicated +rag_phase4_test database. PostgreSQL 16.15 / pgvector 0.8.7 passed the prerequisite +probe. Tests used disposable schemas and temporary originals; no deployment +database was written. Existing containers were preserved. + +Executed commands: + +~~~powershell +.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short +$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:phase4-test-only@127.0.0.1:54940/rag_phase4_test" +.venv/Scripts/python -m tests.postgres_prerequisites +.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short +.venv/Scripts/python -m pip check +git diff --check +.venv/Scripts/python -m tests.evaluate_search --help +~~~ + +Initial full results: **1248 passed, 3 skipped, 311 deselected** provider-free; +**311 passed, 1251 deselected**, zero skips, PostgreSQL (326.90 seconds). +The three skips are existing Windows symlink-permission checks. The provider-free +suite was rerun after adding the evaluation tests: **1258 passed, 3 skipped, +311 deselected**, 71.74 seconds. See [checkpoint status](../calibration/phase4-status.json). +pip check reported no broken requirements. New-file Python parsing/whitespace, +JSON parsing and applied-migration comparisons are recorded there as well. + +## Originals and labels + +[Draft annotations](../calibration/phase4-cases.draft.json) bind SHA-256 hashes of +the four supplied originals. Both PDFs were inspected from original text; +critical original pages were rendered and visually checked. The infographic +was visually inspected. DOCX factual candidates were read from original OOXML, +not indexed FAQs or search output. Draft labels retain thresholds, conditions, +negations, exceptions and actual page/section locators. + +There are **16 original-annotated answerable questions, six draft unsupported +questions, and four explicitly empty unseen-document slots**. This is an +incomplete draft, not a frozen 20-question acceptance set. DOCX groups and all +original approvals remain pending; none was approved automatically. Original +hashes have no actual approved document-ID bindings yet. Literal transcription +differences must be resolved against originals before freezing. The negative +labels must be checked against the entire approved unseen corpus before freeze. + +Missing prerequisites: + +- Four unseen-document questions annotated from approved unseen originals. +- Approved factual DOCX groups and required exact-output human review decisions. +- Actual ready document IDs bound to approved original hashes. +- A finalized measured Phase 2 calibration report; local phase2-status.json + currently records cutoff:null. +- Explicit funded profile approval, provider/network opt-in and a bounded budget + covering ingestion separately from the maximum 26 query embedding calls. + +No retrieval cases were executed. Per-case not_run records, zero provider calls, +null latency, unavailable usage/billing and precise blocking reasons are in +[status](../calibration/phase4-status.json). There is no measured failure to assign +to a production phase at this checkpoint. + +## Operator workflow after prerequisites arrive + +Deployment setup/migration/bootstrap instructions are in +[foundation setup](ingestion-foundation-setup.md) and +[ingestion handoff](ingestion-operator-handoff.md). They were not executed against +deployment by this evaluation. Keep INGEST_DATABASE_URL, server-side credentials, +embedding identity/dimension/preprocessing/request limits and storage directories +compatible with the approved frozen profile. Do not switch models to obtain a pass. + +Import each approved original through intake and process through the existing +worker, retaining the actual IDs: + +~~~powershell +.venv/Scripts/python -m app.ingest import --administrator-id --idempotency-key +.venv/Scripts/python -m app.worker --once +.venv/Scripts/python -m app.ingest status --administrator-id +~~~ + +Worker execution can call funded extraction/embedding providers; authorize and +bound that work separately before running. Inspect retained candidates through +SqlReviewRepository.read / preview and submit only a human's actual ReviewDecision +through SqlReviewRepository.decide, using trusted AdministratorIdentity. +[Review service](../../app/infrastructure/review_repository.py) is implemented; +there is no app.review CLI or authenticated review HTTP transport to claim. +Retry the same eligible failed document/job through intake retry after review. +Do not set ready flags, insert chunks manually, or approve decisions programmatically. + +Activate only eligible documents through the selection service: + +~~~powershell +.venv/Scripts/python -m app.knowledge selection get --administrator-id +.venv/Scripts/python -m app.knowledge selection replace --administrator-id --expected-revision --document-id --document-id +~~~ + +Use all approved evaluation corpus IDs, with no extra active documents. Save an +external JSON mapping {"":""} for every original. +The evaluator verifies exact selection, organization, readiness, deletion/purge, +hashes, profile and persisted factual DOCX approval using read-only SQL. + +For diagnostic queries only: + +~~~powershell +.venv/Scripts/python -m app.search --inspect --user-id --query "" --allow-provider-calls +~~~ + +That command reports uncalibrated candidates and does not satisfy the quality +gate. Canonical evaluation uses the same SearchService with load_cutoff from the +successful frozen Phase 2 report. Complete and freeze the independent labels +before retrieval. Never tune the cutoff or weaken labels using held-out results. + +~~~powershell +.venv/Scripts/python -m tests.evaluate_search --cases --bindings --calibration --user-id --output --allow-provider-calls --provider-call-budget 26 +~~~ + +This command is outside ordinary pytest. Opt-in is required; the budget is a +hard maximum of 26 adapter calls, includes failed calls, and permits no automatic +retry. Lower budgets retain unrun cases and cannot satisfy full acceptance. +The existing adapter does not expose token usage or billing; both are +unavailable. Timeouts use the existing bounded provider/SQL policy. + +The evaluator refuses incomplete/unapproved labels, altered original hashes, +missing measured cutoff and mismatched profile/policy before provider calls. +Missing/malformed calibration annotations and overlapping held-out questions are +rejected before settings, database or provider setup. See the repair notes below. +Each executed record is flushed to an exclusive new JSONL report with expected +evidence, actual source text/IDs/locators, canonical outcome, latency, call count, +pass/failure and usage availability. It checks source text/locator identity in +PostgreSQL and revalidates authority/selection after the run. Technical failure +stops further calls while retaining all remaining cases as not_run. + +## Gate and troubleshooting + +Pass requires at least **18/20**, **every critical case**, **6/6 unsupported +no_evidence**, and no unauthorized/ineligible sources. Errors never count as +unsupported success. Each evidence group must occur intact in one chunk of its +bound original, collectively within the first five chunks/12000 characters. +Literal matching is deliberately strict; manually review draft orthography +against originals before freeze. This is evidence assessment, not generated +answer assessment or a model judge. + +Keep every failed case and the immutable report. Provisional retrieval/ranking +classification requires stage inspection before attributing a root cause: + +| Observed stage defect | Category | Responsible phase | +| --- | --- | --- | +| Missing/incorrect original recovery or absent human inclusion | extraction/review | Ingestion 3/5 | +| Faithful extraction split so required qualifier is unavailable | chunking | Ingestion 3 | +| Missing/partial durable publication | publication | Ingestion 5 | +| Wrong authorized active corpus/revision | selection | Fast-Track 1 | +| Profile, dimension, preprocessing or cutoff mismatch | compatibility | Ingestion 4 / Fast-Track 1-2 | +| Published complete evidence not ranked in admitted results | retrieval/ranking | Fast-Track 2 | +| Complete ranked chunk excluded by count/character admission | evidence budgeting | Fast-Track 2 | +| Provider outage/timeout or SQL connectivity/transaction error | technical provider/database errors | Environment or owning adapter/phase, based on evidence | + +Do not infer extraction versus chunking versus budgeting from a missing answer +alone. Inspect retained output, human decisions, published chunks and ranking/ +admission diagnostics without changing the failed artifact. Production repairs +require a separate authorized phase; then perform a valid fresh evaluation. +Missing approvals/corpus/cutoff are unrun prerequisites rather than quality passes. + + +Cleanup confirmed zero disposable schemas and zero public tables. The created +Phase 4 test container and its anonymous volume were removed; existing containers +were preserved. Temporary original-page renderings were removed. Baseline +comparison found a concurrent change to scripts/live_voice_server.py, which this +evaluation did not edit. All other unrelated baseline files were unchanged. + + +## Review repairs and current checks (2026-10-08) + +On-disk inspection confirmed literal ASCII question-mark replacement in all 22 +populated queries and evidence/locators, duplicated in the status snapshot. +All 16 answerable and six unsupported annotations were reconstructed from the +actual originals, with zero unresolved annotations. Both PDF pages were rendered +and visually checked; DOCX evidence was recovered from original OOXML paragraphs; +the infographic was visually inspected, including an enlarged original detail. +A13 now faithfully asks about connecting compensation/rewards to actual +performance-evaluation results. No wording was inferred from replacement counts, +retrieval output, indexed FAQs or generated answers. + +UTF-8 was written without sending raw Persian through a shell text pipeline. +Strict UTF-8 read-back verifies exact persisted objects and synchronized status +expected annotations. Original hashes, pending approvals, null document bindings, +draft status and all four empty unseen slots remain unchanged. The previous +checks are retained under historical_checks in the status snapshot. + +The evaluator rejects U+FFFD, repeated ASCII replacement marks (including runs +separated by whitespace), question marks embedded between word characters and +unreadable questions. It permits a single legitimate ASCII question mark, +Persian question punctuation, ordinary numeric/identifier separators and +Unicode letters. These checks apply to queries, evidence literals and section +locators. An unresolved annotation cannot enter a frozen run. + +Before any settings/database/provider setup, the evaluator reads the supplied +Phase 2 report's annotations.cases and requires the full six-answerable/four- +unsupported original-bound structure. Missing, malformed, corrupted or duplicate +comparison-equivalent calibration questions fail closed. A missing/unreadable +calibration JSON report also fails before setup. + +Comparison is question-only: NFKC and casefold; Persian/Arabic kaf, yeh and digit +equivalence; collapsed Unicode whitespace; ZWNJ/ZWSP as spaces; removal of other +Unicode format controls; and removal of terminal period/exclamation/question +punctuation. Internal separators, words, numeric values and negation remain +significant. Evidence literals, stored queries and retrieval preprocessing are +never rewritten. This conservative equality check is not a semantic paraphrase +detector. Shared original documents are allowed when questions differ. + +Safe JSON diagnostics identify HELD_OUT_QUESTION_OVERLAP, +CALIBRATION_ANNOTATIONS_INVALID, ANNOTATION_TEXT_CORRUPT or unresolved/invalid +annotations and give the corrective action. They do not echo questions, evidence, +credentials or paths. Resolve overlap by independently annotating different +held-out questions before freezing; obtain a complete measured calibration report +rather than supplying a cutoff-only summary. + +Actual checks for this repair: + +- Targeted: .venv/Scripts/python -m pytest tests/unit/test_search_phase4_gate.py + tests/unit/test_search_phase4_repairs.py -q --tb=short: **52 passed**, zero skips, + 1.82 seconds. +- Full provider-free: .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: + **1300 passed, 3 skipped, 311 deselected**, 78.88 seconds. Skips are the existing + Windows symlink-permission checks. +- .venv/Scripts/python -m pip check: **No broken requirements found.** +- git diff --check, separate new-file whitespace, Python AST/JSON, strict UTF-8 + read-back and applied-migration byte comparisons: **passed**. +- Mandatory isolated PostgreSQL: **not run**, TEST_DATABASE_URL is not configured. + The 311 PostgreSQL results above are historical, not repair acceptance. +- Offline comparison: the 22 repaired populated questions are distinct from the + local ten Phase 2 annotations. The four unseen questions and complete future + measured calibration report must still be checked before real execution. + +All 26 status slots remain not_run, with zero provider calls and unavailable +usage/billing. Required original/FAQ approvals, actual document bindings, four +unseen questions, measured cutoff and funded-profile/call authorization/budget +remain pending. No production retrieval, cutoff, provider profile, admission, +migration or gate threshold changed. Retrieval, generated-answer and Live +readiness are not claimed. + +Final preservation inspection observed a change to scripts/live_voice_server.py +outside this repair. It was left untouched; all other unrelated baseline files +were unchanged. All three applied migrations match HEAD byte-for-byte. Local +documentation links and new-file inspection passed. Existing intentional Markdown +hard breaks were preserved. Temporary original-image inspection files were removed. diff --git a/docs/plans/live-document-mvp-todo.md b/docs/plans/live-document-mvp-todo.md index b3d44c1..8fc3b3e 100644 --- a/docs/plans/live-document-mvp-todo.md +++ b/docs/plans/live-document-mvp-todo.md @@ -1,6 +1,6 @@ # Live document MVP TODO -Updated 2026-10-07 against the revision 1.3 specifications. +Updated 2026-10-08 against the revision 1.3 specifications and scoped-search repair review. This checklist tracks implementation; it does not replace the governing [delivery plan](../specifications/RAG-AI-Phase1-Delivery-Plan.md), @@ -48,7 +48,7 @@ reported before promising a live demo. The four supplied examples are acceptance fixtures, not a filename allowlist or a four-document capacity limit. -## WP3 - Worker, review and publication (backend implemented; transport/selection pending) +## WP3 - Worker, review and publication (backend implemented; authenticated transport and Live invalidation pending) - [x] Add reviewed forward extraction-state/audit changes without editing applied revisions. - [x] Implement separate worker claim tokens, leases, heartbeats, bounded attempts and recovery. @@ -60,22 +60,22 @@ or a four-document capacity limit. - [x] Resume the same eligible failed document/job through the trusted retry backend/CLI after approval; fresh output requires fresh review. Authenticated D04 transport remains pending. - [x] Retain faithful complete FAQ extraction and explicitly approve included factual Q&A groups. - [x] Publish all validated chunks plus ready state in one transaction; keep new ready documents inactive. -- [ ] Implement activation/selection revisions, access epochs and invalidation with the documented lock order. +- [x] Implement atomic backend activation/selection, revision counters, access epochs and search-context rechecks with the documented lock order; see [search Phase 1/2 evidence](../agent-reference-map.md). - [x] Verify duplicate workers, expired leases, stale approvals, retries and partial failures against isolated PostgreSQL. ## WP4 - Shared scoped search -- [ ] Implement one backend pgvector search service using compatible bounded query embeddings. -- [ ] Derive organization/user/conversation scope from backend identity. -- [ ] Filter to authorized, ready, active and undeleted documents. -- [ ] Combine semantic evidence with exact normalized identifiers and bounded context. -- [ ] Return faithful text and document_id/chunk_id/location sources. +- [x] Implement one backend pgvector search service using compatible bounded query embeddings; see [Phase 2 handoff](../guides/scoped-search-phase2.md). +- [x] Resolve persisted enabled actors and derive organization/user scope at the trusted operator boundary; model arguments cannot override scope. Browser identity and owned conversation integration remain pending in WP2/WP5. +- [x] Filter to authorized, ready, active, undeleted and unpurged documents in every retrieval branch. +- [x] Combine semantic evidence with exact normalized identifiers and bounded untrusted context in the same retrieval core. +- [x] Return faithful whole-chunk text, document_id/chunk_id/location and execution-wide source references within evidence budgets. - [ ] Evaluate real Persian questions, numbers, conditions, exceptions and insufficient-evidence behavior. - [ ] Record the measured decision on reranking/ANN; implement only if evaluation demonstrates a need. ## WP5 - LangChain and native Live -- [ ] Expose the shared search through a small LangChain retriever/tool boundary. +- [x] Expose the shared search through a strict sync/async LangChain tool with lazy imports, bounded admission/deadlines, cancellation and shutdown; see [Phase 3 handoff](../guides/scoped-search-phase3.md). - [ ] Keep persistent secrets and provider-specific objects behind server adapters. - [ ] Add minimal owned voice conversations, Live sessions and voice tool-call persistence through forward migrations. - [ ] Implement session reservation and authenticated backend WSS audio relay to Gemini Live. @@ -101,6 +101,27 @@ or a four-document capacity limit. - [ ] Verify restart recovery, revocation, failure reporting and all MVP-01 through MVP-14 criteria. - [ ] Record actual results, remaining limits and demo run instructions. +## Scoped-search technical checkpoint (2026-10-08) + +Search milestone phases below are separate from ingestion Phases 1-6. +Implemented component checkmarks do not establish practical retrieval or Live readiness. + +- [x] Phase 4 evaluation preparation and review repairs: 16 answerable and six unsupported original-derived draft annotations restored as UTF-8; status aligned; calibration-question overlap/malformed annotations rejected before settings/database/provider setup. +- [x] Final repair review: 52 targeted provider-free tests rerun and passed; original hashes/status/DOCX literal checks, pip check, tracked whitespace and all three applied-migration byte comparisons passed. +- [ ] Complete and freeze 20 answerable cases, including four unseen cases, plus six unsupported cases; obtain original approvals and required exact-output/factual DOCX human decisions. The unseen slots remain empty. +- [ ] Bind approved original hashes to actual eligible ready documents and select the corpus through the atomic selection service. +- [ ] Obtain funded-profile/provider-call authorization and separate bounded ingestion, calibration and evaluation budgets; measure and freeze the Phase 2 cutoff before held-out evaluation. +- [ ] Rerun mandatory isolated PostgreSQL acceptance with --require-postgres for the current repair checkpoint. TEST_DATABASE_URL is absent; the earlier 311-pass result is historical. +- [ ] Pass the real Phase 4 gate: at least 18/20, every critical case, all six unsupported cases returning no_evidence, and no unauthorized/ineligible sources. + +The repair records a full provider-free run of 1300 passed with three existing +Windows symlink skips; that full run was not repeated during final review. +See the [Phase 4 operator guide](../guides/scoped-search-phase4.md), +[status snapshot](../calibration/phase4-status.json) and +[scoped-search plan](scoped-search-implementation-plan.md) for actual commands, +historical results and remaining prerequisites. Quality acceptance is not run; +provider calls are zero. Generated-answer and Live readiness remain unevaluated. + ## Conditional delivery checkpoints | Checkpoint | Required progress | diff --git a/docs/plans/scoped-search-implementation-plan.md b/docs/plans/scoped-search-implementation-plan.md index 2eac47a..de726f9 100644 --- a/docs/plans/scoped-search-implementation-plan.md +++ b/docs/plans/scoped-search-implementation-plan.md @@ -2,7 +2,7 @@ **Date:** 2026-10-07 **Target file:** `docs/plans/scoped-search-implementation-plan.md` -**Status:** Phase 1 first-result checkpoint implemented with provider-free PostgreSQL acceptance (2026-10-07); real-provider demonstration is pending ingestion database connectivity. Phases 2-4 remain pending. This four-phase plan replaces the earlier seven-phase proposal. +**Status:** Phase 1 first-result checkpoint implemented with provider-free PostgreSQL acceptance (2026-10-07); real-provider demonstration is pending ingestion database connectivity. Phase 2 technical retrieval correctness is implemented with provider-free unit/PostgreSQL acceptance (2026-10-08); real-model cutoff calibration remains pending explicit call authorization and approved original/document bindings. Phase 3 thin LangChain integration is technically accepted (2026-10-08): 162 affected unit and 103 affected PostgreSQL tests (including the runner shutdown repair), zero skips, with the declared search extra installed; see [Phase 3 handoff](../guides/scoped-search-phase3.md). Phase 4 historical preparatory regressions passed (2026-10-08): 1258 provider-free tests and 311 mandatory isolated PostgreSQL tests. Real quality acceptance remains not run; see [Phase 4 handoff](../guides/scoped-search-phase4.md). All six Phase 2 repairs passed 107 affected unit tests, 100 isolated PostgreSQL tests and 1193 provider-free regression tests; see [repair acceptance](../guides/scoped-search-phase2-repairs.md) and [Phase 2 results](../guides/scoped-search-phase2.md). This four-phase plan replaces the earlier seven-phase proposal. ## 1. Delivery Strategy @@ -211,7 +211,7 @@ Use a thin `StructuredTool` adapter with an explicit argument schema and synchro Default execution limits: four running calls, eight waiting calls, and a 75-second total deadline. SQL statement/lock timeouts are five/two seconds. Validate configuration; retain the explicit provider timeout policy. -Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries. +Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries. Runner closure returns nonretryable SEARCH_CANCELLED for queued/new calls and suppresses late running results. Repeated close is safe; submission and closure share a lock, submitted slots remain held until actual completion, and close joins work plus queued admission releases. Call blocking close outside active event loops and its worker pool. See [shutdown repair acceptance](../guides/scoped-search-phase3.md#shutdown-repair-acceptance-2026-10-08). **Execution prompt** @@ -332,3 +332,69 @@ Each phase reports its working command, observed output, actual checks, and rema No latency or concurrent-user service-level target has been approved. Measure timings and enforce the stated execution bounds without claiming an unapproved performance target. Actual provider runs require explicit opt-in, compatible credentials, approved inputs, and a bounded operator call budget. **Speed rule:** finish and demonstrate each usable checkpoint before expanding it. Optimize only a reproduced quality or latency problem. The MVP search milestone remains incomplete until the confirmed real-quality gate passes. + + +## Historical Phase 4 preparatory checkpoint (2026-10-08) + +Final regression acceptance: 1258 provider-free passed, three existing Windows +symlink skips; 311 mandatory isolated PostgreSQL passed with zero skips. +pip check, tracked/new-file whitespace, Python/JSON inspection and byte +preservation of all three applied migrations passed. No production fixes. + +[Original annotations](../calibration/phase4-cases.draft.json) contain 16 draft +answerable and six unsupported cases, with four explicitly empty unseen slots. +Original SHA-256 hashes are recorded; approval and actual document bindings +remain pending. This is not a completed/frozen 20-case set. +[Opt-in evaluator](../../tests/evaluate_search.py) calls canonical SearchService +with the frozen Phase 2 calibration, validates actual selection/bindings and +sources, enforces a maximum 26-query call budget, retains every failure/not-run +case, and applies the exact gate. Ten provider-free evaluation regressions pass. + +[Status](../calibration/phase4-status.json) and +[operator guide](../guides/scoped-search-phase4.md) record actual results. +Real provider calls: zero. Phase 2 has no measured cutoff. Funded-profile/call +authorization, approved unseen originals, human review/DOCX inclusion and actual +ready document bindings remain missing. Phase 4 quality gate is not run; +retrieval readiness, generated-answer readiness and Live readiness are not claimed. + +Cleanup confirmed zero disposable schemas and zero public tables. The created +Phase 4 test container and its anonymous volume were removed; existing containers +were preserved. Temporary original-page renderings were removed. Baseline +comparison found a concurrent change to scripts/live_voice_server.py, which this +evaluation did not edit. All other unrelated baseline files were unchanged. + + +## Phase 4 review repairs (2026-10-08) + +The two review findings are fixed in the evaluation boundary. All 16 answerable +and six unsupported annotations were reconstructed from actual original PDFs, +infographic and DOCX, verified by strict UTF-8 read-back and synchronized with +the status snapshot. Zero unresolved populated annotations; all four unseen +slots remain empty. No original/review approvals or document bindings changed. + +Question-only comparison against the supplied full Phase 2 report now rejects +exact and formatting-equivalent overlap and missing/malformed annotations before +settings/database/provider setup. NFKC, casefold, Persian/Arabic letter/digit +variants, Unicode whitespace/format controls and terminal punctuation are +comparison-only; original evidence and retrieval preprocessing remain unchanged. +Different questions may share original documents; semantic paraphrases are not +automatically detected. Safe errors identify the prerequisite/corrective action. + +Current checks: **52 targeted tests passed**; full provider-free **1300 passed, +3 existing Windows symlink skips, 311 deselected**; pip check, tracked/new-file +whitespace, AST/JSON, persisted UTF-8 and all three migration byte comparisons +passed. Mandatory isolated PostgreSQL is **not run**: TEST_DATABASE_URL is not +configured. Earlier PostgreSQL counts remain historical evidence only. +[Operator guide](../guides/scoped-search-phase4.md) and +[status](../calibration/phase4-status.json) record commands and limitations. + +Quality acceptance remains not_run with zero provider calls. Pending: measured +Phase 2 cutoff/funded-profile authorization and bounded budget, approved +originals/DOCX human review, actual eligible bindings and four unseen annotations. +No retrieval, generated-answer or Live readiness is claimed. + +Final preservation inspection observed a change to scripts/live_voice_server.py +outside this repair. It was left untouched; all other unrelated baseline files +were unchanged. All three applied migrations match HEAD byte-for-byte. Local +documentation links and new-file inspection passed. Existing intentional Markdown +hard breaks were preserved. Temporary original-image inspection files were removed. diff --git a/docs/specifications/RAG-Phase1-API-Catalog.md b/docs/specifications/RAG-Phase1-API-Catalog.md index ded96af..4461a6b 100644 --- a/docs/specifications/RAG-Phase1-API-Catalog.md +++ b/docs/specifications/RAG-Phase1-API-Catalog.md @@ -367,7 +367,7 @@ Illustrative successful result; text/location must be populated from actual reta {"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}} ``` -`no_evidence` is completed retrieval with insufficient support, not a provider failure. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search. +`no_evidence` is completed retrieval with insufficient support, not a provider failure. The shared core requires a measured profile-specific cutoff for canonical evidence admission; absent calibration returns `error` with `CALIBRATION_REQUIRED`, never an invented default threshold. Operator inspection may return explicitly labeled uncalibrated candidates without claiming evidence sufficiency. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search. Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence. diff --git a/pyproject.toml b/pyproject.toml index 898c59a..720502a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ ] [project.optional-dependencies] +search = ["langchain-core>=1,<2"] embedding = ["tiktoken>=0.8,<1"] test = ["pytest>=8.3,<10"] prototype = [ diff --git a/tests/evaluate_search.py b/tests/evaluate_search.py new file mode 100644 index 0000000..c8e0979 --- /dev/null +++ b/tests/evaluate_search.py @@ -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()) diff --git a/tests/integration/test_search_phase2.py b/tests/integration/test_search_phase2.py new file mode 100644 index 0000000..0d182fd --- /dev/null +++ b/tests/integration/test_search_phase2.py @@ -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 diff --git a/tests/integration/test_search_phase2_remaining.py b/tests/integration/test_search_phase2_remaining.py new file mode 100644 index 0000000..d4a9900 --- /dev/null +++ b/tests/integration/test_search_phase2_remaining.py @@ -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) diff --git a/tests/integration/test_search_phase2_repairs.py b/tests/integration/test_search_phase2_repairs.py new file mode 100644 index 0000000..94e7726 --- /dev/null +++ b/tests/integration/test_search_phase2_repairs.py @@ -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) diff --git a/tests/integration/test_search_phase3.py b/tests/integration/test_search_phase3.py new file mode 100644 index 0000000..193cdfb --- /dev/null +++ b/tests/integration/test_search_phase3.py @@ -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() diff --git a/tests/phase4_gate.py b/tests/phase4_gate.py new file mode 100644 index 0000000..86d7f1f --- /dev/null +++ b/tests/phase4_gate.py @@ -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) diff --git a/tests/support/search.py b/tests/support/search.py index 6938e43..a2fe941 100644 --- a/tests/support/search.py +++ b/tests/support/search.py @@ -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, diff --git a/tests/unit/test_search_phase2.py b/tests/unit/test_search_phase2.py new file mode 100644 index 0000000..8943b58 --- /dev/null +++ b/tests/unit/test_search_phase2.py @@ -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" diff --git a/tests/unit/test_search_phase2_remaining.py b/tests/unit/test_search_phase2_remaining.py new file mode 100644 index 0000000..5bfc6b1 --- /dev/null +++ b/tests/unit/test_search_phase2_remaining.py @@ -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"]) diff --git a/tests/unit/test_search_phase2_repairs.py b/tests/unit/test_search_phase2_repairs.py new file mode 100644 index 0000000..eab9950 --- /dev/null +++ b/tests/unit/test_search_phase2_repairs.py @@ -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 diff --git a/tests/unit/test_search_phase3.py b/tests/unit/test_search_phase3.py new file mode 100644 index 0000000..0930683 --- /dev/null +++ b/tests/unit/test_search_phase3.py @@ -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()) diff --git a/tests/unit/test_search_phase3_shutdown.py b/tests/unit/test_search_phase3_shutdown.py new file mode 100644 index 0000000..0115f39 --- /dev/null +++ b/tests/unit/test_search_phase3_shutdown.py @@ -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) diff --git a/tests/unit/test_search_phase4_gate.py b/tests/unit/test_search_phase4_gate.py new file mode 100644 index 0000000..4b20270 --- /dev/null +++ b/tests/unit/test_search_phase4_gate.py @@ -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() diff --git a/tests/unit/test_search_phase4_repairs.py b/tests/unit/test_search_phase4_repairs.py new file mode 100644 index 0000000..be49587 --- /dev/null +++ b/tests/unit/test_search_phase4_repairs.py @@ -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()