Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: cache and dedupe docstore probes in kb list / knowledge API (#859) (#870)

0xTidalBorecbc6538273c5
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 52904740f..5cdb2329e 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -1163,7 +1163,9 @@ class KnowledgeBaseManager:
index_versions = inspect_kb_versions(kb_dir, rag_provider)
has_ready_provider = any(bool(version.get("ready")) for version in index_versions)
provider_error_summary = (
- provider_failure_summary(kb_dir, rag_provider) if dir_exists else ""
+ provider_failure_summary(kb_dir, rag_provider, versions=index_versions)
+ if dir_exists
+ else ""
)
# For old KBs without status field, determine status from rag_storage
@@ -1304,11 +1306,18 @@ class KnowledgeBaseManager:
if (kb_probe_dir and active_signature)
else None
)
- active_match = (
- inspect_provider_version(matched_entry, rag_provider).ready
- if matched_entry
- else False
- )
+ active_match = False
+ if matched_entry:
+ # Reuse the probe results already computed for ``index_versions``
+ # instead of probing the matched storage a second time — probing
+ # parses provider-owned files (e.g. the multi-MB LlamaIndex
+ # docstore.json) and is the dominant cost of kb list / the
+ # knowledge API (see issue #859).
+ matched_path = matched_entry.get("storage_path")
+ active_match = any(
+ entry.get("storage_path") == matched_path and entry.get("ready")
+ for entry in index_versions
+ )
else:
active_match = rag_initialized
diff --git a/deeptutor/services/rag/index_probe.py b/deeptutor/services/rag/index_probe.py
index d449f0208..d23335109 100644
--- a/deeptutor/services/rag/index_probe.py
+++ b/deeptutor/services/rag/index_probe.py
@@ -9,6 +9,7 @@ answer without knowing provider-specific filenames.
from __future__ import annotations
from dataclasses import dataclass, field
+from functools import lru_cache
import json
from pathlib import Path
from typing import Any
@@ -111,10 +112,17 @@ def provider_failure_summary(
provider: str | None,
*,
limit: int = 3,
+ versions: list[dict[str, Any]] | None = None,
) -> str:
- """Return the first provider-specific failure summary under ``kb_dir``."""
+ """Return the first provider-specific failure summary under ``kb_dir``.
+
+ ``versions`` may carry a pre-computed :func:`inspect_kb_versions` result so
+ bulk callers (e.g. ``KnowledgeBaseManager.get_info``) do not rescan and
+ re-parse every index version just to collect failure text.
+ """
+ entries = versions if versions is not None else inspect_kb_versions(kb_dir, provider)
failures: list[str] = []
- for entry in inspect_kb_versions(kb_dir, provider):
+ for entry in entries:
summary = str(entry.get("failure_summary") or "").strip()
if summary:
failures.append(summary)
@@ -222,14 +230,30 @@ def _inspect_lightrag(storage_dir: Path) -> ProviderIndexProbe:
)
-def _llamaindex_doc_count(docstore_path: Path) -> int | None:
- payload = _read_json(docstore_path)
+# docstore.json holds one entry per chunk/node and can be multi-MB, so parsing
+# it is the dominant cost of a LlamaIndex readiness probe. The count only
+# changes when the file itself changes, so it is cached keyed on size +
+# mtime_ns (same freshness convention as storage._freshness_token).
+_DOCSTORE_COUNT_CACHE_SIZE = 128
+
+
+@lru_cache(maxsize=_DOCSTORE_COUNT_CACHE_SIZE)
+def _llamaindex_doc_count_cached(path: str, size: int, mtime_ns: int) -> int | None:
+ payload = _read_json(Path(path))
if not isinstance(payload, dict):
return None
data = payload.get("docstore/data")
return len(data) if isinstance(data, dict) else None
+def _llamaindex_doc_count(docstore_path: Path) -> int | None:
+ try:
+ stat = docstore_path.stat()
+ except OSError:
+ return None
+ return _llamaindex_doc_count_cached(str(docstore_path), stat.st_size, stat.st_mtime_ns)
+
+
def _lightrag_doc_count(storage_dir: Path) -> int | None:
payload = _read_json(storage_dir / "kv_store_doc_status.json")
if not isinstance(payload, dict):
diff --git a/tests/knowledge/test_manager_get_info_status.py b/tests/knowledge/test_manager_get_info_status.py
index 71e396c67..a4cdc9244 100644
--- a/tests/knowledge/test_manager_get_info_status.py
+++ b/tests/knowledge/test_manager_get_info_status.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from typing import Any
import pytest
@@ -263,3 +264,43 @@ def test_needs_reindex_takes_precedence(tmp_path: Path, monkeypatch: pytest.Monk
info = manager.get_info("kb7")
assert info["status"] == "needs_reindex"
+
+
+def test_get_info_does_not_reparse_docstore_on_repeat_calls(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """``kb list`` / the knowledge API must not re-parse docstore.json per call.
+
+ Regression test for issue #859: probing every index version parses the
+ multi-MB LlamaIndex docstore.json, and get_info used to probe the same
+ versions two or three times per KB (scan, failure summary, active-match
+ re-probe). With the docstore-count cache and version reuse, a second
+ get_info call must not read the file again at all.
+ """
+ _patch_active_embedding(monkeypatch)
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ manager.update_kb_status(name="kb-perf", status="ready")
+ _create_ready_version(tmp_path / "kb-perf")
+
+ from deeptutor.services.rag import index_probe as probe_module
+
+ real_read = probe_module._read_json
+ reads: list[str] = []
+
+ def counting_read(path: Path) -> dict[str, Any] | None:
+ reads.append(str(path))
+ return real_read(path)
+
+ monkeypatch.setattr(probe_module, "_read_json", counting_read)
+
+ info = manager.get_info("kb-perf")
+ assert info["status"] == "ready"
+ assert info["statistics"]["active_match"] is True
+ parses_after_first_call = len(reads)
+ assert parses_after_first_call == 1 # one docstore.json read for the probe
+
+ info_again = manager.get_info("kb-perf")
+ assert info_again["status"] == "ready"
+ assert info_again["statistics"]["active_match"] is True
+ # Cached count + reused version probes: no re-read of the docstore.
+ assert len(reads) == parses_after_first_call
diff --git a/tests/services/rag/test_index_probe.py b/tests/services/rag/test_index_probe.py
index 65438f4f0..6eaf53f83 100644
--- a/tests/services/rag/test_index_probe.py
+++ b/tests/services/rag/test_index_probe.py
@@ -2,8 +2,12 @@ from __future__ import annotations
import json
from pathlib import Path
+from typing import Any
+
+import pytest
from deeptutor.services.rag.index_probe import (
+ _llamaindex_doc_count,
has_ready_provider_index,
inspect_kb_versions,
inspect_provider_index,
@@ -151,3 +155,84 @@ def test_provider_mismatch_is_not_ready(tmp_path: Path) -> None:
assert probe.ready is False
assert probe.diagnostics["provider_mismatch"] is True
+
+
+def test_llamaindex_doc_count_cached_until_file_changes(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Repeated probes must not re-parse docstore.json (issue #859)."""
+ from deeptutor.services.rag.index_probe import _read_json
+
+ docstore = tmp_path / "docstore.json"
+ docstore.write_text(
+ json.dumps({"docstore/data": {"doc-1": {}, "doc-2": {}}}),
+ encoding="utf-8",
+ )
+
+ real_read = _read_json
+ reads: list[str] = []
+
+ def counting_read(path: Path) -> dict[str, Any] | None:
+ reads.append(str(path))
+ return real_read(path)
+
+ monkeypatch.setattr("deeptutor.services.rag.index_probe._read_json", counting_read)
+
+ assert _llamaindex_doc_count(docstore) == 2
+ # Second probe on an unchanged file must be served from the cache.
+ assert _llamaindex_doc_count(docstore) == 2
+ assert reads == [str(docstore)]
+
+ # A real file change must invalidate the cache entry.
+ docstore.write_text(
+ json.dumps({"docstore/data": {"doc-1": {}}}),
+ encoding="utf-8",
+ )
+ assert _llamaindex_doc_count(docstore) == 1
+ assert reads == [str(docstore), str(docstore)]
+
+
+def test_llamaindex_doc_count_missing_file_is_not_cached(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A missing docstore must not poison the cache for a later-created file."""
+ from deeptutor.services.rag.index_probe import _read_json
+
+ docstore = tmp_path / "docstore.json"
+
+ real_read = _read_json
+ reads: list[str] = []
+
+ def counting_read(path: Path) -> dict[str, Any] | None:
+ reads.append(str(path))
+ return real_read(path)
+
+ monkeypatch.setattr("deeptutor.services.rag.index_probe._read_json", counting_read)
+
+ assert _llamaindex_doc_count(docstore) is None
+ # A missing docstore short-circuits on stat() — no parse is attempted, and
+ # no cache entry is created that could shadow a later-created file.
+ assert reads == []
+ docstore.write_text(
+ json.dumps({"docstore/data": {"doc-1": {}}}),
+ encoding="utf-8",
+ )
+ assert _llamaindex_doc_count(docstore) == 1
+ assert reads == [str(docstore)]
+
+
+def test_provider_failure_summary_reuses_precomputed_versions(tmp_path: Path) -> None:
+ """Pre-annotated versions must not trigger another on-disk scan (#859)."""
+ versions = [
+ {"storage_path": str(tmp_path / "version-1"), "ready": True},
+ {
+ "storage_path": str(tmp_path / "version-2"),
+ "ready": False,
+ "failure_summary": "Missing LlamaIndex docstore.json.",
+ },
+ ]
+ # Nothing exists on disk under tmp_path; the precomputed list is the only
+ # source of failure text and must be honored without a rescan.
+ assert provider_failure_summary(tmp_path, "llamaindex", versions=versions) == (
+ "Missing LlamaIndex docstore.json."
+ )