Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
perf: direct self-call resolution and cached pagerank for cascade ordering (#891)
Raghav Chamadiya6384a82cf367
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex 4bb3d056a..626c410e7 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -697,7 +697,14 @@ def run_update(cascade_budget = compute_adaptive_budget(file_diffs, file_count)if verbose:console.print(f"Adaptive cascade budget: [cyan]{cascade_budget}[/cyan]")- affected = detector.get_affected_pages(file_diffs, graph_builder.graph(), cascade_budget)+ # Pass the builder's cached file pagerank so the cascade ordering does+ # not recompute a full-graph pagerank pass on every update.+ affected = detector.get_affected_pages(+ file_diffs,+ graph_builder.graph(),+ cascade_budget,+ pagerank=graph_builder.pagerank(),+ )console.print(f"Pages to regenerate: [cyan]{len(affected.regenerate)}[/cyan]")if affected.decay_only:diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 0bfcb4efd..d9f898118 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -80,9 +80,6 @@ class CallResolver:# Global symbol index: {name: [symbol_ids]} — for Tier 3self._global_symbols: dict[str, list[str]] = defaultdict(list)- # Global class index: {name: symbol_id} — for receiver resolution- self._global_classes: dict[str, list[str]] = defaultdict(list)-# Import graph: {file_path: set of imported file paths}self._import_targets = import_targets@@ -408,8 +405,6 @@ class CallResolver:# Global indicesself._global_symbols[sym.name].append(sym.id)- if sym.kind in ("class", "struct", "interface", "enum"):- self._global_classes[sym.name].append(sym.id)self._file_symbols[path] = file_symsself._file_methods[path] = file_methods@@ -640,31 +635,25 @@ class CallResolver:continuereturn ResolvedCall(caller_id, sym_id, 0.75, call.line)- # Strategy 3: receiver is "self" or "this" — look in same class+ # Strategy 3: receiver is "self" or "this" — look in same class.+ # Only the caller's own file can hold the match, so index straight+ # into it instead of scanning every file's method dict.if receiver_name in ("self", "this"):- # The caller is inside a class method — find its parent class- # and resolve the method within that class's methods- for path_key, methods in self._file_methods.items():- if path_key != file_path:- continue- for (cls_name, meth_name), sym_id in methods.items():- if meth_name == method_name and sym_id != caller_id:- # Verify caller is in the same class- caller_class = _extract_class_from_symbol_id(caller_id)- if caller_class and caller_class == cls_name:- return ResolvedCall(caller_id, sym_id, 0.95, call.line)-- # Strategy 4: global class match for receiver- class_candidates = self._global_classes.get(receiver_name, [])- if len(class_candidates) == 1:- # Found unique class — look for the method in any file- # that defines methods for this class- for _path, methods in self._file_methods.items():- if (receiver_name, method_name) in methods:- return ResolvedCall(- caller_id, methods[(receiver_name, method_name)], 0.50, call.line- )-+ caller_class = _extract_class_from_symbol_id(caller_id)+ if caller_class:+ for (cls_name, meth_name), sym_id in self._file_methods.get(+ file_path, {}+ ).items():+ if (+ meth_name == method_name+ and sym_id != caller_id+ and cls_name == caller_class+ ):+ return ResolvedCall(caller_id, sym_id, 0.95, call.line)++ # No further fallback: any (class, method) pair present in any file's+ # method index was already resolved by strategy 2 (same file) or 2b+ # (global method index), which are built from the same symbols.return Nonediff --git a/packages/core/src/repowise/core/ingestion/change_detector.py b/packages/core/src/repowise/core/ingestion/change_detector.pyindex e97143828..060a0411c 100644--- a/packages/core/src/repowise/core/ingestion/change_detector.py+++ b/packages/core/src/repowise/core/ingestion/change_detector.py@@ -262,6 +262,7 @@ class ChangeDetector:file_diffs: list[FileDiff],graph: object, # nx.DiGraphcascade_budget: int = 30,+ pagerank: dict[str, float] | None = None,) -> AffectedPages:"""Compute which wiki pages need action after a set of file changes.@@ -269,6 +270,10 @@ class ChangeDetector:file_diffs: Output of get_changed_files().graph: The dependency graph (networkx DiGraph, nodes are file paths).cascade_budget: Max number of pages to fully regenerate per run.+ pagerank: Precomputed scores for budget ordering (the update path+ passes GraphBuilder's cached file pagerank so this function+ does not recompute a full-graph pass). Falls back to an+ internal computation when omitted."""import networkx as nx@@ -322,10 +327,13 @@ class ChangeDetector:two_hop -= directly_changed | one_hop | co_change_decay# Apply cascade budget sorted by PageRank (highest priority first)- try:- pr = nx.pagerank(graph)- except Exception:- pr = {}+ if pagerank is not None:+ pr = pagerank+ else:+ try:+ pr = nx.pagerank(graph)+ except Exception:+ pr = {}all_pages_needing_regen = sorted(directly_changed | one_hop,diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.pyindex ec2124182..402ea9857 100644--- a/packages/server/src/repowise/server/job_executor.py+++ b/packages/server/src/repowise/server/job_executor.py@@ -778,7 +778,10 @@ async def _incremental_page_regen(cascade_budget = compute_adaptive_budget(file_diffs, result.file_count)affected = detector.get_affected_pages(- file_diffs, result.graph_builder.graph(), cascade_budget+ file_diffs,+ result.graph_builder.graph(),+ cascade_budget,+ pagerank=result.graph_builder.pagerank(),)if not affected.regenerate:diff --git a/tests/unit/ingestion/test_change_detector.py b/tests/unit/ingestion/test_change_detector.pyindex ccb3c534f..92673f4f1 100644--- a/tests/unit/ingestion/test_change_detector.py+++ b/tests/unit/ingestion/test_change_detector.py@@ -287,3 +287,61 @@ class TestGetAffectedPages:assert result.regenerate == []assert result.rename_patch == []assert result.decay_only == []+++class TestAffectedPagesPagerankParam:+ """A caller-supplied pagerank map must drive cascade-budget ordering+ instead of a fresh in-function ``nx.pagerank`` pass (the update path+ already holds GraphBuilder's cached file pagerank)."""++ def _diff(self, path: str):+ from repowise.core.ingestion.change_detector import FileDiff++ return FileDiff(+ path=path,+ status="modified",+ old_path=None,+ old_parsed=None,+ new_parsed=_parsed([], path=path),+ symbol_diff=None,+ )++ def test_provided_pagerank_orders_cascade(self, tmp_path: Path) -> None:+ d = ChangeDetector(tmp_path)+ g = nx.DiGraph()+ g.add_node("f0.py")+ for i in range(1, 6):+ g.add_node(f"f{i}.py")+ g.add_edge(f"f{i}.py", "f0.py") # all import f0++ pr = {+ "f5.py": 0.9,+ "f4.py": 0.8,+ "f0.py": 0.7,+ "f1.py": 0.01,+ "f2.py": 0.01,+ "f3.py": 0.01,+ }+ result = d.get_affected_pages(+ [self._diff("f0.py")], graph=g, cascade_budget=3, pagerank=pr+ )+ assert result.regenerate == ["f5.py", "f4.py", "f0.py"]+ assert set(result.decay_only) == {"f1.py", "f2.py", "f3.py"}++ def test_without_pagerank_falls_back_to_internal_computation(+ self, tmp_path: Path+ ) -> None:+ """Omitting the param keeps the old self-computed ordering path:+ the candidate partition (regenerate + decay) is unchanged."""+ d = ChangeDetector(tmp_path)+ g = nx.DiGraph()+ g.add_node("f0.py")+ for i in range(1, 6):+ g.add_node(f"f{i}.py")+ g.add_edge(f"f{i}.py", "f0.py")++ result = d.get_affected_pages([self._diff("f0.py")], graph=g, cascade_budget=3)+ assert len(result.regenerate) == 3+ assert set(result.regenerate) | set(result.decay_only) == {+ f"f{i}.py" for i in range(6)+ }diff --git a/tests/unit/ingestion/test_self_call_resolution.py b/tests/unit/ingestion/test_self_call_resolution.pynew file mode 100644index 000000000..17d77180c--- /dev/null+++ b/tests/unit/ingestion/test_self_call_resolution.py@@ -0,0 +1,138 @@+"""Behavior pins for CallResolver member-call strategies 3 and 4.++Strategy 3 (self/this receiver) used to scan ``_file_methods`` for every file+in the repo just to find the caller's own entry; the fix is a direct dict+lookup. Strategy 4 (unique global class, any-file method scan) was provably+shadowed: any (class, method) pair present in ANY file's method index is+already resolved by strategy 2 (same file, 0.93) or strategy 2b (global+method index, 0.75) before strategy 4 is reached. These tests pin the+observable resolution behavior around both so the rewrite is equivalence-+checked, not just plausible.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++from repowise.core.ingestion.call_resolver import CallResolver+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 _edges(parsed, tmp_path, import_targets=None):+ resolver = CallResolver(parsed, import_targets or {}, 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+++WIDGET_PY = '''+class Widget:+ def helper(self):+ return 1++ def run(self):+ return self.helper()+++class Other:+ def lonely(self):+ return self.helper()+'''++PAINTER_PY = '''+class Painter:+ def draw(self):+ return "ok"+'''++CALLER_PY = '''+def use():+ return Painter.draw()+'''++MISSING_PY = '''+def use_missing():+ return Painter.missing()+'''+++class TestSelfCallStrategy:+ def test_self_call_resolves_within_same_class(self, tmp_path: Path) -> None:+ parsed = _parse_all(tmp_path, {"src/widget.py": ("python", WIDGET_PY)})+ edges = _edges(parsed, tmp_path)+ hits = [+ e+ for e in edges+ if e[0].endswith("::Widget::run") and e[1].endswith("::Widget::helper")+ ]+ assert hits, f"self.helper() inside Widget.run must resolve; edges: {edges}"+ assert hits[0][2] == 0.95++ def test_self_call_does_not_cross_classes(self, tmp_path: Path) -> None:+ """Other.lonely calls self.helper() but Other has no helper: no edge."""+ parsed = _parse_all(tmp_path, {"src/widget.py": ("python", WIDGET_PY)})+ edges = _edges(parsed, tmp_path)+ bad = [e for e in edges if e[0].endswith("::Other::lonely")]+ assert bad == [], f"cross-class self-call must not resolve: {bad}"+++class TestStrategy4Shadowing:+ def test_cross_file_class_method_resolves_via_global_index(self, tmp_path: Path) -> None:+ """Painter.draw() from a non-importing file resolves at 2b's 0.75,+ never at old strategy 4's 0.50."""+ parsed = _parse_all(+ tmp_path,+ {+ "src/painter.py": ("python", PAINTER_PY),+ "src/caller.py": ("python", CALLER_PY),+ },+ )+ edges = _edges(parsed, tmp_path)+ hits = [e for e in edges if e[1].endswith("::Painter::draw")]+ assert hits, f"Painter.draw() must resolve cross-file; edges: {edges}"+ assert hits[0][2] == 0.75++ def test_unknown_method_on_unique_class_stays_unresolved(self, tmp_path: Path) -> None:+ """Painter is a unique global class but has no `missing` method: the+ old strategy-4 any-file scan could never find one either, so the+ outcome (no edge) is identical with the scan removed."""+ parsed = _parse_all(+ tmp_path,+ {+ "src/painter.py": ("python", PAINTER_PY),+ "src/missing_caller.py": ("python", MISSING_PY),+ },+ )+ edges = _edges(parsed, tmp_path)+ bad = [e for e in edges if e[0].endswith("::use_missing")]+ assert bad == [], f"unknown method must stay unresolved: {bad}"diff --git a/tests/unit/server/test_job_executor.py b/tests/unit/server/test_job_executor.pyindex a01f136d7..075db6c79 100644--- a/tests/unit/server/test_job_executor.py+++ b/tests/unit/server/test_job_executor.py@@ -282,7 +282,7 @@ async def test_incremental_page_regen_passes_repo_path(tmp_path):file_count=10,parsed_files=[],source_map={},- graph_builder=SimpleNamespace(graph=lambda: object()),+ graph_builder=SimpleNamespace(graph=lambda: object(), pagerank=lambda: {}),repo_structure=object(),repo_name="test-repo",git_meta_map={},