Skip to content

Commit 8c07821

Browse files
authored
Merge pull request #163 from BrahmendraBachi/feat/cache-batch-cluster-response
fix: cache batched LLM clustering responses for resume on failure
2 parents 07425bc + 3e59b85 commit 8c07821

9 files changed

Lines changed: 962 additions & 5 deletions

‎codewiki/cli/adapters/doc_generator.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,9 @@ async def _run_backend_generation(self, backend_config: BackendConfig):
365365
validate_module_file_coverage(module_tree, components)
366366
file_manager.save_json(module_tree, first_module_tree_path)
367367
file_manager.save_json(module_tree, module_tree_path)
368+
from codewiki.src.be.cluster_batch_cache import delete_clustering_batch_cache
369+
370+
delete_clustering_batch_cache(working_dir)
368371

369372
self.job.module_count = len(module_tree)
370373

Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
"""Disk cache for per-batch LLM clustering partial module trees."""
2+
3+
from __future__ import annotations
4+
5+
import hashlib
6+
import json
7+
import logging
8+
import os
9+
import tempfile
10+
from copy import deepcopy
11+
from typing import Any
12+
13+
from codewiki.src.config import CLUSTERING_BATCH_CACHE_FILENAME, Config
14+
from codewiki.src.utils import file_manager
15+
16+
logger = logging.getLogger(__name__)
17+
18+
CACHE_VERSION = 4
19+
20+
21+
def clustering_cache_scope(module_path: list[str]) -> str:
22+
"""Stable scope id for one ``cluster_modules`` invocation."""
23+
if not module_path:
24+
return "__root__"
25+
return "/".join(module_path)
26+
27+
28+
def clustering_request_fingerprint(config: Config, prompt: str) -> str:
29+
"""Identify the rendered request and configured routing without persisting secrets."""
30+
routing = {
31+
name: getattr(config, name, None)
32+
for name in (
33+
"provider",
34+
"cluster_model",
35+
"main_model",
36+
"llm_base_url",
37+
"azure_deployment",
38+
"api_version",
39+
"aws_region",
40+
"google_project",
41+
"google_location",
42+
"max_tokens",
43+
)
44+
}
45+
if routing["provider"] == "google-vertex":
46+
routing["google_project"] = routing["google_project"] or os.getenv(
47+
"GOOGLE_CLOUD_PROJECT", ""
48+
)
49+
routing["google_location"] = (
50+
routing["google_location"] or os.getenv("GOOGLE_CLOUD_LOCATION") or "global"
51+
)
52+
context = {
53+
"repo": os.path.realpath(config.repo_path),
54+
"routing": routing,
55+
"prompt": prompt,
56+
}
57+
canonical = json.dumps(context, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
58+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
59+
60+
61+
def batch_entry_key(
62+
scope: str, batch_index: int, node_ids: list[str], request_fingerprint: str
63+
) -> str:
64+
"""Scope, batch index, component set, and exact request identity."""
65+
canonical = json.dumps(sorted(node_ids), ensure_ascii=False, separators=(",", ":"))
66+
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
67+
return f"{scope}|{batch_index}|{digest}|{request_fingerprint}"
68+
69+
70+
def clustering_batch_cache_path(docs_dir: str) -> str:
71+
return os.path.join(os.path.abspath(docs_dir), "temp", CLUSTERING_BATCH_CACHE_FILENAME)
72+
73+
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."""
76+
if not docs_dir:
77+
return
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:
86+
try:
87+
os.remove(path)
88+
except FileNotFoundError:
89+
return
90+
except OSError as exc:
91+
logger.warning("Could not remove clustering batch cache at %s: %s", path, exc)
92+
return
93+
logger.info("Removed clustering batch cache at %s", path)
94+
95+
96+
def _valid_entry(entry: Any) -> bool:
97+
if not isinstance(entry, dict):
98+
return False
99+
ids = entry.get("node_ids")
100+
partial = entry.get("partial_tree")
101+
return (
102+
isinstance(entry.get("scope"), str)
103+
and isinstance(entry.get("request_fingerprint"), str)
104+
and bool(entry["request_fingerprint"])
105+
and isinstance(entry.get("batch_index"), int)
106+
and not isinstance(entry["batch_index"], bool)
107+
and entry["batch_index"] > 0
108+
and isinstance(ids, list)
109+
and all(isinstance(cid, str) for cid in ids)
110+
and isinstance(partial, dict)
111+
and bool(partial)
112+
and all(
113+
isinstance(name, str)
114+
and isinstance(info, dict)
115+
and isinstance(info.get("path", ""), str)
116+
and isinstance(info.get("components"), list)
117+
and all(isinstance(cid, str) and cid in ids for cid in info["components"])
118+
for name, info in partial.items()
119+
)
120+
)
121+
122+
123+
class ClusterBatchCache:
124+
"""Read/write partial clustering results keyed by scope, batch index, and node set."""
125+
126+
def __init__(self, docs_dir: str, *, enabled: bool = True) -> None:
127+
self._enabled = enabled and bool(docs_dir)
128+
self._path = clustering_batch_cache_path(docs_dir) if self._enabled else ""
129+
self._data: dict[str, Any] = {"version": CACHE_VERSION, "entries": {}}
130+
if self._enabled:
131+
self._load()
132+
133+
def _load(self) -> None:
134+
try:
135+
raw = file_manager.load_json(self._path)
136+
except (OSError, ValueError, UnicodeError) as exc:
137+
logger.warning("Ignoring unreadable clustering batch cache at %s: %s", self._path, exc)
138+
return
139+
if not isinstance(raw, dict) or raw.get("version") != CACHE_VERSION:
140+
return
141+
entries = raw.get("entries")
142+
if isinstance(entries, dict):
143+
entries = {key: entry for key, entry in entries.items() if _valid_entry(entry)}
144+
self._data = {"version": CACHE_VERSION, "entries": entries}
145+
logger.info(
146+
"Loaded clustering batch cache: %d entries from %s",
147+
len(entries),
148+
self._path,
149+
)
150+
151+
def _save(self) -> bool:
152+
"""Publish a complete checkpoint while keeping the previous one on interruption."""
153+
temporary_path = None
154+
try:
155+
directory = os.path.dirname(self._path)
156+
file_manager.ensure_directory(directory)
157+
with tempfile.NamedTemporaryFile(
158+
mode="w", encoding="utf-8", dir=directory, prefix=".clustering-cache-", delete=False
159+
) as stream:
160+
temporary_path = stream.name
161+
json.dump(self._data, stream, indent=4, ensure_ascii=False)
162+
stream.flush()
163+
os.fsync(stream.fileno())
164+
os.replace(temporary_path, self._path)
165+
return True
166+
except OSError as exc:
167+
logger.warning("Could not save clustering batch cache at %s: %s", self._path, exc)
168+
return False
169+
finally:
170+
if temporary_path is not None:
171+
try:
172+
os.remove(temporary_path)
173+
except FileNotFoundError:
174+
pass
175+
except OSError as exc:
176+
logger.warning("Could not remove temporary clustering cache: %s", exc)
177+
178+
def entry_count(self) -> int:
179+
entries = self._data.get("entries")
180+
return len(entries) if isinstance(entries, dict) else 0
181+
182+
def scope_entry_count(self, scope: str) -> int:
183+
entries = self._data.get("entries")
184+
if not isinstance(entries, dict):
185+
return 0
186+
return sum(1 for entry in entries.values() if entry.get("scope") == scope)
187+
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+
208+
def lookup(
209+
self, scope: str, batch_index: int, node_ids: list[str], *, request_fingerprint: str
210+
) -> dict[str, Any] | None:
211+
if not self._enabled:
212+
return None
213+
key = batch_entry_key(scope, batch_index, node_ids, request_fingerprint)
214+
entry = self._data["entries"].get(key)
215+
if not _valid_entry(entry):
216+
return None
217+
stored_ids = entry.get("node_ids")
218+
if (
219+
stored_ids != sorted(node_ids)
220+
or entry["scope"] != scope
221+
or entry["batch_index"] != batch_index
222+
or entry["request_fingerprint"] != request_fingerprint
223+
):
224+
return None
225+
partial = entry.get("partial_tree")
226+
if not isinstance(partial, dict) or not partial:
227+
return None
228+
logger.info(
229+
"Using cached clustering result for scope %s batch %d (%d components).",
230+
scope,
231+
batch_index,
232+
len(node_ids),
233+
)
234+
return deepcopy(partial)
235+
236+
def store(
237+
self,
238+
scope: str,
239+
batch_index: int,
240+
node_ids: list[str],
241+
partial_tree: dict[str, Any],
242+
*,
243+
request_fingerprint: str,
244+
) -> None:
245+
if not self._enabled or not partial_tree:
246+
return
247+
key = batch_entry_key(scope, batch_index, node_ids, request_fingerprint)
248+
entry = {
249+
"scope": scope,
250+
"batch_index": batch_index,
251+
"node_ids": sorted(node_ids),
252+
"request_fingerprint": request_fingerprint,
253+
"partial_tree": deepcopy(partial_tree),
254+
}
255+
if not _valid_entry(entry):
256+
return
257+
self._data["entries"][key] = entry
258+
if not self._save():
259+
return
260+
module_names = list(partial_tree.keys())
261+
logger.info(
262+
"Stored clustering batch cache for scope %s batch %d (%d components, %d modules: %s); "
263+
"%d total entries at %s",
264+
scope,
265+
batch_index,
266+
len(node_ids),
267+
len(module_names),
268+
", ".join(module_names[:5]) + ("..." if len(module_names) > 5 else ""),
269+
self.entry_count(),
270+
self._path,
271+
)

‎codewiki/src/be/cluster_modules.py‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
from collections.abc import Callable
66
from typing import Any
77

8+
from codewiki.src.be.cluster_batch_cache import (
9+
ClusterBatchCache,
10+
clustering_cache_scope,
11+
clustering_request_fingerprint,
12+
)
813
from codewiki.src.be.dependency_analyzer.models.core import Node
914
from codewiki.src.be.llm_services import call_llm
1015
from codewiki.src.be.module_naming import resolve_unique_name, sanitize_module_name
@@ -170,16 +175,19 @@ def _cluster_via_llm(
170175
current_module_name: str | None,
171176
module_label: str,
172177
completer: Completer | None,
178+
*,
179+
prompt: str | None = None,
173180
) -> dict[str, Any]:
174181
"""Run one clustering LLM call over these nodes.
175182
176183
Returns {} for any empty, malformed, or non-dict response instead of
177184
raising, so callers can fall back gracefully.
178185
"""
179-
potential_core_components, _ = format_potential_core_components(leaf_nodes, components)
180-
prompt = format_cluster_prompt(
181-
potential_core_components, current_module_tree, current_module_name
182-
)
186+
if prompt is None:
187+
potential_core_components, _ = format_potential_core_components(leaf_nodes, components)
188+
prompt = format_cluster_prompt(
189+
potential_core_components, current_module_tree, current_module_name
190+
)
183191
if completer is not None:
184192
response = completer(prompt)
185193
else:
@@ -428,9 +436,37 @@ def cluster_modules(
428436
module_label,
429437
len(batches),
430438
)
439+
batch_cache: ClusterBatchCache | None = None
440+
cache_scope = clustering_cache_scope(current_module_path)
441+
if getattr(config, "cluster_batch_cache", True) and config.docs_dir:
442+
batch_cache = ClusterBatchCache(config.docs_dir)
431443
module_tree = {}
444+
cache_hits = 0
445+
if batch_cache is not None:
446+
logger.info(
447+
"Clustering batch cache for %r: %d on-disk entries (%d for this scope), %d batches to run.",
448+
cache_scope,
449+
batch_cache.entry_count(),
450+
batch_cache.scope_entry_count(cache_scope),
451+
len(batches),
452+
)
432453
for i, batch in enumerate(batches, 1):
433454
batch_label = f"{module_label} (batch {i}/{len(batches)})"
455+
potential_core_components, _ = format_potential_core_components(batch, components)
456+
prompt = format_cluster_prompt(
457+
potential_core_components, current_module_tree, current_module_name
458+
)
459+
request_fingerprint = (
460+
clustering_request_fingerprint(config, prompt) if batch_cache is not None else ""
461+
)
462+
if batch_cache is not None:
463+
cached = batch_cache.lookup(
464+
cache_scope, i, batch, request_fingerprint=request_fingerprint
465+
)
466+
if cached is not None:
467+
cache_hits += 1
468+
_merge_module_trees(module_tree, cached)
469+
continue
434470
# Each batch gets the *unmodified* current_module_tree: passing the
435471
# accumulating merge would flip format_cluster_prompt into its
436472
# module-level variant mid-partition.
@@ -442,7 +478,14 @@ def cluster_modules(
442478
current_module_name,
443479
batch_label,
444480
completer,
481+
prompt=prompt,
445482
)
483+
# Only validated LLM responses are resumable. A structural fallback
484+
# keeps this pass usable but must be retried after a later failure.
485+
if batch_cache is not None and partial:
486+
batch_cache.store(
487+
cache_scope, i, batch, partial, request_fingerprint=request_fingerprint
488+
)
446489
if not partial:
447490
name = _batch_fallback_name(batch, components, module_tree)
448491
partial = {
@@ -460,6 +503,14 @@ def cluster_modules(
460503
name,
461504
)
462505
_merge_module_trees(module_tree, partial)
506+
if batch_cache is not None:
507+
logger.info(
508+
"Clustering batch cache for %r: %d/%d batches from cache, %d LLM batch call(s) this pass.",
509+
cache_scope,
510+
cache_hits,
511+
len(batches),
512+
len(batches) - cache_hits,
513+
)
463514

464515
module_tree = normalize_module_partition(module_tree, candidates, components)
465516
if len(module_tree) <= 1:

‎codewiki/src/be/documentation_generator.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,9 @@ async def run(self) -> None:
545545
validate_module_file_coverage(module_tree, components)
546546
file_manager.save_json(module_tree, first_module_tree_path)
547547
file_manager.save_json(module_tree, module_tree_path)
548+
from codewiki.src.be.cluster_batch_cache import delete_clustering_batch_cache
549+
550+
delete_clustering_batch_cache(working_dir)
548551

549552
if len(module_tree) == 0:
550553
logger.info(

0 commit comments

Comments
 (0)