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
+170
View File
@@ -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:
`{"<original_sha256 from phase2-cases.json>":"<selected document UUID>"}`.
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 <enabled-user-id> --bindings <bindings.json> --output <new-report.json> --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 <enabled-user-id> --query "<question>" --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.