Skip to content

Commit 3e59b85

Browse files
committed
fix: clear clustering caches after incremental tree persistence
1 parent cbd3bdb commit 3e59b85

4 files changed

Lines changed: 201 additions & 3 deletions

File tree

‎codewiki/src/be/cluster_batch_cache.py‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,18 @@ def clustering_batch_cache_path(docs_dir: str) -> str:
7171
return os.path.join(os.path.abspath(docs_dir), "temp", CLUSTERING_BATCH_CACHE_FILENAME)
7272

7373

74-
def delete_clustering_batch_cache(docs_dir: str) -> None:
75-
"""Remove the on-disk batch cache after clustering finished successfully."""
74+
def delete_clustering_batch_cache(docs_dir: str, *, scopes: list[str] | None = None) -> None:
75+
"""Remove committed scopes and descendants, or the whole cache after a full build."""
7676
if not docs_dir:
7777
return
78-
path = clustering_batch_cache_path(docs_dir)
78+
if scopes is not None:
79+
if scopes:
80+
ClusterBatchCache(docs_dir).delete_scopes(scopes)
81+
return
82+
_delete_cache_file(clustering_batch_cache_path(docs_dir))
83+
84+
85+
def _delete_cache_file(path: str) -> None:
7986
try:
8087
os.remove(path)
8188
except FileNotFoundError:
@@ -178,6 +185,26 @@ def scope_entry_count(self, scope: str) -> int:
178185
return 0
179186
return sum(1 for entry in entries.values() if entry.get("scope") == scope)
180187

188+
def delete_scopes(self, scopes: list[str]) -> None:
189+
"""Keep checkpoints for failed or unrelated subtrees available for retry."""
190+
if not self._enabled or not scopes:
191+
return
192+
selected = set(scopes)
193+
prefixes = tuple(scope + "/" for scope in selected)
194+
entries = self._data["entries"]
195+
remaining = {
196+
key: entry
197+
for key, entry in entries.items()
198+
if entry["scope"] not in selected and not entry["scope"].startswith(prefixes)
199+
}
200+
if len(remaining) == len(entries):
201+
return
202+
self._data["entries"] = remaining
203+
if remaining:
204+
self._save()
205+
else:
206+
_delete_cache_file(self._path)
207+
181208
def lookup(
182209
self, scope: str, batch_index: int, node_ids: list[str], *, request_fingerprint: str
183210
) -> dict[str, Any] | None:

‎codewiki/src/be/updater/orchestrator.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
from typing import Any
1010

