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
+264 -1
View File
@@ -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.