knowledge-rag 5.0.1__tar.gz → 5.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/PKG-INFO +24 -18
  2. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/README.md +23 -17
  3. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/config.example.yaml +37 -0
  4. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/__init__.py +1 -1
  5. knowledge_rag-5.2.0/mcp_server/_index_access.py +114 -0
  6. knowledge_rag-5.2.0/mcp_server/_preflight_probe.py +156 -0
  7. knowledge_rag-5.2.0/mcp_server/_preflight_repair.py +194 -0
  8. knowledge_rag-5.2.0/mcp_server/_sidecar_lock.py +38 -0
  9. knowledge_rag-5.2.0/mcp_server/_writer_role.py +312 -0
  10. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/config.py +30 -1
  11. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/config.example.yaml +37 -0
  12. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/health.py +41 -19
  13. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/ingestion.py +94 -9
  14. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/instance_lock.py +114 -78
  15. knowledge_rag-5.2.0/mcp_server/preflight.py +245 -0
  16. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/server.py +1229 -208
  17. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/pyproject.toml +1 -1
  18. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/maintenance/rag-evaluate-quality/SKILL.md +1 -1
  19. knowledge_rag-5.0.1/mcp_server/preflight.py +0 -300
  20. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/.gitignore +0 -0
  21. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/LICENSE +0 -0
  22. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/bench/dashboard/README.md +0 -0
  23. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/assistants.py +0 -0
  24. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/cybersecurity.yaml +0 -0
  25. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/developer.yaml +0 -0
  26. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/general.yaml +0 -0
  27. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/multilingual.yaml +0 -0
  28. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/data/research.yaml +0 -0
  29. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/file_transaction.py +0 -0
  30. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/filesystem.py +0 -0
  31. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/fts5_index.py +0 -0
  32. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/guarded.py +0 -0
  33. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/logging_config.py +0 -0
  34. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/metrics.py +0 -0
  35. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/pdf_support.py +0 -0
  36. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/publication.py +0 -0
  37. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/query_router.py +0 -0
  38. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/ratelimit.py +0 -0
  39. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/search_candidates.py +0 -0
  40. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/search_scope.py +0 -0
  41. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/security.py +0 -0
  42. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/skills_bundle.py +0 -0
  43. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/mcp_server/skills_cli.py +0 -0
  44. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/npm/README.md +0 -0
  45. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/presets/cybersecurity.yaml +0 -0
  46. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/presets/developer.yaml +0 -0
  47. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/presets/general.yaml +0 -0
  48. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/presets/multilingual.yaml +0 -0
  49. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/presets/research.yaml +0 -0
  50. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/requirements.txt +0 -0
  51. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/README.md +0 -0
  52. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/domain/rag-security-first/SKILL.md +0 -0
  53. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/foundation/rag-check-first/SKILL.md +0 -0
  54. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/foundation/rag-cite-sources/SKILL.md +0 -0
  55. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/foundation/rag-onboard-context/SKILL.md +0 -0
  56. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/maintenance/rag-index-decisions/SKILL.md +0 -0
  57. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/workflow/rag-code-review/SKILL.md +0 -0
  58. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/workflow/rag-deep-dive/SKILL.md +0 -0
  59. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/workflow/rag-troubleshoot/SKILL.md +0 -0
  60. {knowledge_rag-5.0.1 → knowledge_rag-5.2.0}/skills/workflow/rag-web-fallback/SKILL.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: knowledge-rag
3
- Version: 5.0.1
3
+ Version: 5.2.0
4
4
  Summary: Local RAG System for Claude Code — Hybrid search + Cross-encoder Reranking + 13 MCP Tools + 20 Format Parsers. Zero external servers.
5
5
  Project-URL: Homepage, https://github.com/lyonzin/knowledge-rag
6
6
  Project-URL: Repository, https://github.com/lyonzin/knowledge-rag
@@ -59,17 +59,20 @@ Description-Content-Type: text/markdown
59
59
 
60
60
  **knowledge-rag** is a local retrieval-augmented generation (RAG) server for the Model Context Protocol (MCP). It indexes the documents and code on your machine and gives Claude Code, Cursor, VS Code and other MCP clients 13 tools to search them, using hybrid search (BM25 keywords plus vector similarity) with cross-encoder reranking on by default. Everything runs in one Python process with embedded ChromaDB and FastEmbed ONNX models: no Docker, no database server, no API key. Indexing and search work offline once the models are cached.
61
61
 
