Skip to content

Commit 019a0f9

Browse files
authored
Merge pull request #13 from Modsofthenation/cursor/oss-pr-graph-verify-cc3d
Fix impact graphs and add a layered 3D view for large graphs
2 parents e9d8f71 + f24e689 commit 019a0f9

30 files changed

Lines changed: 5561 additions & 171 deletions

‎src/loadpath/architecture/snapshot.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from loadpath.architecture.depth import deepening_candidates
99
from loadpath.architecture.rules import evaluate
1010
from loadpath.config import LoadpathConfig, load_config
11-
from loadpath.graph.store import GraphStore
11+
from loadpath.graph.store import GraphStore, linked_edges
1212
from loadpath.index import default_db_path, index_drift
1313
from loadpath.types import NodeType
1414

@@ -18,6 +18,7 @@
1818
NodeType.ROUTE.value,
1919
NodeType.VIEW.value,
2020
NodeType.SERIALIZER.value,
21+
NodeType.FORM.value,
2122
NodeType.MODEL.value,
2223
NodeType.TASK.value,
2324
NodeType.MANAGEMENT_COMMAND.value,
@@ -77,9 +78,7 @@ def summarize_index(store: GraphStore, config: LoadpathConfig) -> dict[str, Any]
7778

7879
def architecture_graph(store: GraphStore) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
7980
nodes = [n for n in store.nodes() if n["type"] in ARCHITECTURE_NODE_TYPES]
80-
ids = {n["id"] for n in nodes}
81-
edges = [e for e in store.edges() if e["src"] in ids and e["dst"] in ids]
82-
return nodes, edges
81+
return nodes, linked_edges(nodes, store.edges())
8382

8483

8584
def architecture_report(repo_root: Path, db_path: Path | None = None) -> dict[str, Any]:

‎src/loadpath/detect.py‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
"site-packages",
2424
}
2525

26+
TESTISH_PARTS = {"test", "tests", "testing"}
27+
2628

2729
def _skip(path: Path) -> bool:
2830
return any(part in SKIP_DIRS or part.startswith(".") for part in path.parts)
@@ -115,15 +117,36 @@ def _first(repo_root: Path, name: str) -> str | None:
115117
return None
116118

117119

120+
def _is_testish(rel: Path) -> bool:
121+
return any(part in TESTISH_PARTS for part in rel.parts)
122+
123+
118124
def _detect_django_root(repo_root: Path) -> str:
119-
manage = None
120-
for path in repo_root.rglob("manage.py"):
121-
if _skip(path):
125+
"""Prefer the package that holds real apps, not a nested test project's manage.py."""
126+
parents: list[tuple[str, ...]] = []
127+
for marker in repo_root.rglob("apps.py"):
128+
if _skip(marker):
129+
continue
130+
app_dir = marker.parent
131+
if app_dir.name in {"migrations", "tests", "management"}:
132+
continue
133+
rel = app_dir.relative_to(repo_root)
134+
if _is_testish(rel):
122135
continue
123-
manage = path
124-
break
125-
if manage is not None:
126-
rel = manage.parent.relative_to(repo_root)
136+
parents.append(rel.parent.parts)
137+
if parents:
138+
common: list[str] = []
139+
for items in zip(*parents):
140+
if len(set(items)) == 1:
141+
common.append(items[0])
142+
else:
143+
break
144+
return "/".join(common) if common else "."
145+
146+
manages = [p for p in repo_root.rglob("manage.py") if not _skip(p)]
147+
manages.sort(key=lambda p: (_is_testish(p.relative_to(repo_root)), len(p.relative_to(repo_root).parts)))
148+
if manages:
149+
rel = manages[0].parent.relative_to(repo_root)
127150
return rel.as_posix() if rel.parts else "."
128151
for candidate in ("backend", "server", "api", "app"):
129152
if (repo_root / candidate).is_dir():
@@ -152,14 +175,15 @@ def _django_apps(repo_root: Path, django_root: str) -> list[str]:
152175
for marker in root.rglob("apps.py"):
153176
if _skip(marker):
154177
continue
155-
if marker.parent.name in {"migrations", "tests", "management"}:
178+
rel = marker.relative_to(repo_root)
179+
if _is_testish(rel) or marker.parent.name in {"migrations", "tests", "management"}:
156180
continue
157181
name = marker.parent.name
158182
if name not in apps and name not in {"config", "project", "settings"}:
159183
apps.append(name)
160184
if not apps:
161185
for marker in root.rglob("models.py"):
162-
if _skip(marker):
186+
if _skip(marker) or _is_testish(marker.relative_to(repo_root)):
163187
continue
164188
name = marker.parent.name
165189
if name not in apps and name not in {"migrations", "config"}:

