feat(search): add calibrated retrieval and LangChain knowledge tool

Add exact and semantic evidence admission, measured calibration, bounded tool execution, and independent held-out evaluation preparation with regression coverage and operator guides. Real-provider quality gates remain pending.

Validation: 1300 provider-free tests passed; 3 Windows symlink skips. PostgreSQL acceptance not rerun because TEST_DATABASE_URL is unset.
This commit is contained in:
amirhosein mazaheri
2026-10-08 12:58:59 +03:30
parent 4d36f2ba35
commit fef381c41b
36 changed files with 6679 additions and 45 deletions
+253
View File
@@ -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 <original-path> --administrator-id <admin-id> --idempotency-key <new-uuid>
.venv/Scripts/python -m app.worker --once
.venv/Scripts/python -m app.ingest status <document-id> --administrator-id <admin-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 <admin-id>
.venv/Scripts/python -m app.knowledge selection replace --administrator-id <admin-id> --expected-revision <revision> --document-id <id-1> --document-id <id-2>
~~~
Use all approved evaluation corpus IDs, with no extra active documents. Save an
external JSON mapping {"<sha256>":"<actual-document-uuid>"} 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 <enabled-user-id> --query "<Persian question>" --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 <frozen-cases.json> --bindings <bindings.json> --calibration <phase2-measured-report.json> --user-id <enabled-user-id> --output <new-results.jsonl> --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.