Skip to content

Elixir: imports edges target a bare module id that matches no node — every cross-module import edge is silently dropped at build (2,586 of 19,337 on a 900-file project) #2556

Closed

Description

@norbu09

Summary

The Elixir extractor emits imports edges whose target is the bare normalized module name, while the module node it should point at is registered under a path-prefixed id. The two never match, so build_from_json drops every cross-module import edge.

On a real 900-file Elixir/Phoenix project this silently discarded 2,586 of 19,337 extracted edges (13%) — the entire internal module dependency graph. Nothing warns; the build reports success and the graph looks plausible. It is only visible via graphify diagnose multigraph.

Python does not have this bug, so this is Elixir-specific (details below).

Repro

Two files, one aliasing the other:

# lib/demo/accounts.ex
defmodule Demo.Accounts do
  def list_users, do: []
end

# lib/demo/web.ex
defmodule Demo.Web do
  alias Demo.Accounts

  def index, do: Accounts.list_users()
end
from pathlib import Path
from graphify.extract import collect_files, extract

res = extract(collect_files(Path("lib")), cache_root=Path("."))
ids = {n["id"] for n in res["nodes"]}
for e in res["edges"]:
    flag = "  <-- DANGLING" if e["target"] not in ids else ""
    print(f"{e['source']} --{e['relation']}--> {e['target']}{flag}")

Output (graphify 0.9.36):

NODES:
  lib_demo_accounts                        label= accounts.ex
  lib_demo_accounts_demo_accounts          label= Demo.Accounts
  lib_demo_accounts_demo_accounts_list_users
  lib_demo_web                             label= web.ex
  lib_demo_web_demo_web                    label= Demo.Web
  lib_demo_web_demo_web_index

EDGES:
  lib_demo_accounts --contains--> lib_demo_accounts_demo_accounts
  lib_demo_accounts_demo_accounts --method--> lib_demo_accounts_demo_accounts_list_users
  lib_demo_web --contains--> lib_demo_web_demo_web
  lib_demo_web --imports--> demo_accounts        <-- DANGLING
  lib_demo_web_demo_web --method--> lib_demo_web_demo_web_index

Expected: lib_demo_web --imports--> lib_demo_accounts_demo_accounts
Actual: target is demo_accounts, which matches no node, and the edge is dropped at build.

Root cause

graphify/extractors/elixir.py builds the module node id and the import target id with different arities:

# L119 — module node: stem IS included
module_nid = _make_id(stem, module_name)      # -> lib_demo_accounts_demo_accounts

# L154 — import target: stem is NOT included
tgt_nid = _make_id(module_name)               # -> demo_accounts

L154 cannot know the stem on its own, because the defining file is usually a different file. The per-file filter at L226 correctly lets the unresolved edge through so a later pass can fix it:

clean_edges = [e for e in edges if e["source"] in seen_ids and
               (e["target"] in seen_ids or e["relation"] == "imports")]

…but no later pass ever does. The cross-file resolver registry in extract.py (~L3173) registers Swift, Python, Ruby, TypeScript, C++ and ObjC — there is no Elixir resolver, so .ex/.exs never gets a resolution pass and the exemption becomes a permanent leak.

That is also why Python is unaffected — the same repro in Python resolves correctly:

pkg_web --imports--> pkg_accounts_accounts     # valid
pkg_web_index --calls--> pkg_accounts_accounts # valid

Suggested fix

Register an Elixir cross-file resolver that rewrites unresolved imports targets to the node id of the module with that name. Matching on the normalized module name of module-level nodes is exact and needs no heuristics — normalize(label) == target.

Worth stressing: matching on id suffix instead is not safe. I tried it first on the real project and it mis-resolved badly — a bare target like application (from use Application) latches onto any node whose id ends in _application, including function nodes such as ..._oauthapplications_update_application. Exact module-name matching gave 382/382 unambiguous resolutions on the same corpus where suffix matching produced 7 wrong ones.

Endpoints with no matching module are genuinely external (stdlib and hex: Logger, Application, Gettext, Ecto.Query, Phoenix.Component, Ash.Resource). On the project above that was 86 distinct modules / 859 edges — small enough to emit as leaf stub nodes, which keeps "who imports Ecto.Query directly" answerable without vendoring deps/.

For reference, on the 900-file project the corrected resolution gave:

before after
dangling endpoint edges 3,445 0
graph edges 13,156 16,578
Boundary.Accounts degree 75 199
communities (Louvain) 966 666

Boundary.Accounts was under-reported by 62%, and ~300 communities were spurious fragments that rejoined once their import edges existed. Because god-node ranking and community detection both run on the degraded edge set, the report's headline conclusions were wrong, not merely incomplete.

Secondary observation