62
+ <div align="center">
63
+
64
+ [![PyPI](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
65
+ [![NPM](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
66
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)
67
+ ![Python](https://img.shields.io/badge/python-3.11%2B-green.svg)
68
+ ![License](https://img.shields.io/badge/license-MIT-yellow.svg)
69
+ ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
70
+ ![GPU](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
62
71
  [![CodeQL](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml)
63
72
  [![Quality Gate](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml)
73
+ [![Glama Score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)
64
74
  [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/13864/badge)](https://bestpractices.coreinfrastructure.org/projects/13864)
65
- [![Glama score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)<br>
66
- [![PyPI version](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
67
- [![npm version](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
68
- [![PyPI downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)<br>
69
- ![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-green.svg)
70
- ![Platforms: Windows, Linux, macOS](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
71
- ![Optional NVIDIA CUDA](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
72
- ![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)
75
+ </div>
73
76
 
74
77
  - **11.1 ms** median uncached hybrid query on CPU, **6.1 ms** on CUDA: 36 queries over 149 chunks on one Windows host, reranker off ([audit](docs/audit-2026-10-03.md#real-cpu-and-nvidia-workload))
75
78
  - **0.03 ms** median for a repeated query served from the cache, same workload ([audit](docs/audit-2026-10-03.md#real-cpu-and-nvidia-workload))
@@ -153,7 +156,7 @@ flowchart TB
153
156
  end
154
157
 
155
158
  subgraph MIDDLEWARE["ASGI middleware (HTTP transports)"]
156
- M1[HealthMiddleware<br/>/health · /healthz]
159
+ M1[HealthMiddleware<br/>/health · /healthz · /readyz]
157
160
  M2[BearerAuthMiddleware<br/>constant-time compare]
158
161
  end
159
162
 
@@ -346,7 +349,8 @@ server:
346
349
 
347
350
  ```bash
348
351
  KNOWLEDGE_RAG_DIR=~/knowledge-rag knowledge-rag # run from the venv where you installed it
349
- curl http://127.0.0.1:8179/health # {"status":"ok","version":"5.0.0",...}
352
+ curl http://127.0.0.1:8179/health # {"status":"ok","version":"5.0.0","uptime_seconds":12,"index":"ready",...}
353
+ curl -i http://127.0.0.1:8179/readyz # 200 once the index serves; 503 while it is checked or repaired
350
354
  claude mcp add --transport http knowledge-rag http://127.0.0.1:8179/mcp \
351
355
  # if server.auth.bearer_token is set, add the token as a Bearer auth header
352
356
  ```
@@ -393,7 +397,7 @@ Any client that starts a stdio MCP server from a command, or connects to a Strea
393
397
  ```
394
398
 
395
399
  > [!WARNING]
396
- > **One writer per data directory.** Over stdio, each MCP client starts and owns its own knowledge-rag process. Do not run a second writer against the same `data_dir` while that client is open: on Windows, two writers corrupted the ChromaDB HNSW segment ([#216](https://github.com/lyonzin/knowledge-rag/issues/216)). Add `"KNOWLEDGE_RAG_SINGLE_INSTANCE": "1"` to the client's `env` block as a safety net, or share one HTTP server. Running CLI commands safely: [docs/single-instance.md](docs/single-instance.md).
400
+ > **One owner per data directory.** Over stdio, each MCP client starts its own knowledge-rag process, and only the first one for a `data_dir` opens the index: two writers, or a reader during writes, corrupted the ChromaDB HNSW segment ([#216](https://github.com/lyonzin/knowledge-rag/issues/216)). The other processes stay up and answer every tool with a refusal that names the owner; the first call after the owner exits takes over. To use one index from several clients at once, share one HTTP server. Running CLI commands safely: [docs/single-instance.md](docs/single-instance.md).
397
401
 
398
402
  > [!WARNING]
399
403
  > **Keep `data_dir` out of cloud-sync folders.** OneDrive (including `OneDrive - <tenant>`), iCloud Drive, Dropbox, Google Drive, Box, pCloud, MEGAsync, Nextcloud/ownCloud and Sync hold handles on the live index while they upload it. That races with ChromaDB's HNSW memory maps and SQLite WAL writes and can crash the process (`0xC0000005` on Windows, `SIGBUS` elsewhere); startup auto-repair then moves the index to `data/backups/auto-repair-*` and you reindex from scratch. Since v4.11.0, startup stops with exit code 78 (`EX_CONFIG`) when `data_dir` resolves under one of these providers. Use a local path such as `%LOCALAPPDATA%\knowledge-rag\data` on Windows or `~/.local/share/knowledge-rag/data` on Linux and macOS, or set `paths.allow_cloud_sync: true` to accept the risk.
@@ -410,7 +414,7 @@ All install methods, GPU setup and troubleshooting for each client: [docs/INSTAL
410
414
  | `evaluate_retrieval` | Reports MRR@5 and Recall@5 for your own query → expected file pairs |
411
415
  | `list_documents` | Lists indexed documents, 100 per page by default (up to 200 with `limit`), paged with `offset` |
412
416
  | `list_categories` | Lists categories, derived from folder paths, with document counts |
413
- | `get_index_stats` | Document and chunk counts, embedding model, BM25 status, cache hit rate, watcher status |
417
+ | `get_index_stats` | Document and chunk counts, embedding model, BM25 status, cache hit rate, watcher status, HNSW self-recall probe |
414
418
  | `add_document` | Saves text as a file under `documents/` and indexes it |
415
419
  | `update_document` | Replaces a document's content and re-indexes it |
416
420
  | `remove_document` | Removes a document's chunks from the index, and optionally the file |
@@ -559,7 +563,7 @@ Each capability says whether it is on by default and links to the test, document
559
563
 
560
564
  | Capability | Default | Enable / tune | Proof |
561
565
  | --- | --- | --- | --- |
562
- | `/health` and `/healthz`, no token needed | On (HTTP) | — | [test](tests/test_health_endpoint.py) |
566
+ | `/health` and `/healthz` (liveness), `/readyz` (readiness), no token needed | On (HTTP) | — | [test](tests/test_health_readiness.py) |
563
567
  | Prometheus metrics on a separate port | Opt-in (HTTP) | `server.metrics` | [test](tests/test_metrics.py) |
564
568
  | Structured JSON logs | Opt-in | `server.logging.format` | [test](tests/test_logging_json.py) |
565
569
  | Public benchmark dashboard | Every push to master | — | [dashboard](https://lyonzin.github.io/knowledge-rag/) |
@@ -584,7 +588,7 @@ Each capability says whether it is on by default and links to the test, document
584
588
 
585
589
  | Capability | Default | Enable / tune | Proof |
586
590
  | --- | --- | --- | --- |
587
- | Single-instance lock | Auto (HTTP) | `KNOWLEDGE_RAG_SINGLE_INSTANCE` | [test](tests/test_instance_lock.py) |
591
+ | One owner per data directory; other processes refuse every tool | On | `KNOWLEDGE_RAG_SINGLE_INSTANCE` (exit 75 instead) | [test](tests/test_single_writer_processes.py) |
588
592
  | Startup probe, auto-repair, 3 backups kept | On | — | [test](tests/test_preflight_backup_retention.py) |
589
593
  | Index kept if `documents_dir` is empty or missing | On | — | [test](tests/test_indexing_integrity.py) |
590
594
  | File watcher, 10 s quiet period | On | `KNOWLEDGE_RAG_WATCHER_DISABLED` | [test](tests/test_watcher_attrib_loop.py) |
@@ -609,9 +613,9 @@ Compliance: the project holds no LGPD, GDPR or HIPAA certification. Local indexi
609
613
  - **Paths:** the six tools that accept a path resolve it inside `documents_dir` and reject traversal, escaping symlinks, NUL bytes and NTFS alternate data streams (CWE-22, CWE-59).
610
614
  - **Fetched content:** `add_from_url` neutralizes known model control tokens and stores a provenance marker with the page. That limits prompt injection; it does not prevent it, so treat retrieved text as untrusted ([SECURITY.md](SECURITY.md)). The tool fetches whatever http(s) URL it receives, private network addresses included, and follows redirects; on a shared server, decide who may call it.
611
615
  - **Network use:** the first model download contacts Hugging Face; set `HF_HUB_OFFLINE=1` once the models are cached.
612
- - **Health payload:** `GET /health` returns `status`, `version`, `uptime_seconds` and query-cache statistics on the MCP port.
613
- - **Single instance:** HTTP transports turn the lock on automatically; for stdio clients, add `KNOWLEDGE_RAG_SINGLE_INSTANCE=1` to the client's `env` block. A second process on the same `data_dir` then exits with code 75.
614
- - **Index safety:** a full rebuild fills a staging collection and swaps it in after validation; handled failures roll back. Startup retries a failing probe 3 times before moving the index to `data/backups/auto-repair-*`, keeping the 3 newest. Recovery steps: [docs/reindex-operations.md](docs/reindex-operations.md).
616
+ - **Health probes:** on the MCP port, `GET /health` (or `/healthz`) answers 200 while the process runs, with `status`, `version`, `uptime_seconds`, `index` (`ready`, `repairing` or `error`) and query-cache statistics; `GET /readyz` answers 200 only when tools can be served and 503 otherwise, with `Retry-After` while the index is repaired. Use `/readyz`, not the status of `/health`, as the readiness check ([details](docs/single-instance.md#http-health-probes)).
617
+ - **One owner per data directory:** over stdio, a second process on the same `data_dir` stays up and refuses every tool until the owner exits, then takes over. With `KNOWLEDGE_RAG_SINGLE_INSTANCE=1` in the client's `env` block it exits with code 75 instead, as HTTP transports always do.
618
+ - **Index safety:** a full rebuild fills a staging collection and swaps it in after validation; handled failures roll back. Startup moves an index to `data/backups/auto-repair-*` only after independent probes confirm damage while reading that specific index. An import failure, a busy index, a timeout or an unexpected probe result does not authorize a move. The three most recent auto-repair backups are kept. [Recovery steps](docs/reindex-operations.md).
615
619
  - **Dependencies:** `requirements.txt` and `pyproject.toml` declare version ranges, not pins. For a reproducible deployment, resolve once and record the tested environment.
616
620
  - **CI gates:** every pull request runs 34 GitHub Actions checks. The performance gate fails a benchmark only when every branch run is more than 10% slower than every master run. Nightly jobs open issues instead of blocking merges; mutation testing is exploratory and never fails the run.
617
621
  - **Disclosure:** private [security advisories](https://github.com/lyonzin/knowledge-rag/security/advisories/new), acknowledged within 48 hours, initial assessment within 5 business days, 90-day coordinated disclosure ([SECURITY.md](SECURITY.md)).
@@ -824,6 +828,8 @@ Any client that can start a stdio MCP server from a command, or connect to a Str
824
828
 
825
829
  ## Recent releases
826
830
 
831
+ - **v5.2.0** (2026-11-28): one process owns each index; startup verifies the repair target before moving data, and keyword-only search no longer reports a false miss while BM25 warms up. Stop all older processes before upgrading. See [the upgrade guide](docs/single-instance.md#upgrading-from-an-older-version).
832
+ - **v5.1.0** (2026-11-14): path-level file watching, background BM25 refresh on large indexes and orphan cleanup.
827
833
  - **v5.0.0** (2026-11-05): **breaking** `list_documents` now returns 100 documents per page by default (up to 200 with `limit`); call it again with `offset` until you reach `total`. Also: an empty or missing `documents_dir` no longer clears the index, search snippets start at the match, `add_from_url` stops overwriting other pages, and failing tests now block merges.
828
834
  - **v4.11.1** (2026-10-25): fresh installs start again, Windows state writes retry through brief file locks, and the Docker image adds `linux/arm64`.
829
835
  - **v4.11.0** (2026-10-04): startup refuses a `data_dir` inside cloud-sync folders.
@@ -10,17 +10,20 @@
10
10
 
11
11
  **knowledge-rag** is a local retrieval-augmented generation (RAG) server for the Model Context Protocol (MCP). It indexes the documents and code on your machine and gives Claude Code, Cursor, VS Code and other MCP clients 13 tools to search them, using hybrid search (BM25 keywords plus vector similarity) with cross-encoder reranking on by default. Everything runs in one Python process with embedded ChromaDB and FastEmbed ONNX models: no Docker, no database server, no API key. Indexing and search work offline once the models are cached.
12
12
 
13
+ <div align="center">
14
+
15
+ [![PyPI](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
16
+ [![NPM](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
17
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)
18
+ ![Python](https://img.shields.io/badge/python-3.11%2B-green.svg)
19
+ ![License](https://img.shields.io/badge/license-MIT-yellow.svg)
20
+ ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
21
+ ![GPU](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
13
22
  [![CodeQL](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml)
14
23
  [![Quality Gate](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml)
24
+ [![Glama Score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)
15
25
  [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/13864/badge)](https://bestpractices.coreinfrastructure.org/projects/13864)
16
- [![Glama score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)<br>
17
- [![PyPI version](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
18
- [![npm version](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
19
- [![PyPI downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)<br>
20
- ![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-green.svg)
21
- ![Platforms: Windows, Linux, macOS](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
22
- ![Optional NVIDIA CUDA](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
23
- ![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)
26
+ </div>
24
27
 
25
28
  - **11.1 ms** median uncached hybrid query on CPU, **6.1 ms** on CUDA: 36 queries over 149 chunks on one Windows host, reranker off ([audit](docs/audit-2026-10-03.md#real-cpu-and-nvidia-workload))
26
29
  - **0.03 ms** median for a repeated query served from the cache, same workload ([audit](docs/audit-2026-10-03.md#real-cpu-and-nvidia-workload))
@@ -104,7 +107,7 @@ flowchart TB
104
107
  end
105
108
 
106
109
  subgraph MIDDLEWARE["ASGI middleware (HTTP transports)"]
107
- M1[HealthMiddleware<br/>/health · /healthz]
110
+ M1[HealthMiddleware<br/>/health · /healthz · /readyz]
108
111
  M2[BearerAuthMiddleware<br/>constant-time compare]
109
112
  end
110
113
 
@@ -297,7 +300,8 @@ server:
297
300
 
298
301
  ```bash
299
302
  KNOWLEDGE_RAG_DIR=~/knowledge-rag knowledge-rag # run from the venv where you installed it
300
- curl http://127.0.0.1:8179/health # {"status":"ok","version":"5.0.0",...}
303
+ curl http://127.0.0.1:8179/health # {"status":"ok","version":"5.0.0","uptime_seconds":12,"index":"ready",...}
304
+ curl -i http://127.0.0.1:8179/readyz # 200 once the index serves; 503 while it is checked or repaired
301
305
  claude mcp add --transport http knowledge-rag http://127.0.0.1:8179/mcp \
302
306
  # if server.auth.bearer_token is set, add the token as a Bearer auth header
303
307
  ```
@@ -344,7 +348,7 @@ Any client that starts a stdio MCP server from a command, or connects to a Strea
344
348
  ```
345
349
 
346
350
  > [!WARNING]
347
- > **One writer per data directory.** Over stdio, each MCP client starts and owns its own knowledge-rag process. Do not run a second writer against the same `data_dir` while that client is open: on Windows, two writers corrupted the ChromaDB HNSW segment ([#216](https://github.com/lyonzin/knowledge-rag/issues/216)). Add `"KNOWLEDGE_RAG_SINGLE_INSTANCE": "1"` to the client's `env` block as a safety net, or share one HTTP server. Running CLI commands safely: [docs/single-instance.md](docs/single-instance.md).
351
+ > **One owner per data directory.** Over stdio, each MCP client starts its own knowledge-rag process, and only the first one for a `data_dir` opens the index: two writers, or a reader during writes, corrupted the ChromaDB HNSW segment ([#216](https://github.com/lyonzin/knowledge-rag/issues/216)). The other processes stay up and answer every tool with a refusal that names the owner; the first call after the owner exits takes over. To use one index from several clients at once, share one HTTP server. Running CLI commands safely: [docs/single-instance.md](docs/single-instance.md).
348
352
 
349
353
  > [!WARNING]
350
354
  > **Keep `data_dir` out of cloud-sync folders.** OneDrive (including `OneDrive - <tenant>`), iCloud Drive, Dropbox, Google Drive, Box, pCloud, MEGAsync, Nextcloud/ownCloud and Sync hold handles on the live index while they upload it. That races with ChromaDB's HNSW memory maps and SQLite WAL writes and can crash the process (`0xC0000005` on Windows, `SIGBUS` elsewhere); startup auto-repair then moves the index to `data/backups/auto-repair-*` and you reindex from scratch. Since v4.11.0, startup stops with exit code 78 (`EX_CONFIG`) when `data_dir` resolves under one of these providers. Use a local path such as `%LOCALAPPDATA%\knowledge-rag\data` on Windows or `~/.local/share/knowledge-rag/data` on Linux and macOS, or set `paths.allow_cloud_sync: true` to accept the risk.
@@ -361,7 +365,7 @@ All install methods, GPU setup and troubleshooting for each client: [docs/INSTAL
361
365
  | `evaluate_retrieval` | Reports MRR@5 and Recall@5 for your own query → expected file pairs |
362
366
  | `list_documents` | Lists indexed documents, 100 per page by default (up to 200 with `limit`), paged with `offset` |
363
367
  | `list_categories` | Lists categories, derived from folder paths, with document counts |
364
- | `get_index_stats` | Document and chunk counts, embedding model, BM25 status, cache hit rate, watcher status |
368
+ | `get_index_stats` | Document and chunk counts, embedding model, BM25 status, cache hit rate, watcher status, HNSW self-recall probe |
365
369
  | `add_document` | Saves text as a file under `documents/` and indexes it |
366
370
  | `update_document` | Replaces a document's content and re-indexes it |
367
371
  | `remove_document` | Removes a document's chunks from the index, and optionally the file |
@@ -510,7 +514,7 @@ Each capability says whether it is on by default and links to the test, document
510
514
 
511
515
  | Capability | Default | Enable / tune | Proof |
512
516
  | --- | --- | --- | --- |
513
- | `/health` and `/healthz`, no token needed | On (HTTP) | — | [test](tests/test_health_endpoint.py) |
517
+ | `/health` and `/healthz` (liveness), `/readyz` (readiness), no token needed | On (HTTP) | — | [test](tests/test_health_readiness.py) |
514
518
  | Prometheus metrics on a separate port | Opt-in (HTTP) | `server.metrics` | [test](tests/test_metrics.py) |
515
519
  | Structured JSON logs | Opt-in | `server.logging.format` | [test](tests/test_logging_json.py) |
516
520
  | Public benchmark dashboard | Every push to master | — | [dashboard](https://lyonzin.github.io/knowledge-rag/) |
@@ -535,7 +539,7 @@ Each capability says whether it is on by default and links to the test, document
535
539
 
536
540
  | Capability | Default | Enable / tune | Proof |
537
541
  | --- | --- | --- | --- |
538
- | Single-instance lock | Auto (HTTP) | `KNOWLEDGE_RAG_SINGLE_INSTANCE` | [test](tests/test_instance_lock.py) |
542
+ | One owner per data directory; other processes refuse every tool | On | `KNOWLEDGE_RAG_SINGLE_INSTANCE` (exit 75 instead) | [test](tests/test_single_writer_processes.py) |
539
543
  | Startup probe, auto-repair, 3 backups kept | On | — | [test](tests/test_preflight_backup_retention.py) |
540
544
  | Index kept if `documents_dir` is empty or missing | On | — | [test](tests/test_indexing_integrity.py) |
541
545
  | File watcher, 10 s quiet period | On | `KNOWLEDGE_RAG_WATCHER_DISABLED` | [test](tests/test_watcher_attrib_loop.py) |
@@ -560,9 +564,9 @@ Compliance: the project holds no LGPD, GDPR or HIPAA certification. Local indexi
560
564
  - **Paths:** the six tools that accept a path resolve it inside `documents_dir` and reject traversal, escaping symlinks, NUL bytes and NTFS alternate data streams (CWE-22, CWE-59).
561
565
  - **Fetched content:** `add_from_url` neutralizes known model control tokens and stores a provenance marker with the page. That limits prompt injection; it does not prevent it, so treat retrieved text as untrusted ([SECURITY.md](SECURITY.md)). The tool fetches whatever http(s) URL it receives, private network addresses included, and follows redirects; on a shared server, decide who may call it.
562
566
  - **Network use:** the first model download contacts Hugging Face; set `HF_HUB_OFFLINE=1` once the models are cached.
563
- - **Health payload:** `GET /health` returns `status`, `version`, `uptime_seconds` and query-cache statistics on the MCP port.
564
- - **Single instance:** HTTP transports turn the lock on automatically; for stdio clients, add `KNOWLEDGE_RAG_SINGLE_INSTANCE=1` to the client's `env` block. A second process on the same `data_dir` then exits with code 75.
565
- - **Index safety:** a full rebuild fills a staging collection and swaps it in after validation; handled failures roll back. Startup retries a failing probe 3 times before moving the index to `data/backups/auto-repair-*`, keeping the 3 newest. Recovery steps: [docs/reindex-operations.md](docs/reindex-operations.md).
567
+ - **Health probes:** on the MCP port, `GET /health` (or `/healthz`) answers 200 while the process runs, with `status`, `version`, `uptime_seconds`, `index` (`ready`, `repairing` or `error`) and query-cache statistics; `GET /readyz` answers 200 only when tools can be served and 503 otherwise, with `Retry-After` while the index is repaired. Use `/readyz`, not the status of `/health`, as the readiness check ([details](docs/single-instance.md#http-health-probes)).
568
+ - **One owner per data directory:** over stdio, a second process on the same `data_dir` stays up and refuses every tool until the owner exits, then takes over. With `KNOWLEDGE_RAG_SINGLE_INSTANCE=1` in the client's `env` block it exits with code 75 instead, as HTTP transports always do.
569
+ - **Index safety:** a full rebuild fills a staging collection and swaps it in after validation; handled failures roll back. Startup moves an index to `data/backups/auto-repair-*` only after independent probes confirm damage while reading that specific index. An import failure, a busy index, a timeout or an unexpected probe result does not authorize a move. The three most recent auto-repair backups are kept. [Recovery steps](docs/reindex-operations.md).
566
570
  - **Dependencies:** `requirements.txt` and `pyproject.toml` declare version ranges, not pins. For a reproducible deployment, resolve once and record the tested environment.
567
571
  - **CI gates:** every pull request runs 34 GitHub Actions checks. The performance gate fails a benchmark only when every branch run is more than 10% slower than every master run. Nightly jobs open issues instead of blocking merges; mutation testing is exploratory and never fails the run.
568
572
  - **Disclosure:** private [security advisories](https://github.com/lyonzin/knowledge-rag/security/advisories/new), acknowledged within 48 hours, initial assessment within 5 business days, 90-day coordinated disclosure ([SECURITY.md](SECURITY.md)).
@@ -775,6 +779,8 @@ Any client that can start a stdio MCP server from a command, or connect to a Str
775
779
 
776
780
  ## Recent releases
777
781
 
782
+ - **v5.2.0** (2026-11-28): one process owns each index; startup verifies the repair target before moving data, and keyword-only search no longer reports a false miss while BM25 warms up. Stop all older processes before upgrading. See [the upgrade guide](docs/single-instance.md#upgrading-from-an-older-version).
783
+ - **v5.1.0** (2026-11-14): path-level file watching, background BM25 refresh on large indexes and orphan cleanup.
778
784
  - **v5.0.0** (2026-11-05): **breaking** `list_documents` now returns 100 documents per page by default (up to 200 with `limit`); call it again with `offset` until you reach `total`. Also: an empty or missing `documents_dir` no longer clears the index, search snippets start at the match, `add_from_url` stops overwriting other pages, and failing tests now block merges.
779
785
  - **v4.11.1** (2026-10-25): fresh installs start again, Windows state writes retry through brief file locks, and the Docker image adds `linux/arm64`.
780
786
  - **v4.11.0** (2026-10-04): startup refuses a `data_dir` inside cloud-sync folders.
@@ -294,6 +294,43 @@ search:
294
294
  # Example: "work_kb", "research_kb", "personal_kb"
295
295
  collection_name: "knowledge_base"
296
296
 
297
+ # HNSW ef_search — search-time exploration depth of the ChromaDB HNSW
298
+ # index (GH #287). ChromaDB's built-in default is 100; higher values raise
299
+ # the chance that an isolated / recently-inserted chunk is found by its own
300
+ # vector (lower self-recall miss rate), at a roughly linear latency cost.
301
+ # Valid: integer >= 1 (invalid values fall back to 100 with a WARN).
302
+ #
303
+ # HONEST LIMITATION: the value only applies to collections CREATED after
304
+ # the change. ChromaDB's collection.modify() updates the stored metadata
305
+ # but does NOT change search behavior — not even after reopening the
306
+ # client (verified empirically on chromadb 1.5.9). To apply a new value:
307
+ # set it here, then run reindex_documents(full_rebuild=True) — the nuclear
308
+ # rebuild with staging swap creates a fresh collection with the new
309
+ # ef_search. A plain reindex_documents(force=True) re-embeds in place and
310
+ # is NOT enough. The self_recall field of get_index_stats() measures the
311
+ # effect (hnsw_ef_search reports the value actually in use). Default: 100
312
+ # (preserves prior behavior).
313
+ ef_search: 100
314
+
315
+ # Repair chunks the vector index cannot reach (GH #313). A query for a
316
+ # chunk's own stored vector does not always return the chunk, and then no
317
+ # semantic search finds it (self_recall in get_index_stats() below 1.0).
318
+ # After each indexing operation — a reindex pass, a watcher pass,
319
+ # add_document, update_document, add_from_url — the chunks it wrote are
320
+ # checked that way, and the unreachable ones are updated in place with the
321
+ # vector they already hold, which makes the index link them again. The
322
+ # chunk stays in the collection and nothing is embedded again. Linking one
323
+ # chunk again can cost another its links, so the chunks are checked up to
324
+ # 3 times; the reindex stats report unreachable_chunks_repaired and
325
+ # unreachable_chunks_remaining. On a 70,752-chunk index of a real corpus,
326
+ # the three checks of a full pass took the unreachable chunks from 4.7% to
327
+ # 0.1%, and one check of all chunks took 11 to 13 s. Only chunks the
328
+ # operation wrote are checked, and indexes with fewer than 1,000 chunks
329
+ # are not checked at all. A check that cannot run is a warning on stderr
330
+ # and never fails the operation. Set to false to switch the check off.
331
+ # Default: true.
332
+ repair_unreachable_chunks: true
333
+
297
334
  # -----------------------------------------------------------------------
298
335
  # FTS5 Lexical Fast-Path (v4.8.2+, opt-in — default OFF pending v4.9.0)
299
336
  # -----------------------------------------------------------------------
@@ -2,7 +2,7 @@
2
2
 
3
3
  from typing import TYPE_CHECKING, Any
4
4
 
5
- __version__ = "5.0.1"
5
+ __version__ = "5.2.0"
6
6
  __author__ = "Ailton Rocha (Lyon.)"
7
7
 
8
8
  __all__ = ["Config", "DocumentParser", "Document"]
@@ -0,0 +1,114 @@
1
+ """Who may touch the index files: the owner, or one of its preflight probes, never both at once.
2
+
3
+ The preflight probe reads the index in a child process, and a reader that
4
+ opens Chroma while it is written can crash or leave HNSW segments unloadable.
5
+ The writer guard (``knowledge-rag.lock.guard``) belongs to the owner process
6
+ alone, so it does not cover a probe that outlives its owner, starts late or
7
+ runs past its timeout. This access guard, an OS lock on the stable
8
+ ``knowledge-rag.lock.access`` sidecar, does. A probe takes it before it
9
+ touches the index and lets it go only by exiting; the owner takes it after
10
+ its probes, before it moves, repairs or opens the index, and keeps it until
11
+ it dies. A probe that finds it taken exits with BUSY_EXIT_CODE without
12
+ touching anything, which the owner reads as contention, not damage. The
13
+ sidecar is never unlinked, for the reason given in ``instance_lock``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ import time
21
+ from contextlib import contextmanager
22
+ from pathlib import Path
23
+ from typing import Iterator, Optional
24
+
25
+ from ._sidecar_lock import lock_sidecar
26
+
27
+ ACCESS_FILENAME = "knowledge-rag.lock.access"
28
+ BUSY_EXIT_CODE = 75 # EX_TEMPFAIL: another process is inside the index; try again later
29
+ WAIT_SECONDS = 120.0 # past a probe's own timeout, so only a process stuck inside runs it out
30
+ _FIRST_POLL_SECONDS = 0.1
31
+ _LONGEST_POLL_SECONDS = 2.0
32
+ _BUSY = (
33
+ "Another process kept the index files of this data directory for more than {seconds} s, so this session "
34
+ "did not open them. It is most likely a startup check left behind by a knowledge-rag session that ended "
35
+ "abruptly: a Python process started with -c that imports mcp_server. End it, then restart this client."
36
+ )
37
+
38
+ # The owner's hold (descriptor, sidecar path): only this process's death releases it.
39
+ _held: Optional[tuple[int, Path]] = None
40
+
41
+
42
+ class IndexAccessBusy(RuntimeError):
43
+ """Another process stayed inside the index files for longer than the owner waits."""
44
+
45
+
46
+ def busy(wait_seconds: float) -> IndexAccessBusy:
47
+ """The error for a process that stayed inside the index past ``wait_seconds``. By Lyon."""
48
+ return IndexAccessBusy(_BUSY.format(seconds=round(wait_seconds)))
49
+
50
+
51
+ def enter_or_exit(path: Path) -> None:
52
+ """Probe only the supplied sidecar; never load config to discover its path in the child."""
53
+ if lock_sidecar(path) is None: # keep the descriptor open until the child exits
54
+ raise SystemExit(BUSY_EXIT_CODE)
55
+
56
+
57
+ @contextmanager
58
+ def held_for_call(path: Path) -> Iterator[None]:
59
+ """Give back only the descriptor this standalone check acquired."""
60
+ path.parent.mkdir(parents=True, exist_ok=True)
61
+ fd = _wait_for(path, WAIT_SECONDS)
62
+ try:
63
+ yield
64
+ finally:
65
+ os.close(fd)
66
+
67
+
68
+ def hold(wait_seconds: float = WAIT_SECONDS, *, path: Optional[Path] = None) -> None:
69
+ """The owner's hold: wait until no probe is inside, then keep the guard until this process dies.
70
+
71
+ Idempotent, so the preflight and the opening can both ask. Raises
72
+ IndexAccessBusy when another process stays inside past ``wait_seconds``.
73
+ By Lyon.
74
+ """
75
+ global _held
76
+ if path is None: # parent-only, when opening the server index
77
+ from .config import config
78
+
79
+ path = config.data_dir.resolve() / ACCESS_FILENAME
80
+ if _held is not None:
81
+ if _held[1] != path:
82
+ raise RuntimeError(f"this process holds the index access of {_held[1].parent}, not {path.parent}")
83
+ return
84
+ path.parent.mkdir(parents=True, exist_ok=True)
85
+ _held = (_wait_for(path, wait_seconds), path)
86
+
87
+
88
+ def _wait_for(path: Path, wait_seconds: float) -> int:
89
+ """The guard's descriptor once no other process holds it, polling with a growing pause. By Lyon."""
90
+ deadline = time.monotonic() + wait_seconds
91
+ pause = _FIRST_POLL_SECONDS
92
+ fd = lock_sidecar(path)
93
+ if fd is None:
94
+ print("[ACCESS] Another process is inside the index files; waiting before touching them.", file=sys.stderr)
95
+ while fd is None:
96
+ if time.monotonic() >= deadline:
97
+ raise busy(wait_seconds)
98
+ time.sleep(pause)
99
+ pause = min(2 * pause, _LONGEST_POLL_SECONDS)
100
+ fd = lock_sidecar(path)
101
+ return fd
102
+
103
+
104
+ def is_held() -> bool:
105
+ """Whether this process holds the access guard. By Lyon."""
106
+ return _held is not None
107
+
108
+
109
+ def _release() -> None:
110
+ """Tests only: give up this process's hold the way its death would. By Lyon."""
111
+ global _held
112
+ if _held is not None:
113
+ fd, _held = _held[0], None
114
+ os.close(fd)
@@ -0,0 +1,156 @@
1
+ """The child probe's wire contract. This module and its guard must not import config."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import signal
7
+ import stat
8
+ import subprocess
9
+ import sys
10
+ from dataclasses import dataclass
11
+ from enum import Enum
12
+ from pathlib import Path
13
+
14
+ from . import _index_access
15
+
16
+ _READING = "counting"
17
+ _HNSW = "hnsw-load-failed"
18
+ _BUSY = "busy"
19
+ _MISSING = "missing"
20
+ _DAMAGED_EXIT = 65 # EX_DATAERR; only meaningful after the exact target and read markers
21
+ _SEGFAULT_CODES = {-signal.SIGSEGV, 0xC0000005, -1073741819} # POSIX signal / Windows access violation
22
+ if hasattr(signal, "SIGBUS"):
23
+ _SEGFAULT_CODES.add(-signal.SIGBUS)
24
+ _HNSW_ERROR = "Error loading hnsw index"
25
+ # Chroma 1.5.9, from a persisted segment opened in a fresh process. Unknown wording fails closed.
26
+ _HNSW_ERRORS = {
27
+ _HNSW_ERROR,
28
+ "Error executing plan: Error sending backfill request to compactor: "
29
+ f"Error constructing hnsw segment reader: Error creating hnsw segment reader: {_HNSW_ERROR}",
30
+ }
31
+
32
+
33
+ def _file_id(path: Path, kind: int) -> tuple[int, int] | None:
34
+ try:
35
+ record = path.lstat()
36
+ except FileNotFoundError:
37
+ return None
38
+ reparse = getattr(record, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
39
+ if stat.S_ISLNK(record.st_mode) or reparse or (kind == stat.S_IFREG and record.st_nlink > 1):
40
+ raise RuntimeError(f"Refusing index alias at {path}")
41
+ if stat.S_IFMT(record.st_mode) != kind or not record.st_ino:
42
+ raise RuntimeError(f"Cannot establish the filesystem identity of {path}")
43
+ return record.st_dev, record.st_ino
44
+
45
+
46
+ _IndexId = tuple[tuple[int, int] | None, tuple[int, int] | None]
47
+
48
+
49
+ def _index_id(directory: Path) -> _IndexId:
50
+ # Check ancestors from the root: lstat of a leaf alone follows a junction or symlink in its parent path.
51
+ if ".." in directory.parts:
52
+ raise RuntimeError(f"Refusing ambiguous index alias at {directory}")
53
+ for parent in reversed(directory.parents):
54
+ if _file_id(parent, stat.S_IFDIR) is None:
55
+ return None, None
56
+ return _file_id(directory, stat.S_IFDIR), _file_id(directory / "chroma.sqlite3", stat.S_IFREG)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _Target:
61
+ data_dir: Path
62
+ chroma_dir: Path
63
+ collection_name: str
64
+ index_id: _IndexId
65
+
66
+ @property
67
+ def access_path(self) -> Path:
68
+ return self.data_dir / _index_access.ACCESS_FILENAME
69
+
70
+ def wire(self) -> str:
71
+ return json.dumps(
72
+ [str(self.data_dir), str(self.chroma_dir), self.collection_name, str(self.access_path), self.index_id]
73
+ )
74
+
75
+ def check_identity(self) -> None:
76
+ if _index_id(self.chroma_dir) != self.index_id:
77
+ raise RuntimeError(f"Index changed since the preflight snapshot: {self.chroma_dir}; refusing to use it.")
78
+
79
+
80
+ class _Outcome(Enum):
81
+ VERIFIED = "verified"
82
+ BUSY = "busy"
83
+ UNVERIFIED = "unverified"
84
+ HNSW = "hnsw"
85
+ NATIVE = "segfault"
86
+
87
+
88
+ def _enter(raw_target: str) -> _Target:
89
+ """Echo the actual arguments; the sidecar stays held until this child exits."""
90
+ data_dir, chroma_dir, collection_name, access_path, _ = json.loads(raw_target)
91
+ try:
92
+ _index_access.enter_or_exit(Path(access_path))
93
+ except SystemExit as exc:
94
+ if exc.code == _index_access.BUSY_EXIT_CODE:
95
+ print(raw_target, _BUSY, sep="\n", flush=True)
96
+ raise
97
+ directory = Path(chroma_dir)
98
+ target = _Target(Path(data_dir), directory, collection_name, _index_id(directory))
99
+ if target.wire() != raw_target:
100
+ raise RuntimeError(f"Index changed before the child could verify {directory}")
101
+ print(target.wire(), flush=True)
102
+ return target
103
+
104
+
105
+ def _read_index(target: _Target) -> None:
106
+ import chromadb
107
+ from chromadb.errors import InternalError, NotFoundError
108
+
109
+ if target.index_id[1] is None:
110
+ if target.index_id[0] is not None and any(target.chroma_dir.iterdir()):
111
+ raise RuntimeError("Non-empty index directory without chroma.sqlite3")
112
+ print(_MISSING, flush=True)
113
+ return
114
+ client = chromadb.PersistentClient(path=str(target.chroma_dir))
115
+ try:
116
+ # GH #248/#252: never create a collection or persist a default embedding function.
117
+ collection = client.get_collection(name=target.collection_name, embedding_function=None)
118
+ except NotFoundError:
119
+ print(_MISSING, flush=True)
120
+ return
121
+ count = collection.count
122
+ target.check_identity()
123
+ print(_READING, flush=True) # No imports, bootstrap or client/collection lookup inside this window.
124
+ try:
125
+ size = count()
126
+ except BaseException as exc:
127
+ if (
128
+ type(exc) is InternalError
129
+ and exc.__cause__ is None
130
+ and exc.__context__ is None
131
+ and str(exc) in _HNSW_ERRORS
132
+ ):
133
+ print(_HNSW, flush=True)
134
+ print(exc, file=sys.stderr)
135
+ raise SystemExit(_DAMAGED_EXIT) from exc
136
+ print("read-error", flush=True) # A crash during unwinding is not a crash in count().
137
+ raise
138
+ print(size, flush=True)
139
+
140
+
141
+ def _classify(target: _Target, done: subprocess.CompletedProcess[str]) -> _Outcome:
142
+ """Only a complete, target-bound transcript or an interrupted native read carries evidence."""
143
+ lines = (done.stdout or "").splitlines()
144
+ if not lines or lines[0] != target.wire():
145
+ return _Outcome.UNVERIFIED
146
+ events = lines[1:]
147
+ if done.returncode == _index_access.BUSY_EXIT_CODE and events == [_BUSY]:
148
+ return _Outcome.BUSY
149
+ if done.returncode == _DAMAGED_EXIT and events == [_READING, _HNSW]:
150
+ return _Outcome.HNSW
151
+ if done.returncode in _SEGFAULT_CODES and events == [_READING]:
152
+ return _Outcome.NATIVE
153
+ counted = len(events) == 2 and events[0] == _READING and events[1].isascii() and events[1].isdigit()
154
+ if done.returncode == 0 and (events == [_MISSING] or counted):
155
+ return _Outcome.VERIFIED
156
+ return _Outcome.UNVERIFIED