1111
from codewiki.src.be.backend import LLMBackend
12+
from codewiki.src.be.cluster_batch_cache import (
13+
clustering_cache_scope,
14+
delete_clustering_batch_cache,
15+
)
1216
from codewiki.src.be.cluster_modules import cluster_modules, get_clustering_input_token_count
1317
from codewiki.src.be.module_scope import get_module_token_count
1418
from codewiki.src.be.dependency_analyzer.models.core import Node
@@ -381,6 +385,10 @@ async def _run(
381385
# Persist the repaired tree so the normal pipeline and the agents see it.
382386
if not self.whole_repo:
383387
file_manager.save_json(new_tree, os.path.join(self.docs_dir, MODULE_TREE_FILENAME))
388+
delete_clustering_batch_cache(
389+
self.docs_dir,
390+
scopes=[clustering_cache_scope(path) for path in rec.reclustered],
391+
)
384392

385393
# ---- Step 5: sequential leaf agents
386394
order = order_active(active, new_tree, new_graph)

‎tests/test_cluster_batch_cache.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from __future__ import annotations
44

55
import json
6+
import asyncio
7+
import importlib
68
from pathlib import Path
79

810
import pytest
@@ -18,6 +20,7 @@
1820
from codewiki.src.be.prompt_template import format_cluster_prompt
1921
from codewiki.src.be.dependency_analyzer.models.core import Node
2022
from codewiki.src.config import Config
23+
from codewiki.src.be.documentation_generator import DocumentationGenerator
2124
from codewiki.src.utils import file_manager
2225

2326

@@ -450,3 +453,86 @@ def test_request_fingerprint_and_component_set_must_match(tmp_path):
450453
assert cache.lookup("__root__", 1, ["b", "a"], request_fingerprint="request-one") == _tree()
451454
assert cache.lookup("__root__", 1, ["a", "b"], request_fingerprint="request-two") is None
452455
assert cache.lookup("__root__", 1, ["a", "c"], request_fingerprint="request-one") is None
456+
457+
458+
def test_scoped_cleanup_preserves_failed_and_unrelated_scopes(tmp_path):
459+
cache = ClusterBatchCache(str(tmp_path))
460+
scopes = ["core", "core/child", "core_extra", "failed", "failed/child", "__root__"]
461+
for scope in scopes:
462+
cache.store(scope, 1, ["a"], _tree(), request_fingerprint="test-request")
463+
delete_clustering_batch_cache(str(tmp_path), scopes=["core"])
464+
resumed = ClusterBatchCache(str(tmp_path))
465+
assert resumed.entry_count() == 4
466+
for scope in scopes:
467+
result = resumed.lookup(scope, 1, ["a"], request_fingerprint="test-request")
468+
assert (result is None) == (scope in {"core", "core/child"})
469+
delete_clustering_batch_cache(str(tmp_path), scopes=scopes[2:])
470+
assert not Path(clustering_batch_cache_path(str(tmp_path))).exists()
471+
472+
473+
def test_empty_scope_cleanup_keeps_checkpoints(tmp_path):
474+
cache = ClusterBatchCache(str(tmp_path))
475+
cache.store("failed", 1, ["a"], _tree(), request_fingerprint="test-request")
476+
delete_clustering_batch_cache(str(tmp_path), scopes=[])
477+
assert ClusterBatchCache(str(tmp_path)).entry_count() == 1
478+
479+
480+
def test_failed_scoped_cleanup_preserves_disk_checkpoints(tmp_path, monkeypatch):
481+
cache = ClusterBatchCache(str(tmp_path))
482+
for scope in ["core", "failed"]:
483+
cache.store(scope, 1, ["a"], _tree(), request_fingerprint="test-request")
484+
485+
def denied(*args):
486+
raise PermissionError("replace denied")
487+
488+
monkeypatch.setattr("codewiki.src.be.cluster_batch_cache.os.replace", denied)
489+
delete_clustering_batch_cache(str(tmp_path), scopes=["core"])
490+
assert ClusterBatchCache(str(tmp_path)).entry_count() == 2
491+
492+
493+
@pytest.mark.parametrize("failed_save", [None, "first_module_tree.json", "module_tree.json"])
494+
def test_full_build_cleanup_follows_both_tree_writes(tmp_path, monkeypatch, failed_save):
495+
ids, components, config = _inputs(tmp_path)
496+
cache = ClusterBatchCache(config.docs_dir)
497+
cache.store("__root__", 1, ["a"], _tree(), request_fingerprint="test-request")
498+
cache_path = Path(clustering_batch_cache_path(config.docs_dir))
499+
tree = {
500+
name: {"components": ids[i : i + 2], "children": {}}
501+
for name, i in [("Alpha", 0), ("Beta", 2), ("Gamma", 4)]
502+
}
503+
generator = DocumentationGenerator(config, backend=object())
504+
monkeypatch.setattr(
505+
generator.graph_builder, "build_dependency_graph", lambda: (components, ids)
506+
)
507+
module = importlib.import_module("codewiki.src.be.documentation_generator")
508+
monkeypatch.setattr(module, "cluster_modules", lambda *args, **kwargs: tree)
509+
510+
async def generate_pages(*args):
511+
for name in ["overview", *tree]:
512+
(Path(config.docs_dir) / (name + ".md")).write_text(
513+
f"# {name}\n\nSmoke documentation.\n"
514+
)
515+
return config.docs_dir
516+
517+
monkeypatch.setattr(generator, "generate_module_documentation", generate_pages)
518+
original_save = file_manager.save_json
519+
writes = []
520+
521+
def save(data, path):
522+
filename = Path(path).name
523+
if filename in {"first_module_tree.json", "module_tree.json"}:
524+
assert cache_path.exists()
525+
writes.append(filename)
526+
if filename == failed_save:
527+
raise PermissionError("tree save failed")
528+
original_save(data, path)
529+
530+
monkeypatch.setattr(file_manager, "save_json", save)
531+
if failed_save:
532+
with pytest.raises(PermissionError, match="tree save failed"):
533+
asyncio.run(generator.run())
534+
assert cache_path.exists()
535+
else:
536+
asyncio.run(generator.run())
537+
assert writes == ["first_module_tree.json", "module_tree.json"]
538+
assert not cache_path.exists()

‎tests/test_updater_orchestrator.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,19 @@
99
from pathlib import Path
1010
from types import SimpleNamespace
1111

12+
import pytest
13+
1214
from updater_toy import OAUTH, USER, graph_r1, graph_r2, node, tracked_r2, tree_r1, write_pages
1315

1416
from codewiki.src.be.agent_tools.str_replace_editor import str_replace_editor
1517
from codewiki.src.be.backend import AgentReply
1618
from codewiki.src.be.documentation_generator import DocumentationGenerator
19+
from codewiki.src.be.cluster_batch_cache import ClusterBatchCache, clustering_batch_cache_path
1720
from codewiki.src.be.updater.graph_store import save_graph
1821
from codewiki.src.be.updater.options import UpdateOptions
1922
from codewiki.src.be.updater.orchestrator import IncrementalUpdater
2023
from codewiki.src.be.updater.record import RECORD_FILENAME
24+
from codewiki.src.utils import file_manager
2125

2226

2327
class FakeBackend:
@@ -383,3 +387,76 @@ def test_ownership_closure_switched_off(tmp_path):
383387
backend = FakeBackend(route_to="api")
384388
docs, rec = _run_untracked(tmp_path / "r1", backend, UpdateOptions.from_rung(1))
385389
assert backend.routing_prompts == [] and rec.ownership == [] and rec.active == []
390+
391+
392+
class BatchedReclusterBackend(FakeBackend):
393+
def __init__(self, *, fail_second=False):
394+
super().__init__()
395+
self.cluster_calls = 0
396+
self.fail_second = fail_second
397+
398+
def complete(self, prompt, *, model=None, system_prompt=None):
399+
if "<POTENTIAL_CORE_COMPONENTS>" not in prompt:
400+
return super().complete(prompt, model=model, system_prompt=system_prompt)
401+
self.cluster_calls += 1
402+
if self.fail_second and self.cluster_calls == 2:
403+
raise RuntimeError("recluster interrupted")
404+
section = prompt.split("<POTENTIAL_CORE_COMPONENTS>")[1].split(
405+
"</POTENTIAL_CORE_COMPONENTS>"
406+
)[0]
407+
ids = [line.strip() for line in section.splitlines() if line.startswith("\t")]
408+
tree = {f"Cluster{self.cluster_calls}": {"components": ids}}
409+
return f"<GROUPED_COMPONENTS>{tree!r}</GROUPED_COMPONENTS>"
410+
411+
412+
def _batched_update_setup(tmp_path):
413+
docs, config, prev = _setup(tmp_path)
414+
config.min_token_per_module = 1
415+
config.max_token_per_module = 1
416+
config.max_leaf_nodes_per_cluster = 2
417+
config.max_tokens = 32768
418+
opts = UpdateOptions(tau_full=2.0, tau_tree=100.0, tau_grow=0.01, use_stale_scan=False)
419+
return docs, config, prev, opts
420+
421+
422+
def test_incremental_recluster_cleans_only_committed_scopes(tmp_path):
423+
docs, config, prev, opts = _batched_update_setup(tmp_path)
424+
cache = ClusterBatchCache(str(docs))
425+
cache.store(
426+
"failed", 1, ["a"], {"A": {"components": ["a"]}}, request_fingerprint="test-request"
427+
)
428+
backend = BatchedReclusterBackend()
429+
rec = _run(docs, config, prev, backend, opts)
430+
assert rec.outcome == "incremental"
431+
assert rec.reclustered == [["core"]]
432+
assert not rec.errors
433+
assert backend.cluster_calls >= 2
434+
resumed = ClusterBatchCache(str(docs))
435+
assert resumed.scope_entry_count("core") == 0
436+
assert resumed.scope_entry_count("failed") == resumed.entry_count() == 1
437+
assert (docs / "module_tree.json").exists()
438+
439+
440+
def test_failed_incremental_recluster_keeps_successful_batch_checkpoints(tmp_path):
441+
docs, config, prev, opts = _batched_update_setup(tmp_path)
442+
rec = _run(docs, config, prev, BatchedReclusterBackend(fail_second=True), opts)
443+
assert rec.outcome == "incremental"
444+
assert any("recluster interrupted" in error for error in rec.errors)
445+
assert rec.reclustered == []
446+
assert ClusterBatchCache(str(docs)).scope_entry_count("core") == 1
447+
448+
449+
def test_incremental_tree_save_failure_retains_checkpoints(tmp_path, monkeypatch):
450+
docs, config, prev, opts = _batched_update_setup(tmp_path)
451+
original_save = file_manager.save_json
452+
453+
def fail_tree_save(data, path):
454+
if Path(path).name == "module_tree.json":
455+
raise PermissionError("tree save failed")
456+
original_save(data, path)
457+
458+
monkeypatch.setattr(file_manager, "save_json", fail_tree_save)
459+
with pytest.raises(PermissionError, match="tree save failed"):
460+
_run(docs, config, prev, BatchedReclusterBackend(), opts)
461+
assert Path(clustering_batch_cache_path(str(docs))).exists()
462+
assert ClusterBatchCache(str(docs)).scope_entry_count("core") >= 2

0 commit comments

Comments
 (0)