Merge pull request #2208 from fanjiahe/fix/llamaindex-version-retention

fix: publish one LlamaIndex version per folder sync
This commit is contained in:
Bingxi Zhao
2026-10-31 18:49:18 +08:00
committed by GitHub
3 changed files with 256 additions and 12 deletions

View File

@@ -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

View File

@@ -34,6 +34,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 +296,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
@@ -527,6 +532,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

View File

@@ -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