‎src/loadpath/extractors/django.py‎

Lines changed: 88 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
}
3131

3232
SERIALIZER_BASES = {"Serializer", "ModelSerializer", "HyperlinkedModelSerializer", "ListSerializer"}
33+
FORM_BASES = {"Form", "ModelForm", "BaseForm", "BaseModelForm"}
3334
MODEL_BASES = {"Model"}
3435
ADMIN_BASES = {"ModelAdmin", "StackedInline", "TabularInline"}
3536
CELERY_DECORATORS = {"shared_task", "task", "periodic_task"}
@@ -141,7 +142,18 @@ def _app_from_path(rel: str) -> str | None:
141142
if idx > 0:
142143
return parts[idx - 1]
143144
for i, part in enumerate(parts):
144-
if part in {"models.py", "views.py", "serializers.py", "urls.py", "signals.py", "tasks.py", "admin.py", "apps.py"}:
145+
if part in {
146+
"models.py",
147+
"views.py",
148+
"serializers.py",
149+
"urls.py",
150+
"signals.py",
151+
"signal_handlers.py",
152+
"forms.py",
153+
"tasks.py",
154+
"admin.py",
155+
"apps.py",
156+
}:
145157
return parts[i - 1] if i > 0 else None
146158
if part == "management" and i > 0:
147159
return parts[i - 1]
@@ -216,6 +228,12 @@ def visit_ClassDef(self, node: ast.ClassDef) -> None:
216228
self._model(node)
217229
elif _has_base(node, SERIALIZER_BASES):
218230
self._serializer(node)
231+
elif _has_base(node, FORM_BASES) or (
232+
node.name.endswith("Form")
233+
and not node.name.startswith("Test")
234+
and not _has_base(node, {"TestCase", "SimpleTestCase", "TransactionTestCase", "LiveServerTestCase", "APITestCase"})
235+
):
236+
self._serializer(node, ntype=NodeType.FORM)
219237
elif _has_base(node, DJANGO_VIEW_BASES) or node.name.endswith(("View", "ViewSet")):
220238
self._view(node)
221239
elif any(b.split(".")[-1] in {"BaseCommand", "AppCommand", "LabelCommand"} for b in _bases(node)):
@@ -240,6 +258,7 @@ def visit_ClassDef(self, node: ast.ClassDef) -> None:
240258
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
241259
self._maybe_task(node)
242260
self._maybe_receiver(node)
261+
self._maybe_plain_signal_handler(node)
243262
self._maybe_command(node)
244263
self._maybe_test(node)
245264
self._maybe_service_fn(node)
@@ -282,8 +301,14 @@ def visit_Call(self, node: ast.Call) -> None:
282301
self.graph.residuals.append(f"Raw SQL ({fname}) in {self.rel_path}:{node.lineno}")
283302
elif short in {"select_related", "prefetch_related"}:
284303
pass
285-
elif short == "connect" and any(s in fname for s in SIGNAL_NAMES | {"signal"}):
286-
self._signal_connect(node, fname)
304+
elif short == "connect":
305+
handler = node.args[0] if node.args else _kw(node, "receiver")
306+
stem = Path(self.rel_path).stem
307+
looks_signal = stem in {"apps", "signals", "signal_handlers", "handlers"} or any(
308+
token in fname.lower() for token in {n.lower() for n in SIGNAL_NAMES} | {"signal"}
309+
)
310+
if looks_signal and isinstance(handler, (ast.Name, ast.Attribute)):
311+
self._signal_connect(node, fname)
287312
elif short == "reverse":
288313
self._reverse(node)
289314
self.generic_visit(node)
@@ -344,9 +369,12 @@ def _model(self, node: ast.ClassDef) -> None:
344369
if extra.get("on_delete") == "CASCADE":
345370
self.add_edge(model.id, rel_id, EdgeType.RELATES_TO, extra={"cascade": True})
346371

