knowledge-rag 5.1.0__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.1.0 → knowledge_rag-5.2.0}/PKG-INFO +12 -9
  2. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/README.md +11 -8
  3. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/config.example.yaml +19 -0
  4. {knowledge_rag-5.1.0 → 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.1.0 → knowledge_rag-5.2.0}/mcp_server/config.py +14 -3
  11. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/config.example.yaml +19 -0
  12. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/health.py +41 -19
  13. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/instance_lock.py +114 -78
  14. knowledge_rag-5.2.0/mcp_server/preflight.py +245 -0
  15. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/server.py +539 -123
  16. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/pyproject.toml +1 -1
  17. knowledge_rag-5.1.0/mcp_server/preflight.py +0 -300
  18. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/.gitignore +0 -0
  19. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/LICENSE +0 -0
  20. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/bench/dashboard/README.md +0 -0
  21. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/assistants.py +0 -0
  22. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/cybersecurity.yaml +0 -0
  23. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/developer.yaml +0 -0
  24. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/general.yaml +0 -0
  25. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/multilingual.yaml +0 -0
  26. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/data/research.yaml +0 -0
  27. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/file_transaction.py +0 -0
  28. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/filesystem.py +0 -0
  29. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/fts5_index.py +0 -0
  30. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/guarded.py +0 -0
  31. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/ingestion.py +0 -0
  32. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/logging_config.py +0 -0
  33. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/metrics.py +0 -0
  34. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/pdf_support.py +0 -0
  35. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/publication.py +0 -0
  36. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/query_router.py +0 -0
  37. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/ratelimit.py +0 -0
  38. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/search_candidates.py +0 -0
  39. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/search_scope.py +0 -0
  40. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/security.py +0 -0
  41. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/skills_bundle.py +0 -0
  42. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/mcp_server/skills_cli.py +0 -0
  43. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/npm/README.md +0 -0
  44. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/presets/cybersecurity.yaml +0 -0
  45. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/presets/developer.yaml +0 -0
  46. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/presets/general.yaml +0 -0
  47. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/presets/multilingual.yaml +0 -0
  48. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/presets/research.yaml +0 -0
  49. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/requirements.txt +0 -0
  50. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/README.md +0 -0
  51. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/domain/rag-security-first/SKILL.md +0 -0
  52. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/foundation/rag-check-first/SKILL.md +0 -0
  53. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/foundation/rag-cite-sources/SKILL.md +0 -0
  54. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/foundation/rag-onboard-context/SKILL.md +0 -0
  55. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/maintenance/rag-evaluate-quality/SKILL.md +0 -0
  56. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/maintenance/rag-index-decisions/SKILL.md +0 -0
  57. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/workflow/rag-code-review/SKILL.md +0 -0
  58. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/workflow/rag-deep-dive/SKILL.md +0 -0
  59. {knowledge_rag-5.1.0 → knowledge_rag-5.2.0}/skills/workflow/rag-troubleshoot/SKILL.md +0 -0
  60. {knowledge_rag-5.1.0 → 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.1.0
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
@@ -156,7 +156,7 @@ flowchart TB
156
156
  end
157
157
 
158
158
  subgraph MIDDLEWARE["ASGI middleware (HTTP transports)"]
159
- M1[HealthMiddleware<br/>/health · /healthz]
159
+ M1[HealthMiddleware<br/>/health · /healthz · /readyz]
160
160
  M2[BearerAuthMiddleware<br/>constant-time compare]
161
161
  end
162
162
 
@@ -349,7 +349,8 @@ server:
349
349
 
350
350
  ```bash
351
351
  KNOWLEDGE_RAG_DIR=~/knowledge-rag knowledge-rag # run from the venv where you installed it
352
- 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
353
354
  claude mcp add --transport http knowledge-rag http://127.0.0.1:8179/mcp \
354
355
  # if server.auth.bearer_token is set, add the token as a Bearer auth header
355
356
  ```
@@ -396,7 +397,7 @@ Any client that starts a stdio MCP server from a command, or connects to a Strea
396
397
  ```
397
398
 
398
399
  > [!WARNING]
399
- > **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).
400
401
 
401
402
  > [!WARNING]
402
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.
@@ -562,7 +563,7 @@ Each capability says whether it is on by default and links to the test, document
562
563
 
563
564
  | Capability | Default | Enable / tune | Proof |
564
565
  | --- | --- | --- | --- |
565
- | `/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) |
566
567
  | Prometheus metrics on a separate port | Opt-in (HTTP) | `server.metrics` | [test](tests/test_metrics.py) |
567
568
  | Structured JSON logs | Opt-in | `server.logging.format` | [test](tests/test_logging_json.py) |
568
569
  | Public benchmark dashboard | Every push to master | — | [dashboard](https://lyonzin.github.io/knowledge-rag/) |
@@ -587,7 +588,7 @@ Each capability says whether it is on by default and links to the test, document
587
588
 
588
589
  | Capability | Default | Enable / tune | Proof |
589
590
  | --- | --- | --- | --- |
590
- | 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) |
591
592
  | Startup probe, auto-repair, 3 backups kept | On | — | [test](tests/test_preflight_backup_retention.py) |
