Skip to content

fix(python): keep TYPE_CHECKING-only imports out of import cycles (#3159) - #4179

Open
Yyunozor wants to merge 1 commit into
Graphify-Labs:v8from
Yyunozor:fix/python-type-checking-import-cycles
Open

Yyunozor wants to merge 1 commit into
Graphify-Labs:v8from
Yyunozor:fix/python-type-checking-import-cycles

Conversation

@Yyunozor

@Yyunozor Yyunozor commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #3159. An import under if TYPE_CHECKING: never runs, yet it became an imports_from edge, so Import Cycles listed impossible cycles. It is now stamped type_only, the marker find_import_cycles already skips for TypeScript import type (#3123); the edge stays in the graph. This follows the approach proposed in the 29 Aug comment on the issue. else: and if not TYPE_CHECKING: stay runtime.

Stamping alone would hide real cycles: when build_from_json or dedupe_edges collapses the edges of one file pair, the marker of one edge can land on an import that runs (from . import b plus a guarded from .b import B). A collapsed edge is now type_only only if every import folded into it is. This also fixes the same hidden cycle for TypeScript import type next to a value import. 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 and #3123's import type cycles stay gone.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a collapsed import edge is type_only only if every import folded into it is, so the marker never lands on an import that runs.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Known limitations:

  • from pkg import submodule under the guard is not stamped (resolution pass), so that cycle is still reported. A natural follow-up: carry the guard through facts.module_imports.
  • A guard is recognised by name, like mypy and ruff do: a hand-set TYPE_CHECKING = True would hide a real cycle. if TYPE_CHECKING and ...: counts as runtime.
  • A graph built by an earlier version keeps its old edges for unchanged files until they are re-extracted.

How was this tested?

macOS, Python 3.12; Windows not tested.
tests/test_type_only_import_cycles.py   f765dcb: 6 failed, 17 passed   this branch: 23 passed
full suite (uv sync --all-extras)       f765dcb: 6702 passed   this branch: 6717 passed, none failed
py3.10 (this module and the import-resolution tests): 97 passed; ruff clean; pyright unchanged
graphify update, 3-file ring closed by a guarded import: "3-file cycle" -> "None detected"
  (the issue's 2-file example needs a directed build to show a cycle)
real cycles through a runtime import next to a guarded one: still reported
12 installed packages and 1300 random Python projects: no runtime cycle lost
300 random TypeScript projects: none lost, no new cycle through an `import type`;
  183 real cycles that a same-file `import type` used to hide are now reported

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments.
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

…aphify-Labs#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` (Graphify-Labs#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
Graphify-Labs#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)
@Yyunozor
Yyunozor requested a review from safishamsi as a code owner October 7, 2026 07:25
Copilot AI balanced review requested due to automatic review settings October 7, 2026 07:25

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

Thanks for the pull request, @Yyunozor. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.

Formal verification. PR-changed functions: 0/3 verified (0 proven, 0 may-equivalent, 0 distinguished) · 3 not verified (3 vacuous).

Not verified on this run: build\_from\_json (vacuous: never exercised), dedupe\_edges (vacuous: never exercised), \_import\_python (vacuous: never exercised).


Graphify review — findings

Stamps Python imports inside an if TYPE_CHECKING: body (including typing.TYPE_CHECKING and nested ifs) as type_only, the same way TS import type is, so find_import_cycles skips them while the edge stays in the graph; the else: branch and if not TYPE_CHECKING: are not stamped. When dedupe_edges or build_from_json collapse two import edges for the same file pair, _execution_wins keeps type_only only if both are type-only, so a runtime import beside a type-only one still reports its cycle. In an undirected graph, the reverse-direction duplicate dropped by #1061 does not touch the surviving edge's marker.

Worth a look

  • dedupe_edges now mutates caller-owned edge dictionaries — graphify/build.py:684 · Escalate · medium · 2 independent checks
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 3435 functions depend on the 401 functions this change touches.

Health — this change adds coupling hotspots:

  • new: extract() — 785 callers, 50 callees
  • new: _rebuild_code() — 151 callers, 56 callees
  • new: build_from_json() — 234 callers, 21 callees
  • new: build_merge() — 85 callers, 14 callees
  • new: to_obsidian() — 41 callers, 14 callees
  • new: to_json() — 62 callers, 9 callees
  • new: extract_js() — 87 callers, 5 callees
  • new: to_wiki() — 45 callers, 8 callees
  • …and 82 more — each is listed as a finding

Verification — 3435 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 3002 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

221 of 337 test file(s) selected (66%) via static blast radius.

  • tests/test_analyze.py — impact
  • tests/test_astro_extraction.py — impact
  • tests/test_astro_import_ids.py — impact
  • tests/test_atomic_canvas_export.py — impact
  • tests/test_atomic_writes.py — impact
  • tests/test_benchmark.py — impact
  • tests/test_benchmark_raw_graph.py — impact
  • tests/test_blade_extractor.py — impact
  • tests/test_build.py — impact
  • tests/test_build_located_semantic_identity.py — impact
  • tests/test_build_merge_dedup_scope.py — impact
  • tests/test_build_merge_hyperedges_and_prune.py — impact
  • tests/test_build_merge_shrink_guard.py — impact
  • tests/test_builtin_global_type_refs.py — impact
  • tests/test_cache.py — impact
  • tests/test_carried_hyperedge_remap.py — impact
  • tests/test_case_sensitive_resolution.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_claude_cli_backend.py — impact
  • tests/test_cli_export.py — impact
  • tests/test_cluster.py — impact
  • tests/test_cobol_extractor.py — impact
  • tests/test_community_labels_skill.py — impact
  • tests/test_confidence.py — impact
  • tests/test_corrupt_graph_json.py — impact
  • tests/test_cpp_method_declarations.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_cpp_objc_cross_file_calls.py — impact
  • tests/test_cross_extension_reexport_self_cycle.py — impact
  • tests/test_cross_language_call_resolution.py — impact
  • tests/test_cross_repo_external_call_guards.py — impact
  • tests/test_cross_repo_member_calls.py — impact
  • tests/test_csharp_call_site_generic_args.py — impact
  • tests/test_csharp_enum_members.py — impact
  • tests/test_csharp_field_generic_args.py — impact
  • tests/test_csharp_generic_callsites.py — impact
  • tests/test_csharp_interface_dispatch.py — impact
  • tests/test_csharp_member_calls.py — impact
  • tests/test_csharp_member_nodes.py — impact
  • tests/test_csharp_object_creation.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_csharp_tuple_type_refs.py — impact
  • tests/test_csharp_type_resolution.py — impact
  • tests/test_dedup.py — impact
  • tests/test_dedup_remaps_hyperedges.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • … and 171 more

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Docs that may be stale (advisory)

…and 10 more.

Formal verification

Could not verify: Could not verify build\_from\_json.

The verifier did not have enough to check build\_from\_json, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 11 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous

Could not verify: Could not verify dedupe\_edges.

The verifier did not have enough to check dedupe\_edges, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: non-vacuity: domain too small (only 1 distinct inputs exercised, need 3) — 'no divergence' would be near-vacuous

Could not verify: Could not verify \_import\_python.

The verifier did not have enough to check \_import\_python, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 264 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

· 2 grounded finding(s) anchored inline below; 88 more finding(s) on lines outside this diff (see the check run).

Comment thread graphify/extract.py
return False


def _import_python(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — _import_python()

fans out to 8 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

# ---------------------------------------------------------------------------

def _cycles(tmp_path, files):
def _cycles(tmp_path, files, directed=True, raw=False):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — _cycles()

10 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Distinguish TYPE_CHECKING imports from runtime import cycles

2 participants