347-
def _serializer(self, node: ast.ClassDef) -> None:
372+
def _serializer(self, node: ast.ClassDef, ntype: NodeType = NodeType.SERIALIZER) -> None:
348373
qname = f"{self.app}.{node.name}"
349-
ser = self.add_node(NodeType.SERIALIZER, node.name, qname, node.lineno, {"app": self.app})
374+
extra: dict = {"app": self.app}
375+
if ntype is NodeType.FORM:
376+
extra["django_form"] = True
377+
ser = self.add_node(ntype, node.name, qname, node.lineno, extra)
350378
meta_model = None
351379
meta_fields: list[str] | None = None
352380
meta_exclude: list[str] | None = None
@@ -805,6 +833,27 @@ def _maybe_receiver(self, node: ast.FunctionDef) -> None:
805833
model_q = sender if "." in sender else f"{self.app}.{sender.split('.')[-1]}"
806834
self.add_edge(recv.id, node_id(NodeType.MODEL, model_q), EdgeType.EMITS_SIGNAL)
807835

836+
def _maybe_plain_signal_handler(self, node: ast.FunctionDef) -> None:
837+
if self.class_stack:
838+
return
839+
if Path(self.rel_path).stem not in {"signals", "signal_handlers", "handlers"}:
840+
return
841+
for dec in node.decorator_list:
842+
dname = _name(dec.func if isinstance(dec, ast.Call) else dec) or ""
843+
if dname.split(".")[-1] == "receiver":
844+
return
845+
args = [a.arg for a in node.args.args]
846+
if not (node.args.kwarg or "instance" in args or "sender" in args):
847+
return
848+
qname = f"{self.app}.{node.name}"
849+
self.add_node(
850+
NodeType.RECEIVER,
851+
node.name,
852+
qname,
853+
node.lineno,
854+
{"app": self.app, "plain_handler": True},
855+
)
856+
808857
def _maybe_command(self, node: ast.FunctionDef) -> None:
809858
if "management/commands" in self.rel_path and node.name == "handle":
810859
cmd = Path(self.rel_path).stem
@@ -833,7 +882,7 @@ def _maybe_test(self, node: ast.FunctionDef) -> None:
833882
# crude: referenced class names in the test become tested_by
834883
for child in ast.walk(node):
835884
if isinstance(child, ast.Name) and child.id[:1].isupper():
836-
for ntype in (NodeType.SERIALIZER, NodeType.VIEW, NodeType.MODEL, NodeType.SERVICE):
885+
for ntype in (NodeType.SERIALIZER, NodeType.FORM, NodeType.VIEW, NodeType.MODEL, NodeType.SERVICE, NodeType.RECEIVER):
837886
self.add_edge(
838887
node_id(ntype, f"{self.app}.{child.id}"),
839888
test.id,
@@ -915,7 +964,39 @@ def _get_model(self, node: ast.Call) -> None:
915964
self.add_node(NodeType.MODEL, label.split(".")[-1], label, node.lineno, {"string_ref": True})
916965

917966
def _signal_connect(self, node: ast.Call, fname: str) -> None:
918-
self.graph.residuals.append(f"signal.connect() at {self.rel_path}:{node.lineno} ({fname})")
967+
handler_ast = node.args[0] if node.args else _kw(node, "receiver")
968+
handler = _name(handler_ast)
969+
signal = fname.rsplit(".", 1)[0] if "." in fname else None
970+
sender = _name(_kw(node, "sender"))
971+
if not handler:
972+
self.graph.residuals.append(f"signal.connect() at {self.rel_path}:{node.lineno} ({fname})")
973+
return
974+
handler_short = handler.split(".")[-1]
975+
qname = handler if "." in handler else f"{self.app}.{handler_short}"
976+
extra = {
977+
"app": self.app,
978+
"signal": signal,
979+
"sender": sender,
980+
"referenced": True,
981+
"via": "connect",
982+
}
983+
recv = self.add_node(NodeType.RECEIVER, handler_short, qname, node.lineno, extra)
984+
if signal:
985+
sig_short = signal.split(".")[-1]
986+
sig_id = node_id(NodeType.SIGNAL, sig_short)
987+
self.graph.nodes.append(
988+
Node(
989+
id=sig_id,
990+
type=NodeType.SIGNAL,
991+
name=sig_short,
992+
qualified_name=sig_short,
993+
extra={"referenced": True},
994+
)
995+
)
996+
self.add_edge(sig_id, recv.id, EdgeType.RECEIVES)
997+
if sender:
998+
model_q = sender if "." in sender else f"{self.app}.{sender.split('.')[-1]}"
999+
self.add_edge(recv.id, node_id(NodeType.MODEL, model_q), EdgeType.EMITS_SIGNAL)
9191000

9201001
def _reverse(self, node: ast.Call) -> None:
9211002
name = _const_str(node.args[0]) if node.args else None

‎src/loadpath/graph/store.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@
5959
"""
6060

6161

62+
def linked_edges(nodes: Iterable[dict[str, Any]], edges: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
63+
"""Keep only edges whose src and dst both exist in `nodes`."""
64+
ids = {n["id"] for n in nodes if n and n.get("id")}
65+
return [e for e in edges if e.get("src") in ids and e.get("dst") in ids]
66+
67+
6268
class GraphStore:
6369
def __init__(self, db_path: Path) -> None:
6470
self.db_path = Path(db_path)
@@ -248,7 +254,8 @@ def nodes_in_files(self, paths: Iterable[str]) -> list[dict[str, Any]]:
248254
return [self._node_from_row(r) for r in rows]
249255

250256
def subgraph(self, seed_ids: Iterable[str], hops: int = 6) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
251-
frontier = set(seed_ids)
257+
known = {r["id"] for r in self.conn.execute("SELECT id FROM nodes")}
258+
frontier = set(seed_ids) & known
252259
seen_nodes = set(frontier)
253260
seen_edges: dict[str, dict[str, Any]] = {}
254261
for _ in range(hops):
@@ -257,14 +264,16 @@ def subgraph(self, seed_ids: Iterable[str], hops: int = 6) -> tuple[list[dict[st
257264
nxt: set[str] = set()
258265
for nid in frontier:
259266
for edge in self.neighbors(nid, "both"):
260-
seen_edges[edge["id"]] = edge
261267
other = edge["dst"] if edge["src"] == nid else edge["src"]
268+
if other not in known:
269+
continue
270+
seen_edges[edge["id"]] = edge
262271
if other not in seen_nodes:
263272
seen_nodes.add(other)
264273
nxt.add(other)
265274
frontier = nxt
266-
nodes = [self.get_node(i) for i in seen_nodes]
267-
return [n for n in nodes if n], list(seen_edges.values())
275+
nodes = [n for n in (self.get_node(i) for i in seen_nodes) if n]
276+
return nodes, linked_edges(nodes, list(seen_edges.values()))
268277

269278
def iter_nodes(self) -> Iterator[dict[str, Any]]:
270279
for row in self.conn.execute("SELECT * FROM nodes"):

‎src/loadpath/index.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
PY_SKIP = {"migrations"} # still extract migrations, just not skip
1616
INDEX_EXTENSIONS = {".py", ".ts", ".tsx", ".js", ".jsx"}
1717
# Bump when extractor/stitch node identity changes so incremental indexes rebuild.
18-
INDEX_REVISION = "3"
18+
INDEX_REVISION = "4"
1919

2020

2121
def default_db_path(repo_root: Path) -> Path:
@@ -143,7 +143,8 @@ def index_repo(
143143
store.set_meta("repo_root", str(repo_root))
144144

145145
drift = index_drift(store, repo_root, config)
146-
if incremental and store.file_count() > 0 and not drift["stale"]:
146+
revision_changed = (store.get_meta("index_revision") or "") != INDEX_REVISION
147+
if incremental and store.file_count() > 0 and not drift["stale"] and not revision_changed:
147148
store.set_meta("reindex_skipped", "1")
148149
store.set_meta("files_extracted", "0")
149150
store.set_meta("files_skipped", str(drift["indexed_count"]))
@@ -161,7 +162,7 @@ def index_repo(
161162
for path in files:
162163
rel = path.relative_to(repo_root).as_posix()
163164
digest = file_hash(path)
164-
if incremental and store.file_hash(rel) == digest:
165+
if incremental and not revision_changed and store.file_hash(rel) == digest:
165166
skipped.add(rel)
166167
continue
167168
store.delete_file_nodes(rel, drop_incoming=False)
@@ -214,6 +215,7 @@ def index_repo(
214215
store.set_meta("django_boot_detail", boot_detail)
215216
store.set_meta("config_hash", _config_digest(repo_root))
216217
store.set_meta("sidecar_hash", _sidecar_digest(repo_root, config))
218+
store.set_meta("index_revision", INDEX_REVISION)
217219
store.conn.commit()
218220
return store
219221

‎src/loadpath/report/graph.html‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,9 @@ <h1>Loadpath</h1>
8989
title: n.qualified_name + "\\n" + (n.file_path || ""),
9090
shape: n.type && n.type.startsWith("react.") ? "box" : "dot",
9191
})));
92+
const nodeIds = new Set(nodes.map(n => n.id));
9293
const weightColor = { cheap: "#4a5568", expensive: "#f4a261", critical: "#e85d04" };
93-
const dataEdges = new vis.DataSet(edges.map(e => ({
94+
const dataEdges = new vis.DataSet(edges.filter(e => nodeIds.has(e.src) && nodeIds.has(e.dst)).map(e => ({
9495
id: e.id,
9596
from: e.src,
9697
to: e.dst,

‎src/loadpath/review/cluster.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22

33
from collections import defaultdict
44

5-
from loadpath.graph.store import GraphStore
5+
from loadpath.graph.store import GraphStore, linked_edges
66
from loadpath.review.diff import DiffSet
77
from loadpath.types import NodeType, SINK_TYPES
88

99
CLUSTER_SEED_PRIORITY = [
1010
NodeType.SERIALIZER,
1111
NodeType.SERIALIZER_FIELD,
12+
NodeType.FORM,
1213
NodeType.MODEL,
1314
NodeType.FIELD,
1415
NodeType.ROUTE,
@@ -113,6 +114,8 @@ def include(nid: str, expand: bool) -> None:
113114
if e["type"] not in FORWARD_TYPES:
114115
continue
115116
other = e["dst"]
117+
if other not in by_id:
118+
continue
116119
other_node = by_id.get(other) or {}
117120
expand = other_node.get("type") not in BRIDGE_TYPES
118121
if (
@@ -143,6 +146,8 @@ def include(nid: str, expand: bool) -> None:
143146
if e["type"] == "belongs_to" and node.get("type") != NodeType.FEATURE_MODULE.value:
144147
continue
145148
other = e["src"]
149+
if other not in by_id:
150+
continue
146151
other_node = by_id.get(other) or {}
147152
if other_node.get("type") in BRIDGE_TYPES:
148153
kept_edges[e["id"]] = e
@@ -155,7 +160,7 @@ def include(nid: str, expand: bool) -> None:
155160
frontier = {i for i in nxt if i not in working}
156161

157162
nodes = [by_id[i] for i in seen if i in by_id]
158-
return nodes, list(kept_edges.values())
163+
return nodes, linked_edges(nodes, list(kept_edges.values()))
159164

160165

161166
def cluster_diff(

0 commit comments

Comments
 (0)