In the Elixir repro above, Accounts.list_users() produces no calls edge at all — extract_elixir() returns raw_calls: [], so cross-module calls are never recorded even before resolution. Python emits pkg_web_index --calls--> pkg_accounts_accounts for the equivalent code. This looks like the same missing-resolver gap plus an extractor gap; happy to file it separately if you'd prefer it tracked on its own.

Environment

  • graphify (graphifyy) 0.9.36, Python 3.13, Linux
  • Corpus: 865 .ex/.exs + 39 .js, Elixir/Phoenix/Ash

Activity

  1. norbu09 commented on Aug 8, 2026

    @norbu09
    Author

    Following up with more data, including a correction to my own secondary note above, and a finding that I think reframes this issue.

    Correction

    I wrote that extract_elixir() produces "no calls edge at all". That was wrong, and my repro misled me — I wrote it with def f, do: expr one-liners. Elixir does produce call edges: on the 904-file codebase I measured, 4,328 EXTRACTED ones. They are just all same-file, because label_to_nid is built per file. Cross-file calls come only from the generic bare-name pass, which found 207 and is mostly noise (real examples from that graph: users → count, attrs → required, call → string).

    That said, the one-liner detail is itself a defect worth recording: function_bodies only collects do_block nodes, so def f, do: expr bodies are never walked for calls. In that codebase that is 2,499 of 11,357 def/defp clauses (22%) invisible to call extraction.

    The bigger problem: tree-sitter cannot model Elixir

    While fixing the import edges I hit something that no amount of extractor patching resolves. Elixir's real module surface is produced by macros at compile time. A representative file from that codebase:

    lib/local_foundation/resources/ab_testing/experiment_assignment.ex
      def/defp in source:               0
      exported functions after compile: 95      # can_create/1, can_create/2, ...
    

    Zero functions in the source text; 95 in the actual module. A syntactic extractor sees an empty file. This is not an edge case in Phoenix/Ash projects — the same codebase has 480 modules getting their surface from use MyAppWeb, 133 from use Phoenix.*, 50 use Ecto.Schema, 40 Ash resources.

    So for Elixir specifically, source text is the wrong input. The compiler already computes exactly what this extractor is trying to approximate.

    What compiler artifacts give instead

    I built an extractor reading :xref (call edges) and :beam_lib (module surface, behaviours, source paths) from an existing _build, emitting the same {nodes, edges} JSON. Same codebase, measured:

    tree-sitter :xref + :beam_lib
    cross-module calls 207, mostly wrong 6,598, exact
    arity collapsed (35 handle_event clauses → 1 node) preserved (transaction/1 ≠ transaction/2)
    macro-generated functions invisible included
    def f, do: expr bodies skipped (2,499 clauses) included
    behaviours none 174 LiveView, 133 LiveComponent, 50 Plug
    dangling edges 3,445 0
    provenance inferred from names EXTRACTED, compiler ground truth

    Whole graph went from 9,591 nodes / 16,843 edges to 20,519 / 42,185. The god-node ranking changed completely — the top hubs turned out to be Ash domain modules that are almost absent from source text, so the syntactic graph could not rank them at all.

    Two things that made it work, in case they are useful regardless of direction:

    • Private functions must come from the abstract_code chunk, not the export table — :xref resolves calls into them.
    • Function ids must encode !/?. Slugging deliver/1 and deliver!/1 identically collided 2,771 functions and silently took 4,427 call edges with them.

    Detection is capability-based (Ash.Resource.Info loadable → introspect resources for relationships/actions/attributes), and project code is identified by asking each BEAM for its compile-time source path and keeping what is under the project root — so no app names, no config, umbrellas work.

    The catch, stated plainly

    It requires a compiled _build, so the graph describes the last compile rather than the working tree. Mine warns when sources are newer than their BEAM and never compiles anything itself. That is a genuine trade against graphify's current "no toolchain needed" property, and it is a project-level design call rather than a bug fix.

    Offer

    I have this working and would be glad to contribute it, but I did not want to open an unsolicited PR that imposes an elixir runtime dependency on a Python project — that is your architecture decision, not mine. Options as I see them:

    1. Bundled .exs invoked by an elixir_beam extractor when _build exists, falling back to tree-sitter otherwise.
    2. Optional plugin, so the dependency stays opt-in.
    3. Not in scope for graphify — in which case the narrower fixes still stand on their own: the import-id mismatch in the original report, the missing Elixir resolver (Python/TS/Ruby/Swift/C++/ObjC have one, .ex does not), the dropped receiver in raw_calls (Python's carries receiver, Elixir's does not, so even a resolver could not disambiguate), and the do: body gap.

    Happy to open a PR against whichever shape you prefer, or to just leave the findings here. Either is fine.

  2. safishamsi commented on Sep 16, 2026

    @safishamsi
    Member

    Fixed in v0.9.63 (on PyPI) via #3603 — Elixir alias/import/require/use targets now resolve onto the module's defmodule node across files. Thanks @ayushcodes10 (and @pavanetti for the parallel diagnosis on #3566).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions