From cfd1e2e3b6b7c8c2bf085a85e1521a22457def21 Mon Sep 17 00:00:00 2001 From: fanjiahe Date: Sat, 31 Oct 2026 00:53:47 +0800 Subject: [PATCH 1/2] fix: publish one LlamaIndex version per folder sync Linked-folder sync wrote a full snapshot for every file and never deleted the old ones. Index a staged batch in one publish and keep the newest three snapshots per embedding signature. Co-authored-by: Cursor --- deeptutor/knowledge/add_documents.py | 108 +++++++++++++- deeptutor/services/rag/index_versioning.py | 57 ++++++++ .../rag/pipelines/llamaindex/pipeline.py | 30 ++-- .../knowledge/test_document_adder_provider.py | 132 ++++++++++++++++++ tests/services/rag/test_index_versioning.py | 44 ++++++ 5 files changed, 359 insertions(+), 12 deletions(-) diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py index 8f338aa4d..869612ec2 100644 --- a/deeptutor/knowledge/add_documents.py +++ b/deeptutor/knowledge/add_documents.py @@ -325,13 +325,119 @@ class DocumentAdder: if self.rag_provider == LIGHTRAG_PROVIDER: return await self._process_lightrag_batch(new_files) + # LlamaIndex publishes a full snapshot on every add_documents call. + # One call for the whole staged list keeps folder sync at one version + # instead of one version per file (#2173). A single file stays on the + # per-file path, and a batch that throws falls back there so one bad + # file does not discard the others. + if self.rag_provider == DEFAULT_PROVIDER and len(new_files) > 1: + return await self._process_llamaindex_batch(new_files) + return await self._process_provider_files_one_by_one(new_files) + async def _process_llamaindex_batch(self, new_files: List[Path]) -> DocumentIndexResult: + """Index every staged file in one LlamaIndex publish.""" + requested = {str(path.resolve()): path for path in new_files} + confirmed: list[Path] = [] + seen: set[str] = set() + callback_fired = False + + def on_indexed(paths: list[str]) -> None: + nonlocal callback_fired + callback_fired = True + for raw in paths: + try: + key = str(Path(raw).resolve()) + except OSError: + continue + path = requested.get(key) + if path is None or key in seen: + continue + seen.add(key) + confirmed.append(path) + + rag_service = RAGService(kb_base_dir=str(self.base_dir), provider=self.rag_provider) + total_files = len(new_files) + if self.progress_tracker is not None: + from deeptutor.knowledge.progress_tracker import ProgressStage + + self.progress_tracker.update( + ProgressStage.PROCESSING_FILE, + message_key="Queued {{count}} files for indexing.", + message_params={"count": total_files}, + current=0, + total=total_files, + ) + try: + success = await rag_service.add_documents( + self.kb_name, + [str(path) for path in new_files], + indexed_file_callback=on_indexed, + ) + except PermissionError as exc: + logger.exception("Permission denied while indexing a LlamaIndex batch: %s", exc) + raise DataVolumePermissionError( + format_data_volume_permission_error(self.kb_dir, cause=exc) + ) from exc + except Exception as exc: + logger.warning( + "LlamaIndex batch of %d file(s) failed (%s); retrying one file at a time", + total_files, + exc, + ) + return await self._process_provider_files_one_by_one(new_files) + + if not success: + return DocumentIndexResult( + processed_files=[], + failures=[ + DocumentIndexFailure(path, "Provider returned failure without details.") + for path in new_files + ], + ) + # Pipelines that do not report per-file receipts still indexed the + # batch. A receipt that omits a file means that file was skipped. + processed = list(new_files) if not callback_fired else confirmed + failures = [ + DocumentIndexFailure(path, "Provider skipped this file.") + for path in new_files + if path not in processed + ] + recorded: list[Path] = [] + for path in processed: + try: + await asyncio.to_thread(self._record_successful_hash, path) + except Exception as exc: + logger.exception("Failed %s: %s", path.name, exc) + failures.append(DocumentIndexFailure(path, str(exc))) + continue + recorded.append(path) + logger.info("Processed: %s", path.name) + if self.progress_tracker is not None: + from deeptutor.knowledge.progress_tracker import ProgressStage + + self.progress_tracker.update( + ProgressStage.PROCESSING_FILE, + message_key="Successfully processed {{count}} files!", + message_params={"count": len(recorded)}, + current=len(recorded), + total=total_files, + ) + return DocumentIndexResult(processed_files=recorded, failures=failures) + + async def _process_provider_files_one_by_one( + self, new_files: List[Path] + ) -> DocumentIndexResult: + """Index each staged file with its own provider call. + + PageIndex and GraphRAG stay on this path. LlamaIndex uses it for a + single file, and as the fallback when a multi-file publish throws. + """ rag_service = RAGService(kb_base_dir=str(self.base_dir), provider=self.rag_provider) processed_files: list[Path] = [] failures: list[DocumentIndexFailure] = [] total_files = len(new_files) - for idx, doc_file in enumerate(new_files, 1): + for doc_file in new_files: try: if self.progress_tracker is not None: from deeptutor.knowledge.progress_tracker import ProgressStage diff --git a/deeptutor/services/rag/index_versioning.py b/deeptutor/services/rag/index_versioning.py index 644e314d2..68721d666 100644 --- a/deeptutor/services/rag/index_versioning.py +++ b/deeptutor/services/rag/index_versioning.py @@ -31,6 +31,7 @@ import json import logging from pathlib import Path import re +import shutil from typing import Any, Optional logger = logging.getLogger(__name__) @@ -39,6 +40,10 @@ VERSION_PREFIX = "version-" LEGACY_VERSION_DIRNAME = "index_versions" LEGACY_STORAGE_DIRNAME = "llamaindex_storage" META_FILENAME = "meta.json" +# Readers use the newest ready store for a signature. A few older snapshots +# stay so a bad publish can still be rolled back. Folder sync used to leave +# one full snapshot per file (#2173). +RETAINED_FLAT_VERSIONS = 3 _VERSION_RE = re.compile(r"^version-(\d+)$") @@ -306,6 +311,56 @@ def storage_dir_for_signature(kb_dir: Path, sig_hash: str) -> Path: return version_dir_for_signature(kb_dir, sig_hash) +def _is_llamaindex_flat_version(path: Path) -> bool: + """True for a published LlamaIndex ``version-N`` directory. + + Other providers share the flat ``version-N`` names. Their stores do not + carry a LlamaIndex docstore. A directory that still has ``.building.json`` + and no published meta is an in-progress build and stays untouched. + """ + if not path.is_dir(): + return False + meta = _read_json(path / META_FILENAME) or {} + if (path / ".building.json").is_file() and meta.get("state") != "published": + return False + if meta.get("provider") not in (None, "llamaindex"): + return False + return (path / "docstore.json").is_file() or (path / "index_store.json").is_file() + + +def prune_flat_versions( + kb_dir: Path, *, keep: int = RETAINED_FLAT_VERSIONS, protect: Path | None = None +) -> list[Path]: + """Delete old LlamaIndex snapshots, keeping the newest ``keep`` per signature. + + Version numbers increase on every publish. The newest directory for a + signature is the one readers open, so dropping everything before the + retained tail does not change the active index. ``protect`` is the + directory just published and is never removed. + """ + if keep < 1: + raise ValueError("keep must be at least 1") + protected = protect.resolve() if protect is not None else None + grouped: dict[str, list[Path]] = {} + for path in _flat_version_dirs(kb_dir): + if not _is_llamaindex_flat_version(path): + continue + meta = _read_json(path / META_FILENAME) or {} + grouped.setdefault(str(meta.get("signature") or ""), []).append(path) + removed: list[Path] = [] + for paths in grouped.values(): + for path in paths[:-keep]: + if protected is not None and path.resolve() == protected: + continue + try: + shutil.rmtree(path) + except OSError: + logger.warning("Could not remove old index version %s", path, exc_info=True) + continue + removed.append(path) + return removed + + def write_version_meta( kb_dir: Path, signature: EmbeddingSignature, storage_dir: Path | None = None ) -> None: @@ -324,6 +379,8 @@ def write_version_meta( if (target / ".building.json").exists(): payload.update(provider="llamaindex", state="published", readiness_verified=True) atomic_write_json(target / META_FILENAME, payload) + if target.parent == kb_dir and _VERSION_RE.match(target.name): + prune_flat_versions(kb_dir, protect=target) def resolve_storage_dir_for_read( diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py index e8f35f571..47b7f4135 100644 --- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py +++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py @@ -17,6 +17,7 @@ from deeptutor.services.embedding import get_embedding_config from deeptutor.services.rag.embedding_signature import signature_from_embedding_config from deeptutor.services.rag.index_versioning import ( EmbeddingSignature, + prune_flat_versions, resolve_storage_dir_for_read, resolve_storage_dir_for_rebuild, write_version_meta, @@ -34,6 +35,21 @@ from .embedding_adapter import ( ) from .errors import search_error_result + +def _notify_indexed_files(documents: list[Any], callback: Callable[..., Any] | None) -> None: + """Tell the caller which source files actually landed in the index.""" + if callback is None: + return + indexed_paths: set[str] = set() + for document in documents: + metadata = getattr(document, "metadata", None) + if isinstance(metadata, dict): + path = metadata.get("file_path") + if isinstance(path, str) and path: + indexed_paths.add(path) + callback(sorted(indexed_paths)) + + DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases") # How long an indexing step may run without reporting any progress before it @@ -281,17 +297,7 @@ class LlamaIndexPipeline: if resumed: self.logger.info(f"Resumed interrupted LlamaIndex candidate at {storage_dir}") await self._publish_verified(kb_dir, storage_dir, signature, documents) - - indexed_file_callback = kwargs.get("indexed_file_callback") - if indexed_file_callback is not None: - indexed_paths: set[str] = set() - for document in documents: - metadata = getattr(document, "metadata", None) - if isinstance(metadata, dict): - path = metadata.get("file_path") - if isinstance(path, str) and path: - indexed_paths.add(path) - indexed_file_callback(sorted(indexed_paths)) + _notify_indexed_files(documents, kwargs.get("indexed_file_callback")) self.logger.info(f"KB '{kb_name}' initialized successfully with LlamaIndex") return True @@ -505,6 +511,7 @@ class LlamaIndexPipeline: self.logger.info(f"Created new index with {num_added} documents") await self._publish_verified(kb_dir, plan.storage_dir, signature, documents) + _notify_indexed_files(documents, kwargs.get("indexed_file_callback")) self.logger.info(f"Successfully added documents to KB '{kb_name}'") return True @@ -541,6 +548,7 @@ class LlamaIndexPipeline: "readiness_verified": True, }, ) + prune_flat_versions(kb_dir, protect=storage_dir) if run: run.data["usable_version"] = storage_dir.name for document in documents: diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.py index e0cb10b57..18f82a9d1 100644 --- a/tests/knowledge/test_document_adder_provider.py +++ b/tests/knowledge/test_document_adder_provider.py @@ -421,3 +421,135 @@ def test_empty_bootstrap_does_not_replace_broken_existing_index(tmp_path, storag (kb_dir / storage).mkdir(parents=True) with pytest.raises(ValueError, match="reindex|not initialized"): DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="llamaindex") + + +def _llamaindex_adder(tmp_path: Path, names: list[str]) -> tuple[DocumentAdder, list[Path]]: + kb_dir = tmp_path / "kb" + raw_dir = kb_dir / "raw" + raw_dir.mkdir(parents=True) + _write_provider_version(kb_dir, "llamaindex") + files = [] + for name in names: + path = raw_dir / name + path.write_text(name, encoding="utf-8") + files.append(path) + return DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="llamaindex"), files + + +def test_llamaindex_indexes_a_folder_batch_in_one_publish(monkeypatch, tmp_path: Path) -> None: + adder, files = _llamaindex_adder(tmp_path, ["a.txt", "b.txt"]) + calls: list[list[str]] = [] + + class _BatchService: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def add_documents(self, _kb_name, file_paths, **kwargs): + calls.append(list(file_paths)) + kwargs["indexed_file_callback"](file_paths) + return True + + monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _BatchService) + + result = asyncio.run(adder.process_new_documents(files)) + + assert calls == [[str(path) for path in files]] + assert result.processed_files == files + assert result.failures == [] + assert set(adder.get_ingested_hashes()) == {"a.txt", "b.txt"} + + +def test_llamaindex_batch_reports_files_the_provider_skipped(monkeypatch, tmp_path: Path) -> None: + adder, files = _llamaindex_adder(tmp_path, ["kept.txt", "skipped.txt"]) + + class _PartialService: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def add_documents(self, _kb_name, file_paths, **kwargs): + kwargs["indexed_file_callback"](file_paths[:1]) + return True + + monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _PartialService) + + result = asyncio.run(adder.process_new_documents(files)) + + assert result.processed_files == [files[0]] + assert result.failed_count == 1 + assert "skipped" in result.failure_summary() + assert set(adder.get_ingested_hashes()) == {"kept.txt"} + + +def test_llamaindex_batch_failure_retries_one_file_at_a_time(monkeypatch, tmp_path: Path) -> None: + adder, files = _llamaindex_adder(tmp_path, ["a.txt", "b.txt"]) + calls: list[list[str]] = [] + + class _FallbackService: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def add_documents(self, _kb_name, file_paths, **_kwargs): + calls.append(list(file_paths)) + if len(file_paths) > 1: + raise RuntimeError("batch exploded") + return True + + monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _FallbackService) + + result = asyncio.run(adder.process_new_documents(files)) + + assert calls == [[str(path) for path in files], [str(files[0])], [str(files[1])]] + assert result.processed_files == files + assert result.failures == [] + + +def test_llamaindex_batch_permission_error_is_not_retried(monkeypatch, tmp_path: Path) -> None: + from deeptutor.services.setup.data_volume import DataVolumePermissionError + + adder, files = _llamaindex_adder(tmp_path, ["a.txt", "b.txt"]) + calls: list[int] = [] + + class _DeniedService: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def add_documents(self, *_args, **_kwargs): + calls.append(1) + raise PermissionError("denied") + + monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _DeniedService) + + with pytest.raises(DataVolumePermissionError): + asyncio.run(adder.process_new_documents(files)) + assert calls == [1] + + +def test_non_llamaindex_provider_still_indexes_one_file_per_call( + monkeypatch, tmp_path: Path +) -> None: + kb_dir = tmp_path / "kb" + raw_dir = kb_dir / "raw" + raw_dir.mkdir(parents=True) + _write_provider_version(kb_dir, "pageindex") + files = [] + for name in ("a.txt", "b.txt"): + path = raw_dir / name + path.write_text(name, encoding="utf-8") + files.append(path) + calls: list[list[str]] = [] + + class _PerFileService: + def __init__(self, *_args, **_kwargs) -> None: + pass + + async def add_documents(self, _kb_name, file_paths, **_kwargs): + calls.append(list(file_paths)) + return True + + monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _PerFileService) + adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="pageindex") + + result = asyncio.run(adder.process_new_documents(files)) + + assert calls == [[str(files[0])], [str(files[1])]] + assert result.processed_files == files diff --git a/tests/services/rag/test_index_versioning.py b/tests/services/rag/test_index_versioning.py index a69847643..7b67c931c 100644 --- a/tests/services/rag/test_index_versioning.py +++ b/tests/services/rag/test_index_versioning.py @@ -5,6 +5,7 @@ import json from pathlib import Path from deeptutor.services.rag.index_versioning import ( + RETAINED_FLAT_VERSIONS, EmbeddingSignature, find_matching_version, list_kb_versions, @@ -180,3 +181,46 @@ def test_list_kb_versions_includes_legacy_nested_and_root_layouts(tmp_path: Path layouts = {entry["layout"] for entry in list_kb_versions(kb_dir)} assert {"nested_legacy", "root_legacy"} <= layouts + + +def test_publishing_a_llamaindex_version_drops_snapshots_beyond_the_retained_tail( + tmp_path: Path, +) -> None: + kb_dir = tmp_path / "kb" + kb_dir.mkdir() + signature = _signature() + other = _signature(model="embed-b") + + building = kb_dir / "version-1" + building.mkdir() + (building / "docstore.json").write_text("{}", encoding="utf-8") + (building / ".building.json").write_text("{}", encoding="utf-8") + + lightrag = kb_dir / "version-2" + lightrag.mkdir() + (lightrag / "kv_store_doc_status.json").write_text("{}", encoding="utf-8") + (lightrag / "meta.json").write_text( + json.dumps({"provider": "lightrag", "signature": "lightrag", "version": "version-2"}), + encoding="utf-8", + ) + + start = 3 + count = RETAINED_FLAT_VERSIONS + 1 + for offset in range(count): + version_dir = kb_dir / f"version-{start + offset}" + version_dir.mkdir() + (version_dir / "docstore.json").write_text("{}", encoding="utf-8") + (version_dir / "index_store.json").write_text("{}", encoding="utf-8") + write_version_meta(kb_dir, signature, storage_dir=version_dir) + + other_dir = kb_dir / f"version-{start + count}" + other_dir.mkdir() + (other_dir / "docstore.json").write_text("{}", encoding="utf-8") + write_version_meta(kb_dir, other, storage_dir=other_dir) + + assert not (kb_dir / f"version-{start}").exists() + for offset in range(1, count): + assert (kb_dir / f"version-{start + offset}").is_dir() + assert building.is_dir() + assert lightrag.is_dir() + assert other_dir.is_dir() From 74a49500a75af5a1f45483bed761bc8bb6a76f18 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Sat, 31 Oct 2026 16:44:19 +0800 Subject: [PATCH 2/2] fix(rag): keep batch publishing independent of version retention --- deeptutor/services/rag/index_versioning.py | 57 ------------------- .../rag/pipelines/llamaindex/pipeline.py | 2 - tests/services/rag/test_index_versioning.py | 44 -------------- 3 files changed, 103 deletions(-) diff --git a/deeptutor/services/rag/index_versioning.py b/deeptutor/services/rag/index_versioning.py index 68721d666..644e314d2 100644 --- a/deeptutor/services/rag/index_versioning.py +++ b/deeptutor/services/rag/index_versioning.py @@ -31,7 +31,6 @@ import json import logging from pathlib import Path import re -import shutil from typing import Any, Optional logger = logging.getLogger(__name__) @@ -40,10 +39,6 @@ VERSION_PREFIX = "version-" LEGACY_VERSION_DIRNAME = "index_versions" LEGACY_STORAGE_DIRNAME = "llamaindex_storage" META_FILENAME = "meta.json" -# Readers use the newest ready store for a signature. A few older snapshots -# stay so a bad publish can still be rolled back. Folder sync used to leave -# one full snapshot per file (#2173). -RETAINED_FLAT_VERSIONS = 3 _VERSION_RE = re.compile(r"^version-(\d+)$") @@ -311,56 +306,6 @@ def storage_dir_for_signature(kb_dir: Path, sig_hash: str) -> Path: return version_dir_for_signature(kb_dir, sig_hash) -def _is_llamaindex_flat_version(path: Path) -> bool: - """True for a published LlamaIndex ``version-N`` directory. - - Other providers share the flat ``version-N`` names. Their stores do not - carry a LlamaIndex docstore. A directory that still has ``.building.json`` - and no published meta is an in-progress build and stays untouched. - """ - if not path.is_dir(): - return False - meta = _read_json(path / META_FILENAME) or {} - if (path / ".building.json").is_file() and meta.get("state") != "published": - return False - if meta.get("provider") not in (None, "llamaindex"): - return False - return (path / "docstore.json").is_file() or (path / "index_store.json").is_file() - - -def prune_flat_versions( - kb_dir: Path, *, keep: int = RETAINED_FLAT_VERSIONS, protect: Path | None = None -) -> list[Path]: - """Delete old LlamaIndex snapshots, keeping the newest ``keep`` per signature. - - Version numbers increase on every publish. The newest directory for a - signature is the one readers open, so dropping everything before the - retained tail does not change the active index. ``protect`` is the - directory just published and is never removed. - """ - if keep < 1: - raise ValueError("keep must be at least 1") - protected = protect.resolve() if protect is not None else None - grouped: dict[str, list[Path]] = {} - for path in _flat_version_dirs(kb_dir): - if not _is_llamaindex_flat_version(path): - continue - meta = _read_json(path / META_FILENAME) or {} - grouped.setdefault(str(meta.get("signature") or ""), []).append(path) - removed: list[Path] = [] - for paths in grouped.values(): - for path in paths[:-keep]: - if protected is not None and path.resolve() == protected: - continue - try: - shutil.rmtree(path) - except OSError: - logger.warning("Could not remove old index version %s", path, exc_info=True) - continue - removed.append(path) - return removed - - def write_version_meta( kb_dir: Path, signature: EmbeddingSignature, storage_dir: Path | None = None ) -> None: @@ -379,8 +324,6 @@ def write_version_meta( if (target / ".building.json").exists(): payload.update(provider="llamaindex", state="published", readiness_verified=True) atomic_write_json(target / META_FILENAME, payload) - if target.parent == kb_dir and _VERSION_RE.match(target.name): - prune_flat_versions(kb_dir, protect=target) def resolve_storage_dir_for_read( diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py index 47b7f4135..4f1e74d7e 100644 --- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py +++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py @@ -17,7 +17,6 @@ from deeptutor.services.embedding import get_embedding_config from deeptutor.services.rag.embedding_signature import signature_from_embedding_config from deeptutor.services.rag.index_versioning import ( EmbeddingSignature, - prune_flat_versions, resolve_storage_dir_for_read, resolve_storage_dir_for_rebuild, write_version_meta, @@ -548,7 +547,6 @@ class LlamaIndexPipeline: "readiness_verified": True, }, ) - prune_flat_versions(kb_dir, protect=storage_dir) if run: run.data["usable_version"] = storage_dir.name for document in documents: diff --git a/tests/services/rag/test_index_versioning.py b/tests/services/rag/test_index_versioning.py index 7b67c931c..a69847643 100644 --- a/tests/services/rag/test_index_versioning.py +++ b/tests/services/rag/test_index_versioning.py @@ -5,7 +5,6 @@ import json from pathlib import Path from deeptutor.services.rag.index_versioning import ( - RETAINED_FLAT_VERSIONS, EmbeddingSignature, find_matching_version, list_kb_versions, @@ -181,46 +180,3 @@ def test_list_kb_versions_includes_legacy_nested_and_root_layouts(tmp_path: Path layouts = {entry["layout"] for entry in list_kb_versions(kb_dir)} assert {"nested_legacy", "root_legacy"} <= layouts - - -def test_publishing_a_llamaindex_version_drops_snapshots_beyond_the_retained_tail( - tmp_path: Path, -) -> None: - kb_dir = tmp_path / "kb" - kb_dir.mkdir() - signature = _signature() - other = _signature(model="embed-b") - - building = kb_dir / "version-1" - building.mkdir() - (building / "docstore.json").write_text("{}", encoding="utf-8") - (building / ".building.json").write_text("{}", encoding="utf-8") - - lightrag = kb_dir / "version-2" - lightrag.mkdir() - (lightrag / "kv_store_doc_status.json").write_text("{}", encoding="utf-8") - (lightrag / "meta.json").write_text( - json.dumps({"provider": "lightrag", "signature": "lightrag", "version": "version-2"}), - encoding="utf-8", - ) - - start = 3 - count = RETAINED_FLAT_VERSIONS + 1 - for offset in range(count): - version_dir = kb_dir / f"version-{start + offset}" - version_dir.mkdir() - (version_dir / "docstore.json").write_text("{}", encoding="utf-8") - (version_dir / "index_store.json").write_text("{}", encoding="utf-8") - write_version_meta(kb_dir, signature, storage_dir=version_dir) - - other_dir = kb_dir / f"version-{start + count}" - other_dir.mkdir() - (other_dir / "docstore.json").write_text("{}", encoding="utf-8") - write_version_meta(kb_dir, other, storage_dir=other_dir) - - assert not (kb_dir / f"version-{start}").exists() - for offset in range(1, count): - assert (kb_dir / f"version-{start + offset}").is_dir() - assert building.is_dir() - assert lightrag.is_dir() - assert other_dir.is_dir()