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