Skip to content

feat: detect circular import dependencies at file level - #961

Merged
safishamsi merged 2 commits into
Graphify-Labs:v8from
deXterbed:feat/circular-dependency-detection
May 30, 2026
Merged

safishamsi merged 2 commits into
Graphify-Labs:v8from
deXterbed:feat/circular-dependency-detection

Conversation

@deXterbed

@deXterbed deXterbed commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds file-level circular import cycle detection on top of v8.

This surfaces dependency loops that are hard to spot in symbol-level graphs and helps identify refactor blockers for tree-shaking and modularization.

Why

Import cycles in JS/TS and mixed-language projects can:

  • make dependency flow harder to reason about
  • increase coupling between modules
  • block or reduce bundler/tree-shaking optimizations
  • create fragile refactor paths

A built-in cycle detector makes these risks visible and actionable in graph analysis.

What changed

  • Added find_import_cycles(G) in analyze.py.
  • Collapses symbol-level graph relationships into a file-level directed import graph.
  • Uses directed-cycle detection to find import loops.
  • Normalizes and deduplicates cycle results so equivalent rotations are not repeated.
  • Returns cycles in a stable, readable order to support reporting and downstream tooling.
  • Added test coverage for:
    • simple 2-node cycles
    • longer multi-node cycles
    • no-cycle graphs
    • deduplication/normalization behavior
    • mixed edge scenarios around import relationships

Related

  • Related to refactor-report goals around identifying high-impact structural problems.
  • Complements barrel re-export resolution by improving dependency analysis accuracy at file level.

Test Plan

Run targeted cycle tests:

uv run --with pytest pytest tests/test_analyze.py -k "cycle"

Result:

7 passed

Optional broader analyze test run:

uv run --with pytest pytest tests/test_analyze.py -q --tb=short

- Add find_import_cycles() to analyze.py
- Collapses symbol nodes to parent files, builds directed file graph
- Uses nx.simple_cycles() bounded by max_cycle_length (default 5)
- Deduplicates rotations, returns shortest cycles first
- Considers both imports_from and re_exports edges

Tested on a 976-file Next.js codebase: found 4 cycles including
a known utils↔barrel circular dependency and a 4-file API cycle.
@safishamsi

Copy link
Copy Markdown
Member

Thanks for the contribution — circular import cycle detection is a genuinely useful feature and the algorithm choice (nx.simple_cycles + rotation-canonical deduplication) is correct. However there are a few blockers before we can merge.

Blocking issues

1. re_exports targets are symbol nodes, not file nodes

The function includes re_exports in its relation set, but those edges point to symbol-level node IDs (e.g. bar:Foo), not file nodes. The fallback at lines 638-644 then tries to use the node label as a filepath — which fabricates junk filenames for any label containing a dot (extremely common). Barrel files (the main motivator for re-export tracking) will produce wrong cycle results.

Fix: either drop re_exports from the relation set entirely, or resolve the symbol target back to its source_file attr and skip nodes that lack one.

2. Label-as-filepath fallback produces garbage for stubs/externals

Any node without a source_file attr (npm packages, Go stdlib imports, external stubs) hits the tgt_label fallback and gets an arbitrary string as a "filename". This corrupts cycle output silently — no error, just wrong results.

Fix: collapse every endpoint to source_file attr only. If a node has no source_file, skip it rather than falling back to label or node ID.

3. No integration — the function is unreachable by users

find_import_cycles has no callers anywhere in the codebase (not in report.py, __main__.py, MCP, or serve). As merged, this is dead code — users have no way to invoke it. Please wire it into at least one of:

  • report.py as a new "Import Cycles" section in GRAPH_REPORT.md
  • A CLI subcommand (e.g. graphify cycles or exposed via graphify query)
  • The MCP server as a new tool

Smaller issues

Return type mismatch — every other function in analyze.py returns list[dict] with fields like why, severity, source locations. find_import_cycles returns list[list[str]] (bare strings), which won't render in the report without a wrapper. Suggested shape: {"cycle": ["a.ts", "b.ts"], "length": 2, "why": "circular dependency"}.

Tests don't match real graph schema — test graphs use human-readable node IDs like node_a.ts, but real graphify graphs use hashed IDs from _make_id() with source_file and label as separate attrs. The tests pass against a sanitized model that won't catch the fallback bugs above.

Missing test cases:

  • Self-loops (a.ts imports itself — currently dropped silently at the src_file != tgt_file guard)
  • Mixed edge types (calls, contains alongside imports_from — confirm they don't bleed into the file graph)
  • Undirected nx.Graph input (graphify's default — all current tests use DiGraph)
  • Nodes without source_file attr (to cover the fallback path and catch Bug 2)

Bare except Exception — nx.simple_cycles doesn't raise on a DiGraph; the catch-all hides real bugs. Remove or narrow.


Once the three blocking issues are fixed we're happy to re-review and merge quickly. The algorithm and deduplication logic are solid — just needs the integration piece and the source_file-only resolution. Thanks!

- use source_file-only endpoint resolution (no label fallback)
- support Graph/DiGraph orientation via edge source_file
- return structured cycle records and include self-loops
- integrate Import Cycles section into GRAPH_REPORT.md
- expand cycle tests for real-schema IDs, undirected input,
  missing source_file nodes, and non-import relations
@deXterbed

Copy link
Copy Markdown
Contributor Author

Addressed all blockers and smaller issues:

  1. source_file-only resolution — Removed the label-as-filepath fallback entirely. Endpoints are resolved exclusively via node.source_file attr; nodes without it are skipped. No garbage paths can leak through.
  2. Undirected graph support — Edge orientation is determined from edge.source_file matching the endpoint's source_file, so it works identically on nx.Graph and nx.DiGraph inputs.
  3. Return type — Now returns list[dict] with stable keys: { "cycle": [...], "length": int, "why": "circular dependency" }.
  4. Report integration — find_import_cycles(G) is called in report.py and renders an ## Import Cycles section in GRAPH_REPORT.md (after Surprising Connections).
  5. Bare except removed — No try/except wrapper; let NetworkX exceptions propagate naturally.
  6. Self-loops — src != tgt guard removed from file_graph.add_edge, so nx.simple_cycles correctly surfaces length-1 self-loops.

Tests (9 total):

  • Structured record format validation
  • 2-cycle and 3-cycle detection
  • Self-loop cycle (length 1)
  • max_cycle_length filtering
  • Nodes without source_file are excluded (no fallback)
  • Undirected nx.Graph input still finds cycles
  • Non-import relations (calls, contains) don't bleed into the file graph
  • Empty graph → []
  • No-cycle graph → []

All tests use _make_id() for realistic hashed node IDs with proper source_file attrs matching the real graphify schema.

Validated on a production repo (~976 TS/TSX files):

  • Extracted 1007 files, 5722 nodes, 17222 edges
  • Detected 4 real cycles (all file paths verified on disk):
    • LoginForm/index.tsx ↔ login/index.tsx
    • breadcrumb/index.tsx ↔ common/index.tsx
    • event-tracker/index.tsx ↔ common/index.tsx
    • ApiClient.ts → ApiHelpers.ts → ApiStore.ts → ApiClientManager.ts → ApiClient.ts
  • Confirmed ## Import Cycles section renders correctly in the generated report
  • Zero nodes without source_file leaked into results

@safishamsi

Copy link
Copy Markdown
Member

Re-reviewed the updated diff — all three blocking issues are resolved correctly.

Verified:

  • source_file-only resolution is airtight — the if not tgt_file: continue guard drops any endpoint that lacks a source_file attr, so no garbage paths can leak through
  • re_exports is not a no-op: symbol nodes produced by barrel-file re-exports do carry source_file (set by add_node in _extract_generic), so real barrel-file cycles will be detected correctly
  • Undirected graph orientation logic handles both edge orderings correctly via the u_file == src_file_attr / v_file == src_file_attr check
  • Tests use realistic _make_id()-hashed node IDs with source_file on both nodes and edges — matching real graphify schema
  • ## Import Cycles section lands in the right place in the report (between Surprising Connections and Hyperedges)

One minor nit (non-blocking): the from .analyze import find_import_cycles import inside generate() in report.py could be hoisted to the module top alongside the other imports — local imports inside functions are typically reserved for circular-import avoidance, which doesn't apply here. Happy to fix in a follow-up.

Merging now — great turnaround, thanks!

@safishamsi
safishamsi merged commit c066511 into Graphify-Labs:v8 May 30, 2026
2 checks passed
@deXterbed
deXterbed deleted the feat/circular-dependency-detection branch June 4, 2026 03:15
PerryLin-0420 pushed a commit to PerryLin-0420/graphify-decouple that referenced this pull request Aug 13, 2026
…s#961)

* feat: detect circular import dependencies at file level

- Add find_import_cycles() to analyze.py
- Collapses symbol nodes to parent files, builds directed file graph
- Uses nx.simple_cycles() bounded by max_cycle_length (default 5)
- Deduplicates rotations, returns shortest cycles first
- Considers both imports_from and re_exports edges

Tested on a 976-file Next.js codebase: found 4 cycles including
a known utils↔barrel circular dependency and a 4-file API cycle.

* fix: resolve import-cycle merge blockers

- use source_file-only endpoint resolution (no label fallback)
- support Graph/DiGraph orientation via edge source_file
- return structured cycle records and include self-loops
- integrate Import Cycles section into GRAPH_REPORT.md
- expand cycle tests for real-schema IDs, undirected input,
  missing source_file nodes, and non-import relations
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.

2 participants