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
+4 -2
View File
@@ -31,8 +31,10 @@ Implementation progress is tracked in the [Live document MVP TODO](plans/live-do
Phase 5 worker/publication/retry and retained review/resume backend services are
implemented; [Phase 6 operator handoff](guides/ingestion-operator-handoff.md)
records integration acceptance and the separate opt-in provider smoke command.
Authenticated D06/D07 transport, scoped pgvector search/selection, HTTP
identity/upload, browser integration, Live and UI remain pending. Real-provider
Scoped pgvector search/selection and Fast-Track Search Phase 2 technical
correctness are implemented; [Phase 2 results and calibration prerequisites](guides/scoped-search-phase2.md)
record actual acceptance. Real-model cutoff calibration, LangChain, authenticated
D06/D07 transport, HTTP identity/upload, browser integration, Live and UI remain pending. Real-provider
compatibility and Persian extraction/semantic quality are not certified by mocks.
The [root README](../README.md) retains prototype startup instructions.
+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.
+115
View File
@@ -0,0 +1,115 @@
{
"original_file": "../../data/calibration/phase2-source.md",
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f",
"annotation_basis": "Literal original paragraphs authored before retrieval; quantities and all qualifiers independently marked. Calibration only, separate from Phase 4.",
"cases": [
{
"id": "A1",
"answerable": true,
"query": "شرط فشار پمپ در ماده ۱ و استثنای شیر کنارگذر چیست؟",
"evidence_groups": [
[
"۲۵ بار",
"فقط وقتی دما کمتر از ۶۰ درجه",
"باز نکنید",
"مگر هنگام خاموشی"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "A2",
"answerable": true,
"query": "ماده ۲ درباره دبی و زمان بازرسی آب‌بندها چه می‌گوید؟",
"evidence_groups": [
[
"۴۰ لیتر در دقیقه",
"مگر ورودی مسدود باشد",
"هر ۳۰ روز"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "A3",
"answerable": true,
"query": "گشتاور و ممنوعیت راه‌اندازی در ماده ۳ چیست؟",
"evidence_groups": [
[
"۱۵ نیوتن‌متر",
"در صورت نشتی",
"راه‌اندازی نکنید",
"مگر پس از بازرسی"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "A4",
"answerable": true,
"query": "تاریخ و مهلت درخواست بخشنامه K-1403/07 با شرط آن چیست؟",
"evidence_groups": [
[
"۱۴۰۳/۰۷/۰۱",
"۱۰ روز",
"فقط برای متقاضی دارای مجوز معتبر"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "A5",
"answerable": true,
"query": "در ماده ۴ میزان تخفیف، تاریخ و استثنا چیست؟",
"evidence_groups": [
[
"۱۲ درصد",
"تا ۱۴۰۳/۰۸/۰۱",
"درخواست بدون مجوز مشمول نیست"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "A6",
"answerable": true,
"query": "تعویض فیلتر PUMP-7 در تبصره ۲ چه شرط و استثنایی دارد؟",
"evidence_groups": [
[
"PUMP-7",
"فقط پس از قطع برق",
"تجهیزات دارای نشتی مستثنا هستند"
]
],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "U1",
"answerable": false,
"query": "قیمت فعلی زمین صنعتی چقدر است؟",
"evidence_groups": [],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "U2",
"answerable": false,
"query": "موجودی حساب مشتری با شناسه ACCOUNT-99 چقدر است؟",
"evidence_groups": [],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "U3",
"answerable": false,
"query": "استثنای تمدید در ماده ۹۹ چیست؟",
"evidence_groups": [],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
},
{
"id": "U4",
"answerable": false,
"query": "نرخ ارز در تاریخ ۱۴۰۴/۰۱/۰۱ چقدر است؟",
"evidence_groups": [],
"original_sha256": "7d1e384210faa9430f715a3f30736c8ad7c782f701843a68bab969845934835f"
}
]
}
+39
View File
@@ -0,0 +1,39 @@
{
"status": "pending",
"date": "2026-10-08",
"cutoff": null,
"provider_calls": 0,
"configured_profile": {
"provider": "ollama",
"endpoint": "http://localhost:11434/v1",
"model": "bge-m3",
"dimensions": 1024,
"preprocessing_version": "v1"
},
"calibration_cases": {
"answerable": 6,
"unsupported": 4,
"annotations": "docs/calibration/phase2-cases.json",
"original": "data/calibration/phase2-source.md"
},
"missing_prerequisites": [
"explicit_authorization_for_real_provider_calls",
"approved_original_to_selected_document_bindings",
"verified_compatible_real_ingestion_database_and_provider"
],
"selection_rule": "Maximize complete-support coverage with zero unsupported false positives; stricter cutoff on ties.",
"model_quality_acceptance": "pending",
"technical_tests": "provider-free; current repairs recorded in docs/guides/scoped-search-phase2-repairs.md",
"technical_repair_status": "verified",
"technical_repair_results": {
"affected_unit_passed": 107,
"affected_postgres_passed": 100,
"provider_free_passed": 1193,
"provider_free_skipped": 3,
"provider_free_deselected": 308
},
"latest_repairs": [
"literal_frozen_annotation_boundaries",
"confirmed_sqlstate_less_connection_invalidation"
]
}
+741
View File
@@ -0,0 +1,741 @@
{
"status": "incomplete_not_frozen",
"date": "2026-10-08",
"originals": {
"letter": {
"path": "data/documents/5905170444656189186_13450510740952.pdf",
"sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"document_id": null,
"approval": "pending"
},
"regulation": {
"path": "data/documents/7364346504113364738_13450847753183.pdf",
"sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"document_id": null,
"approval": "pending"
},
"infographic": {
"path": "data/documents/photo_1_2026-10-06_09-05-11.jpg",
"sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"document_id": null,
"approval": "pending"
},
"docx": {
"path": "data/documents/-2348240626507047168_13449360743721.docx",
"sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"document_id": null,
"approval": "pending"
}
},
"cases": [
{
"id": "A01",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "مشوق دهه فجر کدام بخش قرارداد واگذاری حق بهره‌برداری زمین را کاهش می‌دهد و میزان کاهش چقدر است؟",
"evidence_groups": [
[
"کاهش بخش نقدی",
"پیش دریافت",
"قراردادهای واگذاری حق بهره برداری زمین",
"۱۰",
"درصد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Reduction of cash advance only; no total-price discount inferred.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A02",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "برای برخورداری از مشوق دهه فجر، قرارداد واگذاری باید در چه بازه زمانی منعقد شود؟",
"evidence_groups": [
[
"از تاریخ",
"۱۲",
"بهمن تا پایان بهمن سال",
"۱۴۰۴",
"منعقد گردد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Contract conclusion within the stated window; not upload date.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A03",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "آیا قراردادهای انصرافی مشمول مشوق دهه فجر هستند و قید زمانی استثنا چیست؟",
"evidence_groups": [
[
"قراردادهای انصرافی",
"از تاریخ ابلاغ این مصوبه",
"مشمول این مشوق نمی گردند"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Exclusion applies from notification date.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A04",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "آیا اراضی و مستحدثات واگذارشده به شیوه مزایده از مشوق دهه فجر برخوردارند؟",
"evidence_groups": [
[
"اراضی و مستحدثاتی",
"وفق مصوبه هیات مدیره شرکت استانی",
"به شیوه مزایده واگذار می شوند",
"مشمول این مشوق نمی گردند"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Preserve provincial board resolution qualifier and negation.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A05",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "قیمت و بازپرداخت اقساط قراردادهای مشمول مشوق دهه فجر تابع کدام ماده و مصوبه معتبر است؟",
"evidence_groups": [
[
"قیمت و بازپرداخت اقساط",
"ماده",
"۸",
"دستورالعمل بهره برداری"
],
[
"مصوبه هیات مدیره شرکت استانی",
"در شش ماه دوم سال جاری معتبر میباشد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Both article and valid provincial resolution; not a new instalment rate.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A06",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "ماده ۵ چه حد نصابی برای واگذاری زمین و تعداد واحدهای بهره‌بردار شهرک صنعتی و ناحیه صنعتی روستایی تعیین کرده است؟",
"evidence_groups": [
[
"بیش از هفتاد و پنج درصد",
"زمین های قابل واگذاری",
"فاز عملیاتی",
"واگذار"
],
[
"حداقل تعداد واحدهای به بهره برداری رسیده",
"در شهرک صنعتی به بیست و پنج واحد",
"در ناحیه صنعتی روستایی به پانزده واحد"
],
[
"بر اساس شرایط مندرج در اساسنامه نمونه",
"تشکیل شرکت خدماتی"
]
],
"locator": {
"page": 3,
"section": "ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Strictly greater than 75%; 25 industrial-town/15 rural-area operating units.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A07",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "ماده ۶ در چه شرایطی شرکت را موظف به تشکیل شرکت خدماتی می‌کند؟",
"evidence_groups": [
[
"حداقل هفتاد و پنج درصد",
"زمین های قابل واگذاری",
"واگذار"
],
[
"حداقل پنجاه درصد",
"واحدهای مستقر",
"با هر تعداد به بهره برداری رسیده باشد",
"موظف به تشکیل شرکت خدماتی"
]
],
"locator": {
"page": 3,
"section": "ماده ۶ (اصلاحی ۱۳۹۶/۰۴/۱۸)"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "At least 75% land and at least 50% resident units operating; any unit count.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A08",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "طبق تبصره ماده ۵، پیش از تشکیل شرکت خدماتی چه کسی امور شهرک و ناحیه صنعتی را اداره می‌کند؟",
"evidence_groups": [
[
"تا قبل از تشکیل شرکت خدماتی",
"اداره امور شهرک و ناحیه صنعتی",
"توسط شرکت صورت می گیرد"
]
],
"locator": {
"page": 3,
"section": "تبصره ماده ۵ (اصلاحی ۱۳۹۶/۰۴/۱۸)"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Before service company formation only.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A09",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "ماده ۸ پرداخت هزینه شرکت خدماتی را تا چه مدت مجاز می‌داند و کسر هزینه پس از تشکیل شرکت چگونه است؟",
"evidence_groups": [
[
"می توانند حداکثر دو ماه",
"هزینه های شرکت خدماتی"
],
[
"پس از تشکیل شرکت خدماتی",
"منطبق با اساسنامه شرکت",
"از هزینه های مشترک قابل پرداخت توسط شرکت کسر نمایند"
]
],
"locator": {
"page": 3,
"section": "ماده ۸ (اصلاحی ۱۳۹۶/۰۴/۱۸)"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Maximum two months, permissible rather than mandatory.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A10",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "اگر ساخت‌وساز غیرمجاز مالک یا متصرف قانونی به مشاعات خسارت بزند، ماده ۴ چه تکلیفی در حالت توافق و عدم توافق مقرر می‌کند؟",
"evidence_groups": [
[
"ساخت و ساز غیرمجاز مالک یا متصرف قانونی",
"قسمتی از مشاعات",
"از بین رفته و یا تخریب گردد"
],
[
"از طریق توافق",
"جبران خسارت وارده",
"اعاده وضع به حال سابق"
],
[
"در صورت عدم توافق",
"جبران خسارت و اعاده وضع به حال سابق",
"مطابق قوانین و مقررات مربوط"
]
],
"locator": {
"page": 3,
"section": "ماده ۴"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Keep negotiated remedy and fallback legal process.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A11",
"answerable": true,
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"query": "شش محور اصلاح نظام اداری دولت چهاردهم در تصویر کدام‌اند؟",
"evidence_groups": [
[
"چابک‌سازی و تمرکززدایی ساختاری"
],
[
"مدیریت شایسته محور سرمایه انسانی"
],
[
"ارتقای سلامت اداری و مقابله با فساد"
],
[
"استقرار دولت هوشمند و داده‌محور"
],
[
"مدیریت عملکرد نتیجه گرا"
],
[
"ارتقای بهره‌وری ملی و انرژی"
]
],
"locator": {
"page": null,
"section": "شش محور؛ دو ستون تحول در ساختار و سرمایه انسانی و هوشمندسازی و ارتقای بهره‌وری"
},
"critical": false,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Six axes across both image columns; no invented numerical target.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A12",
"answerable": true,
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"query": "محور ارتقای سلامت اداری و مقابله با فساد چه اقداماتی را درباره تعارض منافع مطرح می‌کند؟",
"evidence_groups": [
[
"شفافیت",
"پاسخگویی",
"پیشگیری از وقوع موقعیت"
],
[
"تعارض منافع",
"دستگاه‌های اجرایی"
]
],
"locator": {
"page": null,
"section": "ارتقای سلامت اداری و مقابله با فساد؛ پایین ستون چپ"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Prevention of conflict-of-interest situations; not a guarantee of elimination.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A13",
"answerable": true,
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"query": "در محور مدیریت عملکرد نتیجه‌گرا، نظام جبران خدمت و پاداش‌ها به چه چیزی متصل می‌شود؟",
"evidence_groups": [
[
"اتصال نظام جبران خدمت و پاداش‌ها به",
"نتایج واقعی ارزیابی عملکرد"
]
],
"locator": {
"page": null,
"section": "مدیریت عملکرد نتیجه گرا؛ میانه ستون راست"
},
"critical": false,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Original infographic states connection of compensation and rewards to actual performance-evaluation results; no claim about a redesigned measurement system.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A14",
"answerable": true,
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"query": "در فایل اصلی ساعت کاری شنبه تا چهارشنبه و پنجشنبه چیست و هنگام تعطیلی یا تغییر ساعات اداری چه ملاکی حاکم است؟",
"evidence_groups": [
[
"از شنبه تا چهارشنبه از ساعت 8 صبح الي 13",
"در روزپنجشنبه از 8 صبح الي 12"
],
[
"در روزهای تعطیل یا تغییر ساعات اداری، آخرین ابلاغ شرکت ملاک است."
]
],
"locator": {
"page": null,
"section": "سؤال ساعت کاری؛ پاسخ در بند ۳ فایل اصلی"
},
"critical": true,
"unseen": false,
"annotation_method": "original DOCX OOXML paragraph reconstruction",
"qualifiers": "Candidate factual group; human authority/inclusion approval absent. Latest official notice governs.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A15",
"answerable": true,
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"query": "برای پیگیری امور انفورماتیک در فایل اصلی نام مخاطب و شماره داخلی چیست؟",
"evidence_groups": [
[
"سرکار خانم آذری، داخلی ۲۹۰"
]
],
"locator": {
"page": null,
"section": "سؤال امور انفورماتیک؛ پاسخ در بند ۱۱ فایل اصلی"
},
"critical": true,
"unseen": false,
"annotation_method": "original DOCX OOXML paragraph reconstruction",
"qualifiers": "Candidate factual group; not approved for publication.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "A16",
"answerable": true,
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"query": "نشانی شرکت در پاسخ مربوط به آدرس در فایل اصلی چیست؟",
"evidence_groups": [
[
"خ 22 بهمن ، مجموعه اداري امير كبير (غدير)"
]
],
"locator": {
"page": null,
"section": "سؤال آدرس شرکت؛ پاسخ در بند ۷ فایل اصلی"
},
"critical": false,
"unseen": false,
"annotation_method": "original DOCX OOXML paragraph reconstruction",
"qualifiers": "Candidate factual group; not independently verified as current address.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U01",
"answerable": false,
"query": "قیمت روز هر متر زمین محمودآباد چقدر است؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "No approved current tariff; DOCX demands current data, gives no price.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U02",
"answerable": false,
"query": "موجودی لحظه‌ای زمین محمودآباد چند مترمربع است؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "No live inventory in supplied originals.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U03",
"answerable": false,
"query": "بدهی فعلی شرکت فلان در پرونده صنعتی چقدر است؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "No authorized case database/evidence; never use behavioral DOCX replies as factual case data.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U04",
"answerable": false,
"query": "در تصویر اصلاح نظام اداری، هدف عددی کاهش مصرف انرژی چند درصد است؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "Infographic gives an axis, not a numeric energy target.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U05",
"answerable": false,
"query": "شماره موبایل مدیرعامل فلان کارخانه چیست؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "No approved personal contact evidence.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
},
{
"id": "U06",
"answerable": false,
"query": "میزان مشوق قراردادهای منعقدشده پس از پایان بهمن ۱۴۰۴ چقدر است؟",
"evidence_groups": [],
"critical": false,
"unseen": false,
"annotation_status": "draft_absence_review",
"absence_basis": "Letter concerns 1404 conclusion window; no 1406 percentage.",
"outcome": "not_run",
"annotation_method": "original corpus absence review; no retrieved or generated output",
"absence_sources": [
{
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"scope": "entire supplied original"
},
{
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"scope": "entire supplied original"
},
{
"original": "infographic",
"original_sha256": "cd177e935f25200c53af958a6c7b4540b820d49043e62fa1d383e6a76954f935",
"scope": "entire supplied original"
},
{
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"scope": "entire supplied original"
}
],
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision."
}
],
"pending_answerable_slots": [
{
"id": "A17",
"unseen": true,
"query": null,
"evidence_groups": null,
"reason": "Approved unseen original unavailable; cannot invent original-bound evidence."
},
{
"id": "A18",
"unseen": true,
"query": null,
"evidence_groups": null,
"reason": "Approved unseen original unavailable; cannot invent original-bound evidence."
},
{
"id": "A19",
"unseen": true,
"query": null,
"evidence_groups": null,
"reason": "Approved unseen original unavailable; cannot invent original-bound evidence."
},
{
"id": "A20",
"unseen": true,
"query": null,
"evidence_groups": null,
"reason": "Approved unseen original unavailable; cannot invent original-bound evidence."
}
],
"required_gate": {
"answerable_total": 20,
"answerable_minimum": 18,
"all_critical": true,
"unsupported_total": 6,
"all_unsupported": true,
"no_ineligible_sources": true
},
"annotation_caveat": "Original-derived draft transcriptions, not search output. Resolve literal rendering differences against originals before freezing; never weaken labels after retrieval. DOCX facts are pending human factual-corpus approval. Unsupported labels must be rechecked against complete approved unseen corpus before freeze.",
"provider_calls": 0,
"usage": "unavailable",
"billing": "unavailable",
"annotation_repair": {
"status": "reconstructed_from_originals",
"answerable_reconstructed": 16,
"unsupported_reconstructed": 6,
"unresolved": [],
"persisted_encoding": "UTF-8",
"human_approvals_changed": false
}
}
File diff suppressed because it is too large Load Diff
@@ -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.
+30 -9
View File
@@ -1,6 +1,6 @@
# Live document MVP TODO
Updated 2026-10-07 against the revision 1.3 specifications.
Updated 2026-10-08 against the revision 1.3 specifications and scoped-search repair review.
This checklist tracks implementation; it does not replace the governing
[delivery plan](../specifications/RAG-AI-Phase1-Delivery-Plan.md),
@@ -48,7 +48,7 @@ reported before promising a live demo.
The four supplied examples are acceptance fixtures, not a filename allowlist
or a four-document capacity limit.
## WP3 - Worker, review and publication (backend implemented; transport/selection pending)
## WP3 - Worker, review and publication (backend implemented; authenticated transport and Live invalidation pending)
- [x] Add reviewed forward extraction-state/audit changes without editing applied revisions.
- [x] Implement separate worker claim tokens, leases, heartbeats, bounded attempts and recovery.
@@ -60,22 +60,22 @@ or a four-document capacity limit.
- [x] Resume the same eligible failed document/job through the trusted retry backend/CLI after approval; fresh output requires fresh review. Authenticated D04 transport remains pending.
- [x] Retain faithful complete FAQ extraction and explicitly approve included factual Q&A groups.
- [x] Publish all validated chunks plus ready state in one transaction; keep new ready documents inactive.
- [ ] Implement activation/selection revisions, access epochs and invalidation with the documented lock order.
- [x] Implement atomic backend activation/selection, revision counters, access epochs and search-context rechecks with the documented lock order; see [search Phase 1/2 evidence](../agent-reference-map.md).
- [x] Verify duplicate workers, expired leases, stale approvals, retries and partial failures against isolated PostgreSQL.
## WP4 - Shared scoped search
- [ ] Implement one backend pgvector search service using compatible bounded query embeddings.
- [ ] Derive organization/user/conversation scope from backend identity.
- [ ] Filter to authorized, ready, active and undeleted documents.
- [ ] Combine semantic evidence with exact normalized identifiers and bounded context.
- [ ] Return faithful text and document_id/chunk_id/location sources.
- [x] Implement one backend pgvector search service using compatible bounded query embeddings; see [Phase 2 handoff](../guides/scoped-search-phase2.md).
- [x] Resolve persisted enabled actors and derive organization/user scope at the trusted operator boundary; model arguments cannot override scope. Browser identity and owned conversation integration remain pending in WP2/WP5.
- [x] Filter to authorized, ready, active, undeleted and unpurged documents in every retrieval branch.
- [x] Combine semantic evidence with exact normalized identifiers and bounded untrusted context in the same retrieval core.
- [x] Return faithful whole-chunk text, document_id/chunk_id/location and execution-wide source references within evidence budgets.
- [ ] Evaluate real Persian questions, numbers, conditions, exceptions and insufficient-evidence behavior.
- [ ] Record the measured decision on reranking/ANN; implement only if evaluation demonstrates a need.
## WP5 - LangChain and native Live
- [ ] Expose the shared search through a small LangChain retriever/tool boundary.
- [x] Expose the shared search through a strict sync/async LangChain tool with lazy imports, bounded admission/deadlines, cancellation and shutdown; see [Phase 3 handoff](../guides/scoped-search-phase3.md).
- [ ] Keep persistent secrets and provider-specific objects behind server adapters.
- [ ] Add minimal owned voice conversations, Live sessions and voice tool-call persistence through forward migrations.
- [ ] Implement session reservation and authenticated backend WSS audio relay to Gemini Live.
@@ -101,6 +101,27 @@ or a four-document capacity limit.
- [ ] Verify restart recovery, revocation, failure reporting and all MVP-01 through MVP-14 criteria.
- [ ] Record actual results, remaining limits and demo run instructions.
## Scoped-search technical checkpoint (2026-10-08)
Search milestone phases below are separate from ingestion Phases 1-6.
Implemented component checkmarks do not establish practical retrieval or Live readiness.
- [x] Phase 4 evaluation preparation and review repairs: 16 answerable and six unsupported original-derived draft annotations restored as UTF-8; status aligned; calibration-question overlap/malformed annotations rejected before settings/database/provider setup.
- [x] Final repair review: 52 targeted provider-free tests rerun and passed; original hashes/status/DOCX literal checks, pip check, tracked whitespace and all three applied-migration byte comparisons passed.
- [ ] Complete and freeze 20 answerable cases, including four unseen cases, plus six unsupported cases; obtain original approvals and required exact-output/factual DOCX human decisions. The unseen slots remain empty.
- [ ] Bind approved original hashes to actual eligible ready documents and select the corpus through the atomic selection service.
- [ ] Obtain funded-profile/provider-call authorization and separate bounded ingestion, calibration and evaluation budgets; measure and freeze the Phase 2 cutoff before held-out evaluation.
- [ ] Rerun mandatory isolated PostgreSQL acceptance with --require-postgres for the current repair checkpoint. TEST_DATABASE_URL is absent; the earlier 311-pass result is historical.
- [ ] Pass the real Phase 4 gate: at least 18/20, every critical case, all six unsupported cases returning no_evidence, and no unauthorized/ineligible sources.
The repair records a full provider-free run of 1300 passed with three existing
Windows symlink skips; that full run was not repeated during final review.
See the [Phase 4 operator guide](../guides/scoped-search-phase4.md),
[status snapshot](../calibration/phase4-status.json) and
[scoped-search plan](scoped-search-implementation-plan.md) for actual commands,
historical results and remaining prerequisites. Quality acceptance is not run;
provider calls are zero. Generated-answer and Live readiness remain unevaluated.
## Conditional delivery checkpoints
| Checkpoint | Required progress |
@@ -2,7 +2,7 @@
**Date:** 2026-10-07
**Target file:** `docs/plans/scoped-search-implementation-plan.md`
**Status:** Phase 1 first-result checkpoint implemented with provider-free PostgreSQL acceptance (2026-10-07); real-provider demonstration is pending ingestion database connectivity. Phases 2-4 remain pending. This four-phase plan replaces the earlier seven-phase proposal.
**Status:** Phase 1 first-result checkpoint implemented with provider-free PostgreSQL acceptance (2026-10-07); real-provider demonstration is pending ingestion database connectivity. Phase 2 technical retrieval correctness is implemented with provider-free unit/PostgreSQL acceptance (2026-10-08); real-model cutoff calibration remains pending explicit call authorization and approved original/document bindings. Phase 3 thin LangChain integration is technically accepted (2026-10-08): 162 affected unit and 103 affected PostgreSQL tests (including the runner shutdown repair), zero skips, with the declared search extra installed; see [Phase 3 handoff](../guides/scoped-search-phase3.md). Phase 4 historical preparatory regressions passed (2026-10-08): 1258 provider-free tests and 311 mandatory isolated PostgreSQL tests. Real quality acceptance remains not run; see [Phase 4 handoff](../guides/scoped-search-phase4.md). All six Phase 2 repairs passed 107 affected unit tests, 100 isolated PostgreSQL tests and 1193 provider-free regression tests; see [repair acceptance](../guides/scoped-search-phase2-repairs.md) and [Phase 2 results](../guides/scoped-search-phase2.md). This four-phase plan replaces the earlier seven-phase proposal.
## 1. Delivery Strategy
@@ -211,7 +211,7 @@ Use a thin `StructuredTool` adapter with an explicit argument schema and synchro
Default execution limits: four running calls, eight waiting calls, and a 75-second total deadline. SQL statement/lock timeouts are five/two seconds. Validate configuration; retain the explicit provider timeout policy.
Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries.
Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries. Runner closure returns nonretryable SEARCH_CANCELLED for queued/new calls and suppresses late running results. Repeated close is safe; submission and closure share a lock, submitted slots remain held until actual completion, and close joins work plus queued admission releases. Call blocking close outside active event loops and its worker pool. See [shutdown repair acceptance](../guides/scoped-search-phase3.md#shutdown-repair-acceptance-2026-10-08).
**Execution prompt**
@@ -332,3 +332,69 @@ Each phase reports its working command, observed output, actual checks, and rema
No latency or concurrent-user service-level target has been approved. Measure timings and enforce the stated execution bounds without claiming an unapproved performance target. Actual provider runs require explicit opt-in, compatible credentials, approved inputs, and a bounded operator call budget.
**Speed rule:** finish and demonstrate each usable checkpoint before expanding it. Optimize only a reproduced quality or latency problem. The MVP search milestone remains incomplete until the confirmed real-quality gate passes.
## Historical Phase 4 preparatory checkpoint (2026-10-08)
Final regression acceptance: 1258 provider-free passed, three existing Windows
symlink skips; 311 mandatory isolated PostgreSQL passed with zero skips.
pip check, tracked/new-file whitespace, Python/JSON inspection and byte
preservation of all three applied migrations passed. No production fixes.
[Original annotations](../calibration/phase4-cases.draft.json) contain 16 draft
answerable and six unsupported cases, with four explicitly empty unseen slots.
Original SHA-256 hashes are recorded; approval and actual document bindings
remain pending. This is not a completed/frozen 20-case set.
[Opt-in evaluator](../../tests/evaluate_search.py) calls canonical SearchService
with the frozen Phase 2 calibration, validates actual selection/bindings and
sources, enforces a maximum 26-query call budget, retains every failure/not-run
case, and applies the exact gate. Ten provider-free evaluation regressions pass.
[Status](../calibration/phase4-status.json) and
[operator guide](../guides/scoped-search-phase4.md) record actual results.
Real provider calls: zero. Phase 2 has no measured cutoff. Funded-profile/call
authorization, approved unseen originals, human review/DOCX inclusion and actual
ready document bindings remain missing. Phase 4 quality gate is not run;
retrieval readiness, generated-answer readiness and Live readiness are not claimed.
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.
## Phase 4 review repairs (2026-10-08)
The two review findings are fixed in the evaluation boundary. All 16 answerable
and six unsupported annotations were reconstructed from actual original PDFs,
infographic and DOCX, verified by strict UTF-8 read-back and synchronized with
the status snapshot. Zero unresolved populated annotations; all four unseen
slots remain empty. No original/review approvals or document bindings changed.
Question-only comparison against the supplied full Phase 2 report now rejects
exact and formatting-equivalent overlap and missing/malformed annotations before
settings/database/provider setup. NFKC, casefold, Persian/Arabic letter/digit
variants, Unicode whitespace/format controls and terminal punctuation are
comparison-only; original evidence and retrieval preprocessing remain unchanged.
Different questions may share original documents; semantic paraphrases are not
automatically detected. Safe errors identify the prerequisite/corrective action.
Current checks: **52 targeted tests passed**; full provider-free **1300 passed,
3 existing Windows symlink skips, 311 deselected**; pip check, tracked/new-file
whitespace, AST/JSON, persisted UTF-8 and all three migration byte comparisons
passed. Mandatory isolated PostgreSQL is **not run**: TEST_DATABASE_URL is not
configured. Earlier PostgreSQL counts remain historical evidence only.
[Operator guide](../guides/scoped-search-phase4.md) and
[status](../calibration/phase4-status.json) record commands and limitations.
Quality acceptance remains not_run with zero provider calls. Pending: measured
Phase 2 cutoff/funded-profile authorization and bounded budget, approved
originals/DOCX human review, actual eligible bindings and four unseen annotations.
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.
@@ -367,7 +367,7 @@ Illustrative successful result; text/location must be populated from actual reta
{"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
```
`no_evidence` is completed retrieval with insufficient support, not a provider failure. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search.
`no_evidence` is completed retrieval with insufficient support, not a provider failure. The shared core requires a measured profile-specific cutoff for canonical evidence admission; absent calibration returns `error` with `CALIBRATION_REQUIRED`, never an invented default threshold. Operator inspection may return explicitly labeled uncalibrated candidates without claiming evidence sufficiency. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search.
Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence.