Skip to content

Commit 1292639

Browse files
Yyunozorsafishamsi
authored andcommitted
fix(python): keep TYPE_CHECKING-only imports out of import cycles (#3159)
Imports under `if TYPE_CHECKING:` never execute, but the Python extractor emitted them as ordinary `imports_from` edges, so the Import Cycles section listed cycles that cannot happen at runtime. Stamp them `type_only`, the marker find_import_cycles already skips for TypeScript `import type` (#3123); the edge stays in the graph. Covers `TYPE_CHECKING` and `<module>.TYPE_CHECKING`, `import x`, `from x import y`, relative imports and nesting. The `else:` branch and the body of `if not TYPE_CHECKING:` stay runtime imports. build_from_json collapses the import edges of one file pair into one, and dedupe_edges those of one (source, target, relation), keeping the marker of either side. Stamping alone would let a guarded import mask a runtime one (for example `from . import b` plus a guarded `from .b import B`) and lose a real cycle. The collapsed edge is therefore `type_only` only if every import folded into it is: an import that runs always wins. The same collapse already hid a real cycle for TypeScript `import type` next to a value import of one file. In the default undirected graph, the reverse-direction duplicate that #1061 drops is the other file's import, so it leaves the surviving edge's marker alone. Not covered: `from pkg import submodule` under the guard. That edge comes from the resolution pass and is not stamped, so its cycle is still reported. Assisted-by: assayer harness on Claude Code (https://github.com/Yyunozor/assayer-memory-mcp) (cherry picked from commit 685b0ff)
1 parent a061e0b commit 1292639

3 files changed

Lines changed: 261 additions & 7 deletions

File tree

‎graphify/build.py‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,21 @@ def dedupe_nodes(nodes: list[dict]) -> list[dict]:
650650
return list(by_id.values())
651651

652652

653+
def _execution_wins(a: dict, b: dict) -> None:
654+
"""Fold the ``type_only`` marker of two import edges that collapse to one.
655+
656+
``type_only`` flags an import that never runs (``import type``, ``if
657+
TYPE_CHECKING:``); ``find_import_cycles`` skips such an edge. When two edges
658+
of one file pair collapse (``G.add_edge`` merges their attributes,
659+
``dedupe_edges`` keeps the first), the marker of one side would stand for a
660+
runtime import on the other and hide its cycle. The surviving edge stays
661+
``type_only`` only if every import folded into it is (#3159).
662+
"""
663+
if bool(a.get("type_only")) != bool(b.get("type_only")):
664+
a.pop("type_only", None)
665+
b.pop("type_only", None)
666+
667+
653668
def dedupe_edges(edges: list[dict]) -> list[dict]:
654669
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
655670
first occurrence.
@@ -660,15 +675,18 @@ def dedupe_edges(edges: list[dict]) -> list[dict]:
660675
duplicates accumulate and edge counts become non-deterministic across build
661676
modes / repeated updates (#1317). Deduping on the connectivity identity is
662677
zero-signal-loss and restores idempotency. Callers that intentionally keep
663-
parallel edges (multigraph output) must not use this.
678+
parallel edges (multigraph output) must not use this. The one attribute that
679+
is not taken from the first occurrence alone is ``type_only`` (see
680+
:func:`_execution_wins`).
664681
"""
665-
seen: set[tuple] = set()
682+
seen: dict[tuple, dict] = {}
666683
out: list[dict] = []
667684
for e in edges:
668685
key = (e.get("source"), e.get("target"), e.get("relation"))
669686
if key in seen:
687+
_execution_wins(seen[key], e)
670688
continue
671-
seen.add(key)
689+
seen[key] = e
672690
out.append(e)
673691
return out
674692

@@ -1423,6 +1441,20 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
14231441
# causing display functions to show edges backwards.
14241442
attrs["_src"] = src
14251443
attrs["_tgt"] = tgt
1444+
# Before the drops below, so a runtime import that folds into a
1445+
# type-only edge still clears its marker (#3159). The reverse-direction
1446+
# duplicate that the undirected graph drops (#1061) is another file's
1447+
# import, not this one: the surviving edge keeps its own marker.
1448+
# `_EXTERNAL_STUB_RELATIONS` is the import family (imports, imports_from, re_exports).
1449+
if _edge_rel in _EXTERNAL_STUB_RELATIONS and G.has_edge(src, tgt):
1450+
_prior = G[src][tgt] # G is a plain Graph/DiGraph here, one dict per pair
1451+
_reverse_dup = (
1452+
not G.is_directed()
1453+
and _prior.get("relation") == attrs.get("relation")
1454+
and _prior.get("_src") == tgt and _prior.get("_tgt") == src
1455+
)
1456+
if _prior.get("relation") in _EXTERNAL_STUB_RELATIONS and not _reverse_dup:
1457+
_execution_wins(_prior, attrs)
14261458
# When the graph is undirected and the same node pair appears twice with
14271459
# the same relation but opposite directions (e.g. a `calls` b and b `calls` a),
14281460
# nx.Graph collapses them into one edge. The deterministic sort above means

‎graphify/extract.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,33 @@ def _missing_relative_module_name(attempted: Path, root: Path, raw: str) -> str:
693693
return ".".join(parts) if parts else f"ref:{raw}"
694694

695695

696+
def _python_under_type_checking(node, source: bytes) -> bool:
697+
"""True when ``node`` sits in the body of an ``if TYPE_CHECKING:`` block.
698+
699+
Matches ``TYPE_CHECKING`` and ``<module>.TYPE_CHECKING`` (``typing.``,
700+
``t.``, ``typing_extensions.``). Only the guarded body counts: the
701+
``else:`` branch of the same ``if`` runs at import time, and so does the
702+
body of ``if not TYPE_CHECKING:``.
703+
"""
704+
child, parent = node, node.parent
705+
while parent is not None:
706+
if (
707+
parent.type in ("if_statement", "elif_clause")
708+
and parent.child_by_field_name("consequence") == child
709+
):
710+
cond = parent.child_by_field_name("condition")
711+
if cond is not None and cond.type == "attribute":
712+
cond = cond.child_by_field_name("attribute")
713+
if (
714+
cond is not None
715+
and cond.type == "identifier"
716+
and _read_text(cond, source) == "TYPE_CHECKING"
717+
):
718+
return True
719+
child, parent = parent, parent.parent
720+
return False
721+
722+
696723
def _import_python(
697724
node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str,
698725
scope_stack: list[str] | None = None, scan_root: Path | None = None,
@@ -708,6 +735,9 @@ def _import_python(
708735
root = root.resolve()
709736
except OSError:
710737
pass
738+
# Imports under `if TYPE_CHECKING:` never run, so they are stamped `type_only`
739+
# like TS `import type`: find_import_cycles skips them, the edge stays (#3159).
740+
type_only = _python_under_type_checking(node, source)
711741
if t == "import_statement":
712742
for child in node.children:
713743
if child.type in ("dotted_name", "aliased_import"):
@@ -755,6 +785,8 @@ def _import_python(
755785
# member-call resolver can match `alias.func()` against this
756786
# edge instead of dropping it (#2082).
757787
edge["local_alias"] = raw_alias.strip()
788+
if type_only:
789+
edge["type_only"] = True
758790
edges.append(edge)
759791
elif t == "import_from_statement":
760792
module_node = node.child_by_field_name("module_name")
@@ -847,6 +879,8 @@ def _import_python(
847879
edge["target_file"] = str(target_path)
848880
except OSError:
849881
pass
882+
if type_only:
883+
edge["type_only"] = True
850884
edges.append(edge)
851885

852886

‎tests/test_type_only_import_cycles.py‎

Lines changed: 192 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,21 @@
1111
The edge is kept — the type dependency is real for "what references this
1212
type" — stamped `type_only`, and `find_import_cycles` excludes it the way
1313
it already excludes deferred `import(...)` (#1241).
14+
15+
Python's `if TYPE_CHECKING:` imports never execute either and get the same
16+
stamp (#3159). Merging two edges of one file pair keeps an attribute from
17+
either, so the merged edge is `type_only` only if every import folded into it
18+
is: a runtime import next to a type-only one keeps its cycle.
1419
"""
1520
from __future__ import annotations
1621

1722
import tempfile
1823
from pathlib import Path
1924

25+
import pytest
26+
2027
from graphify.analyze import find_import_cycles
21-
from graphify.build import build_from_json
28+
from graphify.build import build_from_json, dedupe_edges
2229
from graphify.extract import extract
2330

2431

@@ -94,13 +101,16 @@ def test_plain_imports_are_untouched(tmp_path):
94101
# The cycles — the reporter's minimal repro
95102
# ---------------------------------------------------------------------------
96103

97-
def _cycles(tmp_path, files):
104+
def _cycles(tmp_path, files, directed=True, raw=False):
98105
r = _extract(tmp_path, files)
99106
# directed=True mirrors a --directed build; in the default undirected
100107
# graph two module edges between one file pair collapse to a single
101108
# stored edge, so a synthetic 2-cycle needs distinct endpoints anyway.
102-
G = build_from_json({"nodes": r["nodes"], "edges": r["edges"], "hyperedges": []},
103-
root=str(tmp_path), directed=True)
109+
# raw=True takes the `update --no-cluster` route: edges are deduplicated
110+
# before the graph is built from that graph.json (`cluster-only`).
111+
edges = dedupe_edges(r["edges"]) if raw else r["edges"]
112+
G = build_from_json({"nodes": r["nodes"], "edges": edges, "hyperedges": []},
113+
root=str(tmp_path), directed=directed)
104114
return find_import_cycles(G)
105115

106116

@@ -131,3 +141,181 @@ def test_a_cycle_with_one_type_only_leg_is_not_a_cycle(tmp_path):
131141
"b.ts": 'import type { AT } from "./a.js";\nexport const b = 2;\n',
132142
})
133143
assert cycles == [], cycles
144+
145+
146+
def test_undirected_graph_keeps_the_marker_when_the_reverse_import_is_dropped(tmp_path):
147+
"""Default undirected graph: b imports a at runtime, a only `import type`s b.
148+
The pair keeps one edge (#1061); a's type-only import must not become a
149+
runtime leg closing a -> b -> c -> a."""
150+
cycles = _cycles(tmp_path, {
151+
"a.ts": "import type { B } from './b';\nexport class A { b?: B; }\n",
152+
"b.ts": ("import { A } from './a';\nimport { C } from './c';\n"
153+
"export class B { a = new A(); c = new C(); }\n"),
154+
"c.ts": "import { A } from './a';\nexport class C { a = new A(); }\n",
155+
}, directed=False)
156+
assert cycles == [], cycles
157+
158+
159+
# ---------------------------------------------------------------------------
160+
# Python: imports under `if TYPE_CHECKING:` (#3159)
161+
# ---------------------------------------------------------------------------
162+
163+
def _stamped_by_line(result, importer):
164+
"""{line: some edge of that import statement is stamped} for one file."""
165+
out: dict[int, bool] = {}
166+
for e in result["edges"]:
167+
if e["source_file"].endswith(importer) and e["relation"] in ("imports", "imports_from"):
168+
line = int(e["source_location"][1:])
169+
out[line] = out.get(line, False) or bool(e.get("type_only"))
170+
return out
171+
172+
173+
def _names(cycles):
174+
return sorted(sorted(Path(f).name for f in c["cycle"]) for c in cycles)
175+
176+
177+
def test_python_imports_under_type_checking_are_stamped(tmp_path):
178+
r = _extract(tmp_path, {
179+
"pkg/__init__.py": "",
180+
"pkg/models.py": "class Item: ...\n",
181+
"pkg/service.py": (
182+
"import sys\n" # 1
183+
"import typing\n" # 2
184+
"from typing import TYPE_CHECKING\n" # 3
185+
"\n" # 4
186+
"if TYPE_CHECKING:\n" # 5
187+
" from pkg.models import Item\n" # 6
188+
" import pkg.models\n" # 7
189+
" from .models import Item as Rel\n" # 8
190+
" if sys.version_info >= (3, 11):\n" # 9
191+
" from pkg.models import Item as Nested\n" # 10
192+
"if typing.TYPE_CHECKING:\n" # 11
193+
" from pkg.models import Item as Attr\n" # 12
194+
),
195+
})
196+
stamped = _stamped_by_line(r, "service.py")
197+
assert [line for line, flag in stamped.items() if flag] == [6, 7, 8, 10, 12]
198+
199+
200+
def test_python_imports_that_run_are_not_stamped(tmp_path):
201+
"""The `else:` of the guard and `if not TYPE_CHECKING:` run at import time."""
202+
r = _extract(tmp_path, {
203+
"models.py": "class Item: ...\n",
204+
"fallback.py": "class Item: ...\n",
205+
"service.py": (
206+
"from typing import TYPE_CHECKING\n" # 1
207+
"import models\n" # 2
208+
"if TYPE_CHECKING:\n" # 3
209+
" from models import Item\n" # 4
210+
"else:\n" # 5
211+
" from fallback import Item\n" # 6
212+
"if not TYPE_CHECKING:\n" # 7
213+
" from models import Item as Late\n" # 8
214+
),
215+
})
216+
stamped = _stamped_by_line(r, "service.py")
217+
assert [line for line, flag in stamped.items() if flag] == [4]
218+
assert {1, 2, 6, 8} <= set(stamped)
219+
220+
221+
@pytest.mark.parametrize("service_import, expected", [
222+
("if TYPE_CHECKING:\n from app import AppState\n", []),
223+
("from app import AppState\n", [["app.py", "service.py"]]),
224+
], ids=["guarded", "runtime"])
225+
def test_python_two_file_cycle_closes_only_through_a_runtime_import(tmp_path, service_import, expected):
226+
"""The shape in the issue, in a directed build."""
227+
cycles = _cycles(tmp_path, {
228+
"app.py": "from service import Service\n\nclass AppState:\n service: Service\n",
229+
"service.py": ("from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\n"
230+
+ service_import
231+
+ "\nclass Service:\n def run(self, state: AppState):\n return state\n"),
232+
})
233+
assert _names(cycles) == expected
234+
235+
236+
@pytest.mark.parametrize("adapter_import, expected", [
237+
("if TYPE_CHECKING:\n from pkg.main import AppState\n", []),
238+
("from pkg.main import AppState\n", [["adapter.py", "main.py", "service.py"]]),
239+
], ids=["guarded", "runtime"])
240+
def test_python_three_file_ring_closes_only_through_a_runtime_import(tmp_path, adapter_import, expected):
241+
"""The reporter's shape, in the default undirected build."""
242+
cycles = _cycles(tmp_path, {
243+
"pkg/__init__.py": "",
244+
"pkg/main.py": "from pkg.service import Service\n\nclass AppState:\n service: Service\n",
245+
"pkg/service.py": "from pkg.adapter import Adapter\n\nclass Service:\n adapter: Adapter\n",
246+
"pkg/adapter.py": ("from typing import TYPE_CHECKING\n\n" + adapter_import
247+
+ "\nclass Adapter:\n def bind(self, state: 'AppState'): ...\n"),
248+
}, directed=False)
249+
assert _names(cycles) == expected
250+
251+
252+
# A runtime import and a guarded one for the same pair: the cycle stays ---------
253+
254+
@pytest.mark.parametrize("a_body", [
255+
"from typing import TYPE_CHECKING\nfrom b import helper\n\nif TYPE_CHECKING:\n from b import B\n",
256+
"from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from b import B\n\nfrom b import helper\n",
257+
], ids=["runtime-first", "guard-first"])
258+
def test_python_runtime_and_guarded_import_of_one_module_keep_the_cycle(tmp_path, a_body):
259+
cycles = _cycles(tmp_path, {
260+
"a.py": a_body + "\ndef f(x: 'B'):\n return helper(x)\n",
261+
"b.py": "from a import f\n\nclass B: ...\n\ndef helper(x):\n return f\n",
262+
})
263+
assert _names(cycles) == [["a.py", "b.py"]]
264+
265+
266+
_RING_X6 = {
267+
# a -> b is `from . import b` (resolution pass, not stamped) plus a guarded `from .b import B`
268+
"pkg/__init__.py": "",
269+
"pkg/a.py": ("from . import b\nfrom typing import TYPE_CHECKING\n\n"
270+
"if TYPE_CHECKING:\n from .b import B\n\n"
271+
"def f(x: 'B'):\n return b.helper(x)\n"),
272+
"pkg/b.py": "from pkg.c import C\n\nclass B: ...\n\ndef helper(x):\n return C\n",
273+
"pkg/c.py": "from pkg.a import f\n\nclass C:\n run = f\n",
274+
}
275+
276+
277+
@pytest.mark.parametrize("directed, raw", [(False, False), (True, False), (False, True)],
278+
ids=["undirected", "directed", "no-cluster-raw"])
279+
def test_python_ring_through_a_submodule_import_and_a_guard_keeps_its_cycle(tmp_path, directed, raw):
280+
cycles = _cycles(tmp_path, _RING_X6, directed=directed, raw=raw)
281+
assert _names(cycles) == [["a.py", "b.py", "c.py"]]
282+
283+
284+
def test_python_guard_in_one_direction_keeps_the_runtime_import_in_the_other(tmp_path):
285+
"""Undirected, a pair is one edge: a.py's guarded `import pkg.b` folds with
286+
b.py's runtime `from pkg.a import A`, which closes the ring a -> c -> b -> a."""
287+
cycles = _cycles(tmp_path, {
288+
"pkg/__init__.py": "",
289+
"pkg/a.py": ("from typing import TYPE_CHECKING\n\nfrom pkg.c import C\n\n"
290+
"if TYPE_CHECKING:\n import pkg.b\n\nclass A:\n c: C\n"),
291+
"pkg/b.py": "from pkg.a import A\n\nclass B:\n a: A\n",
292+
"pkg/c.py": "from pkg.b import B\n\nclass C:\n b: B\n",
293+
}, directed=False)
294+
assert _names(cycles) == [["a.py", "b.py", "c.py"]]
295+
296+
297+
def test_a_type_import_beside_a_value_import_of_the_same_file_keeps_the_cycle(tmp_path):
298+
"""The same merge hid a real cycle for TypeScript (#3123)."""
299+
cycles = _cycles(tmp_path, {
300+
"a.ts": ('import type { B } from "./b.js";\nimport { helper } from "./b.js";\n'
301+
"export const a = (x: B) => helper(x);\n"),
302+
"b.ts": ('import { a } from "./a.js";\nexport type B = number;\n'
303+
"export function helper(x: number) { return a; }\n"),
304+
})
305+
assert _names(cycles) == [["a.ts", "b.ts"]]
306+
307+
308+
def test_a_runtime_import_dropped_by_the_merge_still_clears_the_marker():
309+
"""build_from_json drops a lower-confidence duplicate of an edge it already
310+
holds; the type-only marker must not outlive the runtime import it dropped."""
311+
def edge(src, tgt, conf, line, **extra):
312+
return {"source": src, "target": tgt, "relation": "imports_from", "confidence": conf,
313+
"source_file": f"{src}.py", "source_location": f"L{line}", **extra}
314+
315+
nodes = [{"id": n, "label": f"{n}.py", "source_file": f"{n}.py", "file_type": "code"}
316+
for n in ("a", "b")]
317+
edges = [edge("a", "b", "EXTRACTED", 1, type_only=True),
318+
edge("a", "b", "INFERRED", 2),
319+
edge("b", "a", "EXTRACTED", 1)]
320+
G = build_from_json({"nodes": nodes, "edges": edges, "hyperedges": []}, directed=True)
321+
assert _names(find_import_cycles(G)) == [["a.py", "b.py"]]

0 commit comments

Comments
 (0)