graphify icon indicating copy to clipboard operation
graphify copied to clipboard

Python: three independent causes drop `mod.func()` calls edges — 177/177 unresolved on a real repo (explains #2428 §3's unexplained 42%)

Open powellns-coder opened this issue 3 months ago • 3 comments

Following up on #2428 §3, where the reporter measured ~42% of unambiguous mod.func() calls having no calls edge and said the alias/stem patch did not explain it ("we chased two further hypotheses and both failed to account for it, so we stopped rather than guess further").

I instrumented the module arm of _resolve_python_member_calls on a private 2,648-file Python repo and captured a bail reason for every mod.func() call site with the same receiver. The result: 177 module-attribute call sites against one target module, 0 resolved, splitting into three independent causes. None is the alias/stem ambiguity of #2428 finding 1 — that patch is orthogonal and leaves all 177 unresolved.

All three are distinct from the closed #1883 (which introduced this arm) and from #2082 / #2428.

# Cause Count Share
A import mod where mod.py is not at the scan root → import edge target id never matches the file node id 72 41%
B Import statement inside a function body → no imports edge emitted at all 11 6%
C Caller is a method in a class (or a nested function) → caller is not a contains child of its file node 94 53%

Cause A — plain import mod never resolves to a path, so the id only matches when the module is at the scan root

_import_python, extract.py:313-338, the import_statement branch:

if t == "import_statement":
    for child in node.children:
        if child.type in ("dotted_name", "aliased_import"):
            raw = _read_text(child, source)
            raw_module, _, raw_alias = raw.partition(" as ")
            module_name = raw_module.strip().lstrip(".")
            tgt_nid = _make_id(module_name)      # <-- id from the MODULE NAME only

This branch is the only import handler that never attempts path resolution. Compare:

  • the sibling import_from_statement branch resolves relative imports to a real path (tgt_nid = _make_id(str(target_path))) and stamps edge["target_file"] so the #2169 remap pass can canonicalize it (added for #2213);
  • _import_js calls _resolve_js_import_target(...) and stamps target_file (#1814).

So for import mod, the edge target is _make_id("mod") → mod. The file node's id is path-derived: pkg_mod for pkg/mod.py. These coincide only when mod.py sits at the scan root.

The module arm then filters on membership in contains_children, extract.py:2419-2421:

mods = [t for t in imported_by_filenode.get(caller_file, ())
        if t in contains_children
        and (_module_stem_key(t) == rkey or file_aliases.get(t) == rkey)]
if len(mods) != 1:
    continue

A module-name-derived id is not a key in contains_children (nothing contains it — it isn't a real node), so mods == [] and every call site bails. Instrumented output, one line per call site:

BAIL mods=0  .../a.py:L221 canonicalize  callerfile=scripts_a
             import_targets_matching=['symbol_aliases'] in_contains=[False]

import_targets_matching shows the import edge does exist and points at symbol_aliases; in_contains=[False] shows that id is not a real node. The real node is scripts_symbol_aliases.

This is invisible in graph.json. A later build-time pass canonicalizes the edge target, so the published graph shows a correct-looking imports edge — while the calls edges were already dropped at resolver time. Auditing the shipped graph therefore cannot find this; only instrumenting the resolver does.

Note this is a flat / sys.path-style import (import mod where mod.py is reachable because its directory is on sys.path), which is extremely common in script-oriented repos and in anything using src/-style layout — cf. the closed #2072, which found scan root silently changing which imports edges survive.

Minimal reproducer (2 files, stock graphifyy==0.9.32, no LLM)

scripts/symbol_aliases.py
scripts/caller_flat.py
# scripts/symbol_aliases.py
def canonicalize(symbol, on_date=None):
    return symbol.upper()
# scripts/caller_flat.py
import symbol_aliases


def call_flat_import(sym):
    return symbol_aliases.canonicalize(sym)

Expected: one calls edge scripts_caller_flat_call_flat_import → scripts_symbol_aliases_canonicalize. Actual: zero. The imports edge is emitted as scripts_caller_flat --imports--> symbol_aliases, and no node with id symbol_aliases exists.

Control: move both files to the scan root (so symbol_aliases.py is at the top level) and the edge appears. That one-variable difference is the whole bug. Measured on both trees with byte-identical file contents:

--- target+caller in scripts/ ---
  nodes: ['scripts_caller_flat', 'scripts_caller_flat_call_flat_import',
          'scripts_symbol_aliases', 'scripts_symbol_aliases_canonicalize']
  imports (target_is_real_node): [('scripts_caller_flat', 'symbol_aliases', False)]
  CALLS into canonicalize: []

--- both at the scan root ---
  nodes: ['caller_flat', 'caller_flat_call_flat_import',
          'symbol_aliases', 'symbol_aliases_canonicalize']
  imports (target_is_real_node): [('caller_flat', 'symbol_aliases', True)]
  CALLS into canonicalize: [('caller_flat_call_flat_import', 'symbol_aliases_canonicalize')]

Suggested direction

Mirror what import_from_statement and _import_js already do: attempt to resolve module_name to a real file (sibling directory, scan root, package path) and either emit the path-derived id or stamp edge["target_file"] so the existing #2169 remap pass canonicalizes it before run_language_resolvers runs at extract.py:5570. The ordering matters — the canonicalization has to land before the resolver, not after.


Cause B — a function-local import emits no imports edge at all

def _canon(symbol):
    import symbol_aliases          # deferred import, avoids a module-load cycle
    return symbol_aliases.canonicalize(symbol)

Instrumented output — note import_targets_matching=[], i.e. the caller's file node has no import edge to that module at all:

BAIL mods=0  .../dedup_set.py:L343 canonicalize  callerfile=scripts_replay_engine_dedup_set
             import_targets_matching=[] in_contains=[]

Deferred imports inside functions are a standard way to break import cycles and to keep optional dependencies lazy, so this is not an exotic shape. The module arm resolves the receiver strictly against modules imported into the caller's file node, so a function-scoped import is invisible to it.


Cause C — the caller is a method in a class, so it is not a contains child of its file (53%, the largest bucket)

file_of_node is built only from contains edges, in the contains loop near the top of _resolve_python_member_calls (extract.py:2287):

for e in all_edges:
    if e.get("relation") == "contains":
        src, tgt = e.get("source"), e.get("target")
        ...
        file_of_node[tgt] = src

A method hangs off its class via a method edge, not off the file via contains. So for any call inside a method, file_of_node.get(caller) is None, imported_by_filenode.get(None, ()) is empty, and the arm bails before it ever looks at the module:

BAIL caller-not-contains-child  .../executor.py:L709 canonicalize_option_symbol
     caller=scripts_replay_engine_executor_replayexecutor_classify_candidate

This is the single largest bucket (94/177). Any class-based codebase loses every mod.func() call made from a method, regardless of how the module was imported. I'd expect this to be a large share of #2428's unexplained 42%, since their measurement counted call sites without conditioning on the caller's scope.

A nested (inner) function fails the same way — the inner function is not emitted as a node, so there is no contains child to attribute the call to. Related but not the same as #1972 (top-level/script-context calls having no caller node); here the caller node exists, it just isn't reachable via contains.

Suggested direction

Fold method edges into file_of_node so a method resolves to its class's file — e.g. after the contains loop, walk method edges and set file_of_node[method_nid] = file_of_node.get(class_nid). Since #2040 landed, nested classes source contains from the parent type rather than the file, so this walk should be transitive to the file node rather than assuming one level.


Reproducer matrix

Varying one dimension at a time, target module at the scan root except where noted (stock 0.9.32, AST only):

# Import Caller scope Caller location Target location calls edge
1 import mod module-level function scan root scan root yes
2 import mod method in class scan root scan root no
3 import mod nested function scan root scan root no
4 import mod inside the function module-level function scan root scan root no
5 import mod module-level function subdirectory scan root yes
6 import mod method in class subdirectory scan root no
7 (control) from mod import f, direct f() module-level function scan root scan root yes
8 import mod module-level function subdirectory subdirectory no

Shape 8 is the real-world shape and the one that isolates cause A: identical to shape 1 in import form and caller scope, differing only in that the target module lives in a subdirectory while the import stays flat. Shapes 2/3/6 isolate cause C, shape 4 isolates cause B.

Impact

The practical effect is that graphify explain / query under-report the blast radius of a widely-called function. In my case the target function shows degree 88 with every inbound calls edge coming from from mod import f call sites, while all 177 mod.f() call sites — including the five highest-risk ones — are absent. Nothing in the output signals the omission, so the graph reads as complete. That is the part I'd flag as most worth fixing: the failure is silent, and callers of the graph can't distinguish "no edge" from "no call".

Environment

  • graphifyy==0.9.32 (uv tool install), Python 3.11, Windows 11
  • AST-only extraction (extract(collect_files(root), cache_root=root)); no LLM, no semantic pass
  • Reproduced on a fresh full extraction, not an incremental update — so this is independent of #2428 finding 2 (update not running the language resolvers)

Happy to run any diagnostic you'd like against the large corpus; I can share the instrumentation wrapper that produced the per-call-site bail reasons, which is what made the three causes separable.

powellns-coder avatar Aug 04 '26 02:08 powellns-coder

Cause C still reproduces on graphifyy 0.9.89 with a minimal three-file package:

pkg/__init__.py   (empty)
pkg/ozon.py       def call(path): return path
pkg/sync.py:
    from pkg import ozon

    def top():
        return ozon.call("a")

    class Command:
        def handle(self):
            return ozon.call("b")

extract(sorted(Path('pkg').resolve().glob('*.py'))) emits one calls edge, pkg_sync_top -> pkg_ozon_call (L5). Command.handle -> call is missing. The same holds for a Django-style class Command(BaseCommand). A function-level caller resolves with every import style I tried (from pkg import ozon, import pkg.ozon as ozon, a local import inside the function, from pkg.ozon import call); a method caller resolves with none of them.

Real-world impact on a Django project: all five ozon.call() call sites in a management command's methods were absent, so graphify explain "call()" and affected listed two callers of five with no sign of incompleteness. Django keeps much of its logic in class methods (management commands, admin classes, model methods), so this cause alone makes call-graph answers unreliable there.

thegreatsao avatar Oct 14 '26 05:10 thegreatsao

A data point for cause B on the current release. It has partly moved since 0.9.32, and the part that remains shows up in GRAPH_REPORT.md.

Version: graphifyy==0.9.102, extract . --code-only, GRAPHIFY_BACKEND=none, empty HOME.

pkg/x.py   from pkg.y import Y
           class X: ...
pkg/y.py   class Y: ...
           def make():
               from pkg.x import X      # function-local: the usual way to break an import cycle
               return X()

graph.json now has an imports link y.py → X (so cause B no longer means "no edge at all"). It has no imports_from y.py → x.py, and no reverse_import stamp on x.py → y.py. find_import_cycles reads imports_from/re_exports only, so ## Import Cycles says "None detected."

Control: with from pkg.x import X moved to module level in y.py, the link x.py → y.py gets reverse_import and the report lists 2-file cycle: pkg/x.py -> pkg/y.py -> pkg/x.py. So the cycle finder is fine; the function-local import never becomes a file-level dependency.

On a real 280-file Python package with 45 import cycles (by networkx.simple_cycles over all module imports, any scope), the report lists 2. 25 of its 266 module dependencies are function-local imports, and 13 of its 14 mutual-import pairs close through one. Everything else in the import layer measured very well there: precision 99.6 %, recall 90 %, byte-identical graph.json across three runs.

Whether a lazy import should count for cycles is a fair design question. A function-local import, like JS import(), is deferred (#1241). If that is the intent, a deferred stamp on an imports_from edge would keep the dependency in the graph and let the report decide, as it already does for JS. Today the dependency is not in the file-level graph at all.

Write-up with the pre-registered expectations and the re-check: https://github.com/kogriv/codemap/blob/main/research/tools/graphify.md (§1, §3).

kogriv avatar Nov 04 '26 02:11 kogriv

A data point for cause B on the current release, plus one neighbouring case I could not find reported: importlib.import_module("pkg.mod") with a string-literal argument.

Version: graphifyy==0.9.109, Python 3.11, Windows, GRAPHIFY_BACKEND=none, extract(sorted(Path("pkg").resolve().glob("*.py"))).

pkg/__init__.py        (empty)
pkg/worker.py          def run(job): return job

pkg/control3.py        from pkg.worker import run
                       def top3(): return run("a3")

pkg/local_import2.py   def lazy2():
                           from pkg.worker import run      # function-local
                           return run("b2")

pkg/local_import.py    def lazy():
                           from pkg import worker          # function-local
                           return worker.run("b")

pkg/dynamic.py         import importlib
                       def dyn():
                           worker = importlib.import_module("pkg.worker")
                           return worker.run("c")
                       def _worker():
                           return importlib.import_module("pkg.worker")
                       def via_helper():
                           return _worker().run("d")

Non-contains edges emitted for these files, verbatim:

imports_from | control3 -> pkg_worker | EXTRACTED
calls        | control3_top3 -> worker_run | INFERRED
calls        | local_import2_lazy2 -> worker_run | INFERRED
imports      | dynamic -> importlib | EXTRACTED
calls        | dynamic_dyn -> importlib | EXTRACTED
calls        | dynamic_worker -> importlib | EXTRACTED
calls        | dynamic_via_helper -> dynamic_worker | EXTRACTED

What that shows:

File Module-level dependency on pkg/worker.py calls edge to worker.run
control3.py (module-level from pkg.worker import run) yes (imports_from) yes
local_import2.py (same import, inside the function) no yes (INFERRED, by name)
local_import.py (function-local from pkg import worker, then worker.run()) no no — the file has no outgoing edge at all
dynamic.py (importlib.import_module("pkg.worker")) no — only an edge to importlib no

So for the function-local case this matches @kogriv's 0.9.102 observation: the call can still be found by name, but the file-level dependency is not in the graph. The importlib.import_module case is the same shape one step further: the target module name is a plain string literal, yet nothing connects dynamic.py to pkg/worker.py, so "what depends on worker.py?" / blast-radius queries miss the file entirely.

Why it matters in practice: we hit this on a real project where an entry-point module loads its sibling modules lazily through small importlib.import_module("name") helpers (to keep start-up light and to let tests rebind a database path before import). That is exactly the wiring one wants the graph for, and it is the part that is invisible, so we fall back to text search for it.

A possible shape, in line with the deferred stamp suggested above: when importlib.import_module / __import__ is called with a string literal that resolves to a scanned module, emit an imports_from edge stamped deferred (or dynamic) from the enclosing file. Non-literal arguments would stay unresolved, as today. That alone would restore the file-level dependency; resolving .attr() on the returned module could come later, or not at all.

(Written with an AI assistant on the account owner's behalf. The repro was run locally; the edge lines above are verbatim, with only the column spacing aligned.)

LuluaneS avatar Nov 14 '26 21:11 LuluaneS