Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

perf: make indexing & incremental update scale with change size (#368)

Raghav Chamadiyad0f2315c87ea
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.py
index d0be19e40..7fb489816 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py
@@ -8,6 +8,7 @@ back to a live in-process analysis when run outside an indexed repo.
from __future__ import annotations
import json
+from pathlib import Path
import click
from rich.table import Table
@@ -215,6 +216,7 @@ def health_command(
git_meta_map=git_meta_map,
parsed_files=parsed_files,
coverage_map=coverage_map,
+ duplication_cache_dir=Path(repo_path) / ".repowise",
)
# Load any .repowise/health-rules.json the user keeps in the repo.
from repowise.core.analysis.health.config import HealthConfig
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index ed1b58ca9..66f6ed916 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -425,6 +425,16 @@ def _rebuild_graph_and_git(
except Exception as exc:
console.print(f"[yellow]Git re-index skipped: {exc}[/yellow]")
+ # Pre-compute centrality/community metrics with the init path's fan-out
+ # parallelism. Without this, persist_graph_nodes computes the same
+ # metrics lazily one-by-one. Runs after the co-change edge refresh so
+ # the cached subgraphs reflect the final structure. Best-effort: every
+ # metric still falls back to lazy computation.
+ try:
+ run_async(graph_builder.compute_metrics_parallel())
+ except Exception as exc:
+ console.print(f"[yellow]Metric pre-computation skipped: {exc}[/yellow]")
+
return parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map
@@ -453,6 +463,7 @@ def _run_partial_analysis(
graph_builder.graph(),
git_meta_map=git_meta_map,
parsed_files=parsed_files,
+ duplication_cache_dir=Path(repo_path) / ".repowise",
)
_health_changed = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}
if _health_changed:
@@ -675,6 +686,13 @@ def _run_full_health_rescore(
repo_path, exclude_patterns
)
+ # Fan-out metric precompute (mirrors _rebuild_graph_and_git) — the
+ # rescore persists graph nodes too, which reads every metric.
+ try:
+ run_async(graph_builder.compute_metrics_parallel())
+ except Exception:
+ pass # metrics fall back to lazy computation
+
exclude_spec = (
pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
if exclude_patterns
@@ -737,6 +755,7 @@ def _run_full_health_rescore(
graph_builder.graph(),
git_meta_map=git_meta_map,
parsed_files=parsed_files,
+ duplication_cache_dir=Path(repo_path) / ".repowise",
)
hcfg = HealthConfig.load(repo_path)
analyzer_config = (
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index de9bb0141..e87adeb0b 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -12,7 +12,10 @@ this package.
from __future__ import annotations
import fnmatch
+import os
+import re
from datetime import UTC, datetime
+from functools import lru_cache
from pathlib import Path
from typing import Any
@@ -321,6 +324,20 @@ def _is_synthetic_node(node: str) -> bool:
return node.startswith("external:") or node.startswith("framework:")
+@lru_cache(maxsize=8)
+def _never_flag_regex(patterns: tuple[str, ...]) -> re.Pattern[str]:
+ """Compile *patterns* into one alternation regex equivalent to fnmatch.
+
+ ``fnmatch.fnmatch(path, p)`` normcases both sides and matches the
+ translated glob; doing that per (node x pattern) costs ~540 fnmatch
+ calls per node and dominated the whole dead-code pass (measured: 50s of
+ a 51s analyze() on a 13k-node graph, mostly Windows ``normcase``).
+ One pre-normcased alternation keeps the exact same match semantics at
+ one regex match per node.
+ """
+ return re.compile("|".join(fnmatch.translate(os.path.normcase(p)) for p in patterns))
+
+
class DeadCodeAnalyzer:
"""Detects unreachable files, unused exports, unused internals, and
zombie packages using the dependency graph and git metadata.
@@ -1138,9 +1155,8 @@ class DeadCodeAnalyzer:
"""Return True if path should never be flagged as dead."""
if path in whitelist:
return True
- for pattern in _NEVER_FLAG_PATTERNS:
- if fnmatch.fnmatch(path, pattern):
- return True
+ if _never_flag_regex(_NEVER_FLAG_PATTERNS).match(os.path.normcase(path)):
+ return True
# Workspace-driven never-flag — set by language warmups that read
# the build manifest (Gradle non-``main`` source sets, Cargo
# ``[[example]]`` / ``[[bench]]`` targets, …). Lets each language
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
index 7396669a3..dfaaedb21 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
@@ -34,7 +34,7 @@ from repowise.core.cancellation import check_cancelled
from .limits import DuplicationDiagnostics, DuplicationLimits, looks_minified
from .rabin_karp import WindowHash, index_by_hash, rolling_hashes
-from .tokenizer import Token, tokenize_file
+from .tokenizer import tokenize_file
log = structlog.get_logger(__name__)
@@ -132,19 +132,21 @@ def _co_change_score(
def _tokens_equal(
- a_tokens: list[Token],
- b_tokens: list[Token],
+ a_kinds: list[str],
+ b_kinds: list[str],
a_start: int,
b_start: int,
window: int,
) -> bool:
- """Verify hash-collision by comparing token ``kind`` sequences."""
- if a_start + window > len(a_tokens) or b_start + window > len(b_tokens):
+ """Verify hash-collision by comparing token ``kind`` sequences.
+
+ Operates on the per-file kind list (all the verifier ever compared of
+ the full ``Token`` records) so cached token streams round-trip without
+ rebuilding Token objects.
+ """
+ if a_start + window > len(a_kinds) or b_start + window > len(b_kinds):
return False
- for offset in range(window):
- if a_tokens[a_start + offset].kind != b_tokens[b_start + offset].kind:
- return False
- return True
+ return a_kinds[a_start : a_start + window] == b_kinds[b_start : b_start + window]
def _merge_adjacent_pairs(raw: list[ClonePair]) -> list[ClonePair]:
@@ -195,6 +197,7 @@ def detect_clones(
window_tokens: int = DEFAULT_WINDOW_TOKENS,
min_lines: int = DEFAULT_MIN_LINES,
limits: DuplicationLimits | None = None,
+ cache_dir: Path | None = None,
) -> DuplicationReport:
"""Run the duplication pipeline over the supplied parsed files.
@@ -216,14 +219,28 @@ def detect_clones(
lim = limits or DuplicationLimits()
diag = DuplicationDiagnostics()
- per_file_tokens, per_file_nloc, all_windows = _collect_windows(
- parsed_files, window_tokens, lim, diag
+ cache = None
+ if cache_dir is not None:
+ from .token_cache import DuplicationTokenCache
+
+ cache = DuplicationTokenCache(cache_dir, window_tokens)
+ cache.load()
+
+ per_file_kinds, per_file_nloc, all_windows = _collect_windows(
+ parsed_files, window_tokens, lim, diag, cache
)
+ if cache is not None:
+ cache.save()
+ log.debug(
+ "duplication_token_cache",
+ hits=cache.hits,
+ misses=cache.misses,
+ )
if not all_windows:
return DuplicationReport(diagnostics=diag.as_log_fields())
bucket = index_by_hash(all_windows)
- raw_pairs = _pairs_from_buckets(bucket, per_file_tokens, window_tokens, lim, diag)
+ raw_pairs = _pairs_from_buckets(bucket, per_file_kinds, window_tokens, lim, diag)
final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)
pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)
@@ -246,15 +263,23 @@ def _collect_windows(
window_tokens: int,
limits: DuplicationLimits,
diag: DuplicationDiagnostics,
-) -> tuple[dict[str, list[Token]], dict[str, int], list[WindowHash]]:
+ cache: Any | None = None,
+) -> tuple[dict[str, list[str]], dict[str, int], list[WindowHash]]:
"""Tokenize each file once and emit its rolling-hash windows.
Files are dropped (and counted in *diag*) when they are unreadable,
minified/generated, shorter than one window, or exceed the per-file
token cap. Collection stops cleanly once the repo-wide window budget
is reached so peak memory stays bounded.
+
+ When a :class:`~.token_cache.DuplicationTokenCache` is supplied,
+ unchanged files (by content hash) skip the tokenize + rolling-hash
+ work and replay their cached kind sequence and window tuples; every
+ gate above still re-evaluates live against the cached lengths.
"""
- per_file_tokens: dict[str, list[Token]] = {}
+ import hashlib
+
+ per_file_kinds: dict[str, list[str]] = {}
per_file_nloc: dict[str, int] = {}
all_windows: list[WindowHash] = []
@@ -272,25 +297,57 @@ def _collect_windows(
diag.skipped_minified += 1
continue
- toks = tokenize_file(language, source)
- if len(toks) < window_tokens:
+ cached = None
+ content_hash = ""
+ if cache is not None:
+ content_hash = hashlib.sha256(source).hexdigest()
+ cached = cache.get(content_hash)
+
+ if cached is not None:
+ kinds, nloc, window_tuples = cached
+ windows = [
+ WindowHash(
+ file_path=path,
+ hash_value=h,
+ start_index=si,
+ start_line=sl,
+ end_line=el,
+ )
+ for h, si, sl, el in window_tuples
+ ]
+ else:
+ toks = tokenize_file(language, source)
+ if len(toks) > limits.max_tokens_per_file:
+ diag.skipped_token_cap += 1
+ continue
+ kinds = [t.kind for t in toks]
+ nloc = _nloc(source)
+ windows = rolling_hashes(path, toks, window_tokens)
+ if cache is not None:
+ cache.put(
+ content_hash,
+ kinds,
+ nloc,
+ [(w.hash_value, w.start_index, w.start_line, w.end_line) for w in windows],
+ )
+
+ if len(kinds) < window_tokens:
continue
- if len(toks) > limits.max_tokens_per_file:
+ if len(kinds) > limits.max_tokens_per_file:
diag.skipped_token_cap += 1
continue
- windows = rolling_hashes(path, toks, window_tokens)
if len(all_windows) + len(windows) > limits.max_total_windows:
diag.window_budget_hit = True
break
- per_file_tokens[path] = toks
- per_file_nloc[path] = _nloc(source)
+ per_file_kinds[path] = kinds
+ per_file_nloc[path] = nloc
all_windows.extend(windows)
diag.files_tokenized += 1
diag.total_windows = len(all_windows)
- return per_file_tokens, per_file_nloc, all_windows
+ return per_file_kinds, per_file_nloc, all_windows
# ---------------------------------------------------------------------------
@@ -300,7 +357,7 @@ def _collect_windows(
def _pairs_from_buckets(
bucket: dict[int, list[WindowHash]],
- per_file_tokens: dict[str, list[Token]],
+ per_file_kinds: dict[str, list[str]],
window_tokens: int,
limits: DuplicationLimits,
diag: DuplicationDiagnostics,
@@ -329,14 +386,14 @@ def _pairs_from_buckets(
if deadline is not None and (i & 0x3FF) == 0 and time.monotonic() > deadline:
diag.timed_out = True
break
- _verify_bucket(windows, per_file_tokens, window_tokens, seen, raw_pairs)
+ _verify_bucket(windows, per_file_kinds, window_tokens, seen, raw_pairs)
return raw_pairs
def _verify_bucket(
windows: list[WindowHash],
- per_file_tokens: dict[str, list[Token]],
+ per_file_kinds: dict[str, list[str]],
window_tokens: int,
seen: set[tuple[str, int, str, int]],
out: list[ClonePair],
@@ -357,8 +414,8 @@ def _verify_bucket(
continue
seen.add(key)
if not _tokens_equal(
- per_file_tokens[a.file_path],
- per_file_tokens[b.file_path],
+ per_file_kinds[a.file_path],
+ per_file_kinds[b.file_path],
a.start_index,
b.start_index,
window_tokens,
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py
new file mode 100644
index 000000000..ec2a92264
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py
@@ -0,0 +1,115 @@
+"""Content-hash keyed cache for duplication token streams + windows.
+
+Tokenizing every file (a full tree-sitter re-parse plus a pure-Python
+leaf walk) and re-rolling 1M+ window hashes dominates the duplication
+pass — and an incremental ``repowise update`` re-pays it for the whole
+repo when a single file changed. Both outputs are pure functions of the
+file *bytes* (given fixed window size and pinned hash constants), so they
+cache safely by content hash.
+
+Cached per file: the normalized token-kind sequence (all the verifier
+ever compares), the non-blank line count, and the rolling-hash windows
+as plain tuples (``WindowHash`` is rebuilt with the file's *current*
+path, which makes hits rename-proof). The minified/token-cap/window-
+budget gates in the detector stay live — they re-evaluate against the
+cached lengths, so config changes apply to cached entries too.
+
+Best-effort by design: any load/save error degrades to a full
+re-tokenize. The cache file is rewritten with only the current file set
+each run, so deleted files age out naturally.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import pickle
+import sys
+import tempfile
+from pathlib import Path
+
+import structlog
+
+log = structlog.get_logger(__name__)
+
+_CACHE_VERSION = 1
+_CACHE_FILENAME = "duplication_cache.pkl"
+
+
+class DuplicationTokenCache:
+ """Pickle-backed ``content_hash -> (kinds, nloc, windows)`` store."""
+
+ def __init__(self, cache_dir: Path, window_tokens: int) -> None:
+ self._path = Path(cache_dir) / _CACHE_FILENAME
+ self._window_tokens = window_tokens
+ self._entries: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}
+ self._fresh: dict[str, tuple[list[str], int, list[tuple[int, int, int, int]]]] = {}
+ self.hits = 0
+ self.misses = 0
+
+ # -- lifecycle ---------------------------------------------------------
+
+ def load(self) -> None:
+ try:
+ with self._path.open("rb") as fh:
+ payload = pickle.load(fh)
+ if (
+ payload.get("version") != _CACHE_VERSION
+ or payload.get("window_tokens") != self._window_tokens
+ ):
+ return
+ self._entries = payload.get("files", {})
+ except FileNotFoundError:
+ return
+ except Exception as exc: # corrupt / unreadable cache -> full tokenize
+ log.debug("duplication_cache_load_failed", error=str(exc))
+
+ def save(self) -> None:
+ """Atomically persist the entries used or created this run."""
+ try:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "version": _CACHE_VERSION,
+ "window_tokens": self._window_tokens,
+ "files": self._fresh,
+ }
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd, "wb") as fh:
+ pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
+ os.replace(tmp_name, self._path)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+ except Exception as exc:
+ log.debug("duplication_cache_save_failed", error=str(exc))
+
+ # -- access ------------------------------------------------------------
+
+ def get(
+ self, content_hash: str
+ ) -> tuple[list[str], int, list[tuple[int, int, int, int]]] | None:
+ entry = self._entries.get(content_hash)
+ if entry is None:
+ self.misses += 1
+ return None
+ self.hits += 1
+ # Entries touched this run survive into the rewritten cache file.
+ self._fresh[content_hash] = entry
+ return entry
+
+ def put(
+ self,
+ content_hash: str,
+ kinds: list[str],
+ nloc: int,
+ windows: list[tuple[int, int, int, int]],
+ ) -> None:
+ # Interned kinds keep the pickle compact (each distinct kind is
+ # memoized once by identity) and make later equality checks cheap.
+ entry = ([sys.intern(k) for k in kinds], nloc, windows)
+ self._entries[content_hash] = entry
+ self._fresh[content_hash] = entry
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index d0e27ef5c..24ab7d593 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -256,6 +256,7 @@ class HealthAnalyzer:
parsed_files: list[Any] | None = None,
coverage_map: dict[str, dict[str, Any]] | None = None,
module_map: dict[str, str] | None = None,
+ duplication_cache_dir: Any | None = None,
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
@@ -271,6 +272,10 @@ class HealthAnalyzer:
# module rollups still group sensibly on small repos that didn't
# produce community labels.
self.module_map = module_map or {}
+ # Directory for the duplication token/window cache (typically the
+ # repo's ``.repowise``). None disables caching — the duplication
+ # pass then re-tokenizes everything, exactly as before.
+ self.duplication_cache_dir = duplication_cache_dir
def analyze(
self,
@@ -309,7 +314,11 @@ class HealthAnalyzer:
dup_report = DuplicationReport()
else:
try:
- dup_report = detect_clones(self.parsed_files, self.git_meta_map)
+ dup_report = detect_clones(
+ self.parsed_files,
+ self.git_meta_map,
+ cache_dir=self.duplication_cache_dir,
+ )
_log_duplication_diagnostics(dup_report)
except Exception as exc:
log.debug("health_duplication_failed", error=str(exc))
@@ -418,7 +427,10 @@ class HealthAnalyzer:
else:
try:
dup_report = await asyncio.to_thread(
- detect_clones, self.parsed_files, self.git_meta_map
+ detect_clones,
+ self.parsed_files,
+ self.git_meta_map,
+ cache_dir=self.duplication_cache_dir,
)
_log_duplication_diagnostics(dup_report)
except Exception as exc:
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 1911fb078..75192e735 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -90,8 +90,14 @@ class ContextAssembler:
page_summaries: dict[str, str] | None = None,
decision_records: list[dict] | None = None,
kg_context: Any | None = None,
+ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,
) -> FilePageContext:
- """Assemble context for the file_page template."""
+ """Assemble context for the file_page template.
+
+ *symbol_index* (see :func:`build_symbol_index`) makes the call-graph /
+ heritage extraction a dict lookup instead of a full graph-node scan —
+ pass it when assembling context for many files against one graph.
+ """
path = parsed.file_info.path
budget = self._config.token_budget
used = 0
@@ -158,8 +164,8 @@ class ContextAssembler:
depth = self._select_generation_depth(path, git_meta, pagerank.get(path, 0.0))
# Graph intelligence: call graph, heritage, community metadata
- call_graph_entries = extract_call_graph(path, graph)
- heritage_entries = extract_heritage(path, graph)
+ call_graph_entries = extract_call_graph(path, graph, symbol_index)
+ heritage_entries = extract_heritage(path, graph, symbol_index)
community_label, community_cohesion = extract_community_meta(path, graph)
return FilePageContext(
diff --git a/packages/core/src/repowise/core/generation/context/graph_intelligence.py b/packages/core/src/repowise/core/generation/context/graph_intelligence.py
index a6fa30481..a9e69af52 100644
--- a/packages/core/src/repowise/core/generation/context/graph_intelligence.py
+++ b/packages/core/src/repowise/core/generation/context/graph_intelligence.py
@@ -9,15 +9,50 @@ from __future__ import annotations
from typing import Any
-def extract_call_graph(file_path: str, graph: Any) -> list[dict]:
- """Extract symbol-level call edges for symbols defined in this file."""
- entries: list[dict] = []
+def build_symbol_index(graph: Any) -> dict[str, list[tuple[Any, dict]]]:
+ """Bucket symbol nodes by ``file_path`` in one pass over the graph.
+
+ ``extract_call_graph`` / ``extract_heritage`` historically scanned every
+ graph node per file — O(files x nodes) across a generation run. Callers
+ that assemble context for many files build this index once and pass it
+ in; per-file extraction becomes a dict lookup. Buckets preserve the
+ graph's node iteration order, so results are byte-identical to the scan.
+ """
+ index: dict[str, list[tuple[Any, dict]]] = {}
try:
for node, data in graph.nodes(data=True):
if data.get("node_type") != "symbol":
continue
- if data.get("file_path") != file_path:
- continue
+ fp = data.get("file_path")
+ if fp:
+ index.setdefault(fp, []).append((node, data))
+ except Exception:
+ return {}
+ return index
+
+
+def _file_symbol_nodes(
+ file_path: str, graph: Any, symbol_index: dict[str, list[tuple[Any, dict]]] | None
+) -> Any:
+ """This file's symbol nodes — from the index when supplied, else a scan."""
+ if symbol_index is not None:
+ return symbol_index.get(file_path, [])
+ return (
+ (node, data)
+ for node, data in graph.nodes(data=True)
+ if data.get("node_type") == "symbol" and data.get("file_path") == file_path
+ )
+
+
+def extract_call_graph(
+ file_path: str,
+ graph: Any,
+ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,
+) -> list[dict]:
+ """Extract symbol-level call edges for symbols defined in this file."""
+ entries: list[dict] = []
+ try:
+ for node, data in _file_symbol_nodes(file_path, graph, symbol_index):
# Outgoing calls from this symbol
for _, target, edata in graph.out_edges(node, data=True):
if edata.get("edge_type") == "calls":
@@ -56,15 +91,15 @@ def extract_call_graph(file_path: str, graph: Any) -> list[dict]:
return unique[:15]
-def extract_heritage(file_path: str, graph: Any) -> list[dict]:
+def extract_heritage(
+ file_path: str,
+ graph: Any,
+ symbol_index: dict[str, list[tuple[Any, dict]]] | None = None,
+) -> list[dict]:
"""Extract extends/implements edges for symbols in this file."""
entries: list[dict] = []
try:
- for node, data in graph.nodes(data=True):
- if data.get("node_type") != "symbol":
- continue
- if data.get("file_path") != file_path:
- continue
+ for node, data in _file_symbol_nodes(file_path, graph, symbol_index):
for _, target, edata in graph.out_edges(node, data=True):
etype = edata.get("edge_type", "")
if etype in ("extends", "implements"):
diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.py
index 67458fb4e..8a4f46f6e 100644
--- a/packages/core/src/repowise/core/generation/page_generator/core.py
+++ b/packages/core/src/repowise/core/generation/page_generator/core.py
@@ -208,15 +208,26 @@ class PageGenerator(PerTypeGenerationMixin):
self,
parsed: ParsedFile,
ctx: FilePageContext,
+ rag_prefetched: bool = False,
) -> GeneratedPage:
- """Generate a file_page from a pre-assembled context (avoids double-assembly)."""
+ """Generate a file_page from a pre-assembled context (avoids double-assembly).
+
+ *rag_prefetched* is set by the level-2 builder when RAG context was
+ already resolved for the whole level in one batched search (see
+ ``levels._prefetch_rag_context``) — the per-page search below would
+ re-fetch identical results inside the LLM semaphore, so it is skipped.
+ """
# RAG context: query vector store for related pages (B1).
# Gated by two short-circuits so we don't burn an embedder
# round-trip on every page when the result wouldn't help:
# 1. ``enable_rag_context`` config flag (off → fully skip).
# 2. ``rag_min_store_size`` — early pages run against an empty
# or near-empty store and the search returns nothing useful.
- if self._vector_store is not None and getattr(self._config, "enable_rag_context", True):
+ if (
+ not rag_prefetched
+ and self._vector_store is not None
+ and getattr(self._config, "enable_rag_context", True)
+ ):
min_store_size = max(0, int(getattr(self._config, "rag_min_store_size", 10) or 0))
store_ok = True
if min_store_size > 0:
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index ff0880693..80ea7ce83 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -130,6 +130,59 @@ async def _prefetch_dependency_summaries(run: _GenerationRun) -> None:
log.debug("rag.batch_dep_prefetch_failed", error=str(exc))
+async def _prefetch_rag_context(
+ run: _GenerationRun, items: list[tuple[Any, FilePageContext]]
+) -> bool:
+ """Resolve RAG context for all tier-1 file pages in one batched search.
+
+ Replicates the per-page gating in ``_generate_file_page_from_ctx`` (flag,
+ store size, query-term derivation, self-exclusion) but runs BEFORE the
+ level starts, outside the LLM semaphore, with all queries embedded in a
+ single embedder call via :meth:`VectorStore.search_many`. The store is
+ static for the whole level (pages embed in one batch at level end), so
+ prefetched results are identical to what each page would have fetched.
+
+ Returns True when the per-page search can be skipped (results resolved,
+ or the per-page gate would have skipped every search anyway); False on
+ batch failure so pages fall back to the per-page path.
+ """
+ if run.vector_store is None or not getattr(run.config, "enable_rag_context", True):
+ return False
+ min_store_size = max(0, int(getattr(run.config, "rag_min_store_size", 10) or 0))
+ if min_store_size > 0:
+ try:
+ current_ids = await run.vector_store.list_page_ids()
+ if len(current_ids) < min_store_size:
+ # Store too small for useful RAG — the per-page gate would
+ # skip every search this level, so there is nothing to fetch.
+ return True
+ except Exception:
+ pass # same as the per-page gate: fall through to the search
+ queries: list[str] = []
+ targets: list[tuple[Any, FilePageContext]] = []
+ for p, ctx in items:
+ query_terms = p.exports or [
+ s["name"] for s in ctx.symbols[:3] if s.get("visibility") == "public"
+ ]
+ if not query_terms:
+ continue
+ queries.append(", ".join(query_terms[:5]))
+ targets.append((p, ctx))
+ if not queries:
+ return True
+ try:
+ all_results = await run.vector_store.search_many(queries, limit=3)
+ except Exception as exc:
+ log.debug("rag.batch_search_failed", error=str(exc))
+ return False
+ for (p, ctx), results in zip(targets, all_results, strict=False):
+ self_id = f"file_page:{p.file_info.path}"
+ ctx.rag_context = [
+ f"[{r.page_id}]\n{r.snippet}" for r in results if r.page_id != self_id
+ ]
+ return True
+
+
async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
"""Level 2 (file_page): topo-ordered context assembly + tier routing.
@@ -141,7 +194,13 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
_topo_order_code_files(run)
await _prefetch_dependency_summaries(run)
- coros: list[tuple[str, Any]] = []
+ # One pass over the graph's symbol nodes feeds every file's call-graph /
+ # heritage extraction (instead of a full node scan per file).
+ from ..context.graph_intelligence import build_symbol_index
+
+ symbol_index = build_symbol_index(run.graph)
+
+ items: list[tuple[Any, FilePageContext]] = []
for p in run.code_files:
kg_file_ctx = run.kg_ctx.get_file_context(p.file_info.path) if run.kg_ctx.available else None
ctx: FilePageContext = gen._assembler.assemble_file_page(
@@ -156,13 +215,32 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
dead_code_findings=run.dead_code_by_file.get(p.file_info.path),
decision_records=run.decisions_by_file.get(p.file_info.path),
kg_context=kg_file_ctx,
+ symbol_index=symbol_index,
)
run.file_page_contexts[p.file_info.path] = ctx
+ items.append((p, ctx))
+
+ def _emits_tier1(p: Any) -> bool:
+ path = p.file_info.path
+ return (
+ path in run.sel_file_paths
+ and path in run.tier1_paths
+ and compute_page_id("file_page", path) not in run.completed_ids
+ )
+
+ rag_prefetched = await _prefetch_rag_context(
+ run, [(p, ctx) for p, ctx in items if _emits_tier1(p)]
+ )
+
+ coros: list[tuple[str, Any]] = []
+ for p, ctx in items:
path = p.file_info.path
pid = compute_page_id("file_page", path)
if path in run.sel_file_paths and pid not in run.completed_ids:
if path in run.tier1_paths:
- coros.append((pid, gen._generate_file_page_from_ctx(p, ctx)))
+ coros.append(
+ (pid, gen._generate_file_page_from_ctx(p, ctx, rag_prefetched=rag_prefetched))
+ )
else:
coros.append((pid, gen._generate_file_page_tier2(p, ctx)))
return coros
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 8d3577d94..392c553a0 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -64,6 +64,7 @@ class CallResolver:
import_targets: dict[str, set[str]],
*,
repo_path: str | None = None,
+ import_maps: Any | None = None,
) -> None:
# Per-file symbol index: {file_path: {symbol_name: symbol_id}}
self._file_symbols: dict[str, dict[str, str]] = {}
@@ -71,6 +72,11 @@ class CallResolver:
# Per-file method index: {file_path: {(class_name, method_name): symbol_id}}
self._file_methods: dict[str, dict[tuple[str, str], str]] = {}
+ # Global method index: {(class_name, method_name): [(file_path, symbol_id)]}
+ # in file-insertion order — replaces the trait-dispatch scan over
+ # every file's method dict with one short-list lookup.
+ self._global_methods: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
+
# Global symbol index: {name: [symbol_ids]} — for Tier 3
self._global_symbols: dict[str, list[str]] = defaultdict(list)
@@ -80,14 +86,27 @@ class CallResolver:
# Import graph: {file_path: set of imported file paths}
self._import_targets = import_targets
- # Import name mapping: {file_path: {local_name: source_file}}
- self._import_names: dict[str, dict[str, str]] = defaultdict(dict)
+ # Shared import-name maps (built once per GraphBuilder.build() and
+ # injected; standalone construction builds them locally).
+ if import_maps is None:
+ from .import_index import build_import_name_maps
+ import_maps = build_import_name_maps(parsed_files)
+ # Import name mapping: {file_path: {local_name: source_file}}
+ self._import_names: dict[str, dict[str, str]] = import_maps.import_names
# Full binding data: {file_path: {local_name: NamedBinding}}
- self._import_bindings: dict[str, dict[str, NamedBinding]] = defaultdict(dict)
-
+ self._import_bindings: dict[str, dict[str, NamedBinding]] = import_maps.import_bindings
# Module alias mapping: {file_path: {alias: source_file}}
- self._module_aliases: dict[str, dict[str, str]] = defaultdict(dict)
+ self._module_aliases: dict[str, dict[str, str]] = import_maps.module_aliases
+
+ # Lazy per-file merged views of every imported file's symbol /
+ # method tables — turns the Tier-2b "scan each imported file"
+ # loops into single dict lookups. Built on first miss per file;
+ # merge order is sorted(import paths) with first-wins so shadowed
+ # names resolve deterministically (the old set-iteration order was
+ # hash-randomized per process).
+ self._merged_import_symbols: dict[str, dict[str, str]] = {}
+ self._merged_import_methods: dict[str, dict[tuple[str, str], str]] = {}
# Barrel re-export origins: {barrel_file: {name: origin_file}}
self._barrel_origins: dict[str, dict[str, str]] = defaultdict(dict)
@@ -366,7 +385,10 @@ class CallResolver:
return None
def _build_indices(self, parsed_files: dict[str, ParsedFile]) -> None:
- """Build all lookup indices from parsed file data."""
+ """Build symbol lookup indices from parsed file data.
+
+ (Import-name maps are shared — see ``import_index.build_import_name_maps``.)
+ """
for path, parsed in parsed_files.items():
file_syms: dict[str, str] = {}
file_methods: dict[tuple[str, str], str] = {}
@@ -377,7 +399,9 @@ class CallResolver:
# Method index: (class_name, method_name) → symbol_id
if sym.parent_name:
- file_methods[(sym.parent_name, sym.name)] = sym.id
+ key = (sym.parent_name, sym.name)
+ file_methods[key] = sym.id
+ self._global_methods[key].append((path, sym.id))
# Global indices
self._global_symbols[sym.name].append(sym.id)
@@ -387,25 +411,35 @@ class CallResolver:
self._file_symbols[path] = file_syms
self._file_methods[path] = file_methods
- # Build import-name mapping using per-import resolved_file
- for imp in parsed.imports:
- if imp.resolved_file is None:
+ def _merged_symbols_for(self, file_path: str) -> dict[str, str]:
+ """Merged ``{name → symbol_id}`` across every file *file_path* imports.
+
+ Sorted-path merge order with first-wins gives deterministic
+ precedence for names exported by multiple imports.
+ """
+ merged = self._merged_import_symbols.get(file_path)
+ if merged is None:
+ merged = {}
+ for imported_file in sorted(self._import_targets.get(file_path, ())):
+ if imported_file.startswith("external:"):
continue
- resolved = imp.resolved_file
- if imp.bindings:
- for binding in imp.bindings:
- if binding.local_name == "*":
- continue
- binding.source_file = resolved
- self._import_names[path][binding.local_name] = resolved
- self._import_bindings[path][binding.local_name] = binding
- if binding.is_module_alias:
- self._module_aliases[path][binding.local_name] = resolved
- else:
- # Fallback for imports without binding data
- for name in imp.imported_names:
- if name != "*":
- self._import_names[path][name] = resolved
+ for name, sym_id in self._file_symbols.get(imported_file, {}).items():
+ merged.setdefault(name, sym_id)
+ self._merged_import_symbols[file_path] = merged
+ return merged
+
+ def _merged_methods_for(self, file_path: str) -> dict[tuple[str, str], str]:
+ """Merged ``{(class, method) → symbol_id}`` across imports (see above)."""
+ merged = self._merged_import_methods.get(file_path)
+ if merged is None:
+ merged = {}
+ for imported_file in sorted(self._import_targets.get(file_path, ())):
+ if imported_file.startswith("external:"):
+ continue
+ for key, sym_id in self._file_methods.get(imported_file, {}).items():
+ merged.setdefault(key, sym_id)
+ self._merged_import_methods[file_path] = merged
+ return merged
def resolve_file(self, file_path: str, calls: list[CallSite]) -> list[ResolvedCall]:
"""Resolve all calls in a single file to symbol-level edges."""
@@ -504,13 +538,10 @@ class CallResolver:
if target_name in source_syms:
return ResolvedCall(caller_id, source_syms[target_name], 0.90, call.line)
- # 2b: Check all imported files for the symbol
- for imported_file in self._import_targets.get(file_path, set()):
- if imported_file.startswith("external:"):
- continue
- imported_syms = self._file_symbols.get(imported_file, {})
- if target_name in imported_syms:
- return ResolvedCall(caller_id, imported_syms[target_name], 0.85, call.line)
+ # 2b: Check all imported files for the symbol (pre-merged lookup)
+ merged_syms = self._merged_symbols_for(file_path)
+ if target_name in merged_syms:
+ return ResolvedCall(caller_id, merged_syms[target_name], 0.85, call.line)
# Tier 3: global unique match — only within the same language
candidates = self._global_symbols.get(target_name, [])
@@ -591,22 +622,20 @@ class CallResolver:
if key in file_methods:
return ResolvedCall(caller_id, file_methods[key], 0.93, call.line)
- # Check imported files for (class, method) pairs
- for imported_file in self._import_targets.get(file_path, set()):
- if imported_file.startswith("external:"):
- continue
- imp_methods = self._file_methods.get(imported_file, {})
- if key in imp_methods:
- return ResolvedCall(caller_id, imp_methods[key], 0.88, call.line)
+ # Check imported files for (class, method) pairs (pre-merged lookup)
+ merged_methods = self._merged_methods_for(file_path)
+ if key in merged_methods:
+ return ResolvedCall(caller_id, merged_methods[key], 0.88, call.line)
# Strategy 2b: trait method dispatch — receiver is a type that
# implements a trait; the method may be defined on the trait's
- # impl block in another file.
- for _path, methods in self._file_methods.items():
+ # impl block in another file. The global index preserves the old
+ # file-insertion match order; entries from the caller's own file
+ # are skipped exactly as before.
+ for _path, sym_id in self._global_methods.get(key, ()):
if _path == file_path:
continue
- if key in methods:
- return ResolvedCall(caller_id, methods[key], 0.75, call.line)
+ return ResolvedCall(caller_id, sym_id, 0.75, call.line)
# Strategy 3: receiver is "self" or "this" — look in same class
if receiver_name in ("self", "this"):
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
index aa464034c..cff6d7250 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
@@ -60,22 +60,18 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
def extract_heritage(
- tree: object,
- query: object,
+ matches: list[dict],
config: object,
file_info: object,
src: str,
- *,
- run_query: Callable,
) -> list[HeritageRelation]:
"""Extract inheritance/implementation relationships from class definitions.
- Walks the same @symbol.def captures used by _extract_symbols, extracting
- superclass/interface/trait information from the definition AST nodes.
+ Walks the same @symbol.def captures used by _extract_symbols (the parser
+ executes the compiled query once per file and shares the capture dicts
+ across all extraction passes), extracting superclass/interface/trait
+ information from the definition AST nodes.
"""
- if query is None:
- return []
-
lang = file_info.language # type: ignore[attr-defined]
heritage_types = heritage_node_types_for(lang)
if not heritage_types:
@@ -88,7 +84,7 @@ def extract_heritage(
relations: list[HeritageRelation] = []
seen: set[tuple[int, str]] = set()
- for capture_dict in run_query(query, tree.root_node): # type: ignore[attr-defined]
+ for capture_dict in matches:
def_nodes = capture_dict.get("symbol.def", [])
name_nodes = capture_dict.get("symbol.name", [])
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py
index 59e815743..938ef0a44 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/enrich.py
@@ -208,15 +208,18 @@ def compute_percentiles(metadata_list: list[dict]) -> None:
total = len(metadata_list)
for rank, idx in enumerate(sorted_by_churn):
- metadata_list[idx]["churn_percentile"] = rank / total if total > 0 else 0.0
-
- # Hotspot: top 25% churn (churn_percentile >= 0.75) AND the absolute
- # activity floors — without the floors, a quiet repo's top quartile is
- # just "every file touched in 90 days" (issue #361).
- for meta in metadata_list:
- churn_pct = meta.get("churn_percentile", 0.0)
+ meta = metadata_list[idx]
+ churn_pct = rank / total if total > 0 else 0.0
+ meta["churn_percentile"] = churn_pct
+ # Hotspot: top 25% churn (churn_percentile >= 0.75) AND the absolute
+ # activity floors — without the floors, a quiet repo's top quartile is
+ # just "every file touched in 90 days" (issue #361). Folded into the
+ # rank loop so the list is scanned once.
if churn_pct >= 0.75 and meets_hotspot_floors(meta):
meta["is_hotspot"] = True
+ # change_entropy percentile default — overwritten below for files
+ # carrying a positive entropy signal.
+ meta.setdefault("change_entropy_pct", 0.0)
# change_entropy percentile (mirrors churn_percentile). Rank ONLY files
# that carry a positive entropy signal; files with zero entropy — every
@@ -224,8 +227,6 @@ def compute_percentiles(metadata_list: list[dict]) -> None:
# alone — keep pct 0.0 so the change_entropy biomarker stays silent. (A
# naive rank-everything would hand the topmost zero-entropy file a high
# percentile when most files are zero.)
- for meta in metadata_list:
- meta.setdefault("change_entropy_pct", 0.0)
entropy_idxs = [
i for i in range(total) if (metadata_list[i].get("change_entropy") or 0.0) > 0.0
]
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 389f1f790..58ed967f7 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -12,6 +12,7 @@ import asyncio
import contextlib
import json
import os
+import threading
import time
from collections.abc import Callable
from pathlib import Path
@@ -134,28 +135,30 @@ class GitIndexer:
include_blame = self.tier.includes_blame
as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ get_thread_repo, close_thread_repos = self._thread_repo_pool()
def _index_one_sync(file_path: str) -> dict:
- """Use a per-thread Repo to avoid shared-handle issues on Windows."""
- try:
- import git as gitpython
+ """Use a per-thread Repo to avoid shared-handle issues on Windows.
- thread_repo = gitpython.Repo(self.repo_path, search_parent_directories=True)
- try:
- precomputed = commit_index.get(file_path) if commit_index else None
- return index_file(
- thread_repo,
- file_path,
- repo_path=self.repo_path,
- commit_limit=self.commit_limit,
- follow_renames=self.follow_renames,
- include_blame=include_blame,
- precomputed_commits=precomputed,
- as_of_ts=as_of_ts,
- provenance_classifier=prov_clf,
- )
- finally:
- thread_repo.close()
+ The Repo is created once per worker thread and reused across files
+ — constructing a fresh ``gitpython.Repo`` per file costs ~40 ms
+ each (config + ref resolution), which dominated the git phase on
+ repos with thousands of files.
+ """
+ try:
+ thread_repo = get_thread_repo()
+ precomputed = commit_index.get(file_path) if commit_index else None
+ return index_file(
+ thread_repo,
+ file_path,
+ repo_path=self.repo_path,
+ commit_limit=self.commit_limit,
+ follow_renames=self.follow_renames,
+ include_blame=include_blame,
+ precomputed_commits=precomputed,
+ as_of_ts=as_of_ts,
+ provenance_classifier=prov_clf,
+ )
except Exception:
return {"file_path": file_path}
@@ -215,6 +218,7 @@ class GitIndexer:
# Abandon any timed-out threads immediately instead of letting
# asyncio.run() block for minutes during default-executor cleanup.
executor.shutdown(wait=False, cancel_futures=True)
+ close_thread_repos()
results: list[dict] = []
for r in metadata_list:
@@ -282,7 +286,14 @@ class GitIndexer:
return summary, results
async def index_changed_files(self, changed_file_paths: list[str]) -> list[dict]:
- """Incremental update: re-index only changed files."""
+ """Incremental update: re-index only changed files.
+
+ Mirrors ``index_repo``'s batched shape: one repo-wide commit-index
+ walk feeds every per-file worker (instead of one ``git log -- <file>``
+ subprocess per changed file), so the metadata an update produces is
+ identical to what a fresh full index would produce — including the
+ agent-provenance rollup, which the old per-file path never classified.
+ """
repo = self._get_repo()
if repo is None:
return []
@@ -290,25 +301,36 @@ class GitIndexer:
loop = asyncio.get_event_loop()
semaphore = asyncio.Semaphore(20)
include_blame = self.tier.includes_blame
- as_of_ts = self._resolve_as_of_ts(repo)
+
+ prov_clf = self._provenance_classifier()
+ commit_index: dict[str, list[_CommitRec]] = {}
+ if not self.follow_renames:
+ from ..git_commit_index import load_commit_index
+
+ commit_index = load_commit_index(
+ repo,
+ self.commit_limit,
+ set(changed_file_paths),
+ provenance_classifier=prov_clf,
+ )
+ as_of_ts = self._resolve_as_of_ts(repo, commit_index)
+ get_thread_repo, close_thread_repos = self._thread_repo_pool()
def _index_one_sync(file_path: str) -> dict:
try:
- import git as gitpython
-
- thread_repo = gitpython.Repo(self.repo_path, search_parent_directories=True)
- try:
- return index_file(
- thread_repo,
- file_path,
- repo_path=self.repo_path,
- commit_limit=self.commit_limit,
- follow_renames=self.follow_renames,
- include_blame=include_blame,
- as_of_ts=as_of_ts,
- )
- finally:
- thread_repo.close()
+ thread_repo = get_thread_repo()
+ precomputed = commit_index.get(file_path) if commit_index else None
+ return index_file(
+ thread_repo,
+ file_path,
+ repo_path=self.repo_path,
+ commit_limit=self.commit_limit,
+ follow_renames=self.follow_renames,
+ include_blame=include_blame,
+ precomputed_commits=precomputed,
+ as_of_ts=as_of_ts,
+ provenance_classifier=prov_clf,
+ )
except Exception:
return {"file_path": file_path}
@@ -328,7 +350,10 @@ class GitIndexer:
return {"file_path": file_path}
tasks = [index_one(fp) for fp in changed_file_paths]
- results_raw = await asyncio.gather(*tasks, return_exceptions=True)
+ try:
+ results_raw = await asyncio.gather(*tasks, return_exceptions=True)
+ finally:
+ close_thread_repos()
results: list[dict] = []
for r in results_raw:
@@ -441,6 +466,42 @@ class GitIndexer:
except Exception:
return None
+ def _thread_repo_pool(self) -> tuple[Callable[[], Any], Callable[[], None]]:
+ """Return ``(get_thread_repo, close_all)`` for per-thread Repo reuse.
+
+ gitpython ``Repo`` handles can't be shared across threads on Windows,
+ but constructing one per *file* costs ~40 ms each. This pool hands
+ each worker thread its own lazily-created ``Repo`` and reuses it for
+ every file that thread processes. ``close_all()`` closes every repo
+ the pool created; a worker thread abandoned mid-file (timeout) will
+ see its repo closed underneath it and fall into the existing
+ per-file exception path, which is the same partial-data outcome the
+ old per-file construction produced on failure.
+ """
+ tls = threading.local()
+ created: list[Any] = []
+ lock = threading.Lock()
+
+ def get_thread_repo() -> Any:
+ repo = getattr(tls, "repo", None)
+ if repo is None:
+ import git as gitpython
+
+ repo = gitpython.Repo(self.repo_path, search_parent_directories=True)
+ tls.repo = repo
+ with lock:
+ created.append(repo)
+ return repo
+
+ def close_all() -> None:
+ with lock:
+ repos, created[:] = list(created), []
+ for repo in repos:
+ with contextlib.suppress(Exception):
+ repo.close()
+
+ return get_thread_repo, close_all
+
def _get_repo(self) -> Any | None:
try:
import git as gitpython
diff --git a/packages/core/src/repowise/core/ingestion/graph/_betweenness.py b/packages/core/src/repowise/core/ingestion/graph/_betweenness.py
new file mode 100644
index 000000000..e2585c9e2
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/graph/_betweenness.py
@@ -0,0 +1,155 @@
+"""Parallel exact betweenness centrality (Brandes) over a process pool.
+
+``nx.betweenness_centrality`` is pure-Python Brandes: O(V·E) per run, single
+threaded, and it does not release the GIL — on a ~11k-node symbol subgraph it
+is by far the most expensive metric kernel (~54s isolated, measured on the
+repowise repo itself). Brandes is embarrassingly parallel over *source*
+nodes: each source's dependency accumulation is independent and the final
+score is the plain sum of the per-source partials. This module fans the
+source set out across a process pool and sums the partials, producing the
+same values as the sequential call (the only difference is floating-point
+summation order, bounded at ~1e-15 relative).
+
+Workers receive the graph once (pool initializer) as an integer edge list —
+node attributes are irrelevant to betweenness, so the pickled payload stays
+small even for graphs whose node ids are long symbol strings.
+
+Falls back to ``nx.betweenness_centrality`` whenever the graph is small
+enough that pool startup would dominate, or the pool / NetworkX internals
+are unavailable.
+"""
+
+from __future__ import annotations
+
+import os
+from concurrent.futures import ProcessPoolExecutor
+
+import networkx as nx
+import structlog
+
+log = structlog.get_logger(__name__)
+
+# Parallelize only when the estimated Brandes cost (~nodes x edges) is large
+# enough to amortize process startup (~2-3s for pool spawn + imports).
+# Measured rates on the repowise graph: file subgraph (1.8k x 5.2k ~ 1e7)
+# runs in ~0.4s sequentially; the symbol subgraph (11.3k x 12k ~ 1.4e8)
+# takes ~54s. The threshold sits between the two.
+_PARALLEL_COST_THRESHOLD = 4e7
+
+# ---------------------------------------------------------------------------
+# Worker side (must be module-level + picklable for Windows spawn)
+# ---------------------------------------------------------------------------
+
+_WORKER_GRAPH: nx.DiGraph | None = None
+
+
+def _init_worker(n: int, edges: list[tuple[int, int]], directed: bool) -> None:
+ """Pool initializer: build the (attribute-free) int-labeled graph once."""
+ global _WORKER_GRAPH
+ g: nx.DiGraph = nx.DiGraph() if directed else nx.Graph()
+ g.add_nodes_from(range(n))
+ g.add_edges_from(edges)
+ _WORKER_GRAPH = g
+
+
+def _partial_betweenness(sources: list[int]) -> dict[int, float]:
+ """Accumulate Brandes dependencies for a chunk of source nodes.
+
+ Mirrors the per-source loop of ``nx.betweenness_centrality`` exactly
+ (unweighted BFS + basic accumulation, no endpoints). Summing the
+ partials over all chunks reproduces the sequential pre-rescale values.
+ """
+ from networkx.algorithms.centrality.betweenness import (
+ _accumulate_basic,
+ _single_source_shortest_path_basic,
+ )
+
+ g = _WORKER_GRAPH
+ assert g is not None, "worker pool initializer did not run"
+ betweenness: dict[int, float] = dict.fromkeys(g, 0.0)
+ for s in sources:
+ S, P, sigma, _ = _single_source_shortest_path_basic(g, s) # noqa: N806 - NX naming
+ betweenness, _ = _accumulate_basic(betweenness, S, P, sigma, s)
+ # Only non-zero entries cross the process boundary.
+ return {v: b for v, b in betweenness.items() if b != 0.0}
+
+
+# ---------------------------------------------------------------------------
+# Parent side
+# ---------------------------------------------------------------------------
+
+
+def _rescale(
+ betweenness: dict[int, float], n: int, *, normalized: bool, directed: bool
+) -> dict[int, float]:
+ """Rescale raw accumulations exactly like NetworkX (k=None, no endpoints)."""
+ if normalized:
+ scale = None if n <= 2 else 1 / ((n - 1) * (n - 2))
+ else:
+ scale = None if directed else 0.5
+ if scale is not None:
+ for v in betweenness:
+ betweenness[v] *= scale
+ return betweenness
+
+
+def betweenness_centrality_fast(
+ g: nx.DiGraph,
+ *,
+ normalized: bool = True,
+ max_workers: int | None = None,
+) -> dict[str, float]:
+ """Exact betweenness centrality, parallelized over sources when worthwhile.
+
+ Drop-in equivalent of ``nx.betweenness_centrality(g, normalized=...)``
+ for unweighted graphs without endpoint counting. Small graphs (or any
+ pool failure) take the sequential NetworkX path, so callers never need
+ a fallback of their own.
+ """
+ n = g.number_of_nodes()
+ e = g.number_of_edges()
+ if n == 0:
+ return {}
+ workers = max_workers or os.cpu_count() or 1
+ if n * e < _PARALLEL_COST_THRESHOLD or workers < 2:
+ return nx.betweenness_centrality(g, normalized=normalized)
+
+ try:
+ # Verify the NetworkX internals the workers rely on exist in this
+ # version before paying for pool spawn.
+ from networkx.algorithms.centrality.betweenness import ( # noqa: F401
+ _accumulate_basic,
+ _single_source_shortest_path_basic,
+ )
+ except ImportError: # pragma: no cover - depends on networkx version
+ log.warning("betweenness_parallel_unavailable", reason="networkx internals moved")
+ return nx.betweenness_centrality(g, normalized=normalized)
+
+ nodes = list(g)
+ index = {node: i for i, node in enumerate(nodes)}
+ edges = [(index[u], index[v]) for u, v in g.edges()]
+
+ # ~3 chunks per worker for load balancing without excessive IPC.
+ chunk_count = max(1, workers * 3)
+ chunk_size = max(1, (n + chunk_count - 1) // chunk_count)
+ chunks = [list(range(i, min(i + chunk_size, n))) for i in range(0, n, chunk_size)]
+
+ totals = [0.0] * n
+ try:
+ with ProcessPoolExecutor(
+ max_workers=workers,
+ initializer=_init_worker,
+ initargs=(n, edges, g.is_directed()),
+ ) as pool:
+ # ``map`` preserves chunk order, keeping float summation
+ # deterministic for a given worker count.
+ for partial in pool.map(_partial_betweenness, chunks):
+ for v, b in partial.items():
+ totals[v] += b
+ except Exception as exc: # pragma: no cover - depends on host environment
+ log.warning("betweenness_parallel_failed_falling_back", error=str(exc))
+ return nx.betweenness_centrality(g, normalized=normalized)
+
+ raw = dict(enumerate(totals))
+ _rescale(raw, n, normalized=normalized, directed=g.is_directed())
+ return {nodes[i]: score for i, score in raw.items()}
diff --git a/packages/core/src/repowise/core/ingestion/graph/_edges.py b/packages/core/src/repowise/core/ingestion/graph/_edges.py
index 737892872..06748cd3b 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_edges.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_edges.py
@@ -62,6 +62,8 @@ class EdgesMixin:
count += 1
log.info("Co-change edges added", count=count)
+ if count:
+ self._invalidate_subgraph_caches()
return count
def update_co_change_edges(self, updated_meta: dict, min_count: int = 3) -> None:
@@ -72,6 +74,7 @@ class EdgesMixin:
edges_to_remove.append((u, v))
self._graph.remove_edges_from(edges_to_remove)
self.add_co_change_edges(updated_meta, min_count)
+ self._invalidate_subgraph_caches()
def add_dynamic_edges(self, edges: list) -> None:
"""Add dynamic-hint edges to the graph. Each edge is a DynamicEdge."""
@@ -97,6 +100,8 @@ class EdgesMixin:
# source file node as is_test so downstream consumers can filter it.
if e.hint_source and e.hint_source.endswith(":test"):
self._graph.nodes[e.source]["is_test"] = True
+ if edges:
+ self._invalidate_subgraph_caches()
def add_framework_edges(self, tech_stack: list[str] | None = None) -> int:
"""Add synthetic edges for framework-mediated relationships.
@@ -124,4 +129,5 @@ class EdgesMixin:
count = add_framework_edges(self._graph, self._parsed_files, ctx, tech_stack)
if count:
log.info("Framework edges added", count=count)
+ self._invalidate_subgraph_caches()
return count
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index 052a8de7f..4cfbcdbd0 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -76,17 +76,35 @@ class MetricsMixin:
# ------------------------------------------------------------------
def file_subgraph(self) -> nx.DiGraph:
- """Return a subgraph containing only file-level nodes and import edges."""
- g = self.graph()
- file_nodes = [
- n for n, d in g.nodes(data=True) if d.get("node_type", "file") in ("file", "external")
- ]
- sub = g.subgraph(file_nodes).copy()
- edges_to_remove = [
- (u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)
- ]
- sub.remove_edges_from(edges_to_remove)
- return sub
+ """Return a subgraph containing only file-level nodes and import edges.
+
+ Cached per build — five metric kernels (SCC, PageRank, betweenness,
+ in/out degree) read it, and rebuilding the filtered copy per call is
+ O(V+E) each time. The cache is guarded by ``_subgraph_lock`` because
+ the init pipeline computes metrics concurrently via
+ ``asyncio.to_thread``. Callers must treat the result as read-only.
+ """
+ cached = self._file_subgraph_cache
+ if cached is not None:
+ return cached
+ with self._subgraph_lock:
+ if self._file_subgraph_cache is not None:
+ return self._file_subgraph_cache
+ g = self.graph()
+ file_nodes = [
+ n
+ for n, d in g.nodes(data=True)
+ if d.get("node_type", "file") in ("file", "external")
+ ]
+ sub = g.subgraph(file_nodes).copy()
+ edges_to_remove = [
+ (u, v)
+ for u, v, d in sub.edges(data=True)
+ if d.get("edge_type") in ("co_changes",)
+ ]
+ sub.remove_edges_from(edges_to_remove)
+ self._file_subgraph_cache = sub
+ return sub
def symbol_subgraph(self) -> nx.DiGraph:
"""Return a subgraph of symbol nodes connected by call + heritage edges.
@@ -94,17 +112,27 @@ class MetricsMixin:
File-to-symbol ``defines`` edges and class-to-method ``has_method``
ownership edges are dropped so that the resulting centrality
scores reflect call/heritage flow rather than containment.
+
+ Cached per build (see :meth:`file_subgraph` for the locking
+ rationale). Callers must treat the result as read-only.
"""
- g = self.graph()
- symbol_nodes = [n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol"]
- sub = g.subgraph(symbol_nodes).copy()
- edges_to_remove = [
- (u, v)
- for u, v, d in sub.edges(data=True)
- if d.get("edge_type") not in ("calls", "extends", "implements")
- ]
- sub.remove_edges_from(edges_to_remove)
- return sub
+ cached = self._symbol_subgraph_cache
+ if cached is not None:
+ return cached
+ with self._subgraph_lock:
+ if self._symbol_subgraph_cache is not None:
+ return self._symbol_subgraph_cache
+ g = self.graph()
+ symbol_nodes = [n for n, d in g.nodes(data=True) if d.get("node_type") == "symbol"]
+ sub = g.subgraph(symbol_nodes).copy()
+ edges_to_remove = [
+ (u, v)
+ for u, v, d in sub.edges(data=True)
+ if d.get("edge_type") not in ("calls", "extends", "implements")
+ ]
+ sub.remove_edges_from(edges_to_remove)
+ self._symbol_subgraph_cache = sub
+ return sub
# ------------------------------------------------------------------
# File-level metrics
@@ -144,7 +172,9 @@ class MetricsMixin:
k = min(500, n)
self._betweenness_cache = nx.betweenness_centrality(g, k=k, normalized=True)
else:
- self._betweenness_cache = nx.betweenness_centrality(g, normalized=True)
+ from ._betweenness import betweenness_centrality_fast
+
+ self._betweenness_cache = betweenness_centrality_fast(g, normalized=True)
return self._betweenness_cache
def in_degree(self) -> dict[str, int]:
@@ -247,7 +277,9 @@ class MetricsMixin:
k = min(500, n)
self._symbol_betweenness_cache = nx.betweenness_centrality(sub, k=k, normalized=True)
else:
- self._symbol_betweenness_cache = nx.betweenness_centrality(sub, normalized=True)
+ from ._betweenness import betweenness_centrality_fast
+
+ self._symbol_betweenness_cache = betweenness_centrality_fast(sub, normalized=True)
return self._symbol_betweenness_cache
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index b05804161..62c94ae56 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -16,6 +16,16 @@ log = structlog.get_logger(__name__)
class ResolveMixin:
"""Symbol-level edge resolution passes run during ``build()``."""
+ def _shared_import_maps(self) -> Any:
+ """Build the import-name maps once per build; both resolvers share them."""
+ maps = getattr(self, "_import_name_maps", None)
+ if maps is None:
+ from ..import_index import build_import_name_maps
+
+ maps = build_import_name_maps(self._parsed_files)
+ self._import_name_maps = maps
+ return maps
+
def _resolve_heritage(
self,
import_targets: dict[str, set[str]],
@@ -24,7 +34,9 @@ class ResolveMixin:
"""Resolve heritage relations and add EXTENDS/IMPLEMENTS edges."""
from ..heritage_resolver import HeritageResolver
- resolver = HeritageResolver(self._parsed_files, import_targets)
+ resolver = HeritageResolver(
+ self._parsed_files, import_targets, import_maps=self._shared_import_maps()
+ )
total_resolved = 0
files_with_heritage = [
@@ -135,7 +147,12 @@ class ResolveMixin:
"""Run three-tier call resolution and add CALLS edges to the graph."""
from ..call_resolver import CallResolver
- resolver = CallResolver(self._parsed_files, import_targets, repo_path=str(self._repo_path) if self._repo_path else None)
+ resolver = CallResolver(
+ self._parsed_files,
+ import_targets,
+ repo_path=str(self._repo_path) if self._repo_path else None,
+ import_maps=self._shared_import_maps(),
+ )
total_resolved = 0
files_with_calls = [
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 9f6223d4d..692e49e64 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -68,6 +68,16 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
self._symbol_pagerank_cache: dict[str, float] | None = None
self._symbol_betweenness_cache: dict[str, float] | None = None
self._execution_flow_cache: Any | None = None
+ # Filtered-subgraph caches — rebuilt lazily; guarded by a lock because
+ # the init pipeline computes metrics concurrently (asyncio.to_thread).
+ import threading
+
+ self._subgraph_lock = threading.Lock()
+ self._file_subgraph_cache: nx.DiGraph | None = None
+ self._symbol_subgraph_cache: nx.DiGraph | None = None
+ # Shared import-name maps (built once per build(), injected into the
+ # call + heritage resolvers; reset whenever files change).
+ self._import_name_maps: Any | None = None
def set_tsconfig_resolver(self, resolver: Any) -> None:
"""Attach a :class:`TsconfigResolver` for TS/JS path-alias resolution."""
@@ -86,6 +96,20 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
self._symbol_pagerank_cache = None
self._symbol_betweenness_cache = None
self._execution_flow_cache = None
+ self._file_subgraph_cache = None
+ self._symbol_subgraph_cache = None
+ self._import_name_maps = None
+
+ def _invalidate_subgraph_caches(self) -> None:
+ """Clear only the filtered-subgraph caches.
+
+ Called by graph mutations that historically did NOT clear the metric
+ caches (co-change edge refresh, framework edges) — those keep their
+ existing semantics, but a cached subgraph must never go stale
+ structurally.
+ """
+ self._file_subgraph_cache = None
+ self._symbol_subgraph_cache = None
def release_graph(self) -> None:
"""Drop the in-memory NetworkX object after metrics are materialized.
@@ -102,6 +126,7 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
"""
self._graph = nx.DiGraph()
self._built = True
+ self._invalidate_subgraph_caches() # they hold the old structure — free it
# ------------------------------------------------------------------
# Building
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
index 6b08f17d9..62b7bbde9 100644
--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -23,6 +23,7 @@ from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
+from typing import Any
import structlog
@@ -75,6 +76,8 @@ class HeritageResolver:
self,
parsed_files: dict[str, ParsedFile],
import_targets: dict[str, set[str]],
+ *,
+ import_maps: Any | None = None,
) -> None:
# Per-file class/interface/trait index: {file: {name: symbol_id}}
self._file_types: dict[str, dict[str, str]] = {}
@@ -85,8 +88,19 @@ class HeritageResolver:
# Import graph
self._import_targets = import_targets
- # Import name mapping (reuses resolved_file from Import objects)
- self._import_names: dict[str, dict[str, str]] = defaultdict(dict)
+ # Import name mapping — shared with CallResolver (built once per
+ # GraphBuilder.build() and injected; standalone construction builds
+ # it locally).
+ if import_maps is None:
+ from .import_index import build_import_name_maps
+
+ import_maps = build_import_name_maps(parsed_files)
+ self._import_names: dict[str, dict[str, str]] = import_maps.import_names
+
+ # Lazy per-file merged view of imported files' type tables —
+ # Tier-2b lookup; sorted-path merge order, first-wins (see
+ # CallResolver for rationale).
+ self._merged_import_types: dict[str, dict[str, str]] = {}
# Keep reference for cross-language checks in Tier 3
self._parsed_files = parsed_files
@@ -105,18 +119,18 @@ class HeritageResolver:
self._file_types[path] = file_types
- # Build import name mapping using resolved_file
- for imp in parsed.imports:
- if imp.resolved_file is None:
+ def _merged_types_for(self, file_path: str) -> dict[str, str]:
+ """Merged ``{type_name → symbol_id}`` across every imported file."""
+ merged = self._merged_import_types.get(file_path)
+ if merged is None:
+ merged = {}
+ for imported_file in sorted(self._import_targets.get(file_path, ())):
+ if imported_file.startswith("external:"):
continue
- for binding in imp.bindings:
- if binding.local_name != "*":
- self._import_names[path][binding.local_name] = imp.resolved_file
- # Fallback for imports without bindings
- if not imp.bindings:
- for name in imp.imported_names:
- if name != "*":
- self._import_names[path][name] = imp.resolved_file
+ for name, sym_id in self._file_types.get(imported_file, {}).items():
+ merged.setdefault(name, sym_id)
+ self._merged_import_types[file_path] = merged
+ return merged
def resolve_file(
self, file_path: str, relations: list[HeritageRelation]
@@ -162,19 +176,16 @@ class HeritageResolver:
line=rel.line,
)
- # Tier 2b: scan all imported files
- for imported_file in self._import_targets.get(file_path, set()):
- if imported_file.startswith("external:"):
- continue
- imported_types = self._file_types.get(imported_file, {})
- if parent_name in imported_types:
- return ResolvedHeritage(
- child_id=child_id,
- parent_id=imported_types[parent_name],
- edge_type=edge_type,
- confidence=0.85,
- line=rel.line,
- )
+ # Tier 2b: all imported files (pre-merged lookup)
+ merged_types = self._merged_types_for(file_path)
+ if parent_name in merged_types:
+ return ResolvedHeritage(
+ child_id=child_id,
+ parent_id=merged_types[parent_name],
+ edge_type=edge_type,
+ confidence=0.85,
+ line=rel.line,
+ )
# Tier 3: global unique match — only within the same language
candidates = self._global_types.get(parent_name, [])
diff --git a/packages/core/src/repowise/core/ingestion/import_index.py b/packages/core/src/repowise/core/ingestion/import_index.py
new file mode 100644
index 000000000..89794c697
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/import_index.py
@@ -0,0 +1,65 @@
+"""Shared import-name index construction for the call and heritage resolvers.
+
+Both resolvers used to derive the same ``{file → {local_name → source_file}}``
+mapping independently from every file's imports. Build it once here and
+inject it into both (the GraphBuilder does this during ``build()``); the
+resolvers keep a backwards-compatible fallback that builds the maps
+themselves when none are supplied.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass, field
+
+from .models import NamedBinding, ParsedFile
+
+
+@dataclass(slots=True)
+class ImportNameMaps:
+ """Per-file import-name lookups shared across resolution passes.
+
+ ``import_names`` — {file: {local_name: source_file}}
+ ``import_bindings`` — {file: {local_name: NamedBinding}} (call resolver only)
+ ``module_aliases`` — {file: {alias: source_file}} (call resolver only)
+ """
+
+ import_names: dict[str, dict[str, str]] = field(
+ default_factory=lambda: defaultdict(dict)
+ )
+ import_bindings: dict[str, dict[str, NamedBinding]] = field(
+ default_factory=lambda: defaultdict(dict)
+ )
+ module_aliases: dict[str, dict[str, str]] = field(
+ default_factory=lambda: defaultdict(dict)
+ )
+
+
+def build_import_name_maps(parsed_files: dict[str, ParsedFile]) -> ImportNameMaps:
+ """Build the shared import-name maps from every file's resolved imports.
+
+ Mirrors the historical ``CallResolver._build_indices`` import loop,
+ including the ``binding.source_file`` back-fill side effect that
+ downstream barrel-origin chasing relies on.
+ """
+ maps = ImportNameMaps()
+ for path, parsed in parsed_files.items():
+ for imp in parsed.imports:
+ if imp.resolved_file is None:
+ continue
+ resolved = imp.resolved_file
+ if imp.bindings:
+ for binding in imp.bindings:
+ if binding.local_name == "*":
+ continue
+ binding.source_file = resolved
+ maps.import_names[path][binding.local_name] = resolved
+ maps.import_bindings[path][binding.local_name] = binding
+ if binding.is_module_alias:
+ maps.module_aliases[path][binding.local_name] = resolved
+ else:
+ # Fallback for imports without binding data
+ for name in imp.imported_names:
+ if name != "*":
+ maps.import_names[path][name] = resolved
+ return maps
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index c49f403fe..d827a4a84 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -257,7 +257,13 @@ class ASTParser:
parse_errors = _collect_error_nodes(root)
query = self._get_query(lang, language, grammar_tag)
- symbols = self._extract_symbols(tree, query, config, file_info, src)
+ # Execute the compiled query ONCE per file. The five extraction
+ # passes below all consume the same capture dicts read-only;
+ # re-running ``cursor.matches()`` per pass multiplied the most
+ # expensive part of parsing by five.
+ matches = _run_query(query, root) if query is not None else []
+
+ symbols = self._extract_symbols(matches, config, file_info, src)
# Per-language synthetic-symbol pass — recognises source-generator
# attributes (e.g. CommunityToolkit.Mvvm) and adds the symbols the
# generator would emit at compile time. No-op for languages
@@ -266,12 +272,12 @@ class ASTParser:
if synthetic:
existing_ids = {s.id for s in symbols}
symbols.extend(s for s in synthetic if s.id not in existing_ids)
- imports = self._extract_imports(tree, query, config, file_info, src)
- calls = self._extract_calls(tree, query, config, file_info, src, symbols)
- heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)
+ imports = self._extract_imports(matches, config, file_info, src)
+ calls = self._extract_calls(matches, config, file_info, src, symbols)
+ heritage = extract_heritage(matches, config, file_info, src)
exports = self._derive_exports(symbols, config, src)
docstring = extract_module_docstring(root, src, lang)
- type_refs = self._extract_type_refs(tree, query, src, lang)
+ type_refs = self._extract_type_refs(matches, src, lang)
if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
log.warning(
@@ -310,19 +316,15 @@ class ASTParser:
def _extract_symbols(
self,
- tree: object,
- query: object,
+ matches: list[dict],
config: LanguageConfig,
file_info: FileInfo,
src: str,
) -> list[Symbol]:
- if query is None:
- return []
-
symbols: list[Symbol] = []
seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes
- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ for capture_dict in matches:
def_nodes = capture_dict.get("symbol.def", [])
name_nodes = capture_dict.get("symbol.name", [])
params_nodes = capture_dict.get("symbol.params", [])
@@ -502,19 +504,15 @@ class ASTParser:
def _extract_imports(
self,
- tree: object,
- query: object,
+ matches: list[dict],
config: LanguageConfig,
file_info: FileInfo,
src: str,
) -> list[Import]:
- if query is None:
- return []
-
imports: list[Import] = []
seen_raws: set[str] = set()
- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ for capture_dict in matches:
stmt_nodes = capture_dict.get("import.statement", [])
module_nodes = capture_dict.get("import.module", [])
@@ -588,17 +586,13 @@ class ASTParser:
def _extract_calls(
self,
- tree: object,
- query: object,
+ matches: list[dict],
config: LanguageConfig,
file_info: FileInfo,
src: str,
symbols: list[Symbol],
) -> list[CallSite]:
"""Extract function/method call sites from the AST."""
- if query is None:
- return []
-
from .language_data import get_builtin_calls
_call_builtins = get_builtin_calls(file_info.language)
@@ -611,7 +605,7 @@ class ASTParser:
calls: list[CallSite] = []
seen: set[tuple[int, str, str | None]] = set()
- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ for capture_dict in matches:
site_nodes = capture_dict.get("call.site", [])
target_nodes = capture_dict.get("call.target", [])
arg_nodes = capture_dict.get("call.arguments", [])
@@ -676,8 +670,7 @@ class ASTParser:
def _extract_type_refs(
self,
- tree: object,
- query: object,
+ matches: list[dict],
src: str,
lang: str = "",
) -> list[TypeReference]:
@@ -697,15 +690,12 @@ class ASTParser:
``field_declaration`` → ``field_type``, ``composite_literal`` →
``composite_literal`` (Go).
"""
- if query is None:
- return []
-
head_of = TYPE_HEAD_EXTRACTORS.get(lang, _head_type_identifier)
refs: list[TypeReference] = []
seen: set[tuple[str, int]] = set()
- for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]
+ for capture_dict in matches:
type_nodes = capture_dict.get("param.type", [])
if not type_nodes:
continue
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
index 594db4d21..657e1ed8e 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -25,6 +25,7 @@ flattened to the first plausible source target. Packages without an
from __future__ import annotations
import json
+import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any
@@ -33,6 +34,81 @@ if TYPE_CHECKING:
from .context import ResolverContext
+# ---------------------------------------------------------------------------
+# Single pruned filesystem scan
+# ---------------------------------------------------------------------------
+# The mdx / vitest-config / package.json finders below all need to locate
+# files by name across the repo. Doing that with per-finder ``rglob`` calls
+# walked the ENTIRE tree (including node_modules, virtualenvs, .git) once
+# per pattern — 12+ full walks, measured at ~6 min on a medium repo with a
+# checked-in .venv. One ``os.walk`` with directory pruning, memoized on the
+# resolver context, replaces all of them.
+#
+# The prune list is deliberately narrow: vendored/derived trees that can
+# never contain *our* manifests or docs. ``.github`` and other dot-dirs that
+# may hold real package.json files (custom actions) are NOT pruned wholesale.
+_SCAN_PRUNE_DIRS: frozenset[str] = frozenset({
+ "node_modules",
+ ".git",
+ ".hg",
+ ".svn",
+ ".venv",
+ "venv",
+ ".tox",
+ "__pycache__",
+ ".repowise",
+ ".repowise.prebench-bak",
+ ".next",
+ ".nuxt",
+ ".turbo",
+ ".cache",
+ ".parcel-cache",
+ ".yarn",
+ ".pnpm-store",
+})
+
+_VITEST_CONFIG_NAMES: frozenset[str] = frozenset({
+ "vitest.config.ts", "vitest.config.js", "vitest.config.mts",
+ "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",
+ "vite.config.ts", "vite.config.js", "vite.config.mts",
+ "vite.config.mjs",
+})
+
+
+@dataclass
+class _RepoFileScan:
+ """File locations gathered by the single pruned walk."""
+
+ mdx_files: list[Path] = field(default_factory=list)
+ vitest_configs: list[Path] = field(default_factory=list)
+ package_jsons: list[Path] = field(default_factory=list)
+
+
+def _scan_repo_files(repo_path: Path) -> _RepoFileScan:
+ """One pruned ``os.walk`` collecting every finder's target files."""
+ scan = _RepoFileScan()
+ for dirpath, dirnames, filenames in os.walk(repo_path):
+ dirnames[:] = [d for d in dirnames if d not in _SCAN_PRUNE_DIRS]
+ for fname in filenames:
+ if fname.endswith(".mdx"):
+ scan.mdx_files.append(Path(dirpath) / fname)
+ elif fname in _VITEST_CONFIG_NAMES:
+ scan.vitest_configs.append(Path(dirpath) / fname)
+ elif fname == "package.json":
+ scan.package_jsons.append(Path(dirpath) / fname)
+ return scan
+
+
+def _get_repo_scan(ctx: "ResolverContext") -> _RepoFileScan:
+ """Memoized accessor — one walk per resolver context."""
+ cached = getattr(ctx, "_ts_repo_file_scan", None)
+ if cached is not None:
+ return cached
+ scan = _scan_repo_files(ctx.repo_path) if ctx.repo_path is not None else _RepoFileScan()
+ ctx._ts_repo_file_scan = scan # type: ignore[attr-defined]
+ return scan
+
+
# Order in which we collapse Node "conditional exports" objects down to
# a single target. Source-pointing conditions come first so a TS-aware
# static analyser sees the original ``.ts`` file rather than a built
@@ -453,7 +529,7 @@ def find_mdx_import_targets(ctx: "ResolverContext") -> set[str]:
from .typescript import resolve_ts_js_import
targets: set[str] = set()
- for mdx in ctx.repo_path.rglob("*.mdx"):
+ for mdx in _get_repo_scan(ctx).mdx_files:
try:
text = mdx.read_text(encoding="utf-8", errors="ignore")
except Exception:
@@ -537,34 +613,25 @@ def find_vitest_include_targets(ctx: "ResolverContext") -> set[str]:
return set()
targets: set[str] = set()
- config_globs = ("vitest.config.ts", "vitest.config.js", "vitest.config.mts",
- "vitest.config.mjs", "vitest.config.cjs", "vitest.config.cts",
- "vite.config.ts", "vite.config.js", "vite.config.mts",
- "vite.config.mjs")
- seen: set[Path] = set()
- for pattern in config_globs:
- for cfg in ctx.repo_path.rglob(pattern):
- if cfg in seen:
- continue
- seen.add(cfg)
- try:
- text = cfg.read_text(encoding="utf-8", errors="ignore")
- except Exception:
- continue
- cfg_dir = cfg.parent
- for inc_match in _VITEST_INCLUDE_RE.finditer(text):
- for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):
- glob_pat = str_match.group(1)
- # Resolve glob relative to the config file's directory.
- base = (cfg_dir / glob_pat).as_posix()
- try:
- rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()
- except ValueError:
- continue
- regex = _vitest_glob_to_regex(rel_glob)
- for candidate in ctx.path_set:
- if regex.match(candidate):
- targets.add(candidate)
+ for cfg in _get_repo_scan(ctx).vitest_configs:
+ try:
+ text = cfg.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ continue
+ cfg_dir = cfg.parent
+ for inc_match in _VITEST_INCLUDE_RE.finditer(text):
+ for str_match in _VITEST_STRING_RE.finditer(inc_match.group(1)):
+ glob_pat = str_match.group(1)
+ # Resolve glob relative to the config file's directory.
+ base = (cfg_dir / glob_pat).as_posix()
+ try:
+ rel_glob = Path(base).relative_to(ctx.repo_path).as_posix()
+ except ValueError:
+ continue
+ regex = _vitest_glob_to_regex(rel_glob)
+ for candidate in ctx.path_set:
+ if regex.match(candidate):
+ targets.add(candidate)
return targets
@@ -640,7 +707,10 @@ def find_npm_script_entry_targets(ctx: "ResolverContext") -> set[str]:
if ctx.repo_path is None:
return set()
- repo_root = ctx.repo_path.resolve()
+ # NOTE: not .resolve()d — the shared scan walks ctx.repo_path as given,
+ # so relative_to() below must use the same base or it silently drops
+ # every manifest.
+ repo_root = ctx.repo_path
path_set = ctx.path_set
targets: set[str] = set()
@@ -656,10 +726,8 @@ def find_npm_script_entry_targets(ctx: "ResolverContext") -> set[str]:
dirs_in_repo.setdefault(p[:slash], []).append(p)
idx = slash + 1
- for pkg_file in repo_root.rglob("package.json"):
- # Skip node_modules — those are dependency manifests, not ours.
- if "node_modules" in pkg_file.parts:
- continue
+ for pkg_file in _get_repo_scan(ctx).package_jsons:
+ # node_modules manifests are already pruned by the shared scan.
try:
data = json.loads(pkg_file.read_text(encoding="utf-8", errors="ignore"))
except Exception:
diff --git a/packages/core/src/repowise/core/persistence/crud/_shared.py b/packages/core/src/repowise/core/persistence/crud/_shared.py
index 617afcfe3..0e2911910 100644
--- a/packages/core/src/repowise/core/persistence/crud/_shared.py
+++ b/packages/core/src/repowise/core/persistence/crud/_shared.py
@@ -1,8 +1,9 @@
"""Shared internals for the ``crud`` package.
Holds the datetime parser, batch-size constant, the job-status whitelist, and
-the generic SELECT-then-INSERT/UPDATE loop (:func:`_batch_upsert`) that the
-per-domain batch upserts delegate to. Private to the package.
+the generic keyed SELECT-once-then-INSERT/UPDATE loop
+(:func:`_batch_upsert_keyed`) that the per-domain batch upserts delegate to.
+Private to the package.
"""
from __future__ import annotations
@@ -28,39 +29,53 @@ def _parse_dt(ts: str) -> datetime:
return dt
-async def _batch_upsert(
+async def _batch_upsert_keyed(
session: AsyncSession,
model: type[Any],
items: Iterable[Any],
*,
- key_fn: Callable[[Any], tuple[Any, ...]],
+ prefilter: tuple[Any, ...],
+ item_key_fn: Callable[[Any], Any],
+ row_key_fn: Callable[[Any], Any],
update_fn: Callable[[Any, Any], None],
insert_fn: Callable[[Any], Any],
batch_size: int | None = None,
) -> None:
- """Generic SELECT-then-INSERT/UPDATE loop shared by the batch upserts.
+ """Generic batch upsert with ONE existence query for the whole batch.
- For each item, look up the existing row with the filter expressions from
- ``key_fn(item)``; if found, mutate it via ``update_fn(existing, item)``,
- otherwise ``session.add(insert_fn(item))``.
+ The previous generic loop issued a SELECT round-trip per item; on bulk writes
+ (graph nodes/edges, symbols, git metadata) that is 10k-30k SELECTs per
+ persist and dominated the whole persist step (measured: 9.3s for a
+ 13k-node ``persist_graph_nodes``). Here all candidate rows matching
+ *prefilter* (typically ``repository_id == X``) are fetched once and
+ matched in memory: ``item_key_fn(item)`` must equal ``row_key_fn(row)``
+ exactly when the legacy ``key_fn`` filter would have found that row.
- Flushes once after the whole sequence, or once per ``batch_size`` chunk when
- *batch_size* is given (matching the SELECT-then-write semantics the callers
- relied on before this was extracted — including no flush at all on an empty
- batched sequence).
+ Within-batch duplicate keys keep the legacy outcome: the first item
+ inserts, later ones update the pending object (the per-item SELECT used
+ to see the autoflushed insert).
"""
+ materialized = list(items)
+ if not materialized:
+ if batch_size is None:
+ await session.flush()
+ return
+
+ existing_rows = (await session.execute(select(model).where(*prefilter))).scalars().all()
+ by_key: dict[Any, Any] = {row_key_fn(row): row for row in existing_rows}
+
if batch_size is None:
- chunks: list[list[Any]] = [list(items)]
+ chunks: list[list[Any]] = [materialized]
else:
- materialized = list(items)
chunks = [materialized[i : i + batch_size] for i in range(0, len(materialized), batch_size)]
for chunk in chunks:
for item in chunk:
- existing = (
- await session.execute(select(model).where(*key_fn(item)))
- ).scalar_one_or_none()
+ key = item_key_fn(item)
+ existing = by_key.get(key)
if existing is not None:
update_fn(existing, item)
else:
- session.add(insert_fn(item))
+ obj = insert_fn(item)
+ session.add(obj)
+ by_key[key] = obj
await session.flush()
diff --git a/packages/core/src/repowise/core/persistence/crud/external_systems.py b/packages/core/src/repowise/core/persistence/crud/external_systems.py
index 97107fda7..5766e39ea 100644
--- a/packages/core/src/repowise/core/persistence/crud/external_systems.py
+++ b/packages/core/src/repowise/core/persistence/crud/external_systems.py
@@ -18,7 +18,7 @@ from ..models import (
_new_uuid,
_now_utc,
)
-from ._shared import _batch_upsert
+from ._shared import _batch_upsert_keyed
# ---------------------------------------------------------------------------
# ExternalSystem CRUD
@@ -153,14 +153,13 @@ async def batch_upsert_symbols(
Accepts ingestion.models.Symbol dataclass instances (duck-typed).
"""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
WikiSymbol,
symbols,
- key_fn=lambda sym: (
- WikiSymbol.repository_id == repository_id,
- WikiSymbol.symbol_id == _symbol_id(sym),
- ),
+ prefilter=(WikiSymbol.repository_id == repository_id,),
+ item_key_fn=_symbol_id,
+ row_key_fn=lambda row: row.symbol_id,
update_fn=_update_wiki_symbol,
insert_fn=lambda sym: WikiSymbol(
id=_new_uuid(),
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index dc2ef0206..04877177b 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -16,7 +16,7 @@ from ..models import (
_new_uuid,
_now_utc,
)
-from ._shared import _BATCH_SIZE, _batch_upsert
+from ._shared import _BATCH_SIZE, _batch_upsert_keyed
# ---------------------------------------------------------------------------
# GitMetadata CRUD
@@ -106,14 +106,13 @@ async def upsert_git_metadata_bulk(
metadata_list: list[dict],
) -> None:
"""Bulk upsert git metadata rows in batches."""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GitMetadata,
metadata_list,
- key_fn=lambda meta: (
- GitMetadata.repository_id == repository_id,
- GitMetadata.file_path == meta.get("file_path", ""),
- ),
+ prefilter=(GitMetadata.repository_id == repository_id,),
+ item_key_fn=lambda meta: meta.get("file_path", ""),
+ row_key_fn=lambda row: row.file_path,
update_fn=_update_git_metadata,
insert_fn=lambda meta: GitMetadata(
id=_new_uuid(),
@@ -219,14 +218,13 @@ async def upsert_git_commits_bulk(
commit_rows: list[dict],
) -> None:
"""Bulk upsert per-commit rows (keyed on ``repository_id`` + ``sha``)."""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GitCommit,
commit_rows,
- key_fn=lambda row: (
- GitCommit.repository_id == repository_id,
- GitCommit.sha == row.get("sha", ""),
- ),
+ prefilter=(GitCommit.repository_id == repository_id,),
+ item_key_fn=lambda row: row.get("sha", ""),
+ row_key_fn=lambda row: row.sha,
update_fn=_update_git_commit,
insert_fn=lambda row: GitCommit(
id=_new_uuid(),
@@ -338,14 +336,13 @@ async def upsert_git_function_blame_bulk(
rows: list[dict],
) -> None:
"""Bulk upsert per-function blame rows (keyed ``repository_id`` + ``symbol_id``)."""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GitFunctionBlame,
rows,
- key_fn=lambda row: (
- GitFunctionBlame.repository_id == repository_id,
- GitFunctionBlame.symbol_id == row.get("symbol_id", ""),
- ),
+ prefilter=(GitFunctionBlame.repository_id == repository_id,),
+ item_key_fn=lambda row: row.get("symbol_id", ""),
+ row_key_fn=lambda row: row.symbol_id,
update_fn=_update_git_function_blame,
insert_fn=lambda row: GitFunctionBlame(
id=_new_uuid(),
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index 977d429a7..3ded527e9 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -17,7 +17,7 @@ from ..models import (
GraphNode,
_new_uuid,
)
-from ._shared import _BATCH_SIZE, _batch_upsert
+from ._shared import _BATCH_SIZE, _batch_upsert_keyed
# ---------------------------------------------------------------------------
# Graph CRUD (batch)
@@ -59,14 +59,13 @@ async def batch_upsert_graph_nodes(
Uses SELECT-then-INSERT/UPDATE for dialect portability.
"""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GraphNode,
nodes,
- key_fn=lambda n: (
- GraphNode.repository_id == repository_id,
- GraphNode.node_id == n.get("node_id", ""),
- ),
+ prefilter=(GraphNode.repository_id == repository_id,),
+ item_key_fn=lambda n: n.get("node_id", ""),
+ row_key_fn=lambda row: row.node_id,
update_fn=_update_graph_node,
insert_fn=lambda n: GraphNode(
id=_new_uuid(),
@@ -89,16 +88,17 @@ async def batch_upsert_graph_edges(
The unique constraint is (repository_id, source, target, edge_type),
allowing multiple edge types between the same pair of nodes.
"""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GraphEdge,
edges,
- key_fn=lambda e: (
- GraphEdge.repository_id == repository_id,
- GraphEdge.source_node_id == e.get("source_node_id", ""),
- GraphEdge.target_node_id == e.get("target_node_id", ""),
- GraphEdge.edge_type == e.get("edge_type", "imports"),
+ prefilter=(GraphEdge.repository_id == repository_id,),
+ item_key_fn=lambda e: (
+ e.get("source_node_id", ""),
+ e.get("target_node_id", ""),
+ e.get("edge_type", "imports"),
),
+ row_key_fn=lambda row: (row.source_node_id, row.target_node_id, row.edge_type),
update_fn=_update_graph_edge,
insert_fn=lambda e: GraphEdge(
id=_new_uuid(),
@@ -125,14 +125,13 @@ async def batch_upsert_graph_metrics(
``GraphBuilder.load_metrics_from_sql`` on large repos. SELECT-then-write
for dialect portability (SQLite + Postgres).
"""
- await _batch_upsert(
+ await _batch_upsert_keyed(
session,
GraphMetric,
list(metrics.items()),
- key_fn=lambda kv: (
- GraphMetric.repository_id == repository_id,
- GraphMetric.node_id == kv[0],
- ),
+ prefilter=(GraphMetric.repository_id == repository_id,),
+ item_key_fn=lambda kv: kv[0],
+ row_key_fn=lambda row: row.node_id,
update_fn=lambda existing, kv: _update_graph_metric(existing, kv[1]),
insert_fn=lambda kv: GraphMetric(
id=_new_uuid(),
diff --git a/packages/core/src/repowise/core/persistence/vector_store/_base.py b/packages/core/src/repowise/core/persistence/vector_store/_base.py
index 95507eb2c..e5d1d970b 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/_base.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/_base.py
@@ -52,6 +52,28 @@ class VectorStore(ABC):
"""Embed *query* and return the *limit* nearest pages."""
...
+ async def search_many(
+ self, queries: list[str], limit: int = 10
+ ) -> list[list[SearchResult]]:
+ """Batch variant of :meth:`search` — one result list per query, aligned
+ by index.
+
+ The default implementation fires the per-query searches concurrently
+ via ``asyncio.gather``; a failed query yields an empty list (matching
+ the caller-side behaviour of swallowing a single failed search).
+ Backends override this to embed *all* queries in a single embedder
+ call — the network round-trip dominates each search, so batching the
+ embedding turns N round-trips into 1.
+ """
+ import asyncio as _asyncio
+
+ if not queries:
+ return []
+ results = await _asyncio.gather(
+ *(self.search(q, limit=limit) for q in queries), return_exceptions=True
+ )
+ return [r if isinstance(r, list) else [] for r in results]
+
@abstractmethod
async def delete(self, page_id: str) -> None:
"""Remove the vector for *page_id* from the store."""
diff --git a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
index b97e04633..02188d188 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
@@ -34,12 +34,7 @@ class InMemoryVectorStore(VectorStore):
for (page_id, _text, metadata), vector in zip(items, vectors, strict=True):
self._store[page_id] = (vector, dict(metadata))
- async def search(self, query: str, limit: int = 10) -> list[SearchResult]:
- if not self._store:
- return []
- q_vecs = await self._embedder.embed([query])
- q_vec = q_vecs[0]
-
+ def _search_by_vector(self, q_vec: list[float], limit: int) -> list[SearchResult]:
scored: list[tuple[float, str, dict]] = []
for pid, (vec, meta) in self._store.items():
score = cosine_similarity(q_vec, vec)
@@ -63,6 +58,23 @@ class InMemoryVectorStore(VectorStore):
)
return results
+ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:
+ if not self._store:
+ return []
+ q_vecs = await self._embedder.embed([query])
+ return self._search_by_vector(q_vecs[0], limit)
+
+ async def search_many(
+ self, queries: list[str], limit: int = 10
+ ) -> list[list[SearchResult]]:
+ """One embedder call for all queries, then local scoring per query."""
+ if not queries:
+ return []
+ if not self._store:
+ return [[] for _ in queries]
+ q_vecs = await self._embedder.embed(list(queries))
+ return [self._search_by_vector(q_vec, limit) for q_vec in q_vecs]
+
async def delete(self, page_id: str) -> None:
self._store.pop(page_id, None)
diff --git a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
index 84f1f415f..4d521c1ba 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
@@ -10,6 +10,17 @@ from ._base import VectorStore
__all__ = ["LanceDBVectorStore"]
+def _paths_in_filter(paths: list[str]) -> str:
+ """Build an SQL-injection-safe ``target_path IN (...)`` LanceDB filter.
+
+ LanceDB's ``.where()`` takes a DataFusion SQL string with no bind
+ parameters, so each path is quoted with the same quote-doubling escape
+ the single-path lookup uses.
+ """
+ quoted = ", ".join("'" + p.replace("'", "''") + "'" for p in paths)
+ return f"target_path IN ({quoted})"
+
+
class LanceDBVectorStore(VectorStore):
"""Vector store backed by LanceDB (embedded, local file storage).
@@ -154,14 +165,7 @@ class LanceDBVectorStore(VectorStore):
]
await self._upsert_rows(rows)
- async def search(self, query: str, limit: int = 10) -> list[SearchResult]:
- await self._ensure_connected()
- if self._table is None:
- return []
-
- q_vecs = await self._embedder.embed([query])
- q_vec = [float(v) for v in q_vecs[0]]
-
+ async def _search_by_vector(self, q_vec: list[float], limit: int) -> list[SearchResult]:
# Query with explicit cosine distance so ``_distance`` is a cosine
# distance (1 - cos); we return ``1 - _distance`` = cosine similarity.
# This makes the score semantics match the other backends
@@ -185,6 +189,32 @@ class LanceDBVectorStore(VectorStore):
for r in raw
]
+ async def search(self, query: str, limit: int = 10) -> list[SearchResult]:
+ await self._ensure_connected()
+ if self._table is None:
+ return []
+
+ q_vecs = await self._embedder.embed([query])
+ return await self._search_by_vector([float(v) for v in q_vecs[0]], limit)
+
+ async def search_many(
+ self, queries: list[str], limit: int = 10
+ ) -> list[list[SearchResult]]:
+ """One embedder call for all queries; the vector lookups are local."""
+ if not queries:
+ return []
+ await self._ensure_connected()
+ if self._table is None:
+ return [[] for _ in queries]
+ q_vecs = await self._embedder.embed(list(queries))
+ out: list[list[SearchResult]] = []
+ for q_vec in q_vecs:
+ try:
+ out.append(await self._search_by_vector([float(v) for v in q_vec], limit))
+ except Exception:
+ out.append([])
+ return out
+
async def delete(self, page_id: str) -> None:
await self._ensure_connected()
if self._table is not None:
@@ -230,3 +260,35 @@ class LanceDBVectorStore(VectorStore):
summary = rows[0].get("content_snippet") or ""
return {"summary": str(summary), "key_exports": []}
+
+ async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:
+ """One ``IN``-filtered scan instead of one filtered query per path.
+
+ Mirrors the single-path semantics (first row per path wins, empty
+ summaries dropped, ``key_exports`` not stored in this schema).
+ """
+ if not paths:
+ return {}
+ await self._ensure_connected()
+ if self._table is None:
+ return {}
+
+ try:
+ rows = (
+ await self._table.query() # type: ignore[union-attr]
+ .where(_paths_in_filter(paths))
+ .select(["target_path", "content_snippet"])
+ .to_list()
+ )
+ except Exception:
+ return {}
+
+ out: dict[str, dict] = {}
+ for r in rows:
+ tp = str(r.get("target_path") or "")
+ if not tp or tp in out:
+ continue
+ summary = r.get("content_snippet") or ""
+ if summary:
+ out[tp] = {"summary": str(summary), "key_exports": []}
+ return out
diff --git a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
index 4a5f7f40e..8c441ed39 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
@@ -20,6 +20,23 @@ def _encode(vector: list[float]) -> str:
return "[" + ",".join(str(v) for v in vector) + "]"
+def _summary_payload(content: object, metadata: object) -> dict:
+ """Build the ``{'summary', 'key_exports'}`` payload from a wiki_pages row."""
+ key_exports: list[str] = []
+ if metadata and isinstance(metadata, dict):
+ key_exports = list(metadata.get("exports", []))
+ elif metadata and isinstance(metadata, str):
+ import json
+
+ try:
+ meta = json.loads(metadata)
+ key_exports = list(meta.get("exports", []))
+ except (json.JSONDecodeError, AttributeError):
+ pass
+
+ return {"summary": str(content or "")[:500], "key_exports": key_exports}
+
+
class PgVectorStore(VectorStore):
"""Vector store that writes embeddings to the ``wiki_pages.embedding`` column.
@@ -71,8 +88,9 @@ class PgVectorStore(VectorStore):
"UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid"
)
async with self._session_factory() as session:
- for p in params:
- await session.execute(stmt, p)
+ # executemany: one driver round-trip batch instead of one UPDATE
+ # round-trip per row.
+ await session.execute(stmt, params)
await session.commit()
async def search(self, query: str, limit: int = 10) -> list[SearchResult]:
@@ -108,6 +126,51 @@ class PgVectorStore(VectorStore):
for r in raw
]
+ async def search_many(
+ self, queries: list[str], limit: int = 10
+ ) -> list[list[SearchResult]]:
+ """One embedder call for all queries; per-query SELECTs share a session."""
+ if not queries:
+ return []
+ q_vecs = await self._embedder.embed(list(queries))
+
+ from sqlalchemy.sql import text as sa_text
+
+ stmt = sa_text(
+ "SELECT id, title, content, page_type, target_path, "
+ " 1 - (embedding <=> CAST(:q AS vector)) AS score "
+ "FROM wiki_pages "
+ "WHERE embedding IS NOT NULL "
+ "ORDER BY embedding <=> CAST(:q AS vector) "
+ "LIMIT :lim"
+ )
+ out: list[list[SearchResult]] = []
+ async with self._session_factory() as session:
+ for q_vec in q_vecs:
+ try:
+ rows = await session.execute(
+ stmt, {"q": _encode(q_vec), "lim": limit}
+ )
+ raw = rows.fetchall()
+ except Exception:
+ out.append([])
+ continue
+ out.append(
+ [
+ SearchResult(
+ page_id=r[0],
+ title=r[1],
+ page_type=r[3],
+ target_path=r[4],
+ score=float(r[5]),
+ snippet=str(r[2])[:200].rstrip(),
+ search_type="vector",
+ )
+ for r in raw
+ ]
+ )
+ return out
+
async def delete(self, page_id: str) -> None:
from sqlalchemy.sql import text as sa_text
@@ -153,17 +216,36 @@ class PgVectorStore(VectorStore):
if row is None:
return None
- content = str(row[0] or "")[:500]
- key_exports: list[str] = []
- if row[1] and isinstance(row[1], dict):
- key_exports = list(row[1].get("exports", []))
- elif row[1] and isinstance(row[1], str):
- import json
+ return _summary_payload(row[0], row[1])
+
+ async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:
+ """One ``IN``-filtered SELECT instead of one query per path.
+
+ Like the single-path variant (``LIMIT 1`` with no ``ORDER BY``), when
+ several pages share a ``target_path`` an arbitrary one wins — here the
+ first row returned per path.
+ """
+ if not paths:
+ return {}
+
+ from sqlalchemy import bindparam
+ from sqlalchemy.sql import text as sa_text
+
+ stmt = sa_text(
+ "SELECT target_path, content, metadata FROM wiki_pages "
+ "WHERE target_path IN :paths"
+ ).bindparams(bindparam("paths", expanding=True))
- try:
- meta = json.loads(row[1])
- key_exports = list(meta.get("exports", []))
- except (json.JSONDecodeError, AttributeError):
- pass
+ async with self._session_factory() as session:
+ rows = await session.execute(stmt, {"paths": list(paths)})
+ raw = rows.fetchall()
- return {"summary": content, "key_exports": key_exports}
+ out: dict[str, dict] = {}
+ for r in raw:
+ tp = str(r[0])
+ if tp in out:
+ continue
+ payload = _summary_payload(r[1], r[2])
+ if payload.get("summary"):
+ out[tp] = payload
+ return out
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 8a0997665..5e07fcaa3 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -106,6 +106,7 @@ async def _run_health_analysis(
git_meta_map=git_meta_map,
parsed_files=parsed_files,
module_map=module_map,
+ duplication_cache_dir=(repo_path / ".repowise") if repo_path is not None else None,
)
# Load per-file override rules from `.repowise/health-rules.json`.
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index 693acf598..c6191932d 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -85,6 +85,34 @@ def _parse_one(path_and_fi_and_bytes: tuple) -> Any:
return (fi.abs_path, str(exc))
+def _read_sources(
+ file_infos: list[Any],
+ progress: ProgressCallback | None,
+) -> list[tuple]:
+ """Read source bytes for *file_infos* with a thread pool (I/O-bound).
+
+ Returns ``(FileInfo, bytes)`` tuples in the same order as the input —
+ the parse aggregation loop indexes positionally. Files that fail to
+ read are dropped, ticking the parse bar once each (matching the old
+ sequential loop's behavior).
+ """
+
+ def _read_one(fi: Any) -> tuple | None:
+ try:
+ return (fi, Path(fi.abs_path).read_bytes())
+ except Exception:
+ if progress:
+ progress.on_item_done("parse")
+ return None
+
+ if not file_infos:
+ return []
+ workers = min(32, max(4, (os.cpu_count() or 4) * 2))
+ with ThreadPoolExecutor(max_workers=workers) as pool:
+ results = list(pool.map(_read_one, file_infos))
+ return [r for r in results if r is not None]
+
+
async def _run_ingestion(
repo_path: Path,
*,
@@ -156,16 +184,9 @@ async def _run_ingestion(
if progress:
progress.on_phase_start("parse", len(file_infos))
- # Read source bytes up front (I/O, sequential — fast enough; keeps worker
+ # Read source bytes up front in a thread pool (I/O-bound; keeps worker
# args small: FileInfo + bytes, both picklable plain dataclasses/bytes).
- fi_and_bytes: list[tuple] = []
- for fi in file_infos:
- try:
- source = Path(fi.abs_path).read_bytes()
- fi_and_bytes.append((fi, source))
- except Exception:
- if progress:
- progress.on_item_done("parse")
+ fi_and_bytes: list[tuple] = _read_sources(file_infos, progress)
parsed_files: list[Any] = []
source_map: dict[str, bytes] = {}
@@ -434,14 +455,7 @@ async def reparse_for_resume(
if progress:
progress.on_phase_start("parse", len(file_infos))
- fi_and_bytes: list[tuple] = []
- for fi in file_infos:
- try:
- source = Path(fi.abs_path).read_bytes()
- fi_and_bytes.append((fi, source))
- except Exception:
- if progress:
- progress.on_item_done("parse")
+ fi_and_bytes: list[tuple] = _read_sources(file_infos, progress)
parsed_files: list[Any] = []
source_map: dict[str, bytes] = {}
diff --git a/tests/unit/dead_code/test_never_flag_regex.py b/tests/unit/dead_code/test_never_flag_regex.py
new file mode 100644
index 000000000..b1ec18468
--- /dev/null
+++ b/tests/unit/dead_code/test_never_flag_regex.py
@@ -0,0 +1,96 @@
+"""The compiled never-flag regex must be glob-for-glob equivalent to fnmatch."""
+
+from __future__ import annotations
+
+import fnmatch
+import os
+
+import networkx as nx
+import pytest
+
+from repowise.core.analysis.dead_code.analyzer import (
+ DeadCodeAnalyzer,
+ _never_flag_regex,
+)
+from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+
+# Positives derived from the glob list plus negatives that brush close to it.
+_PROBE_PATHS = [
+ "pkg/__init__.py",
+ "src/app/__main__.py",
+ "tests/conftest.py",
+ "alembic/env.py",
+ "backend/alembic/versions/0042_add_users.py",
+ "manage.py",
+ "site/wsgi.py",
+ "api/asgi.py",
+ "app/migrations/0001_initial.py",
+ "db/schema.sql",
+ "scripts/seed_users.py",
+ "types/global.d.ts",
+ "setup.py",
+ "setup.cfg",
+ "next.config.mjs",
+ "apps/web/vite.config.ts",
+ "tailwind.config.js",
+ "postcss.config.cjs",
+ "jest.config.ts",
+ "vitest.config.mts",
+ "app/dashboard/page.tsx",
+ "app/dashboard/layout.ts",
+ "app/api/users/route.ts",
+ "app/loading.tsx",
+ "app/error.tsx",
+ "app/not-found.tsx",
+ # Negatives — close but should NOT match.
+ "src/pages.py",
+ "core/router.py",
+ "lib/pagination.tsx",
+ "app/page_helpers.ts",
+ "frontend/layouts.css",
+ "packages/core/src/engine.py",
+ "tools/configure.py",
+ "src/seedling_data.txt", # *seed* glob actually matches this — keep parity either way
+ "docs/setup.md",
+]
+
+
+def _fnmatch_any(path: str) -> bool:
+ return any(fnmatch.fnmatch(path, pat) for pat in _NEVER_FLAG_PATTERNS)
+
+
+class TestRegexEquivalence:
+ @pytest.mark.parametrize("path", _PROBE_PATHS)
+ def test_probe_paths_match_fnmatch(self, path):
+ regex = _never_flag_regex(_NEVER_FLAG_PATTERNS)
+ assert bool(regex.match(os.path.normcase(path))) == _fnmatch_any(path), path
+
+ def test_every_pattern_has_a_matching_path(self):
+ """Synthesize a concrete path per glob and assert both sides agree."""
+ regex = _never_flag_regex(_NEVER_FLAG_PATTERNS)
+ for pat in _NEVER_FLAG_PATTERNS:
+ concrete = pat.replace("*", "x")
+ assert bool(regex.match(os.path.normcase(concrete))) == _fnmatch_any(concrete), pat
+
+
+class TestShouldNeverFlag:
+ def _analyzer(self) -> DeadCodeAnalyzer:
+ return DeadCodeAnalyzer(nx.DiGraph(), {})
+
+ def test_whitelist_takes_priority(self):
+ assert self._analyzer()._should_never_flag("anything.py", {"anything.py"})
+
+ def test_glob_hit(self):
+ assert self._analyzer()._should_never_flag("app/dashboard/page.tsx", set())
+
+ def test_glob_miss(self):
+ assert not self._analyzer()._should_never_flag("core/router.py", set())
+
+ def test_workspace_never_flag_node_attr(self):
+ g = nx.DiGraph()
+ g.add_node("bench/jmh_runner.java", is_never_flag=True)
+ analyzer = DeadCodeAnalyzer(g, {})
+ assert analyzer._should_never_flag("bench/jmh_runner.java", set())
+
+ def test_init_py_barrel(self):
+ assert self._analyzer()._should_never_flag("pkg/sub/__init__.py", set())
diff --git a/tests/unit/generation/test_rag_prefetch.py b/tests/unit/generation/test_rag_prefetch.py
new file mode 100644
index 000000000..b286bd732
--- /dev/null
+++ b/tests/unit/generation/test_rag_prefetch.py
@@ -0,0 +1,230 @@
+"""Batched RAG prefetch for level-2 file pages.
+
+The level-2 builder resolves RAG context for every tier-1 page in ONE
+``search_many`` call before the level starts (one embedder round-trip
+instead of one per page, outside the LLM semaphore). The per-page search
+in ``_generate_file_page_from_ctx`` is skipped when prefetch succeeded and
+must still run as the fallback when it didn't.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.generation.context_assembler import ContextAssembler
+from repowise.core.generation.models import GenerationConfig
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.generation.page_generator.levels import _prefetch_rag_context
+from repowise.core.persistence.search import SearchResult
+from repowise.core.persistence.vector_store import InMemoryVectorStore, VectorStore
+from repowise.core.providers.embedding.base import MockEmbedder
+from repowise.core.providers.llm.mock import MockProvider
+
+from .conftest import _make_file_info, _make_symbol
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _result(page_id: str) -> SearchResult:
+ return SearchResult(
+ page_id=page_id,
+ title="t",
+ page_type="file_page",
+ target_path=page_id.split(":", 1)[-1],
+ score=0.9,
+ snippet=f"snippet for {page_id}",
+ search_type="vector",
+ )
+
+
+class _SpyStore(VectorStore):
+ """Counts search/search_many/list_page_ids calls; canned results."""
+
+ def __init__(self, page_count: int = 50, fail_batch: bool = False) -> None:
+ self.search_calls: list[str] = []
+ self.search_many_calls: list[list[str]] = []
+ self.page_count = page_count
+ self.fail_batch = fail_batch
+
+ async def embed_and_upsert(self, page_id, text, metadata) -> None: # pragma: no cover
+ pass
+
+ async def search(self, query: str, limit: int = 10):
+ self.search_calls.append(query)
+ return [_result("file_page:other/file.py")]
+
+ async def search_many(self, queries, limit: int = 10):
+ if self.fail_batch:
+ raise RuntimeError("batch search down")
+ self.search_many_calls.append(list(queries))
+ return [[_result("file_page:other/file.py")] for _ in queries]
+
+ async def delete(self, page_id) -> None: # pragma: no cover
+ pass
+
+ async def close(self) -> None: # pragma: no cover
+ pass
+
+ async def list_page_ids(self) -> set[str]:
+ return {f"p{i}" for i in range(self.page_count)}
+
+
+class _CountingEmbedder(MockEmbedder):
+ def __init__(self) -> None:
+ super().__init__()
+ self.embed_calls: list[list[str]] = []
+
+ async def embed(self, texts):
+ self.embed_calls.append(list(texts))
+ return await super().embed(texts)
+
+
+def _parsed(path: str = "pkg/mod.py", exports: list[str] | None = None):
+ from repowise.core.ingestion.models import ParsedFile
+
+ return ParsedFile(
+ file_info=_make_file_info(path=path),
+ symbols=[_make_symbol(name="Thing", file_path=path)],
+ imports=[],
+ exports=exports if exports is not None else ["Thing"],
+ docstring="mod",
+ parse_errors=[],
+ content_hash="h",
+ )
+
+
+def _ctx_for(parsed):
+ config = GenerationConfig()
+ assembler = ContextAssembler(config)
+ import networkx as nx
+
+ g = nx.DiGraph()
+ g.add_node(parsed.file_info.path)
+ return assembler.assemble_file_page(parsed, g, {}, {}, {}, b"x = 1\n")
+
+
+def _run_obj(store, **config_overrides):
+ config = GenerationConfig(**config_overrides)
+ return SimpleNamespace(vector_store=store, config=config)
+
+
+# ---------------------------------------------------------------------------
+# VectorStore.search_many
+# ---------------------------------------------------------------------------
+
+
+async def test_search_many_default_aligns_with_per_query_search() -> None:
+ embedder = _CountingEmbedder()
+ store = InMemoryVectorStore(embedder)
+ await store.embed_batch(
+ [
+ ("p1", "alpha beta", {"target_path": "a.py", "content": "alpha"}),
+ ("p2", "gamma delta", {"target_path": "b.py", "content": "gamma"}),
+ ]
+ )
+
+ singles = [await store.search(q, limit=2) for q in ("alpha", "gamma")]
+ batched = await store.search_many(["alpha", "gamma"], limit=2)
+
+ assert [[r.page_id for r in rs] for rs in batched] == [
+ [r.page_id for r in rs] for rs in singles
+ ]
+
+
+async def test_in_memory_search_many_embeds_once() -> None:
+ embedder = _CountingEmbedder()
+ store = InMemoryVectorStore(embedder)
+ await store.embed_batch([("p1", "alpha", {"target_path": "a.py"})])
+ embedder.embed_calls.clear()
+
+ await store.search_many(["q1", "q2", "q3"], limit=2)
+
+ assert len(embedder.embed_calls) == 1
+ assert embedder.embed_calls[0] == ["q1", "q2", "q3"]
+
+
+async def test_search_many_empty_queries() -> None:
+ store = InMemoryVectorStore(MockEmbedder())
+ assert await store.search_many([]) == []
+
+
+# ---------------------------------------------------------------------------
+# _prefetch_rag_context
+# ---------------------------------------------------------------------------
+
+
+async def test_prefetch_populates_rag_context_with_self_exclusion() -> None:
+ store = _SpyStore()
+ run = _run_obj(store)
+ parsed = _parsed("other/file.py") # search result IS this page → excluded
+ ctx = _ctx_for(parsed)
+ parsed2 = _parsed("pkg/two.py")
+ ctx2 = _ctx_for(parsed2)
+
+ ok = await _prefetch_rag_context(run, [(parsed, ctx), (parsed2, ctx2)])
+
+ assert ok is True
+ assert store.search_many_calls == [["Thing", "Thing"]]
+ assert ctx.rag_context == [] # self-hit filtered out
+ assert ctx2.rag_context == ["[file_page:other/file.py]\nsnippet for file_page:other/file.py"]
+
+
+async def test_prefetch_skips_when_store_below_min_size() -> None:
+ store = _SpyStore(page_count=3)
+ run = _run_obj(store, rag_min_store_size=10)
+ parsed = _parsed()
+ ctx = _ctx_for(parsed)
+
+ ok = await _prefetch_rag_context(run, [(parsed, ctx)])
+
+ assert ok is True # per-page gate would skip every search too
+ assert store.search_many_calls == []
+ assert ctx.rag_context == []
+
+
+async def test_prefetch_returns_false_without_store_or_on_batch_failure() -> None:
+ parsed = _parsed()
+ ctx = _ctx_for(parsed)
+
+ assert await _prefetch_rag_context(_run_obj(None), [(parsed, ctx)]) is False
+
+ failing = _SpyStore(fail_batch=True)
+ assert await _prefetch_rag_context(_run_obj(failing), [(parsed, ctx)]) is False
+ assert ctx.rag_context == []
+
+
+async def test_prefetch_disabled_flag_returns_false() -> None:
+ store = _SpyStore()
+ run = _run_obj(store, enable_rag_context=False)
+ parsed = _parsed()
+ ctx = _ctx_for(parsed)
+ assert await _prefetch_rag_context(run, [(parsed, ctx)]) is False
+ assert store.search_many_calls == []
+
+
+# ---------------------------------------------------------------------------
+# Per-page fallback in _generate_file_page_from_ctx
+# ---------------------------------------------------------------------------
+
+
+ ("rag_prefetched", "expected_searches"),
+ [(True, 0), (False, 1)],
+)
+async def test_per_page_search_skipped_iff_prefetched(
+ rag_prefetched: bool, expected_searches: int
+) -> None:
+ store = _SpyStore()
+ config = GenerationConfig()
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config, vector_store=store)
+ parsed = _parsed()
+ ctx = _ctx_for(parsed)
+
+ page = await gen._generate_file_page_from_ctx(parsed, ctx, rag_prefetched=rag_prefetched)
+
+ assert page.page_type == "file_page"
+ assert len(store.search_calls) == expected_searches
diff --git a/tests/unit/generation/test_symbol_index.py b/tests/unit/generation/test_symbol_index.py
new file mode 100644
index 000000000..ff4426be8
--- /dev/null
+++ b/tests/unit/generation/test_symbol_index.py
@@ -0,0 +1,95 @@
+"""Symbol-index equivalence: indexed call-graph/heritage extraction must be
+byte-identical to the historical full-node-scan path."""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.generation.context.graph_intelligence import (
+ build_symbol_index,
+ extract_call_graph,
+ extract_heritage,
+)
+
+
+def _mixed_graph() -> nx.DiGraph:
+ g = nx.DiGraph()
+ files = [f"pkg/f{i}.py" for i in range(6)]
+ for fp in files:
+ g.add_node(fp, language="python")
+ # Symbol nodes spread across files, with call + heritage edges.
+ for i, fp in enumerate(files):
+ for j in range(4):
+ g.add_node(
+ f"{fp}::sym{j}",
+ node_type="symbol",
+ file_path=fp,
+ name=f"sym{j}_{i}",
+ )
+ for i in range(5):
+ g.add_edge(
+ f"pkg/f{i}.py::sym0",
+ f"pkg/f{i + 1}.py::sym1",
+ edge_type="calls",
+ confidence=0.9,
+ )
+ g.add_edge(
+ f"pkg/f{i}.py::sym2",
+ f"pkg/f{i + 1}.py::sym3",
+ edge_type="extends",
+ )
+ # A non-call/heritage symbol edge and a file-level import edge (ignored).
+ g.add_edge("pkg/f0.py::sym1", "pkg/f2.py::sym0", edge_type="references")
+ g.add_edge("pkg/f0.py", "pkg/f1.py", imported_names=["x"])
+ return g
+
+
+def test_indexed_extraction_matches_scan() -> None:
+ g = _mixed_graph()
+ index = build_symbol_index(g)
+
+ for fp in [f"pkg/f{i}.py" for i in range(6)] + ["missing.py"]:
+ assert extract_call_graph(fp, g, index) == extract_call_graph(fp, g)
+ assert extract_heritage(fp, g, index) == extract_heritage(fp, g)
+
+
+def test_index_buckets_only_symbol_nodes() -> None:
+ g = _mixed_graph()
+ index = build_symbol_index(g)
+ assert set(index) == {f"pkg/f{i}.py" for i in range(6)}
+ assert all(len(nodes) == 4 for nodes in index.values())
+ # Bucket order matches graph node iteration order.
+ assert [n for n, _ in index["pkg/f0.py"]] == [
+ "pkg/f0.py::sym0",
+ "pkg/f0.py::sym1",
+ "pkg/f0.py::sym2",
+ "pkg/f0.py::sym3",
+ ]
+
+
+def test_assemble_file_page_identical_with_index() -> None:
+ from repowise.core.generation.context_assembler import ContextAssembler
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.ingestion.models import ParsedFile
+
+ from .conftest import _make_file_info, _make_symbol
+
+ g = _mixed_graph()
+ path = "pkg/f1.py"
+ parsed = ParsedFile(
+ file_info=_make_file_info(path=path),
+ symbols=[_make_symbol(name="sym0_1", file_path=path)],
+ imports=[],
+ exports=["sym0_1"],
+ docstring="d",
+ parse_errors=[],
+ content_hash="h",
+ )
+ assembler = ContextAssembler(GenerationConfig())
+ index = build_symbol_index(g)
+
+ plain = assembler.assemble_file_page(parsed, g, {}, {}, {}, b"x = 1\n")
+ indexed = assembler.assemble_file_page(
+ parsed, g, {}, {}, {}, b"x = 1\n", symbol_index=index
+ )
+ assert plain == indexed
diff --git a/tests/unit/health/test_duplication_cache.py b/tests/unit/health/test_duplication_cache.py
new file mode 100644
index 000000000..c1d950c3f
--- /dev/null
+++ b/tests/unit/health/test_duplication_cache.py
@@ -0,0 +1,115 @@
+"""Cached duplication runs must reproduce the uncached report exactly."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from repowise.core.analysis.health.duplication import detect_clones
+from repowise.core.analysis.health.duplication.token_cache import (
+ _CACHE_FILENAME,
+ DuplicationTokenCache,
+)
+
+
+def _pf(path: str, abs_path: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ file_info=SimpleNamespace(path=path, abs_path=abs_path, language="python"), symbols=[]
+ )
+
+
+_BODY = "\n".join(
+ [
+ "def doit(x, y, z):",
+ " if x:",
+ " a = x + y",
+ " else:",
+ " a = x - y",
+ " if z:",
+ " b = a * 2",
+ " else:",
+ " b = a - 1",
+ " return a + b + x + y + z",
+ "",
+ ]
+)
+
+
+def _setup(tmp_path: Path) -> list[SimpleNamespace]:
+ (tmp_path / "a.py").write_text(_BODY)
+ (tmp_path / "b.py").write_text(_BODY.replace("doit", "renamed"))
+ (tmp_path / "c.py").write_text("x = 1\n")
+ return [
+ _pf("a.py", str(tmp_path / "a.py")),
+ _pf("b.py", str(tmp_path / "b.py")),
+ _pf("c.py", str(tmp_path / "c.py")),
+ ]
+
+
+def _report_key(report):
+ return (
+ sorted(
+ (p.file_a, p.file_b, p.a_start_line, p.a_end_line, p.b_start_line, p.b_end_line)
+ for p in report.pairs
+ ),
+ report.duplication_pct,
+ )
+
+
+def test_cached_run_equals_uncached(tmp_path: Path):
+ parsed = _setup(tmp_path)
+ cache_dir = tmp_path / ".repowise"
+
+ baseline = detect_clones(parsed, window_tokens=20, min_lines=4)
+ first = detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+ assert (cache_dir / _CACHE_FILENAME).exists()
+ second = detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+
+ assert _report_key(first) == _report_key(baseline)
+ assert _report_key(second) == _report_key(baseline)
+
+
+def test_second_run_hits_cache_and_edit_misses(tmp_path: Path):
+ parsed = _setup(tmp_path)
+ cache_dir = tmp_path / ".repowise"
+ detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+
+ cache = DuplicationTokenCache(cache_dir, 20)
+ cache.load()
+ import hashlib
+
+ for pf in parsed:
+ digest = hashlib.sha256(Path(pf.file_info.abs_path).read_bytes()).hexdigest()
+ assert cache.get(digest) is not None
+
+ # Edit one file -> its hash misses; the others still hit.
+ (tmp_path / "a.py").write_text(_BODY.replace("doit", "changed"))
+ fresh = DuplicationTokenCache(cache_dir, 20)
+ fresh.load()
+ a_digest = hashlib.sha256((tmp_path / "a.py").read_bytes()).hexdigest()
+ assert fresh.get(a_digest) is None
+
+ # And the changed-file run still produces the right pairs.
+ report = detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+ assert any({p.file_a, p.file_b} == {"a.py", "b.py"} for p in report.pairs)
+
+
+def test_window_size_mismatch_invalidates(tmp_path: Path):
+ parsed = _setup(tmp_path)
+ cache_dir = tmp_path / ".repowise"
+ detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+
+ other = DuplicationTokenCache(cache_dir, 10)
+ other.load()
+ assert other._entries == {}
+
+
+def test_corrupt_cache_degrades_to_full_run(tmp_path: Path):
+ parsed = _setup(tmp_path)
+ cache_dir = tmp_path / ".repowise"
+ cache_dir.mkdir()
+ (cache_dir / _CACHE_FILENAME).write_bytes(b"not a pickle")
+
+ baseline = detect_clones(parsed, window_tokens=20, min_lines=4)
+ report = detect_clones(parsed, window_tokens=20, min_lines=4, cache_dir=cache_dir)
+ assert _report_key(report) == _report_key(baseline)
diff --git a/tests/unit/ingestion/test_git_update_equivalence.py b/tests/unit/ingestion/test_git_update_equivalence.py
new file mode 100644
index 000000000..bd3a908f0
--- /dev/null
+++ b/tests/unit/ingestion/test_git_update_equivalence.py
@@ -0,0 +1,133 @@
+"""Update-path git indexing must produce the same per-file metadata as init.
+
+``index_changed_files`` now reads from the same batched repo-wide commit
+index as ``index_repo`` (instead of one ``git log -- <file>`` per changed
+file), so an updated file's metadata — including the agent-provenance
+rollup, which the old per-file path never classified — must match what a
+fresh full index produces.
+"""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+# Fields produced by BOTH the full-index and changed-file paths. Excludes
+# full-index-only enrichment (co-change, entropy, percentiles, hotspot flags)
+# and the float temporal score (compared separately with a tolerance).
+_COMPARED_FIELDS = [
+ "commit_count_total",
+ "commit_count_90d",
+ "commit_count_30d",
+ "first_commit_at",
+ "last_commit_at",
+ "age_days",
+ "primary_owner_name",
+ "primary_owner_email",
+ "top_authors_json",
+ "significant_commits_json",
+ "commit_categories_json",
+ "lines_added_90d",
+ "lines_deleted_90d",
+ "contributor_count",
+ "bus_factor",
+ "prior_defect_count",
+ "agent_commit_count",
+ "agent_authored_pct",
+ "agent_tier_counts_json",
+]
+
+
+def _build_repo(tmp_path):
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ with repo.config_writer() as cw:
+ cw.set_value("user", "name", "Alice")
+ cw.set_value("user", "email", "[email protected]")
+
+ (tmp_path / "a.py").write_text("x = 1\n")
+ repo.index.add(["a.py"])
+ repo.index.commit("feat: add module a with the initial implementation")
+
+ (tmp_path / "b.py").write_text("y = 2\n")
+ repo.index.add(["b.py"])
+ repo.index.commit("feat: add module b for the second subsystem")
+
+ (tmp_path / "a.py").write_text("x = 1\nz = 3\n")
+ repo.index.add(["a.py"])
+ # Agent-attributed commit (co-author trailer channel).
+ repo.index.commit(
+ "fix: correct the boundary condition in module a\n\n"
+ "Co-Authored-By: Claude <[email protected]>"
+ )
+
+ (tmp_path / "b.py").write_text("y = 2\nw = 4\n")
+ repo.index.add(["b.py"])
+ repo.index.commit("fix: resolve crash in module b error handling")
+ repo.close()
+
+
+async def test_changed_file_metadata_matches_full_index(tmp_path) -> None:
+ _build_repo(tmp_path)
+
+ full = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
+ _summary, full_meta = await full.index_repo("repo1")
+ full_by_path = {m["file_path"]: m for m in full_meta}
+
+ upd = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
+ upd_meta = await upd.index_changed_files(["a.py", "b.py"])
+ upd_by_path = {m["file_path"]: m for m in upd_meta}
+
+ assert set(upd_by_path) == {"a.py", "b.py"}
+ for path in ("a.py", "b.py"):
+ for field in _COMPARED_FIELDS:
+ assert upd_by_path[path].get(field) == full_by_path[path].get(field), (
+ f"{path}: field {field!r} diverges between update and init"
+ )
+ assert upd_by_path[path]["temporal_hotspot_score"] == pytest.approx(
+ full_by_path[path]["temporal_hotspot_score"], rel=1e-3
+ )
+
+
+async def test_update_path_classifies_agent_provenance(tmp_path) -> None:
+ """Regression: the per-file fallback never classified provenance, so
+ updates silently zeroed a file's agent rollup."""
+ _build_repo(tmp_path)
+
+ upd = GitIndexer(tmp_path, tier=GitIndexTier.FULL)
+ upd_meta = await upd.index_changed_files(["a.py"])
+ (meta,) = upd_meta
+
+ assert meta["agent_commit_count"] == 1
+ assert meta["agent_authored_pct"] == pytest.approx(0.5)
+ assert meta["agent_tier_counts_json"] != "{}"
+
+
+def test_thread_repo_pool_reuses_per_thread_and_closes(tmp_path) -> None:
+ _build_repo(tmp_path)
+ indexer = GitIndexer(tmp_path)
+ get_repo, close_all = indexer._thread_repo_pool()
+
+ first = get_repo()
+ assert get_repo() is first # same thread → same handle
+
+ seen_other: list = []
+
+ def _worker() -> None:
+ seen_other.append(get_repo())
+
+ t = threading.Thread(target=_worker)
+ t.start()
+ t.join()
+ assert seen_other and seen_other[0] is not first # new thread → new handle
+
+ close_all()
+ # close() released the handles; a fresh pool hands out new ones.
+ get_repo2, close_all2 = indexer._thread_repo_pool()
+ assert get_repo2() is not first
+ close_all2()
diff --git a/tests/unit/ingestion/test_metrics_precompute.py b/tests/unit/ingestion/test_metrics_precompute.py
new file mode 100644
index 000000000..e716f739a
--- /dev/null
+++ b/tests/unit/ingestion/test_metrics_precompute.py
@@ -0,0 +1,69 @@
+"""compute_metrics_parallel() equivalence — the update path now pre-computes
+metrics with fan-out parallelism; values must match lazy computation."""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+
+def _parsed(tmp_path: Path, rel: str, content: str):
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content)
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language="python", # type: ignore[arg-type]
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return parse_file(fi, content.encode("utf-8"))
+
+
+_FILES = {
+ "a.py": "from b import helper\nfrom c import C\n\ndef run():\n return helper() + C().go()\n",
+ "b.py": "def helper():\n return 1\n",
+ "c.py": "from b import helper\n\nclass C:\n def go(self):\n return helper()\n",
+}
+
+
+def _build(tmp_path: Path) -> GraphBuilder:
+ gb = GraphBuilder(str(tmp_path))
+ for rel, content in _FILES.items():
+ gb.add_file(_parsed(tmp_path, rel, content))
+ gb.build()
+ return gb
+
+
+class TestMetricsPrecompute:
+ def test_parallel_matches_lazy(self, tmp_path: Path) -> None:
+ lazy = _build(tmp_path)
+ eager = _build(tmp_path)
+ asyncio.run(eager.compute_metrics_parallel())
+ # deterministic metrics must be identical
+ assert eager.pagerank() == lazy.pagerank()
+ assert eager.betweenness_centrality() == lazy.betweenness_centrality()
+ assert eager.symbol_pagerank() == lazy.symbol_pagerank()
+ assert eager.symbol_betweenness_centrality() == lazy.symbol_betweenness_centrality()
+
+ def test_caches_populated(self, tmp_path: Path) -> None:
+ gb = _build(tmp_path)
+ assert gb._pagerank_cache is None
+ asyncio.run(gb.compute_metrics_parallel())
+ assert gb._pagerank_cache is not None
+ assert gb._betweenness_cache is not None
+ assert gb._symbol_pagerank_cache is not None
+ assert gb._symbol_betweenness_cache is not None
+ assert gb._community_cache is not None
+ assert gb._symbol_community_cache is not None
diff --git a/tests/unit/ingestion/test_parallel_betweenness.py b/tests/unit/ingestion/test_parallel_betweenness.py
new file mode 100644
index 000000000..4d88e8375
--- /dev/null
+++ b/tests/unit/ingestion/test_parallel_betweenness.py
@@ -0,0 +1,93 @@
+"""Equivalence tests for the parallel exact betweenness kernel.
+
+The parallel path must reproduce ``nx.betweenness_centrality`` exactly
+(modulo float summation order, bounded well below 1e-9 relative).
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+
+from repowise.core.ingestion.graph import _betweenness as bw
+
+
+def _random_digraph(n: int, p: float, seed: int) -> nx.DiGraph:
+ g = nx.gnp_random_graph(n, p, seed=seed, directed=True)
+ # Relabel to strings to mirror real node ids (file paths / symbol ids).
+ return nx.relabel_nodes(g, {i: f"pkg/mod_{i}.py::sym_{i}" for i in g.nodes()})
+
+
+def _assert_close(ours: dict, theirs: dict) -> None:
+ assert set(ours) == set(theirs)
+ for node, expected in theirs.items():
+ assert ours[node] == pytest.approx(expected, rel=1e-9, abs=1e-12), node
+
+
+class TestSequentialFallback:
+ """Below the cost threshold the call must route to NetworkX directly."""
+
+ def test_small_graph_equals_networkx(self):
+ g = _random_digraph(60, 0.08, seed=1)
+ _assert_close(
+ bw.betweenness_centrality_fast(g, normalized=True),
+ nx.betweenness_centrality(g, normalized=True),
+ )
+
+ def test_empty_graph(self):
+ assert bw.betweenness_centrality_fast(nx.DiGraph()) == {}
+
+ def test_single_worker_stays_sequential(self, monkeypatch):
+ monkeypatch.setattr(bw, "_PARALLEL_COST_THRESHOLD", 0)
+ g = _random_digraph(40, 0.1, seed=2)
+ _assert_close(
+ bw.betweenness_centrality_fast(g, max_workers=1),
+ nx.betweenness_centrality(g, normalized=True),
+ )
+
+
+class TestParallelPath:
+ """Force the pool on small graphs and compare against NetworkX."""
+
+ @pytest.fixture()
+ def force_parallel(self, monkeypatch):
+ monkeypatch.setattr(bw, "_PARALLEL_COST_THRESHOLD", 0)
+
+ @pytest.mark.parametrize("seed", [3, 4])
+ def test_directed_equivalence(self, force_parallel, seed):
+ g = _random_digraph(80, 0.06, seed=seed)
+ ours = bw.betweenness_centrality_fast(g, normalized=True, max_workers=2)
+ _assert_close(ours, nx.betweenness_centrality(g, normalized=True))
+
+ def test_unnormalized_equivalence(self, force_parallel):
+ g = _random_digraph(70, 0.07, seed=5)
+ ours = bw.betweenness_centrality_fast(g, normalized=False, max_workers=2)
+ _assert_close(ours, nx.betweenness_centrality(g, normalized=False))
+
+ def test_disconnected_components_and_isolates(self, force_parallel):
+ g = _random_digraph(50, 0.05, seed=6)
+ g.add_nodes_from(["lonely.py", "isolated.py::sym"])
+ ours = bw.betweenness_centrality_fast(g, normalized=True, max_workers=2)
+ _assert_close(ours, nx.betweenness_centrality(g, normalized=True))
+ assert ours["lonely.py"] == 0.0
+
+
+class TestRescale:
+ """The inlined rescale must match NetworkX for our (k=None, no-endpoint) use."""
+
+ @pytest.mark.parametrize("normalized", [True, False])
+ @pytest.mark.parametrize("directed", [True, False])
+ def test_matches_networkx_rescale(self, normalized, directed):
+ from networkx.algorithms.centrality.betweenness import _rescale as nx_rescale
+
+ raw = {0: 4.0, 1: 0.0, 2: 7.5, 3: 1.25}
+ ours = bw._rescale(dict(raw), 10, normalized=normalized, directed=directed)
+ theirs = nx_rescale(
+ dict(raw), 10, normalized=normalized, directed=directed, endpoints=False
+ )
+ assert ours == theirs
+
+ @pytest.mark.parametrize("n", [0, 1, 2])
+ def test_degenerate_sizes_no_scale(self, n):
+ raw = {0: 3.0}
+ assert bw._rescale(dict(raw), n, normalized=True, directed=True) == raw
diff --git a/tests/unit/ingestion/test_resolver_merged_index.py b/tests/unit/ingestion/test_resolver_merged_index.py
new file mode 100644
index 000000000..ee206cd45
--- /dev/null
+++ b/tests/unit/ingestion/test_resolver_merged_index.py
@@ -0,0 +1,193 @@
+"""Unit tests for Tier-2b merged-import-symbol resolution and the
+trait-dispatch global method index (perf refactor: O(imports) scan → O(1)
+lookup with deterministic precedence).
+
+Destination: tests/unit/ingestion/test_resolver_merged_index.py
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.heritage_resolver import HeritageResolver
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import parse_file
+
+
+def _file_info(rel: str, abs_: Path, lang: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language=lang, # type: ignore[arg-type]
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _parse_all(tmp_path: Path, files: dict[str, tuple[str, str]]) -> dict[str, ParsedFile]:
+ out: dict[str, ParsedFile] = {}
+ for rel, (lang, content) in files.items():
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content)
+ fi = _file_info(rel, abs_, lang)
+ out[rel] = parse_file(fi, content.encode("utf-8"))
+ return out
+
+
+def _resolve(parsed, tmp_path, import_targets):
+ resolver = CallResolver(parsed, import_targets, repo_path=str(tmp_path))
+ edges = []
+ for path, pf in parsed.items():
+ for rc in resolver.resolve_file(path, pf.calls):
+ edges.append((rc.caller_id, rc.callee_id, rc.confidence))
+ return edges
+
+
+class TestTier2bFreeCall:
+ """Tier-2b: name not import-bound, but defined in an imported file."""
+
+ def test_resolves_via_import_targets(self, tmp_path: Path) -> None:
+ # caller.py has no parseable import binding for `helper` (the
+ # import_targets edge is supplied directly, mimicking a resolved
+ # wildcard/module import), so Tier-2a misses and Tier-2b must hit.
+ files = {
+ "lib.py": ("python", "def helper():\n return 1\n"),
+ "caller.py": ("python", "def run():\n return helper()\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(parsed, tmp_path, {"caller.py": {"lib.py"}, "lib.py": set()})
+ assert ("caller.py::run", "lib.py::helper", 0.85) in edges, edges
+
+ def test_external_imports_skipped(self, tmp_path: Path) -> None:
+ files = {
+ "caller.py": ("python", "def run():\n return helper()\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(parsed, tmp_path, {"caller.py": {"external:numpy"}})
+ assert edges == [], edges
+
+ def test_shadowed_name_resolves_deterministically(self, tmp_path: Path) -> None:
+ """Two imported files export the same name → sorted-path-first wins.
+
+ (Pre-refactor this iterated a set → hash-randomized winner; the
+ merged index pins the winner to the lexicographically first path.)
+ """
+ files = {
+ "a_lib.py": ("python", "def helper():\n return 'a'\n"),
+ "z_lib.py": ("python", "def helper():\n return 'z'\n"),
+ "caller.py": ("python", "def run():\n return helper()\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(
+ parsed,
+ tmp_path,
+ {"caller.py": {"z_lib.py", "a_lib.py"}, "a_lib.py": set(), "z_lib.py": set()},
+ )
+ tier2b = [e for e in edges if e[2] == 0.85]
+ assert tier2b == [("caller.py::run", "a_lib.py::helper", 0.85)], edges
+
+
+class TestTier2bMemberCall:
+ def test_class_method_in_imported_file(self, tmp_path: Path) -> None:
+ files = {
+ "models.py": (
+ "python",
+ "class User:\n def save(self):\n return 1\n",
+ ),
+ "caller.py": (
+ "python",
+ "def run():\n return User.save()\n",
+ ),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(parsed, tmp_path, {"caller.py": {"models.py"}, "models.py": set()})
+ assert ("caller.py::run", "models.py::User::save", 0.88) in edges, edges
+
+ def test_shadowed_method_pair_deterministic(self, tmp_path: Path) -> None:
+ files = {
+ "a_mod.py": ("python", "class User:\n def save(self):\n return 1\n"),
+ "z_mod.py": ("python", "class User:\n def save(self):\n return 2\n"),
+ "caller.py": ("python", "def run():\n return User.save()\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(
+ parsed,
+ tmp_path,
+ {"caller.py": {"z_mod.py", "a_mod.py"}, "a_mod.py": set(), "z_mod.py": set()},
+ )
+ hits = [e for e in edges if e[2] == 0.88]
+ assert hits == [("caller.py::run", "a_mod.py::User::save", 0.88)], edges
+
+
+class TestTraitDispatchGlobalIndex:
+ """Strategy 2b: (class, method) found in a NON-imported file → 0.75 edge."""
+
+ def test_resolves_without_import_edge(self, tmp_path: Path) -> None:
+ files = {
+ "impls.py": ("python", "class Walker:\n def visit(self):\n return 1\n"),
+ "caller.py": ("python", "def run():\n return Walker.visit()\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ # no import_targets edge at all — forces the global fallback
+ edges = _resolve(parsed, tmp_path, {p: set() for p in parsed})
+ assert ("caller.py::run", "impls.py::Walker::visit", 0.75) in edges, edges
+
+ def test_same_file_occurrence_skipped(self, tmp_path: Path) -> None:
+ """The global fallback must skip the caller's own file (the same-file
+ case is Tier-1/Strategy-2 territory and was already missed there)."""
+ files = {
+ # `visit` is nested under a DIFFERENT class in caller.py, so the
+ # same-file (receiver, method) lookup misses; the global index
+ # must not return caller.py's own entry for another class either.
+ "caller.py": (
+ "python",
+ "class Other:\n def helper(self):\n return 1\n"
+ "def run():\n return Walker.visit()\n",
+ ),
+ "impls.py": ("python", "class Walker:\n def visit(self):\n return 1\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _resolve(parsed, tmp_path, {p: set() for p in parsed})
+ assert ("caller.py::run", "impls.py::Walker::visit", 0.75) in edges, edges
+
+
+class TestHeritageTier2b:
+ def test_parent_in_imported_file(self, tmp_path: Path) -> None:
+ files = {
+ "base.py": ("python", "class Base:\n pass\n"),
+ "child.py": ("python", "class Child(Base):\n pass\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(parsed, {"child.py": {"base.py"}, "base.py": set()})
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ hits = [(r.child_id, r.parent_id, r.confidence) for r in results]
+ # Tier 3 (global unique) would also find Base at 0.50 — assert the
+ # 2b path wins with its higher confidence.
+ assert ("child.py::Child", "base.py::Base", 0.85) in hits, hits
+
+ def test_shadowed_parent_deterministic(self, tmp_path: Path) -> None:
+ files = {
+ "a_base.py": ("python", "class Base:\n pass\n"),
+ "z_base.py": ("python", "class Base:\n pass\n"),
+ "child.py": ("python", "class Child(Base):\n pass\n"),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(
+ parsed,
+ {"child.py": {"z_base.py", "a_base.py"}, "a_base.py": set(), "z_base.py": set()},
+ )
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ hits = [(r.child_id, r.parent_id, r.confidence) for r in results if r.confidence == 0.85]
+ assert hits == [("child.py::Child", "a_base.py::Base", 0.85)], hits
diff --git a/tests/unit/ingestion/test_single_query_pass.py b/tests/unit/ingestion/test_single_query_pass.py
new file mode 100644
index 000000000..6f28fed45
--- /dev/null
+++ b/tests/unit/ingestion/test_single_query_pass.py
@@ -0,0 +1,71 @@
+"""The compiled tree-sitter query must execute exactly once per parse_file.
+
+The five extraction passes (symbols, imports, calls, heritage, type refs)
+share one materialized capture list; re-running ``cursor.matches()`` per
+pass silently multiplies the dominant parse cost by five. This guards the
+single-execution contract; per-language output correctness is pinned by
+the existing fixture suites.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+from repowise.core.ingestion import ASTParser
+from repowise.core.ingestion.models import FileInfo
+
+_PY_SOURCE = b'''\
+import os
+from collections import OrderedDict
+
+
+class Base:
+ def greet(self) -> str:
+ return "hi"
+
+
+class Child(Base):
+ def greet(self) -> str:
+ return helper(os.getcwd())
+
+
+def helper(arg: str) -> str:
+ return arg.upper()
+'''
+
+
+def _file_info(path: str = "pkg/mod.py") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="python",
+ size_bytes=len(_PY_SOURCE),
+ git_hash="",
+ last_modified=datetime.now(UTC),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def test_query_runs_once_and_output_is_complete(monkeypatch):
+ import repowise.core.ingestion.parser as parser_mod
+
+ calls = {"n": 0}
+ real_run_query = parser_mod._run_query
+
+ def counting_run_query(query, root):
+ calls["n"] += 1
+ return real_run_query(query, root)
+
+ monkeypatch.setattr(parser_mod, "_run_query", counting_run_query)
+
+ parsed = ASTParser().parse_file(_file_info(), _PY_SOURCE)
+
+ assert calls["n"] == 1, f"compiled query executed {calls['n']} times, expected 1"
+ # The single pass must still feed every extraction stage.
+ assert {s.name for s in parsed.symbols} >= {"Base", "Child", "helper", "greet"}
+ assert {i.module_path for i in parsed.imports} == {"os", "collections"}
+ assert any(c.target_name == "helper" for c in parsed.calls)
+ assert any(h.parent_name == "Base" for h in parsed.heritage)
diff --git a/tests/unit/ingestion/test_subgraph_cache.py b/tests/unit/ingestion/test_subgraph_cache.py
new file mode 100644
index 000000000..78b1cfc46
--- /dev/null
+++ b/tests/unit/ingestion/test_subgraph_cache.py
@@ -0,0 +1,98 @@
+"""Unit tests for GraphBuilder subgraph caching (perf: 7 metric methods used
+to rebuild file/symbol subgraphs per call).
+
+Destination: tests/unit/ingestion/test_subgraph_cache.py
+"""
+
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion import GraphBuilder
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import parse_file
+
+
+def _parsed(tmp_path: Path, rel: str, content: str):
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content)
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language="python", # type: ignore[arg-type]
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return parse_file(fi, content.encode("utf-8"))
+
+
+def _builder(tmp_path: Path) -> GraphBuilder:
+ gb = GraphBuilder(str(tmp_path))
+ gb.add_file(_parsed(tmp_path, "a.py", "from b import helper\n\ndef run():\n return helper()\n"))
+ gb.add_file(_parsed(tmp_path, "b.py", "def helper():\n return 1\n"))
+ gb.build()
+ return gb
+
+
+class TestSubgraphCache:
+ def test_file_subgraph_cached_instance(self, tmp_path: Path) -> None:
+ gb = _builder(tmp_path)
+ assert gb.file_subgraph() is gb.file_subgraph()
+
+ def test_symbol_subgraph_cached_instance(self, tmp_path: Path) -> None:
+ gb = _builder(tmp_path)
+ assert gb.symbol_subgraph() is gb.symbol_subgraph()
+
+ def test_contents_unchanged_by_caching(self, tmp_path: Path) -> None:
+ gb = _builder(tmp_path)
+ sub = gb.file_subgraph()
+ assert set(sub.nodes) == {
+ n for n, d in gb.graph().nodes(data=True)
+ if d.get("node_type", "file") in ("file", "external")
+ }
+ assert not any(
+ d.get("edge_type") == "co_changes" for _, _, d in sub.edges(data=True)
+ )
+
+ def test_invalidated_on_add_file(self, tmp_path: Path) -> None:
+ gb = _builder(tmp_path)
+ before = gb.file_subgraph()
+ gb.add_file(_parsed(tmp_path, "c.py", "def extra():\n return 2\n"))
+ gb.build()
+ after = gb.file_subgraph()
+ assert after is not before
+ assert "c.py" in after
+
+ def test_invalidated_on_co_change_update(self, tmp_path: Path) -> None:
+ gb = _builder(tmp_path)
+ before_file = gb.file_subgraph()
+ before_sym = gb.symbol_subgraph()
+ gb.update_co_change_edges(
+ {
+ "a.py": {"file_path": "a.py", "co_change_files": [["b.py", 5]]},
+ }
+ )
+ # co_changes edges are excluded from the file subgraph, but the cache
+ # must still refresh — callers may rely on node attrs staying live.
+ assert gb.file_subgraph() is not before_file
+ assert gb.symbol_subgraph() is not before_sym
+
+ def test_concurrent_metric_access_safe(self, tmp_path: Path) -> None:
+ """Init computes metrics concurrently via asyncio.to_thread — the
+ cache must never hand out a half-built subgraph."""
+ gb = _builder(tmp_path)
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ futures = [pool.submit(gb.pagerank) for _ in range(4)]
+ futures += [pool.submit(gb.betweenness_centrality) for _ in range(4)]
+ futures += [pool.submit(gb.symbol_pagerank) for _ in range(4)]
+ results = [f.result() for f in futures]
+ # pagerank dicts agree across threads
+ assert results[0] == results[1] == results[2] == results[3]
diff --git a/tests/unit/ingestion/test_ts_workspace_scan.py b/tests/unit/ingestion/test_ts_workspace_scan.py
new file mode 100644
index 000000000..9f41a4afb
--- /dev/null
+++ b/tests/unit/ingestion/test_ts_workspace_scan.py
@@ -0,0 +1,82 @@
+"""Unit tests for the single pruned filesystem scan behind the ts_workspace
+finders (perf: 12+ unpruned rglob walks → one os.walk that skips
+node_modules / dot-dirs).
+
+Destination: tests/unit/ingestion/test_ts_workspace_scan.py
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.resolvers.context import ResolverContext # adjust import at apply time
+from repowise.core.ingestion.resolvers.ts_workspace import (
+ find_mdx_import_targets,
+ find_vitest_include_targets,
+)
+
+
+def _write(root: Path, rel: str, content: str) -> None:
+ p = root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content, encoding="utf-8")
+
+
+def _ctx(root: Path, path_set: set[str]) -> ResolverContext:
+ return ResolverContext(
+ path_set=path_set,
+ stem_map={},
+ graph=None,
+ repo_path=root,
+ )
+
+
+class TestPrunedScan:
+ def test_mdx_in_node_modules_ignored(self, tmp_path: Path) -> None:
+ _write(tmp_path, "docs/page.mdx", "import { B } from '../src/b'\n")
+ _write(tmp_path, "node_modules/pkg/readme.mdx", "import { X } from '../../src/c'\n")
+ _write(tmp_path, "src/b.ts", "export const B = 1\n")
+ _write(tmp_path, "src/c.ts", "export const X = 1\n")
+ ctx = _ctx(tmp_path, {"src/b.ts", "src/c.ts", "docs/page.mdx"})
+ targets = find_mdx_import_targets(ctx)
+ assert "src/b.ts" in targets, targets
+ assert "src/c.ts" not in targets, targets
+
+ def test_mdx_in_hidden_dir_ignored(self, tmp_path: Path) -> None:
+ _write(tmp_path, ".cache/stale.mdx", "import { B } from '../src/b'\n")
+ _write(tmp_path, "src/b.ts", "export const B = 1\n")
+ ctx = _ctx(tmp_path, {"src/b.ts"})
+ targets = find_mdx_import_targets(ctx)
+ assert targets == set(), targets
+
+ def test_vitest_config_in_node_modules_ignored(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "vitest.config.ts",
+ "export default { test: { include: ['runtime-tests/**/*.ts'] } }\n",
+ )
+ _write(
+ tmp_path,
+ "node_modules/dep/vitest.config.ts",
+ "export default { test: { include: ['poison/**/*.ts'] } }\n",
+ )
+ path_set = {"runtime-tests/a.ts", "poison/b.ts"}
+ ctx = _ctx(tmp_path, path_set)
+ targets = find_vitest_include_targets(ctx)
+ assert "runtime-tests/a.ts" in targets, targets
+ # the node_modules config's include glob resolves relative to its own
+ # dir, so even pre-refactor it could not match; the point here is the
+ # walk no longer descends at all.
+ assert "poison/b.ts" not in targets, targets
+
+ def test_root_configs_still_found(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "packages/app/vitest.config.mts",
+ "export default { test: { include: ['src/**/*.spec.ts'] } }\n",
+ )
+ path_set = {"packages/app/src/x.spec.ts", "packages/app/src/x.ts"}
+ ctx = _ctx(tmp_path, path_set)
+ targets = find_vitest_include_targets(ctx)
+ assert "packages/app/src/x.spec.ts" in targets, targets
+ assert "packages/app/src/x.ts" not in targets, targets
diff --git a/tests/unit/persistence/test_batch_upsert_keyed.py b/tests/unit/persistence/test_batch_upsert_keyed.py
new file mode 100644
index 000000000..18b44f6fa
--- /dev/null
+++ b/tests/unit/persistence/test_batch_upsert_keyed.py
@@ -0,0 +1,146 @@
+"""Behavioral tests for the single-existence-query batch upsert.
+
+The keyed implementation replaced a per-item SELECT loop; these tests pin
+the semantics the callers rely on: insert-then-update convergence,
+within-batch duplicate handling, per-repo isolation, and empty input.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import select
+
+from repowise.core.persistence.crud import (
+ batch_upsert_graph_edges,
+ batch_upsert_graph_nodes,
+ upsert_git_metadata_bulk,
+)
+from repowise.core.persistence.models import GitMetadata, GraphEdge, GraphNode
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _node(node_id: str, pagerank: float = 0.0) -> dict:
+ return {
+ "node_id": node_id,
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": pagerank,
+ "betweenness": 0.0,
+ "community_id": 0,
+ }
+
+
+async def _node_rows(session, repo_id: str) -> dict[str, GraphNode]:
+ rows = (
+ (await session.execute(select(GraphNode).where(GraphNode.repository_id == repo_id)))
+ .scalars()
+ .all()
+ )
+ return {r.node_id: r for r in rows}
+
+
+async def test_insert_then_update_converges(async_session):
+ repo = await insert_repo(async_session)
+ await batch_upsert_graph_nodes(async_session, repo.id, [_node("a.py"), _node("b.py")])
+ await async_session.commit()
+
+ await batch_upsert_graph_nodes(
+ async_session, repo.id, [_node("a.py", pagerank=0.5), _node("c.py")]
+ )
+ await async_session.commit()
+
+ rows = await _node_rows(async_session, repo.id)
+ assert set(rows) == {"a.py", "b.py", "c.py"}
+ assert rows["a.py"].pagerank == 0.5
+ # Update must not duplicate the row.
+ ids = [r.id for r in rows.values()]
+ assert len(ids) == len(set(ids))
+
+
+async def test_within_batch_duplicate_keys_last_wins_single_row(async_session):
+ repo = await insert_repo(async_session)
+ await batch_upsert_graph_nodes(
+ async_session, repo.id, [_node("dup.py", 0.1), _node("dup.py", 0.9)]
+ )
+ await async_session.commit()
+
+ rows = await _node_rows(async_session, repo.id)
+ assert set(rows) == {"dup.py"}
+ assert rows["dup.py"].pagerank == 0.9
+
+
+async def test_repos_are_isolated(async_session):
+ repo_a = await insert_repo(async_session)
+ repo_b = await insert_repo(async_session, name="other", local_path="/other")
+ await batch_upsert_graph_nodes(async_session, repo_a.id, [_node("shared.py", 0.1)])
+ await batch_upsert_graph_nodes(async_session, repo_b.id, [_node("shared.py", 0.7)])
+ await async_session.commit()
+
+ rows_a = await _node_rows(async_session, repo_a.id)
+ rows_b = await _node_rows(async_session, repo_b.id)
+ assert rows_a["shared.py"].pagerank == 0.1
+ assert rows_b["shared.py"].pagerank == 0.7
+
+
+async def test_empty_input_is_a_noop(async_session):
+ repo = await insert_repo(async_session)
+ await batch_upsert_graph_nodes(async_session, repo.id, [])
+ await upsert_git_metadata_bulk(async_session, repo.id, [])
+ await async_session.commit()
+ assert await _node_rows(async_session, repo.id) == {}
+
+
+async def test_edges_composite_key(async_session):
+ repo = await insert_repo(async_session)
+ edge = {
+ "source_node_id": "a.py",
+ "target_node_id": "b.py",
+ "edge_type": "imports",
+ "imported_names_json": "[]",
+ "confidence": 0.5,
+ }
+ await batch_upsert_graph_edges(async_session, repo.id, [edge])
+ # Same pair, different edge_type -> second row; same triple -> update.
+ await batch_upsert_graph_edges(
+ async_session,
+ repo.id,
+ [
+ {**edge, "edge_type": "calls"},
+ {**edge, "confidence": 1.0},
+ ],
+ )
+ await async_session.commit()
+
+ rows = (
+ (await session_exec(async_session, repo.id)).scalars().all()
+ )
+ by_type = {r.edge_type: r for r in rows}
+ assert set(by_type) == {"imports", "calls"}
+ assert by_type["imports"].confidence == 1.0
+
+
+async def session_exec(session, repo_id):
+ return await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
+
+
+async def test_git_metadata_update_path(async_session):
+ repo = await insert_repo(async_session)
+ await upsert_git_metadata_bulk(
+ async_session, repo.id, [{"file_path": "a.py", "commit_count_30d": 1}]
+ )
+ await upsert_git_metadata_bulk(
+ async_session, repo.id, [{"file_path": "a.py", "commit_count_30d": 7}]
+ )
+ await async_session.commit()
+
+ rows = (
+ (
+ await async_session.execute(
+ select(GitMetadata).where(GitMetadata.repository_id == repo.id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert len(rows) == 1
+ assert rows[0].commit_count_30d == 7
diff --git a/tests/unit/persistence/test_vector_store_batching.py b/tests/unit/persistence/test_vector_store_batching.py
new file mode 100644
index 000000000..5a7a8e237
--- /dev/null
+++ b/tests/unit/persistence/test_vector_store_batching.py
@@ -0,0 +1,163 @@
+"""Batched vector-store operations: pgvector executemany + IN-filtered
+summary lookups (pgvector, LanceDB)."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.vector_store.lancedb_store import _paths_in_filter
+from repowise.core.persistence.vector_store.pgvector_store import (
+ PgVectorStore,
+ _summary_payload,
+)
+from repowise.core.providers.embedding.base import MockEmbedder
+
+# ---------------------------------------------------------------------------
+# Fake async-SQLAlchemy session plumbing
+# ---------------------------------------------------------------------------
+
+
+class _FakeResult:
+ def __init__(self, rows: list[tuple]) -> None:
+ self._rows = rows
+
+ def fetchall(self) -> list[tuple]:
+ return self._rows
+
+ def fetchone(self):
+ return self._rows[0] if self._rows else None
+
+
+class _FakeSession:
+ """Records every execute() call; serves canned rows."""
+
+ def __init__(self, rows: list[tuple] | None = None) -> None:
+ self.executed: list[tuple[str, object]] = []
+ self.commits = 0
+ self._rows = rows or []
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def execute(self, stmt, params=None):
+ self.executed.append((str(stmt), params))
+ return _FakeResult(self._rows)
+
+ async def commit(self):
+ self.commits += 1
+
+
+def _factory(session: _FakeSession):
+ def make() -> _FakeSession:
+ return session
+
+ return make
+
+
+# ---------------------------------------------------------------------------
+# pgvector embed_batch — one executemany, not N round-trips
+# ---------------------------------------------------------------------------
+
+
+async def test_pg_embed_batch_single_executemany() -> None:
+ session = _FakeSession()
+ store = PgVectorStore(_factory(session), MockEmbedder())
+
+ await store.embed_batch(
+ [("p1", "alpha", {}), ("p2", "beta", {}), ("p3", "gamma", {})]
+ )
+
+ assert len(session.executed) == 1 # one statement, list-of-params
+ stmt, params = session.executed[0]
+ assert "UPDATE wiki_pages SET embedding" in stmt
+ assert isinstance(params, list) and len(params) == 3
+ assert [p["pid"] for p in params] == ["p1", "p2", "p3"]
+ assert all(p["emb"].startswith("[") for p in params)
+ assert session.commits == 1
+
+
+async def test_pg_embed_batch_empty_is_noop() -> None:
+ session = _FakeSession()
+ store = PgVectorStore(_factory(session), MockEmbedder())
+ await store.embed_batch([])
+ assert session.executed == []
+
+
+# ---------------------------------------------------------------------------
+# pgvector get_page_summaries_by_paths — one IN query
+# ---------------------------------------------------------------------------
+
+
+async def test_pg_batch_summaries_single_query_first_row_wins() -> None:
+ rows = [
+ ("a.py", "Summary of a", {"exports": ["A"]}),
+ ("a.py", "duplicate row ignored", {}),
+ ("b.py", "Summary of b", '{"exports": ["B1", "B2"]}'),
+ ("c.py", "", {}), # empty summary dropped
+ ]
+ session = _FakeSession(rows=rows)
+ store = PgVectorStore(_factory(session), MockEmbedder())
+
+ out = await store.get_page_summaries_by_paths(["a.py", "b.py", "c.py"])
+
+ assert len(session.executed) == 1
+ stmt, params = session.executed[0]
+ assert "target_path IN" in stmt
+ assert params == {"paths": ["a.py", "b.py", "c.py"]}
+ assert out == {
+ "a.py": {"summary": "Summary of a", "key_exports": ["A"]},
+ "b.py": {"summary": "Summary of b", "key_exports": ["B1", "B2"]},
+ }
+
+
+async def test_pg_batch_summaries_empty_paths() -> None:
+ session = _FakeSession()
+ store = PgVectorStore(_factory(session), MockEmbedder())
+ assert await store.get_page_summaries_by_paths([]) == {}
+ assert session.executed == []
+
+
+def test_summary_payload_matches_single_path_parsing() -> None:
+ assert _summary_payload("x" * 600, {"exports": ["E"]}) == {
+ "summary": "x" * 500,
+ "key_exports": ["E"],
+ }
+ assert _summary_payload(None, "not json") == {"summary": "", "key_exports": []}
+
+
+# ---------------------------------------------------------------------------
+# LanceDB IN-filter escaping + optional round-trip
+# ---------------------------------------------------------------------------
+
+
+def test_lancedb_paths_filter_escapes_quotes() -> None:
+ flt = _paths_in_filter(["a.py", "weird'name.py"])
+ assert flt == "target_path IN ('a.py', 'weird''name.py')"
+
+
+async def test_lancedb_batch_summaries_roundtrip(tmp_path) -> None:
+ pytest.importorskip("lancedb")
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ store = LanceDBVectorStore(str(tmp_path / "lance"), MockEmbedder())
+ try:
+ await store.embed_batch(
+ [
+ ("p1", "Summary text for module a", {"target_path": "a.py"}),
+ ("p2", "Summary text for module b", {"target_path": "b.py"}),
+ ("p3", "Summary text for module c", {"target_path": "c.py"}),
+ ]
+ )
+ batch = await store.get_page_summaries_by_paths(["a.py", "c.py", "missing.py"])
+ singles = {
+ p: await store.get_page_summary_by_path(p) for p in ("a.py", "c.py")
+ }
+ assert set(batch) == {"a.py", "c.py"}
+ for p in ("a.py", "c.py"):
+ assert batch[p]["summary"] == singles[p]["summary"]
+ finally:
+ await store.close()
diff --git a/tests/unit/pipeline/test_parallel_source_reads.py b/tests/unit/pipeline/test_parallel_source_reads.py
new file mode 100644
index 000000000..48dcb3305
--- /dev/null
+++ b/tests/unit/pipeline/test_parallel_source_reads.py
@@ -0,0 +1,67 @@
+"""Unit tests for the parallel source-read helper in the ingestion phase
+(perf: sequential read loop → ThreadPoolExecutor, preserving order, error
+handling, and progress ticks).
+
+Destination: tests/unit/pipeline/test_parallel_source_reads.py
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.pipeline.phases.ingestion import _read_sources # name fixed at apply time
+
+
+def _fi(rel: str, abs_: Path) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language="python", # type: ignore[arg-type]
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+class _TickCounter:
+ def __init__(self) -> None:
+ self.ticks = 0
+
+ def on_item_done(self, phase: str) -> None:
+ assert phase == "parse"
+ self.ticks += 1
+
+
+class TestReadSources:
+ def test_order_and_contents_preserved(self, tmp_path: Path) -> None:
+ infos = []
+ for i in range(20):
+ p = tmp_path / f"f{i:02d}.py"
+ p.write_bytes(f"# file {i}\n".encode())
+ infos.append(_fi(f"f{i:02d}.py", p))
+ out = _read_sources(infos, progress=None)
+ assert [fi.path for fi, _ in out] == [fi.path for fi in infos]
+ assert all(src == f"# file {i}\n".encode() for i, (_, src) in enumerate(out))
+
+ def test_unreadable_file_skipped_and_ticked(self, tmp_path: Path) -> None:
+ good = tmp_path / "good.py"
+ good.write_bytes(b"x = 1\n")
+ infos = [
+ _fi("good.py", good),
+ _fi("missing.py", tmp_path / "missing.py"), # does not exist
+ ]
+ progress = _TickCounter()
+ out = _read_sources(infos, progress=progress)
+ assert [fi.path for fi, _ in out] == ["good.py"]
+ # the failed read must tick the parse bar exactly once (pre-refactor
+ # behavior at ingestion.py:166-168)
+ assert progress.ticks == 1
+
+ def test_empty_input(self) -> None:
+ assert _read_sources([], progress=None) == []