592
593
  | Index kept if `documents_dir` is empty or missing | On | — | [test](tests/test_indexing_integrity.py) |
593
594
  | File watcher, 10 s quiet period | On | `KNOWLEDGE_RAG_WATCHER_DISABLED` | [test](tests/test_watcher_attrib_loop.py) |
@@ -612,9 +613,9 @@ Compliance: the project holds no LGPD, GDPR or HIPAA certification. Local indexi
612
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).
613
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.
614
615
  - **Network use:** the first model download contacts Hugging Face; set `HF_HUB_OFFLINE=1` once the models are cached.
615
- - **Health payload:** `GET /health` returns `status`, `version`, `uptime_seconds` and query-cache statistics on the MCP port.
616
- - **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.
617
- - **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).
618
619
  - **Dependencies:** `requirements.txt` and `pyproject.toml` declare version ranges, not pins. For a reproducible deployment, resolve once and record the tested environment.
619
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.
620
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)).
@@ -827,6 +828,8 @@ Any client that can start a stdio MCP server from a command, or connect to a Str
827
828
 
828
829
  ## Recent releases
829
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.
830
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.
831
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`.
832
835
  - **v4.11.0** (2026-10-04): startup refuses a `data_dir` inside cloud-sync folders.
@@ -107,7 +107,7 @@ flowchart TB
107
107
  end
108
108
 
109
109
  subgraph MIDDLEWARE["ASGI middleware (HTTP transports)"]
110
- M1[HealthMiddleware<br/>/health · /healthz]
110
+ M1[HealthMiddleware<br/>/health · /healthz · /readyz]
111
111
  M2[BearerAuthMiddleware<br/>constant-time compare]
112
112
  end
113
113
 
@@ -300,7 +300,8 @@ server:
300
300
 
301
301
  ```bash
302
302
  KNOWLEDGE_RAG_DIR=~/knowledge-rag knowledge-rag # run from the venv where you installed it
303
- 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
304
305
  claude mcp add --transport http knowledge-rag http://127.0.0.1:8179/mcp \
305
306
  # if server.auth.bearer_token is set, add the token as a Bearer auth header
306
307
  ```
@@ -347,7 +348,7 @@ Any client that starts a stdio MCP server from a command, or connects to a Strea
347
348
  ```
348
349
 
349
350
  > [!WARNING]
350
- > **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).
351
352
 
352
353
  > [!WARNING]
353
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.
@@ -513,7 +514,7 @@ Each capability says whether it is on by default and links to the test, document
513
514
 
514
515
  | Capability | Default | Enable / tune | Proof |
515
516
  | --- | --- | --- | --- |
516
- | `/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) |
517
518
  | Prometheus metrics on a separate port | Opt-in (HTTP) | `server.metrics` | [test](tests/test_metrics.py) |
518
519
  | Structured JSON logs | Opt-in | `server.logging.format` | [test](tests/test_logging_json.py) |
519
520
  | Public benchmark dashboard | Every push to master | — | [dashboard](https://lyonzin.github.io/knowledge-rag/) |
@@ -538,7 +539,7 @@ Each capability says whether it is on by default and links to the test, document
538
539
 
539
540
  | Capability | Default | Enable / tune | Proof |
540
541
  | --- | --- | --- | --- |
541
- | 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) |
542
543
  | Startup probe, auto-repair, 3 backups kept | On | — | [test](tests/test_preflight_backup_retention.py) |
543
544
  | Index kept if `documents_dir` is empty or missing | On | — | [test](tests/test_indexing_integrity.py) |
544
545
  | File watcher, 10 s quiet period | On | `KNOWLEDGE_RAG_WATCHER_DISABLED` | [test](tests/test_watcher_attrib_loop.py) |
@@ -563,9 +564,9 @@ Compliance: the project holds no LGPD, GDPR or HIPAA certification. Local indexi
563
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).
564
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.
565
566
  - **Network use:** the first model download contacts Hugging Face; set `HF_HUB_OFFLINE=1` once the models are cached.
566
- - **Health payload:** `GET /health` returns `status`, `version`, `uptime_seconds` and query-cache statistics on the MCP port.
567
- - **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.
568
- - **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).
569
570
  - **Dependencies:** `requirements.txt` and `pyproject.toml` declare version ranges, not pins. For a reproducible deployment, resolve once and record the tested environment.
570
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.
571
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)).
@@ -778,6 +779,8 @@ Any client that can start a stdio MCP server from a command, or connect to a Str
778
779
 
779
780
  ## Recent releases
780
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.
781
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.
782
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`.
783
786
  - **v4.11.0** (2026-10-04): startup refuses a `data_dir` inside cloud-sync folders.
@@ -312,6 +312,25 @@ search:
312
312
  # (preserves prior behavior).
313
313
  ef_search: 100
314
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
+
315
334
  # -----------------------------------------------------------------------
316
335
  # FTS5 Lexical Fast-Path (v4.8.2+, opt-in — default OFF pending v4.9.0)
317
336
  # -----------------------------------------------------------------------
@@ -2,7 +2,7 @@
2
2
 
3
3
  from typing import TYPE_CHECKING, Any
4
4
 
5
- __version__ = "5.1.0"
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