|
| 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 | + ) |
0 commit comments