Files
rag-technical-docs-assistant/docs/guides/scoped-search-phase3.md
T
amirhosein mazaheri fef381c41b 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.
2026-10-08 12:58:59 +03:30

11 KiB

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:

.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.

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 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.

{
  "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.

.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 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:

.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:

.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.