mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 19:39:42 +08:00
Merge PR #2837: fix(rag): batch LlamaIndex rebuild checkpoints
Batch resumable embedding checkpoints and write the BM25 sidecar once after the final checkpoint, carrying over #2903. 45 targeted tests passed with the PR applied to dev. A 19-source rebuild retrieved the last source from the persisted BM25 index.
This commit is contained in:
@@ -6,6 +6,7 @@ from collections import OrderedDict
|
||||
from dataclasses import asdict, dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
@@ -28,6 +29,16 @@ from deeptutor.services.rag.index_versioning import (
|
||||
from . import ingestion, retrievers, vector_store
|
||||
from .config import should_show_progress, vector_index_config_from_settings
|
||||
|
||||
_EMBEDDING_CHECKPOINT_SOURCE_LIMIT = 16
|
||||
_EMBEDDING_CHECKPOINT_INTERVAL_SECONDS = 30.0
|
||||
|
||||
# Candidate top-k for the persisted BM25 sidecar. The sidecar is a retrieval
|
||||
# accelerator only: it is rebuilt from the docstore when missing, so checkpoints
|
||||
# can skip it and it is written once when the candidate is complete.
|
||||
_BM25_SIDECAR_TOP_K = 20
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AddStoragePlan:
|
||||
@@ -294,20 +305,21 @@ def _write_embedding_snapshot(
|
||||
*,
|
||||
source_records: dict[str, EmbeddingSourceRecord],
|
||||
completed_keys: set[str],
|
||||
document_group: list[Any],
|
||||
checkpoint_documents: list[Any],
|
||||
signature: EmbeddingSignature | None,
|
||||
) -> None:
|
||||
snapshot = Path(tempfile.mkdtemp(prefix=f".{candidate.name}.checkpoint-", dir=candidate.parent))
|
||||
try:
|
||||
index.storage_context.persist(persist_dir=str(snapshot))
|
||||
retrievers.persist_bm25_retriever(index, snapshot, top_k=20)
|
||||
# Building the BM25 sidecar scans the full corpus. Defer it until the
|
||||
# final checkpoint so intermediate snapshots only save resumable state.
|
||||
atomic_write_json(snapshot / ".building.json", {"state": "building"})
|
||||
existing_catalog = candidate / "source_pages.json"
|
||||
if existing_catalog.is_file():
|
||||
shutil.copy2(existing_catalog, snapshot / existing_catalog.name)
|
||||
from deeptutor.services.rag.source_pages import persist_page_catalog
|
||||
|
||||
persist_page_catalog(document_group, snapshot)
|
||||
persist_page_catalog(checkpoint_documents, snapshot)
|
||||
atomic_write_json(
|
||||
snapshot / ".embedding-checkpoint.json",
|
||||
{
|
||||
@@ -332,6 +344,92 @@ def _write_embedding_snapshot(
|
||||
shutil.rmtree(snapshot, ignore_errors=True)
|
||||
|
||||
|
||||
def _discard_sidecar_debris(storage_dir: Path, target: Path) -> None:
|
||||
"""Drop staging/backup directories a crashed sidecar publish may have left."""
|
||||
for stale in storage_dir.glob(".bm25-sidecar-*"):
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
for stale in storage_dir.glob(f".{target.name}.previous-*"):
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
def _persist_bm25_sidecar(index: Any, storage_dir: Path) -> bool:
|
||||
"""Write the BM25 sidecar once, after the candidate index is complete.
|
||||
|
||||
Each checkpoint would rebuild the BM25 sidecar from all indexed sources,
|
||||
even when checkpoints are batched. The sidecar can be rebuilt from the
|
||||
docstore, so defer writing it until all sources are indexed.
|
||||
|
||||
The sidecar is staged in a hidden directory inside the candidate, fsynced and
|
||||
swapped in by rename, so a crash mid-write can never publish a partial or
|
||||
stale sidecar (a loadable stale sidecar would silently drop the sources added
|
||||
since it was built). Failures are non-fatal: they remove any older sidecar so
|
||||
the query path rebuilds from the docstore instead of serving a stale corpus.
|
||||
"""
|
||||
target = storage_dir / retrievers.BM25_PERSIST_DIRNAME
|
||||
try:
|
||||
_discard_sidecar_debris(storage_dir, target)
|
||||
staging = Path(tempfile.mkdtemp(prefix=".bm25-sidecar-", dir=storage_dir))
|
||||
except OSError as exc:
|
||||
# A path-length/permission failure while preparing the staging directory
|
||||
# must not fail an otherwise complete rebuild (Windows MAX_PATH).
|
||||
logger.warning("Skipped BM25 sidecar for %s: %s", storage_dir, exc)
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
return False
|
||||
try:
|
||||
try:
|
||||
persisted = retrievers.persist_bm25_retriever(index, staging, top_k=_BM25_SIDECAR_TOP_K)
|
||||
except Exception as exc: # noqa: BLE001 - the sidecar is optional
|
||||
# e.g. a path-length or permission error escaping the helper; a
|
||||
# missing accelerator must not fail an otherwise complete rebuild.
|
||||
logger.warning("Failed to build BM25 sidecar for %s: %s", storage_dir, exc)
|
||||
persisted = False
|
||||
if not persisted:
|
||||
# Never leave a sidecar built from an earlier (partial) corpus.
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
if retrievers.bm25_available():
|
||||
logger.warning("BM25 sidecar was not persisted for %s", storage_dir)
|
||||
else:
|
||||
logger.debug(
|
||||
"BM25 retriever package unavailable; skipped sidecar for %s", storage_dir
|
||||
)
|
||||
return False
|
||||
staged = staging / retrievers.BM25_PERSIST_DIRNAME
|
||||
if not staged.is_dir():
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
return False
|
||||
# The old path fsynced the sidecar as part of the checkpoint tree; keep
|
||||
# that durability now that it is written outside the snapshot swap.
|
||||
_sync_checkpoint_tree(staged)
|
||||
backup: Path | None = None
|
||||
if target.exists():
|
||||
backup = storage_dir / f".{target.name}.previous-{uuid4().hex}"
|
||||
try:
|
||||
target.replace(backup)
|
||||
except OSError as exc:
|
||||
# Never let an unmovable stale sidecar survive the publish.
|
||||
logger.warning(
|
||||
"Failed to move the old BM25 sidecar aside in %s: %s", storage_dir, exc
|
||||
)
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
backup = None
|
||||
try:
|
||||
staged.replace(target)
|
||||
except OSError as exc:
|
||||
logger.warning("Failed to publish BM25 sidecar to %s: %s", target, exc)
|
||||
# Never keep (or restore) a sidecar that does not match the candidate
|
||||
# corpus: stale BM25 data silently drops sources added afterwards.
|
||||
if target.exists():
|
||||
shutil.rmtree(target, ignore_errors=True)
|
||||
if backup is not None:
|
||||
shutil.rmtree(backup, ignore_errors=True)
|
||||
return False
|
||||
if backup is not None:
|
||||
shutil.rmtree(backup, ignore_errors=True)
|
||||
return True
|
||||
finally:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
|
||||
|
||||
def create_resumable_index(
|
||||
documents: list[Any],
|
||||
storage_dir: Path,
|
||||
@@ -341,7 +439,7 @@ def create_resumable_index(
|
||||
show_progress: bool | None = None,
|
||||
checkpoint_callback: Callable[[Path, bool], None] | None = None,
|
||||
) -> int:
|
||||
"""Build a rebuild candidate one source at a time and snapshot each source."""
|
||||
"""Embed sources individually and persist bounded batches as restart checkpoints."""
|
||||
if show_progress is None:
|
||||
show_progress = should_show_progress()
|
||||
if (storage_dir / "meta.json").exists():
|
||||
@@ -358,9 +456,11 @@ def create_resumable_index(
|
||||
for key in sorted(completed_keys):
|
||||
checkpoint_callback(source_records[key].path, True)
|
||||
|
||||
for key, document_group in grouped.items():
|
||||
if key in completed_keys:
|
||||
continue
|
||||
remaining = [(key, group) for key, group in grouped.items() if key not in completed_keys]
|
||||
checkpoint_keys: list[str] = []
|
||||
checkpoint_documents: list[Any] = []
|
||||
checkpointed_at = time.monotonic()
|
||||
for position, (key, document_group) in enumerate(remaining, start=1):
|
||||
nodes = ingestion.documents_to_nodes(document_group, show_progress=show_progress)
|
||||
if index is None:
|
||||
storage_context = vector_store.storage_context_for_nodes(
|
||||
@@ -375,16 +475,34 @@ def create_resumable_index(
|
||||
else:
|
||||
index.insert_nodes(nodes)
|
||||
completed_keys.add(key)
|
||||
checkpoint_keys.append(key)
|
||||
checkpoint_documents.extend(document_group)
|
||||
# A new rebuild gets an early restart point; a resumed one already has it.
|
||||
checkpoint_due = (
|
||||
len(completed_keys) == 1
|
||||
or position == len(remaining)
|
||||
or len(checkpoint_keys) >= _EMBEDDING_CHECKPOINT_SOURCE_LIMIT
|
||||
or time.monotonic() - checkpointed_at >= _EMBEDDING_CHECKPOINT_INTERVAL_SECONDS
|
||||
)
|
||||
if not checkpoint_due:
|
||||
continue
|
||||
|
||||
_write_embedding_snapshot(
|
||||
index,
|
||||
storage_dir,
|
||||
source_records=source_records,
|
||||
completed_keys=completed_keys,
|
||||
document_group=document_group,
|
||||
checkpoint_documents=checkpoint_documents,
|
||||
signature=signature,
|
||||
)
|
||||
if checkpoint_callback is not None:
|
||||
checkpoint_callback(source_records[key].path, False)
|
||||
for checkpoint_key in checkpoint_keys:
|
||||
checkpoint_callback(source_records[checkpoint_key].path, False)
|
||||
checkpoint_keys.clear()
|
||||
checkpoint_documents.clear()
|
||||
checkpointed_at = time.monotonic()
|
||||
if index is not None:
|
||||
_persist_bm25_sidecar(index, storage_dir)
|
||||
return len(documents)
|
||||
|
||||
|
||||
@@ -394,7 +512,7 @@ def create_index(
|
||||
index, count = ingestion.create_index_from_documents(
|
||||
documents, storage_dir, show_progress=show_progress
|
||||
)
|
||||
retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
|
||||
_persist_bm25_sidecar(index, storage_dir)
|
||||
from deeptutor.services.rag.source_pages import persist_page_catalog
|
||||
|
||||
persist_page_catalog(documents, storage_dir)
|
||||
@@ -412,7 +530,7 @@ def insert_documents(existing_storage: Path, storage_dir: Path, documents: list[
|
||||
index.insert(document)
|
||||
count = len(documents)
|
||||
index.storage_context.persist(persist_dir=str(storage_dir))
|
||||
retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
|
||||
_persist_bm25_sidecar(index, storage_dir)
|
||||
from deeptutor.services.rag.source_pages import persist_page_catalog
|
||||
|
||||
if existing_storage != storage_dir and (existing_storage / "source_pages.json").is_file():
|
||||
|
||||
456
tests/services/rag/test_llamaindex_bm25_checkpointing.py
Normal file
456
tests/services/rag/test_llamaindex_bm25_checkpointing.py
Normal file
@@ -0,0 +1,456 @@
|
||||
"""BM25 sidecar lifecycle during a resumable (per-source) rebuild.
|
||||
|
||||
The sidecar is a retrieval accelerator rebuilt from the docstore on demand, so a
|
||||
resumable rebuild must not rebuild it for every source checkpoint: that is a full
|
||||
corpus pass per source (O(N^2) over the rebuild) and it dominated indexing time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _records(kb_dir: Path, names: list[str]) -> dict:
|
||||
from deeptutor.services.rag.pipelines.llamaindex import storage
|
||||
|
||||
records = {}
|
||||
for name in names:
|
||||
path = kb_dir / "raw" / name
|
||||
records[name] = storage.EmbeddingSourceRecord(
|
||||
key=name,
|
||||
path=path,
|
||||
source_hash=hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resumable_rebuild_writes_bm25_sidecar_once_after_checkpoints(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from llama_index.core import Document, Settings
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import storage
|
||||
|
||||
kb_dir = tmp_path / "kb"
|
||||
raw = kb_dir / "raw"
|
||||
raw.mkdir(parents=True)
|
||||
names = ["first.txt", "second.txt"]
|
||||
documents = []
|
||||
for name in names:
|
||||
path = raw / name
|
||||
text = f"{name} explains Fourier transforms and sampling."
|
||||
path.write_text(text, encoding="utf-8")
|
||||
documents.append(Document(text=text, metadata={"file_path": str(path)}))
|
||||
|
||||
monkeypatch.setattr(Settings, "_embed_model", MockEmbedding(embed_dim=4))
|
||||
|
||||
calls: list[Path] = []
|
||||
|
||||
def record_persist(index, storage_dir, *, top_k):
|
||||
calls.append(Path(storage_dir))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(storage.retrievers, "persist_bm25_retriever", record_persist)
|
||||
|
||||
storage_dir = kb_dir / "version-1"
|
||||
written = storage.create_resumable_index(
|
||||
documents,
|
||||
storage_dir,
|
||||
source_records=_records(kb_dir, names),
|
||||
signature=None,
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
assert written == len(names)
|
||||
# Two per-source checkpoints ran, but the whole-corpus BM25 rebuild happens
|
||||
# exactly once, on the completed candidate, never on a `.checkpoint-*` dir.
|
||||
assert len(calls) == 1
|
||||
assert calls[0].parent == storage_dir
|
||||
assert calls[0].name.startswith(".bm25-sidecar-")
|
||||
assert not list(storage_dir.parent.glob(".*.checkpoint-*"))
|
||||
checkpoint = json.loads(
|
||||
(storage_dir / ".embedding-checkpoint.json").read_text(encoding="utf-8")
|
||||
)
|
||||
assert set(checkpoint["sources"]) == set(names)
|
||||
assert (storage_dir / "docstore.json").is_file()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resumable_rebuild_persists_a_loadable_bm25_sidecar(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
pytest.importorskip("bm25s")
|
||||
pytest.importorskip("llama_index.retrievers.bm25")
|
||||
|
||||
from llama_index.core import Document, Settings
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
kb_dir = tmp_path / "kb"
|
||||
raw = kb_dir / "raw"
|
||||
raw.mkdir(parents=True)
|
||||
names = ["first.txt", "second.txt"]
|
||||
documents = []
|
||||
for name in names:
|
||||
path = raw / name
|
||||
text = f"{name} explains Fourier transforms and sampling."
|
||||
path.write_text(text, encoding="utf-8")
|
||||
documents.append(Document(text=text, metadata={"file_path": str(path)}))
|
||||
|
||||
monkeypatch.setattr(Settings, "_embed_model", MockEmbedding(embed_dim=4))
|
||||
|
||||
storage_dir = kb_dir / "version-1"
|
||||
storage.create_resumable_index(
|
||||
documents,
|
||||
storage_dir,
|
||||
source_records=_records(kb_dir, names),
|
||||
signature=None,
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
# The sidecar only exists after the last checkpoint, and it is complete
|
||||
# enough for the query path to load it instead of rebuilding from docstore.
|
||||
assert (storage_dir / "bm25_retriever" / "corpus.jsonl").is_file()
|
||||
assert not list(storage_dir.parent.glob(".*.checkpoint-*"))
|
||||
index = storage.vector_store.load_index(storage_dir)
|
||||
retriever = retrievers.build_bm25_retriever(index, storage_dir, top_k=1)
|
||||
assert retriever is not None
|
||||
assert not list(storage_dir.parent.glob(".*.checkpoint-*"))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intermediate_checkpoints_carry_no_bm25_sidecar(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Per-source checkpoints must stay cheap: no whole-corpus sidecar in them."""
|
||||
from llama_index.core import Document, Settings
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import storage
|
||||
|
||||
kb_dir = tmp_path / "kb"
|
||||
raw = kb_dir / "raw"
|
||||
raw.mkdir(parents=True)
|
||||
names = ["first.txt", "second.txt", "third.txt"]
|
||||
documents = []
|
||||
for name in names:
|
||||
path = raw / name
|
||||
text = f"{name} explains Fourier transforms and sampling."
|
||||
path.write_text(text, encoding="utf-8")
|
||||
documents.append(Document(text=text, metadata={"file_path": str(path)}))
|
||||
|
||||
monkeypatch.setattr(Settings, "_embed_model", MockEmbedding(embed_dim=4))
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers
|
||||
|
||||
sidecar_writes: list[Path] = []
|
||||
|
||||
def record_sidecar(index, storage_dir, *, top_k):
|
||||
sidecar_writes.append(Path(storage_dir))
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", record_sidecar)
|
||||
|
||||
storage_dir = kb_dir / "version-1"
|
||||
checkpoints: list[int] = []
|
||||
original_snapshot = storage._write_embedding_snapshot
|
||||
|
||||
def snapshot_with_assertions(*args, **kwargs):
|
||||
candidate = kwargs.get("candidate") or args[1]
|
||||
result = original_snapshot(*args, **kwargs)
|
||||
assert not (Path(candidate) / "bm25_retriever").exists(), (
|
||||
"an intermediate checkpoint must not carry a whole-corpus BM25 sidecar"
|
||||
)
|
||||
checkpoints.append(len(checkpoints) + 1)
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(storage, "_write_embedding_snapshot", snapshot_with_assertions)
|
||||
|
||||
storage.create_resumable_index(
|
||||
documents,
|
||||
storage_dir,
|
||||
source_records=_records(kb_dir, names),
|
||||
signature=None,
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
# Checkpoint frequency is a policy choice (upstream PR #2837 batches them:
|
||||
# first source + batches), so the count is not necessarily one per source.
|
||||
# What must hold is that no checkpoint carries a whole-corpus sidecar.
|
||||
assert 1 <= len(checkpoints) <= len(names)
|
||||
assert len(sidecar_writes) == 1
|
||||
assert sidecar_writes[0].parent == storage_dir
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resume_with_every_source_done_backfills_the_missing_sidecar(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A candidate killed between the last checkpoint and the sidecar write resumes.
|
||||
|
||||
Every source is already checkpointed, so the rebuild loop does nothing; the
|
||||
sidecar write must still happen once, and the candidate must then pass the
|
||||
publish-time verification. This is the regression seam for the new order of
|
||||
operations (checkpoints first, sidecar last).
|
||||
"""
|
||||
pytest.importorskip("bm25s")
|
||||
pytest.importorskip("llama_index.retrievers.bm25")
|
||||
import shutil
|
||||
|
||||
from llama_index.core import Document, Settings
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
kb_dir = tmp_path / "kb"
|
||||
raw = kb_dir / "raw"
|
||||
raw.mkdir(parents=True)
|
||||
names = ["first.txt", "second.txt"]
|
||||
documents = []
|
||||
for name in names:
|
||||
path = raw / name
|
||||
text = f"{name} explains Fourier transforms and sampling."
|
||||
path.write_text(text, encoding="utf-8")
|
||||
documents.append(Document(text=text, metadata={"file_path": str(path)}))
|
||||
|
||||
monkeypatch.setattr(Settings, "_embed_model", MockEmbedding(embed_dim=4))
|
||||
source_records = _records(kb_dir, names)
|
||||
storage_dir = kb_dir / "version-1"
|
||||
|
||||
storage.create_resumable_index(
|
||||
documents,
|
||||
storage_dir,
|
||||
source_records=source_records,
|
||||
signature=None,
|
||||
show_progress=False,
|
||||
)
|
||||
assert (storage_dir / "bm25_retriever").is_dir()
|
||||
|
||||
# Simulate the crash window: all sources checkpointed, sidecar absent.
|
||||
shutil.rmtree(storage_dir / "bm25_retriever")
|
||||
assert not (storage_dir / "bm25_retriever").exists()
|
||||
|
||||
writes: list[Path] = []
|
||||
original_persist = retrievers.persist_bm25_retriever
|
||||
|
||||
def counting_persist(index, target, *, top_k):
|
||||
writes.append(Path(target))
|
||||
return original_persist(index, target, top_k=top_k)
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", counting_persist)
|
||||
|
||||
storage.create_resumable_index(
|
||||
documents,
|
||||
storage_dir,
|
||||
source_records=source_records,
|
||||
signature=None,
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
assert len(writes) == 1
|
||||
assert writes[0].parent == storage_dir
|
||||
assert (storage_dir / "bm25_retriever" / "corpus.jsonl").is_file()
|
||||
assert not list(storage_dir.glob(".bm25-sidecar-*"))
|
||||
assert not list(storage_dir.glob(".*.previous-*"))
|
||||
storage.verify_persisted_index(storage_dir)
|
||||
|
||||
|
||||
def test_successful_sidecar_write_replaces_the_old_one_atomically(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
def fake_persist(index, target, *, top_k):
|
||||
staged = Path(target) / "bm25_retriever"
|
||||
staged.mkdir(parents=True)
|
||||
(staged / "corpus.jsonl").write_text("fresh", encoding="utf-8")
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", fake_persist)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is True
|
||||
assert (storage_dir / "bm25_retriever" / "corpus.jsonl").read_text(encoding="utf-8") == "fresh"
|
||||
assert not list(storage_dir.glob(".bm25-sidecar-*"))
|
||||
assert not list(storage_dir.glob(".*.previous-*"))
|
||||
|
||||
|
||||
def test_failed_sidecar_write_drops_the_old_sidecar(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", lambda *args, **kwargs: False)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is False
|
||||
# A failed write must not leave a stale sidecar behind: the query path
|
||||
# rebuilds from the docstore instead of silently using an older corpus.
|
||||
assert not (storage_dir / "bm25_retriever").exists()
|
||||
assert not list(storage_dir.glob(".bm25-sidecar-*"))
|
||||
|
||||
|
||||
def _fake_persist_writer(payload: str = "fresh"):
|
||||
def fake_persist(index, target, *, top_k):
|
||||
staged = Path(target) / "bm25_retriever"
|
||||
staged.mkdir(parents=True)
|
||||
(staged / "corpus.jsonl").write_text(payload, encoding="utf-8")
|
||||
return True
|
||||
|
||||
return fake_persist
|
||||
|
||||
|
||||
def test_sidecar_build_failure_does_not_fail_the_rebuild(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A missing/broken accelerator must degrade to vector-only, not fail indexing."""
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
def exploding_persist(index, target, *, top_k):
|
||||
raise OSError("WinError 206: filename or extension is too long")
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", exploding_persist)
|
||||
monkeypatch.setattr(retrievers, "bm25_available", lambda: True)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is False
|
||||
assert not old.exists()
|
||||
assert not list(storage_dir.glob(".bm25-sidecar-*"))
|
||||
|
||||
|
||||
def test_sidecar_debris_from_a_crashed_publish_is_cleaned(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
stale_staging = storage_dir / ".bm25-sidecar-crashed"
|
||||
(stale_staging / "bm25_retriever").mkdir(parents=True)
|
||||
stale_backup = storage_dir / ".bm25_retriever.previous-crashed"
|
||||
stale_backup.mkdir()
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", _fake_persist_writer("fresh"))
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is True
|
||||
assert (storage_dir / "bm25_retriever" / "corpus.jsonl").read_text(encoding="utf-8") == "fresh"
|
||||
assert not list(storage_dir.glob(".bm25-sidecar-*"))
|
||||
assert not list(storage_dir.glob(".bm25_retriever.previous-*"))
|
||||
|
||||
|
||||
def test_unmovable_stale_sidecar_is_dropped_before_publish(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""If the old sidecar cannot be moved aside, publish the new one anyway."""
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", _fake_persist_writer("fresh"))
|
||||
|
||||
original_replace = Path.replace
|
||||
|
||||
def locked_replace(self, target_path, *args, **kwargs):
|
||||
target_str = str(target_path)
|
||||
if self.name == "bm25_retriever" and ".previous-" in target_str:
|
||||
raise OSError("file is locked")
|
||||
return original_replace(self, target_path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "replace", locked_replace)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is True
|
||||
assert (storage_dir / "bm25_retriever" / "corpus.jsonl").read_text(encoding="utf-8") == "fresh"
|
||||
|
||||
|
||||
def test_staged_sidecar_is_fsynced_before_publish(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", _fake_persist_writer("fresh"))
|
||||
|
||||
synced: list[Path] = []
|
||||
monkeypatch.setattr(storage, "_sync_checkpoint_tree", lambda root: synced.append(Path(root)))
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is True
|
||||
assert len(synced) == 1
|
||||
assert synced[0].name == "bm25_retriever"
|
||||
|
||||
|
||||
def test_sidecar_setup_failure_is_non_fatal(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A staging-directory OSError (e.g. Windows MAX_PATH) must not fail the rebuild."""
|
||||
import tempfile as tempfile_module
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
def exploding_mkdtemp(*args, **kwargs):
|
||||
raise OSError("WinError 206: filename or extension is too long")
|
||||
|
||||
monkeypatch.setattr(tempfile_module, "mkdtemp", exploding_mkdtemp)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is False
|
||||
assert not old.exists()
|
||||
|
||||
|
||||
def test_failed_publish_drops_the_old_sidecar(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A failed swap must never restore a stale sidecar (it would leak missed sources)."""
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers, storage
|
||||
|
||||
storage_dir = tmp_path / "version-1"
|
||||
storage_dir.mkdir()
|
||||
old = storage_dir / "bm25_retriever"
|
||||
old.mkdir()
|
||||
(old / "corpus.jsonl").write_text("stale", encoding="utf-8")
|
||||
|
||||
monkeypatch.setattr(retrievers, "persist_bm25_retriever", _fake_persist_writer("fresh"))
|
||||
|
||||
original_replace = Path.replace
|
||||
|
||||
def fail_staged_swap(self, target_path, *args, **kwargs):
|
||||
if self.parent.name.startswith(".bm25-sidecar-"):
|
||||
raise OSError("sharing violation")
|
||||
return original_replace(self, target_path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "replace", fail_staged_swap)
|
||||
|
||||
assert storage._persist_bm25_sidecar(object(), storage_dir) is False
|
||||
assert not (storage_dir / "bm25_retriever").exists()
|
||||
assert not list(storage_dir.glob(".bm25_retriever.previous-*"))
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -33,6 +34,83 @@ def _records(kb_dir: Path, names: list[str]) -> dict[str, object]:
|
||||
return records
|
||||
|
||||
|
||||
def test_rebuild_checkpoints_batches_and_flushes_the_tail(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from llama_index.core import Document, Settings
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import storage
|
||||
from deeptutor.services.rag.source_pages import SOURCE_SCHEMA_VERSION
|
||||
|
||||
raw = tmp_path / "raw"
|
||||
raw.mkdir()
|
||||
paths = [raw / f"source-{number}.txt" for number in range(1, 8)]
|
||||
documents = []
|
||||
for path in paths:
|
||||
path.write_text(f"Contents of {path.name}", encoding="utf-8")
|
||||
documents.append(
|
||||
Document(
|
||||
text=path.read_text(encoding="utf-8"),
|
||||
metadata={
|
||||
"file_path": str(path),
|
||||
"document_key": path.name,
|
||||
"page_index": 0,
|
||||
"source_schema_version": SOURCE_SCHEMA_VERSION,
|
||||
},
|
||||
)
|
||||
)
|
||||
candidate = tmp_path / "version-1"
|
||||
saved_counts = []
|
||||
reported = []
|
||||
now = 0.0
|
||||
original_snapshot = storage._write_embedding_snapshot
|
||||
original_chunk = storage.ingestion.documents_to_nodes
|
||||
|
||||
def record_snapshot(*args, **kwargs):
|
||||
original_snapshot(*args, **kwargs)
|
||||
saved_counts.append(len(kwargs["completed_keys"]))
|
||||
|
||||
def chunk(source_documents, **kwargs):
|
||||
nonlocal now
|
||||
if source_documents[0].metadata["file_path"] == str(paths[4]):
|
||||
now = 31.0
|
||||
return original_chunk(source_documents, **kwargs)
|
||||
|
||||
def record_completion(path: Path, reused: bool) -> None:
|
||||
assert not reused
|
||||
checkpoint = json.loads(
|
||||
(candidate / ".embedding-checkpoint.json").read_text(encoding="utf-8")
|
||||
)
|
||||
assert checkpoint["sources"][path.name]["completed"]
|
||||
reported.append(path)
|
||||
|
||||
monkeypatch.setattr(Settings, "_embed_model", MockEmbedding(embed_dim=4))
|
||||
monkeypatch.setattr(storage, "_EMBEDDING_CHECKPOINT_SOURCE_LIMIT", 3)
|
||||
monkeypatch.setattr(storage, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
monkeypatch.setattr(storage, "_write_embedding_snapshot", record_snapshot)
|
||||
monkeypatch.setattr(storage.ingestion, "documents_to_nodes", chunk)
|
||||
monkeypatch.setattr(
|
||||
storage.retrievers, "persist_bm25_retriever", lambda *_args, **_kwargs: False
|
||||
)
|
||||
|
||||
count = storage.create_resumable_index(
|
||||
documents,
|
||||
candidate,
|
||||
source_records=_records(tmp_path, [path.name for path in paths]),
|
||||
signature=_signature(),
|
||||
show_progress=False,
|
||||
checkpoint_callback=record_completion,
|
||||
)
|
||||
|
||||
assert count == len(documents)
|
||||
assert saved_counts == [1, 4, 5, 7]
|
||||
assert reported == paths
|
||||
storage.verify_persisted_index(candidate)
|
||||
catalog = json.loads((candidate / "source_pages.json").read_text(encoding="utf-8"))
|
||||
assert [page["document_key"] for page in catalog["pages"]] == [path.name for path in paths]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("interrupted_swap", [False, True])
|
||||
@pytest.mark.parametrize("blocked_preflights", [0, 2])
|
||||
|
||||
Reference in New Issue
Block a user