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 685b0fffb5)
This commit is contained in:
1 parent
a061e0b727
commit
1292639344
3 files changed
+261
-7
No files matched your search
+35
-3
@@ -650,6 +650,21 @@ def dedupe_nodes(nodes: list[dict]) -> list[dict]:
|
||||
return list(by_id.values())
|
||||
|
||||
|
||||
def _execution_wins(a: dict, b: dict) -> None:
|
||||
"""Fold the ``type_only`` marker of two import edges that collapse to one.
|
||||
|
||||
``type_only`` flags an import that never runs (``import type``, ``if
|
||||
TYPE_CHECKING:``); ``find_import_cycles`` skips such an edge. When two edges
|
||||
of one file pair collapse (``G.add_edge`` merges their attributes,
|
||||
``dedupe_edges`` keeps the first), the marker of one side would stand for a
|
||||
runtime import on the other and hide its cycle. The surviving edge stays
|
||||
``type_only`` only if every import folded into it is (#3159).
|
||||
"""
|
||||
if bool(a.get("type_only")) != bool(b.get("type_only")):
|
||||
a.pop("type_only", None)
|
||||
b.pop("type_only", None)
|
||||
|
||||
|
||||
def dedupe_edges(edges: list[dict]) -> list[dict]:
|
||||
"""Collapse exact parallel edges by ``(source, target, relation)``, keeping the
|
||||
first occurrence.
|
||||
@@ -660,15 +675,18 @@ def dedupe_edges(edges: list[dict]) -> list[dict]:
|
||||
duplicates accumulate and edge counts become non-deterministic across build
|
||||
modes / repeated updates (#1317). Deduping on the connectivity identity is
|
||||
zero-signal-loss and restores idempotency. Callers that intentionally keep
|
||||
parallel edges (multigraph output) must not use this.
|
||||
parallel edges (multigraph output) must not use this. The one attribute that
|
||||
is not taken from the first occurrence alone is ``type_only`` (see
|
||||
:func:`_execution_wins`).
|
||||
"""
|
||||
seen: set[tuple] = set()
|
||||
seen: dict[tuple, dict] = {}
|
||||
out: list[dict] = []
|
||||
for e in edges:
|
||||
key = (e.get("source"), e.get("target"), e.get("relation"))
|
||||
if key in seen:
|
||||
_execution_wins(seen[key], e)
|
||||
continue
|
||||
seen.add(key)
|
||||
seen[key] = e
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
@@ -1423,6 +1441,20 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
# causing display functions to show edges backwards.
|
||||
attrs["_src"] = src
|
||||
attrs["_tgt"] = tgt
|
||||
# Before the drops below, so a runtime import that folds into a
|
||||
# type-only edge still clears its marker (#3159). The reverse-direction
|
||||
# duplicate that the undirected graph drops (#1061) is another file's
|
||||
# import, not this one: the surviving edge keeps its own marker.
|
||||
# `_EXTERNAL_STUB_RELATIONS` is the import family (imports, imports_from, re_exports).
|
||||
if _edge_rel in _EXTERNAL_STUB_RELATIONS and G.has_edge(src, tgt):
|
||||
_prior = G[src][tgt] # G is a plain Graph/DiGraph here, one dict per pair
|
||||
_reverse_dup = (
|
||||
not G.is_directed()
|
||||
and _prior.get("relation") == attrs.get("relation")
|
||||
and _prior.get("_src") == tgt and _prior.get("_tgt") == src
|
||||
)
|
||||
if _prior.get("relation") in _EXTERNAL_STUB_RELATIONS and not _reverse_dup:
|
||||
_execution_wins(_prior, attrs)
|
||||
# When the graph is undirected and the same node pair appears twice with
|
||||
# the same relation but opposite directions (e.g. a `calls` b and b `calls` a),
|
||||
# nx.Graph collapses them into one edge. The deterministic sort above means
|
||||
|
||||
@@ -693,6 +693,33 @@ def _missing_relative_module_name(attempted: Path, root: Path, raw: str) -> str:
|
||||
return ".".join(parts) if parts else f"ref:{raw}"
|
||||
|
||||
|
||||
def _python_under_type_checking(node, source: bytes) -> bool:
|
||||
"""True when ``node`` sits in the body of an ``if TYPE_CHECKING:`` block.
|
||||
|
||||
Matches ``TYPE_CHECKING`` and ``<module>.TYPE_CHECKING`` (``typing.``,
|
||||
``t.``, ``typing_extensions.``). Only the guarded body counts: the
|
||||
``else:`` branch of the same ``if`` runs at import time, and so does the
|
||||
body of ``if not TYPE_CHECKING:``.
|
||||
"""
|
||||
child, parent = node, node.parent
|
||||
while parent is not None:
|
||||
if (
|
||||
parent.type in ("if_statement", "elif_clause")
|
||||
and parent.child_by_field_name("consequence") == child
|
||||
):
|
||||
cond = parent.child_by_field_name("condition")
|
||||
if cond is not None and cond.type == "attribute":
|
||||
cond = cond.child_by_field_name("attribute")
|
||||
if (
|
||||
cond is not None
|
||||
and cond.type == "identifier"
|
||||
and _read_text(cond, source) == "TYPE_CHECKING"
|
||||
):
|
||||
return True
|
||||
child, parent = parent, parent.parent
|
||||
return False
|
||||
|
||||
|
||||
def _import_python(
|
||||
node, source: bytes, file_nid: str, stem: str, edges: list, str_path: str,
|
||||
scope_stack: list[str] | None = None, scan_root: Path | None = None,
|
||||
@@ -708,6 +735,9 @@ def _import_python(
|
||||
root = root.resolve()
|
||||
except OSError:
|
||||
pass
|
||||
# Imports under `if TYPE_CHECKING:` never run, so they are stamped `type_only`
|
||||
# like TS `import type`: find_import_cycles skips them, the edge stays (#3159).
|
||||
type_only = _python_under_type_checking(node, source)
|
||||
if t == "import_statement":
|
||||
for child in node.children:
|
||||
if child.type in ("dotted_name", "aliased_import"):
|
||||
@@ -755,6 +785,8 @@ def _import_python(
|
||||
# member-call resolver can match `alias.func()` against this
|
||||
# edge instead of dropping it (#2082).
|
||||
edge["local_alias"] = raw_alias.strip()
|
||||
if type_only:
|
||||
edge["type_only"] = True
|
||||
edges.append(edge)
|
||||
elif t == "import_from_statement":
|
||||
module_node = node.child_by_field_name("module_name")
|
||||
@@ -847,6 +879,8 @@ def _import_python(
|
||||
edge["target_file"] = str(target_path)
|
||||
except OSError:
|
||||
pass
|
||||
if type_only:
|
||||
edge["type_only"] = True
|
||||
edges.append(edge)
|
||||
|
||||
|
||||
|
||||
@@ -11,14 +11,21 @@ defect.
|
||||
The edge is kept — the type dependency is real for "what references this
|
||||
type" — stamped `type_only`, and `find_import_cycles` excludes it the way
|
||||
it already excludes deferred `import(...)` (#1241).
|
||||
|
||||
Python's `if TYPE_CHECKING:` imports never execute either and get the same
|
||||
stamp (#3159). Merging two edges of one file pair keeps an attribute from
|
||||
either, so the merged edge is `type_only` only if every import folded into it
|
||||
is: a runtime import next to a type-only one keeps its cycle.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.analyze import find_import_cycles
|
||||
from graphify.build import build_from_json
|
||||
from graphify.build import build_from_json, dedupe_edges
|
||||
from graphify.extract import extract
|
||||
|
||||
|
||||
@@ -94,13 +101,16 @@ def test_plain_imports_are_untouched(tmp_path):
|
||||
# The cycles — the reporter's minimal repro
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cycles(tmp_path, files):
|
||||
def _cycles(tmp_path, files, directed=True, raw=False):
|
||||
r = _extract(tmp_path, files)
|
||||
# directed=True mirrors a --directed build; in the default undirected
|
||||
# graph two module edges between one file pair collapse to a single
|
||||
# stored edge, so a synthetic 2-cycle needs distinct endpoints anyway.
|
||||
G = build_from_json({"nodes": r["nodes"], "edges": r["edges"], "hyperedges": []},
|
||||
root=str(tmp_path), directed=True)
|
||||
# raw=True takes the `update --no-cluster` route: edges are deduplicated
|
||||
# before the graph is built from that graph.json (`cluster-only`).
|
||||
edges = dedupe_edges(r["edges"]) if raw else r["edges"]
|
||||
G = build_from_json({"nodes": r["nodes"], "edges": edges, "hyperedges": []},
|
||||
root=str(tmp_path), directed=directed)
|
||||
return find_import_cycles(G)
|
||||
|
||||
|
||||
@@ -131,3 +141,181 @@ def test_a_cycle_with_one_type_only_leg_is_not_a_cycle(tmp_path):
|
||||
"b.ts": 'import type { AT } from "./a.js";\nexport const b = 2;\n',
|
||||
})
|
||||
assert cycles == [], cycles
|
||||
|
||||
|
||||
def test_undirected_graph_keeps_the_marker_when_the_reverse_import_is_dropped(tmp_path):
|
||||
"""Default undirected graph: b imports a at runtime, a only `import type`s b.
|
||||
The pair keeps one edge (#1061); a's type-only import must not become a
|
||||
runtime leg closing a -> b -> c -> a."""
|
||||
cycles = _cycles(tmp_path, {
|
||||
"a.ts": "import type { B } from './b';\nexport class A { b?: B; }\n",
|
||||
"b.ts": ("import { A } from './a';\nimport { C } from './c';\n"
|
||||
"export class B { a = new A(); c = new C(); }\n"),
|
||||
"c.ts": "import { A } from './a';\nexport class C { a = new A(); }\n",
|
||||
}, directed=False)
|
||||
assert cycles == [], cycles
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Python: imports under `if TYPE_CHECKING:` (#3159)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _stamped_by_line(result, importer):
|
||||
"""{line: some edge of that import statement is stamped} for one file."""
|
||||
out: dict[int, bool] = {}
|
||||
for e in result["edges"]:
|
||||
if e["source_file"].endswith(importer) and e["relation"] in ("imports", "imports_from"):
|
||||
line = int(e["source_location"][1:])
|
||||
out[line] = out.get(line, False) or bool(e.get("type_only"))
|
||||
return out
|
||||
|
||||
|
||||
def _names(cycles):
|
||||
return sorted(sorted(Path(f).name for f in c["cycle"]) for c in cycles)
|
||||
|
||||
|
||||
def test_python_imports_under_type_checking_are_stamped(tmp_path):
|
||||
r = _extract(tmp_path, {
|
||||
"pkg/__init__.py": "",
|
||||
"pkg/models.py": "class Item: ...\n",
|
||||
"pkg/service.py": (
|
||||
"import sys\n" # 1
|
||||
"import typing\n" # 2
|
||||
"from typing import TYPE_CHECKING\n" # 3
|
||||
"\n" # 4
|
||||
"if TYPE_CHECKING:\n" # 5
|
||||
" from pkg.models import Item\n" # 6
|
||||
" import pkg.models\n" # 7
|
||||
" from .models import Item as Rel\n" # 8
|
||||
" if sys.version_info >= (3, 11):\n" # 9
|
||||
" from pkg.models import Item as Nested\n" # 10
|
||||
"if typing.TYPE_CHECKING:\n" # 11
|
||||
" from pkg.models import Item as Attr\n" # 12
|
||||
),
|
||||
})
|
||||
stamped = _stamped_by_line(r, "service.py")
|
||||
assert [line for line, flag in stamped.items() if flag] == [6, 7, 8, 10, 12]
|
||||
|
||||
|
||||
def test_python_imports_that_run_are_not_stamped(tmp_path):
|
||||
"""The `else:` of the guard and `if not TYPE_CHECKING:` run at import time."""
|
||||
r = _extract(tmp_path, {
|
||||
"models.py": "class Item: ...\n",
|
||||
"fallback.py": "class Item: ...\n",
|
||||
"service.py": (
|
||||
"from typing import TYPE_CHECKING\n" # 1
|
||||
"import models\n" # 2
|
||||
"if TYPE_CHECKING:\n" # 3
|
||||
" from models import Item\n" # 4
|
||||
"else:\n" # 5
|
||||
" from fallback import Item\n" # 6
|
||||
"if not TYPE_CHECKING:\n" # 7
|
||||
" from models import Item as Late\n" # 8
|
||||
),
|
||||
})
|
||||
stamped = _stamped_by_line(r, "service.py")
|
||||
assert [line for line, flag in stamped.items() if flag] == [4]
|
||||
assert {1, 2, 6, 8} <= set(stamped)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("service_import, expected", [
|
||||
("if TYPE_CHECKING:\n from app import AppState\n", []),
|
||||
("from app import AppState\n", [["app.py", "service.py"]]),
|
||||
], ids=["guarded", "runtime"])
|
||||
def test_python_two_file_cycle_closes_only_through_a_runtime_import(tmp_path, service_import, expected):
|
||||
"""The shape in the issue, in a directed build."""
|
||||
cycles = _cycles(tmp_path, {
|
||||
"app.py": "from service import Service\n\nclass AppState:\n service: Service\n",
|
||||
"service.py": ("from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\n"
|
||||
+ service_import
|
||||
+ "\nclass Service:\n def run(self, state: AppState):\n return state\n"),
|
||||
})
|
||||
assert _names(cycles) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("adapter_import, expected", [
|
||||
("if TYPE_CHECKING:\n from pkg.main import AppState\n", []),
|
||||
("from pkg.main import AppState\n", [["adapter.py", "main.py", "service.py"]]),
|
||||
], ids=["guarded", "runtime"])
|
||||
def test_python_three_file_ring_closes_only_through_a_runtime_import(tmp_path, adapter_import, expected):
|
||||
"""The reporter's shape, in the default undirected build."""
|
||||
cycles = _cycles(tmp_path, {
|
||||
"pkg/__init__.py": "",
|
||||
"pkg/main.py": "from pkg.service import Service\n\nclass AppState:\n service: Service\n",
|
||||
"pkg/service.py": "from pkg.adapter import Adapter\n\nclass Service:\n adapter: Adapter\n",
|
||||
"pkg/adapter.py": ("from typing import TYPE_CHECKING\n\n" + adapter_import
|
||||
+ "\nclass Adapter:\n def bind(self, state: 'AppState'): ...\n"),
|
||||
}, directed=False)
|
||||
assert _names(cycles) == expected
|
||||
|
||||
|
||||
# A runtime import and a guarded one for the same pair: the cycle stays ---------
|
||||
|
||||
@pytest.mark.parametrize("a_body", [
|
||||
"from typing import TYPE_CHECKING\nfrom b import helper\n\nif TYPE_CHECKING:\n from b import B\n",
|
||||
"from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from b import B\n\nfrom b import helper\n",
|
||||
], ids=["runtime-first", "guard-first"])
|
||||
def test_python_runtime_and_guarded_import_of_one_module_keep_the_cycle(tmp_path, a_body):
|
||||
cycles = _cycles(tmp_path, {
|
||||
"a.py": a_body + "\ndef f(x: 'B'):\n return helper(x)\n",
|
||||
"b.py": "from a import f\n\nclass B: ...\n\ndef helper(x):\n return f\n",
|
||||
})
|
||||
assert _names(cycles) == [["a.py", "b.py"]]
|
||||
|
||||
|
||||
_RING_X6 = {
|
||||
# a -> b is `from . import b` (resolution pass, not stamped) plus a guarded `from .b import B`
|
||||
"pkg/__init__.py": "",
|
||||
"pkg/a.py": ("from . import b\nfrom typing import TYPE_CHECKING\n\n"
|
||||
"if TYPE_CHECKING:\n from .b import B\n\n"
|
||||
"def f(x: 'B'):\n return b.helper(x)\n"),
|
||||
"pkg/b.py": "from pkg.c import C\n\nclass B: ...\n\ndef helper(x):\n return C\n",
|
||||
"pkg/c.py": "from pkg.a import f\n\nclass C:\n run = f\n",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("directed, raw", [(False, False), (True, False), (False, True)],
|
||||
ids=["undirected", "directed", "no-cluster-raw"])
|
||||
def test_python_ring_through_a_submodule_import_and_a_guard_keeps_its_cycle(tmp_path, directed, raw):
|
||||
cycles = _cycles(tmp_path, _RING_X6, directed=directed, raw=raw)
|
||||
assert _names(cycles) == [["a.py", "b.py", "c.py"]]
|
||||
|
||||
|
||||
def test_python_guard_in_one_direction_keeps_the_runtime_import_in_the_other(tmp_path):
|
||||
"""Undirected, a pair is one edge: a.py's guarded `import pkg.b` folds with
|
||||
b.py's runtime `from pkg.a import A`, which closes the ring a -> c -> b -> a."""
|
||||
cycles = _cycles(tmp_path, {
|
||||
"pkg/__init__.py": "",
|
||||
"pkg/a.py": ("from typing import TYPE_CHECKING\n\nfrom pkg.c import C\n\n"
|
||||
"if TYPE_CHECKING:\n import pkg.b\n\nclass A:\n c: C\n"),
|
||||
"pkg/b.py": "from pkg.a import A\n\nclass B:\n a: A\n",
|
||||
"pkg/c.py": "from pkg.b import B\n\nclass C:\n b: B\n",
|
||||
}, directed=False)
|
||||
assert _names(cycles) == [["a.py", "b.py", "c.py"]]
|
||||
|
||||
|
||||
def test_a_type_import_beside_a_value_import_of_the_same_file_keeps_the_cycle(tmp_path):
|
||||
"""The same merge hid a real cycle for TypeScript (#3123)."""
|
||||
cycles = _cycles(tmp_path, {
|
||||
"a.ts": ('import type { B } from "./b.js";\nimport { helper } from "./b.js";\n'
|
||||
"export const a = (x: B) => helper(x);\n"),
|
||||
"b.ts": ('import { a } from "./a.js";\nexport type B = number;\n'
|
||||
"export function helper(x: number) { return a; }\n"),
|
||||
})
|
||||
assert _names(cycles) == [["a.ts", "b.ts"]]
|
||||
|
||||
|
||||
def test_a_runtime_import_dropped_by_the_merge_still_clears_the_marker():
|
||||
"""build_from_json drops a lower-confidence duplicate of an edge it already
|
||||
holds; the type-only marker must not outlive the runtime import it dropped."""
|
||||
def edge(src, tgt, conf, line, **extra):
|
||||
return {"source": src, "target": tgt, "relation": "imports_from", "confidence": conf,
|
||||
"source_file": f"{src}.py", "source_location": f"L{line}", **extra}
|
||||
|
||||
nodes = [{"id": n, "label": f"{n}.py", "source_file": f"{n}.py", "file_type": "code"}
|
||||
for n in ("a", "b")]
|
||||
edges = [edge("a", "b", "EXTRACTED", 1, type_only=True),
|
||||
edge("a", "b", "INFERRED", 2),
|
||||
edge("b", "a", "EXTRACTED", 1)]
|
||||
G = build_from_json({"nodes": nodes, "edges": edges, "hyperedges": []}, directed=True)
|
||||
assert _names(find_import_cycles(G)) == [["a.py", "b.py"]]
|
||||
Reference in new issue
Block a user