Files
AleFlyX 5ff2627aee fix(knowledge): reclaim parse cache when a document or KB is deleted (#2941)
The parse cache is content-addressed and has no eviction of any kind: no size
cap, no TTL, no LRU, no CLI command, no settings entry. Neither deleting a raw
document nor deleting a whole knowledge base removed anything from it, and the
only cleanup that exists (clean_rag_storage) removes index storage - not the
parse cache - and is CLI-only. A deleted KB therefore kept its entire derived
parse output on disk forever.

Measured with a realistic document: a 30-page PDF with ~18 extracted images
leaves about 6.5 MB under parse_cache/. 64 such documents accumulate ~418 MB
that is never reclaimed; the directory only grows.

cache.reclaim_sources(paths, cache_root=...) removes the
<parse_cache>/<hash[:2]>/<hash>/ shard for each document being deleted - every
parser signature for that source, since the cache is derived and the next parse
recreates what it needs. It hashes the bytes while they still exist, because
the cache key is the content hash. Wired into two call sites, both before the
bytes disappear:

- remove_raw_document (single file, before unlink())
- KnowledgeBaseManager.delete_knowledge_base (every raw document, before the
  KB directory is removed)

The cache root is derived from the KB directory (a sibling of knowledge_bases/)
rather than from the ambient path service, because requests served from the
knowledge-base library run in the account workspace scope. Deriving it from the
request scope would reclaim another workspace's cache while leaking this KB's
own. KB deletion enumerates exactly what rmtree removes: dotfiles included,
symlinks skipped because only the link goes away.

Reclaiming is scoped strictly to the hashes of the files being deleted, so
nothing else under the cache root is touched. The cache is shared across all
parse consumers in the workspace (KB indexing, chat attachments, reading
figures), so a byte-identical copy loses its entry too and is re-parsed once on
next use - slower, never incorrect. Proving liveness would mean hashing every
live source on every delete, and metadata.json only records documents that
indexed successfully; that tradeoff is documented on the helper and at both
call sites. The key is a truncated 64-bit hash; a collision costs one extra
re-parse, never wrong output.

Best-effort by contract: an unreadable source, a locked shard (a stale Windows
handle is the common case) or a missing cache root is logged and skipped, and
both call sites additionally wrap the call, so no cache failure can fail a
user's delete.

Note: this reclaims on delete; it does not bound growth of the live cache. A
size cap / LRU sweeper is a separate change and should be its own issue (the
scope split is recorded on #2946).

Verified on the current dev base (14796c70f): 14 new tests; mutation checks show
disabling the helper at either call site fails its positive-reclamation test.
A workspace/library-view reproduction (real ContentWorkspaceService, account
scope, KB stored in a workspace) confirms the KB's own shard is now reclaimed
while an account-level lookalike shard is left alone. tests/knowledge: 205
passed, 6 pre-existing failures (same as dev, missing llama_index/jose). ruff
check/format clean with the pinned 0.16.0.
2026-11-30 14:17:47 +08:00

274 lines
10 KiB
Python

"""Content-addressed parse cache + canonical IR loader.
The cache is keyed by ``(source_hash, parser_signature)`` and shared across all
consumers (question extraction, RAG indexing). Re-parsing the same bytes with
the same engine config is a directory lookup; a different engine/version/knob
lands in a different signature dir and re-parses. Layout::
parse_cache/<hash[:2]>/<source_hash>/<signature>/
manifest.json # atomically written last → completed
<stem>.md
<stem>_content_list.json # optional (engines that emit structure)
images/ # optional
``load_ir`` turns such a dir back into ``(markdown, blocks, asset_dir)``,
mirroring the question extractor's loader but free of stdout side effects so
both it and the engines share one loader.
"""
from __future__ import annotations
from datetime import datetime, timezone
import hashlib
import json
import logging
from pathlib import Path
import shutil
from typing import Any, Iterable, Optional
from uuid import uuid4
from deeptutor.services.file_io import atomic_write_json
logger = logging.getLogger(__name__)
MANIFEST_FILENAME = "manifest.json"
_HASH_PREFIX = "sha256"
_READ_CHUNK = 1 << 20 # 1 MiB
def source_hash_from_path(path: Path) -> str:
"""Hash the *bytes* of ``path`` (not its name) so re-uploads of the same
document under a random temp name still hit cache."""
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(_READ_CHUNK), b""):
digest.update(chunk)
return digest.hexdigest()[:16]
def source_dir(cache_root: Path, source_hash: str) -> Path:
"""Root holding every cached parser signature for one source document."""
return cache_root / source_hash[:2] / source_hash
def signature_dir(cache_root: Path, source_hash: str, sig_hash: str) -> Path:
return source_dir(cache_root, source_hash) / sig_hash
def cache_root_for(kb_base_dir: Path) -> Path:
"""Parse-cache root that owns the knowledge bases under ``kb_base_dir``.
``path_service`` keeps ``parse_cache/`` as a sibling of ``knowledge_bases/``
inside the workspace root, so the caller can derive it from the KB directory
it is deleting. Deriving it from the resource matters: requests served from
the knowledge-base library run in the account scope, so asking the ambient
path service for the cache root can name a different workspace than the KB
being deleted.
"""
return Path(kb_base_dir).parent / "parse_cache"
def reclaim_sources(source_paths: Iterable[Path], *, cache_root: Path) -> int:
"""Best-effort removal of the cached parse entries for ``source_paths``.
Call this with the raw files that are *about to* be deleted — one raw
document, or every document of a knowledge base. Each file's bytes are
hashed while it still exists (the cache key is the content hash, not the
name), then the whole ``<cache_root>/<hash[:2]>/<hash>/`` shard is removed:
every parser signature for that source. Dropping all signatures is correct
because the cache is derived and content-addressed — the next parse
re-creates exactly the signature it needs.
The cache is shared by every parse consumer in the workspace (knowledge-base
indexing, chat attachments, reading figures), so a byte-identical copy of a
deleted document kept by another consumer shares the same shard. We do not
prove liveness: that would mean hashing every live source on every delete,
and ``metadata.json`` only records documents that indexed successfully. A
duplicate therefore loses its entry and re-parses once on next use — slower,
never incorrect. Reclaiming is still scoped strictly to the hashes of the
files being deleted; nothing else under the cache root is touched. The key
is a truncated 64-bit hash, and the failure mode of a collision here is one
extra re-parse, not wrong output.
Best-effort by design: an unreadable file or a locked cache dir (a stale
Windows handle is the common case) must not fail the user's delete, so
those failures are logged and skipped. Returns how many shards were removed.
"""
if not cache_root.is_dir():
return 0
reclaimed = 0
for source_path in source_paths:
try:
source_hash = source_hash_from_path(Path(source_path))
except OSError as exc:
logger.warning("Could not hash %s to reclaim its parse cache: %s", source_path, exc)
continue
shard = source_dir(cache_root, source_hash)
if not shard.exists():
continue
try:
shutil.rmtree(shard)
except OSError as exc:
logger.warning("Could not reclaim parse cache %s: %s", shard, exc)
continue
reclaimed += 1
return reclaimed
def is_ready(workdir: Optional[Path]) -> bool:
if workdir is None:
return False
try:
manifest = json.loads((workdir / MANIFEST_FILENAME).read_text(encoding="utf-8"))
return isinstance(manifest, dict) and bool(manifest.get("created_at"))
except (OSError, ValueError):
return False
def lookup(cache_root: Path, source_hash: str, sig_hash: str) -> Optional[Path]:
"""Return a ready cache dir for the key, or ``None`` on miss."""
target = signature_dir(cache_root, source_hash, sig_hash)
return target if is_ready(target) else None
def reserve(cache_root: Path, source_hash: str, sig_hash: str) -> Path:
"""Create (or reuse) the signature dir the engine writes its artifacts into.
Incomplete attempts are retained beside the cache entry for diagnosis, but
never reused as completed parser output (#1612).
"""
target = signature_dir(cache_root, source_hash, sig_hash)
if target.exists() and not is_ready(target):
cleanup_failed(target)
if target.exists():
raise OSError(f"Could not retain incomplete parse output: {target}")
target.mkdir(parents=True, exist_ok=True)
return target
def write_manifest(workdir: Path, meta: dict[str, Any]) -> None:
"""Stamp the cache dir ready. Written last so a half-written dir never reads
as a cache hit."""
payload = {
**meta,
"created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
}
atomic_write_json(workdir / MANIFEST_FILENAME, payload)
def cleanup_failed(workdir: Path) -> None:
"""Retain unfinished work outside the active signature directory."""
try:
if workdir.is_dir() and not is_ready(workdir):
retained = workdir.with_name(f".{workdir.name}.failed-{uuid4().hex}")
workdir.rename(retained)
logger.warning("Retained incomplete parse output at %s", retained)
except Exception as exc: # pragma: no cover - best-effort
logger.warning("Could not clean up failed parse dir %s: %s", workdir, exc)
def find_content_dir(workdir: Path) -> Path:
"""Locate the dir holding parsed markdown artifacts.
Engines (MinerU especially) may nest output under ``auto/``/``hybrid_auto/``
or a per-document subdir. Mirrors the question extractor's resolver.
"""
candidate_dirs: list[Path] = []
for preferred_name in ("auto", "hybrid_auto"):
preferred = workdir / preferred_name
if preferred.is_dir():
candidate_dirs.append(preferred)
for child in sorted(workdir.iterdir()) if workdir.is_dir() else []:
if child.is_dir() and child not in candidate_dirs:
candidate_dirs.append(child)
nested = {
artifact.parent
for pattern in ("*.md", "*_content_list.json")
for artifact in (workdir.rglob(pattern) if workdir.is_dir() else [])
}
for artifact_dir in sorted(nested):
if artifact_dir not in candidate_dirs:
candidate_dirs.append(artifact_dir)
for candidate in candidate_dirs:
if list(candidate.glob("*.md")):
return candidate
return candidate_dirs[0] if candidate_dirs else workdir
def _absolutize_img_paths(blocks: list[dict], content_dir: Path) -> list[dict]:
"""Anchor relative ``img_path`` entries at ``content_dir``.
Engines (MinerU especially) emit ``img_path`` values like ``images/x.png``
relative to the content-list file. Consumers such as LightRAG resolve
them against their own working directory instead, so the images are never
found (issue #624). The cached JSON stays relative — paths are rewritten
only on load, keeping the cache dir relocatable.
"""
for block in blocks:
if not isinstance(block, dict):
continue
img_path = block.get("img_path")
if not isinstance(img_path, str) or not img_path:
continue
p = Path(img_path)
if p.is_absolute():
continue
if ".." in p.parts:
logger.warning("Skipping traversal img_path in content_list: %s", img_path)
continue
block["img_path"] = str(content_dir / img_path)
return blocks
def load_ir(workdir: Path) -> tuple[str, Optional[list[dict]], Optional[Path]]:
"""Load ``(markdown, blocks, asset_dir)`` from a parsed/cached dir.
``markdown`` is "" if no ``.md`` exists; ``blocks`` is the parsed
``*_content_list.json`` or ``None``; ``asset_dir`` is the ``images/`` dir if
present.
"""
content_dir = find_content_dir(workdir)
markdown = ""
md_files = list(content_dir.glob("*.md"))
if md_files:
markdown = md_files[0].read_text(encoding="utf-8")
blocks: Optional[list[dict]] = None
json_files = list(content_dir.glob("*_content_list.json"))
if json_files:
try:
loaded = json.loads(json_files[0].read_text(encoding="utf-8"))
if isinstance(loaded, list):
blocks = _absolutize_img_paths(loaded, content_dir)
except Exception as exc:
logger.warning("Failed to read content_list %s: %s", json_files[0], exc)
images_dir = content_dir / "images"
asset_dir = images_dir if images_dir.is_dir() else None
return markdown, blocks, asset_dir
__all__ = [
"MANIFEST_FILENAME",
"source_hash_from_path",
"source_dir",
"signature_dir",
"cache_root_for",
"reclaim_sources",
"is_ready",
"lookup",
"reserve",
"write_manifest",
"cleanup_failed",
"find_content_dir",
"load_ir",
]