Skip to content

Commit cbd3bdb

Browse files
committed
fix: fingerprint clustering requests for cache reuse
1 parent 6275c13 commit cbd3bdb

3 files changed

Lines changed: 245 additions & 39 deletions

File tree

‎codewiki/src/be/cluster_batch_cache.py‎

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
from copy import deepcopy
1111
from typing import Any
1212

13-
from codewiki.src.config import CLUSTERING_BATCH_CACHE_FILENAME
13+
from codewiki.src.config import CLUSTERING_BATCH_CACHE_FILENAME, Config
1414
from codewiki.src.utils import file_manager
1515

1616
logger = logging.getLogger(__name__)
1717

18-
CACHE_VERSION = 3
18+
CACHE_VERSION = 4
1919

2020

2121
def clustering_cache_scope(module_path: list[str]) -> str:
@@ -25,11 +25,46 @@ def clustering_cache_scope(module_path: list[str]) -> str:
2525
return "/".join(module_path)
2626

2727

28-
def batch_entry_key(scope: str, batch_index: int, node_ids: list[str]) -> str:
29-
"""Scope, 1-based batch index, and a fingerprint of the batch's component IDs."""
30-
canonical = "\n".join(sorted(node_ids))
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=(",", ":"))
3166
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]
32-
return f"{scope}|{batch_index}|{digest}"
67+
return f"{scope}|{batch_index}|{digest}|{request_fingerprint}"
3368

3469

3570
def clustering_batch_cache_path(docs_dir: str) -> str:
@@ -58,6 +93,8 @@ def _valid_entry(entry: Any) -> bool:
5893
partial = entry.get("partial_tree")
5994
return (
6095
isinstance(entry.get("scope"), str)
96+
and isinstance(entry.get("request_fingerprint"), str)
97+
and bool(entry["request_fingerprint"])
6198
and isinstance(entry.get("batch_index"), int)
6299
and not isinstance(entry["batch_index"], bool)
63100
and entry["batch_index"] > 0
@@ -141,15 +178,22 @@ def scope_entry_count(self, scope: str) -> int:
141178
return 0
142179
return sum(1 for entry in entries.values() if entry.get("scope") == scope)
143180

144-
def lookup(self, scope: str, batch_index: int, node_ids: list[str]) -> dict[str, Any] | None:
181+
def lookup(
182+
self, scope: str, batch_index: int, node_ids: list[str], *, request_fingerprint: str
183+
) -> dict[str, Any] | None:
145184
if not self._enabled:
146185
return None
147-
key = batch_entry_key(scope, batch_index, node_ids)
186+
key = batch_entry_key(scope, batch_index, node_ids, request_fingerprint)
148187
entry = self._data["entries"].get(key)
149188
if not _valid_entry(entry):
150189
return None
151190
stored_ids = entry.get("node_ids")
152-
if stored_ids != sorted(node_ids):
191+
if (
192+
stored_ids != sorted(node_ids)
193+
or entry["scope"] != scope
194+
or entry["batch_index"] != batch_index
195+
or entry["request_fingerprint"] != request_fingerprint
196+
):
153197
return None
154198
partial = entry.get("partial_tree")
155199
if not isinstance(partial, dict) or not partial:
@@ -168,14 +212,17 @@ def store(
168212
batch_index: int,
169213
node_ids: list[str],
170214
partial_tree: dict[str, Any],
215+
*,
216+
request_fingerprint: str,
171217
) -> None:
172218
if not self._enabled or not partial_tree:
173219
return
174-
key = batch_entry_key(scope, batch_index, node_ids)
220+
key = batch_entry_key(scope, batch_index, node_ids, request_fingerprint)
175221
entry = {
176222
"scope": scope,
177223
"batch_index": batch_index,
178224
"node_ids": sorted(node_ids),
225+
"request_fingerprint": request_fingerprint,
179226
"partial_tree": deepcopy(partial_tree),
180227
}
181228
if not _valid_entry(entry):

‎codewiki/src/be/cluster_modules.py‎

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

8-
from codewiki.src.be.cluster_batch_cache import ClusterBatchCache, clustering_cache_scope
8+
from codewiki.src.be.cluster_batch_cache import (
9+
ClusterBatchCache,
10+
clustering_cache_scope,
11+
clustering_request_fingerprint,
12+
)
913
from codewiki.src.be.dependency_analyzer.models.core import Node
1014
from codewiki.src.be.llm_services import call_llm
1115
from codewiki.src.be.module_naming import resolve_unique_name, sanitize_module_name
@@ -171,16 +175,19 @@ def _cluster_via_llm(
171175
current_module_name: str | None,
172176
module_label: str,
173177
completer: Completer | None,
178+
*,
179+
prompt: str | None = None,
174180
) -> dict[str, Any]:
175181
"""Run one clustering LLM call over these nodes.
176182
177183
Returns {} for any empty, malformed, or non-dict response instead of
178184
raising, so callers can fall back gracefully.
179185
"""
180-
potential_core_components, _ = format_potential_core_components(leaf_nodes, components)
181-
prompt = format_cluster_prompt(
182-
potential_core_components, current_module_tree, current_module_name
183-
)
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+
)
184191
if completer is not None:
185192
response = completer(prompt)
186193
else:
@@ -445,8 +452,17 @@ def cluster_modules(
445452
)
446453
for i, batch in enumerate(batches, 1):
447454
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+
)
448462
if batch_cache is not None:
449-
cached = batch_cache.lookup(cache_scope, i, batch)
463+
cached = batch_cache.lookup(
464+
cache_scope, i, batch, request_fingerprint=request_fingerprint
465+
)
450466
if cached is not None:
451467
cache_hits += 1
452468
_merge_module_trees(module_tree, cached)
@@ -462,11 +478,14 @@ def cluster_modules(
462478
current_module_name,
463479
batch_label,
464480
completer,
481+
prompt=prompt,
465482
)
466483
# Only validated LLM responses are resumable. A structural fallback
467484
# keeps this pass usable but must be retried after a later failure.
468485
if batch_cache is not None and partial:
469-
batch_cache.store(cache_scope, i, batch, partial)
486+
batch_cache.store(
487+
cache_scope, i, batch, partial, request_fingerprint=request_fingerprint
488+
)
470489
if not partial:
471490
name = _batch_fallback_name(batch, components, module_tree)
472491
partial = {

0 commit comments

Comments
 (0)