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(hints): feed dynamic-hint extractors from the traversed file list (#898)

Raghav Chamadiya8544a043555a
diff --git a/packages/core/src/repowise/core/fs_walk.py b/packages/core/src/repowise/core/fs_walk.py
index 78ee29f40..4b9c3a3d4 100644
--- a/packages/core/src/repowise/core/fs_walk.py
+++ b/packages/core/src/repowise/core/fs_walk.py
@@ -234,6 +234,49 @@ class WalkSnapshot:
(dirpath, "" if rel == "." else rel, list(dirnames), list(filenames))
)
+ @classmethod
+ def from_files(cls, root: Path | str, rel_paths: Iterable[str]) -> WalkSnapshot:
+ """Build a snapshot from an already-discovered file list, with no walk.
+
+ *rel_paths* are root-relative posix file paths (e.g. the ingestion
+ traverser's ``FileInfo.path`` values). The snapshot answers
+ :meth:`iter_glob` queries against exactly that file set — directory
+ entries are reconstructed from the paths so directory-name patterns
+ and subtree-rooted queries keep working. Entries are emitted in
+ sorted preorder, which is deterministic but not necessarily the
+ order a live walk would produce; callers that need a stable order
+ must sort their results (the dynamic-hints registry does).
+ """
+ snap = cls.__new__(cls)
+ snap.root = Path(root)
+ snap._prune_dirs = PRUNED_DIRS
+ snap._prune_nested_git = True
+ files_by_dir: dict[str, set[str]] = {"": set()}
+ subdirs: dict[str, set[str]] = {"": set()}
+ for rel in rel_paths:
+ rel_dir, _, name = rel.rpartition("/")
+ files_by_dir.setdefault(rel_dir, set()).add(name)
+ # Register the ancestor chain so every intermediate directory
+ # exists as an entry even when it holds no files directly.
+ child_dir = rel_dir
+ while child_dir:
+ parent, _, seg = child_dir.rpartition("/")
+ subdirs.setdefault(parent, set()).add(seg)
+ files_by_dir.setdefault(parent, set())
+ child_dir = parent
+ snap._entries = []
+
+ def _emit(rel_dir: str) -> None:
+ dirnames = sorted(subdirs.get(rel_dir, ()))
+ filenames = sorted(files_by_dir.get(rel_dir, ()))
+ dirpath = snap.root if rel_dir == "" else snap.root / rel_dir
+ snap._entries.append((dirpath, rel_dir, dirnames, filenames))
+ for d in dirnames:
+ _emit(f"{rel_dir}/{d}" if rel_dir else d)
+
+ _emit("")
+ return snap
+
def iter_glob(self, root: Path | str, patterns: str | Iterable[str]) -> Iterator[Path]:
"""Replay of ``iter_glob(root, patterns)`` against the snapshot."""
query_root = Path(root)
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
index ebf7655d3..779b26214 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py
@@ -69,7 +69,13 @@ class DjangoDynamicHints(DynamicHintExtractor):
settings_files: list[Path] = list(self._rglob(repo_root, "settings.py"))
for settings_dir in self._rglob(repo_root, "settings"):
if settings_dir.is_dir():
- settings_files.extend(settings_dir.glob("*.py"))
+ # Subtree query through _rglob, not a raw Path.glob: when the
+ # shared snapshot is fed from the traverser's file list this
+ # keeps gitignored files (local_settings.py) out of the scan.
+ # The parent check preserves glob's single-level semantics.
+ settings_files.extend(
+ p for p in self._rglob(settings_dir, "*.py") if p.parent == settings_dir
+ )
for settings_file in settings_files:
try:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
index 1a0fcf70a..9fb8c3e77 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -15,6 +15,7 @@ now completes in seconds on most codebases regardless of language mix.
from __future__ import annotations
+from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
@@ -27,15 +28,15 @@ from .cpp import CppDynamicHints
from .django import DjangoDynamicHints
from .dotnet import DotNetDynamicHints
from .go import GoDynamicHints
-from .rust import RustDynamicHints
+from .jvm import JvmDynamicHints
from .luau import LuauDynamicHints
from .node import NodeDynamicHints
from .php import PhpDynamicHints
-from .python_imports import PythonDynamicHints
from .pytest_hints import PytestDynamicHints
+from .python_imports import PythonDynamicHints
from .ruby import RubyDynamicHints
+from .rust import RustDynamicHints
from .scala import ScalaDynamicHints
-from .jvm import JvmDynamicHints
from .spring import SpringDynamicHints
from .swift import SwiftDynamicHints
from .xaml import XamlDynamicHints
@@ -78,7 +79,11 @@ class HintRegistry:
self._max_workers = max_workers or min(_DEFAULT_MAX_WORKERS, len(self._extractors))
def extract_all(
- self, repo_root: Path, *, dotnet_index: object | None = None
+ self,
+ repo_root: Path,
+ *,
+ dotnet_index: object | None = None,
+ file_paths: Iterable[str] | None = None,
) -> list[DynamicEdge]:
"""Run every registered extractor and merge their edges.
@@ -92,6 +97,15 @@ class HintRegistry:
The XAML extractor needs the repo's type map and otherwise rebuilds
the index from scratch (a full .cs walk + read + scan); passing the
one the graph resolvers already built skips that duplicate work.
+
+ *file_paths* is the ingestion traverser's repo-relative file list
+ (``FileInfo.path`` values). When provided, the shared snapshot is
+ built from it directly — no second filesystem walk — and hint
+ queries see exactly the indexed file set: gitignored files (built
+ ``bin``/``obj`` trees, ``local_settings.py``) and generated files
+ (``*.Designer.cs``) can no longer produce edges to files the index
+ does not contain. Omitted (tests, standalone use), the registry
+ falls back to its own pruned walk.
"""
edges: list[DynamicEdge] = []
if not self._extractors:
@@ -104,9 +118,12 @@ class HintRegistry:
try:
from repowise.core.fs_walk import WalkSnapshot
- from ._walk import PRUNED_DIRS
+ if file_paths is not None:
+ snapshot = WalkSnapshot.from_files(repo_root, file_paths)
+ else:
+ from ._walk import PRUNED_DIRS
- snapshot = WalkSnapshot(repo_root, prune_dirs=PRUNED_DIRS)
+ snapshot = WalkSnapshot(repo_root, prune_dirs=PRUNED_DIRS)
except Exception as e: # pragma: no cover - snapshot is best-effort
log.warning("dynamic_hints_snapshot_failed", error=str(e))
for ex in self._extractors:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 0570d9f0c..3a665e91f 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -177,7 +177,9 @@ def build_repo_graph(
from repowise.core.ingestion.dynamic_hints import HintRegistry
dynamic_edges = HintRegistry().extract_all(
- Path(repo_path), dotnet_index=graph_builder.dotnet_index
+ Path(repo_path),
+ dotnet_index=graph_builder.dotnet_index,
+ file_paths=[fi.path for fi in file_infos],
)
graph_builder.add_dynamic_edges(dynamic_edges)
if dynamic_edges:
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index 654be34ad..e2d749957 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -389,9 +389,15 @@ async def _run_ingestion(
from repowise.core.ingestion.dynamic_hints import HintRegistry
registry = HintRegistry()
+ # Feed the traversed file list so hints query the indexed set
+ # directly instead of re-walking the tree (keeps gitignored and
+ # generated files out of hint edges, and skips a full walk).
+ hint_paths = [fi.path for fi in file_infos]
dynamic_edges = await loop.run_in_executor(
None,
- lambda: registry.extract_all(repo_path, dotnet_index=graph_builder.dotnet_index),
+ lambda: registry.extract_all(
+ repo_path, dotnet_index=graph_builder.dotnet_index, file_paths=hint_paths
+ ),
)
graph_builder.add_dynamic_edges(dynamic_edges)
logger.info("dynamic_hints_added", count=len(dynamic_edges))
diff --git a/tests/unit/ingestion/test_dynamic_hints_file_feed.py b/tests/unit/ingestion/test_dynamic_hints_file_feed.py
new file mode 100644
index 000000000..cd7ae3322
--- /dev/null
+++ b/tests/unit/ingestion/test_dynamic_hints_file_feed.py
@@ -0,0 +1,109 @@
+"""Equivalence tests for HintRegistry.extract_all fed from a traversed file list.
+
+The ingestion pipeline passes the traverser's ``FileInfo.path`` list into
+``extract_all(file_paths=...)`` so the extractor fleet queries the indexed
+file set directly instead of re-walking the tree. Two guarantees are pinned
+here:
+
+1. When the fed list equals what the registry's own walk would find, the
+ emitted edges are identical (pure mechanism swap).
+2. Files excluded from the list (gitignored build output, generated
+ ``*.Designer.cs``, ``local_settings.py``) produce no hint edges, because
+ the index does not contain them and an edge to a nonexistent node is a
+ dangling reference downstream.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.fs_walk import PRUNED_DIRS_DERIVED, WalkSnapshot
+from repowise.core.ingestion.dynamic_hints import HintRegistry
+
+
+def _write(root: Path, rel: str, text: str) -> None:
+ p = root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+
+
+def repo(tmp_path: Path) -> Path:
+ """A mixed-language fixture exercising django, node, pytest, and dotnet."""
+ _write(tmp_path, "myapp/__init__.py", "")
+ _write(tmp_path, "myapp/urls.py", "urlpatterns = []\n")
+ _write(tmp_path, "settings.py", 'INSTALLED_APPS = ["myapp"]\nROOT_URLCONF = "myapp.urls"\n')
+ _write(tmp_path, "urls.py", "from django.urls import include\ninclude('myapp.urls')\n")
+ _write(tmp_path, "config/settings/base.py", 'INSTALLED_APPS = ["myapp"]\n')
+ _write(tmp_path, "package.json", '{"name": "x", "main": "./index.js"}\n')
+ _write(tmp_path, "index.js", "module.exports = {}\n")
+ _write(
+ tmp_path,
+ "conftest.py",
+ "import pytest\[email protected]\ndef db():\n return 1\n",
+ )
+ _write(tmp_path, "test_app.py", "def test_x(db):\n assert db\n")
+ _write(tmp_path, "src/Foo.cs", "public class Foo { }\npublic interface IFoo { }\n")
+ _write(
+ tmp_path,
+ "src/Startup.cs",
+ "class Startup { void C(IServiceCollection s) { s.AddScoped<IFoo, Foo>(); } }\n",
+ )
+ return tmp_path
+
+
+def _walked_files(root: Path) -> list[str]:
+ snap = WalkSnapshot(root, prune_dirs=PRUNED_DIRS_DERIVED)
+ return [
+ p.relative_to(root).as_posix() for p in snap.iter_glob(root, "*") if p.is_file()
+ ]
+
+
+class TestFileFeedEquivalence:
+ def test_full_list_produces_identical_edges(self, repo: Path) -> None:
+ walked = HintRegistry().extract_all(repo)
+ fed = HintRegistry().extract_all(repo, file_paths=_walked_files(repo))
+ assert fed == walked
+ # Sanity: the fixture actually produces edges for several extractors.
+ sources = {e.hint_source for e in walked}
+ assert "django_settings" in sources
+ assert "node_package" in sources
+ assert "pytest_conftest" in sources
+ assert any(s.startswith("dotnet") for s in sources)
+
+ def test_excluded_files_emit_no_edges(self, repo: Path) -> None:
+ # On-disk files the index would exclude: generated partial defining a
+ # DI-registered type, and a gitignored local settings module.
+ _write(repo, "src/Bar.Designer.cs", "public partial class Bar { }\n")
+ _write(
+ repo,
+ "src/Reg.cs",
+ "class Reg { void C(IServiceCollection s) { s.AddScoped<Bar>(); } }\n",
+ )
+ _write(repo, "config/settings/local_settings.py", 'INSTALLED_APPS = ["myapp"]\n')
+
+ walked = HintRegistry().extract_all(repo)
+ walked_refs = {e.source for e in walked} | {e.target for e in walked}
+ # The registry's own walk still sees both files (this is the bug the
+ # file feed fixes); if this stops holding, the fixture needs updating.
+ assert "src/Bar.Designer.cs" in walked_refs
+ assert "config/settings/local_settings.py" in walked_refs
+
+ indexed = [
+ p for p in _walked_files(repo)
+ if p not in ("src/Bar.Designer.cs", "config/settings/local_settings.py")
+ ]
+ fed = HintRegistry().extract_all(repo, file_paths=indexed)
+ fed_refs = {e.source for e in fed} | {e.target for e in fed}
+ assert "src/Bar.Designer.cs" not in fed_refs
+ assert "config/settings/local_settings.py" not in fed_refs
+ # Everything else is untouched (both lists share extract_all's
+ # deterministic sort, so filtering preserves comparability).
+ assert fed == [
+ e
+ for e in walked
+ if "Bar.Designer" not in e.target + e.source
+ and "local_settings" not in e.target + e.source
+ ]
diff --git a/tests/unit/ingestion/test_walk_snapshot.py b/tests/unit/ingestion/test_walk_snapshot.py
index 2b723c3cd..b175b3abb 100644
--- a/tests/unit/ingestion/test_walk_snapshot.py
+++ b/tests/unit/ingestion/test_walk_snapshot.py
@@ -89,6 +89,45 @@ class TestWalkSnapshotEquivalence:
snap = WalkSnapshot(tree, prune_dirs=PRUNED_DIRS_DERIVED)
assert [p.name for p in snap.iter_glob(other, "*.go")] == ["lone.go"]
+ def test_from_files_matches_walk_snapshot(self, tree: Path) -> None:
+ """A from_files snapshot over the walk's own file set answers every
+ query with the same results (set-wise; entry order is sorted preorder
+ rather than walk order, and extract_all sorts its output anyway)."""
+ walk_snap = WalkSnapshot(tree, prune_dirs=PRUNED_DIRS_DERIVED)
+ rel_files = [
+ p.relative_to(tree).as_posix() for p in walk_snap.iter_glob(tree, "*") if p.is_file()
+ ]
+ list_snap = WalkSnapshot.from_files(tree, rel_files)
+ for pattern in QUERIES:
+ walked = {p for p in walk_snap.iter_glob(tree, pattern) if p.is_file()}
+ listed = {p for p in list_snap.iter_glob(tree, pattern) if p.is_file()}
+ assert listed == walked, pattern
+
+ def test_from_files_reconstructs_directories(self, tree: Path) -> None:
+ list_snap = WalkSnapshot.from_files(
+ tree, ["app/settings/base.py", "pkg/settings/local.py", "pkg/sub/deep/b.go"]
+ )
+ # Directory-name pattern yields the reconstructed dirs.
+ dirs = sorted(
+ p.relative_to(tree).as_posix() for p in list_snap.iter_glob(tree, "settings")
+ )
+ assert dirs == ["app/settings", "pkg/settings"]
+ # Subtree-rooted query serves only that subtree.
+ sub = [p.name for p in list_snap.iter_glob(tree / "pkg", "*.py")]
+ assert sub == ["local.py"]
+
+ def test_from_files_hides_files_not_in_list(self, tree: Path) -> None:
+ # settings.py exists on disk but is not in the fed list: invisible.
+ list_snap = WalkSnapshot.from_files(tree, ["main.go"])
+ assert list(list_snap.iter_glob(tree, "settings.py")) == []
+ assert [p.name for p in list_snap.iter_glob(tree, "*.go")] == ["main.go"]
+
+ def test_from_files_is_deterministic(self, tree: Path) -> None:
+ rels = ["b/two.py", "a/one.py", "a/sub/three.py"]
+ first = list(WalkSnapshot.from_files(tree, rels).iter_glob(tree, "*.py"))
+ second = list(WalkSnapshot.from_files(tree, reversed(rels)).iter_glob(tree, "*.py"))
+ assert first == second
+
def test_extractor_rglob_uses_attached_snapshot(self, tree: Path) -> None:
from repowise.core.ingestion.dynamic_hints.base import DynamicHintExtractor