Repository navigation
Description
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 onlyThis branch is the only import handler that never attempts path resolution. Compare:
- the sibling
import_from_statementbranch resolves relative imports to a real path (tgt_nid = _make_id(str(target_path))) and stampsedge["target_file"]so the Incremental --no-cluster extraction overwrites the full graph with the changed-file subset #2169 remap pass can canonicalize it (added for v0.9.27 incremental --no-cluster preserves nodes but loses and mis-targets cross-file edges after #2169 #2213); _import_jscalls_resolve_js_import_target(...)and stampstarget_file(Phantom self-cycles: same-basename cross-extension re-exports (X.ts → ./X.mjs) collapse to one node #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:
continueA 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] = srcA 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 Python: aliased import still matches by module stem, so a same-named sibling module drops resolvablemod.func()calls #2428 finding 2 (updatenot 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.
Activity
fix(python): walk enclosing scopes for module member calls (Graphify-…
fix(python): walk enclosing scopes for module member calls (#2447)
thegreatsao commentedon Oct 14, 2026
Cause C still reproduces on graphifyy 0.9.89 with a minimal three-file package:
extract(sorted(Path('pkg').resolve().glob('*.py')))emits onecallsedge,pkg_sync_top -> pkg_ozon_call(L5).Command.handle -> callis missing. The same holds for a Django-styleclass 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, sographify explain "call()"andaffectedlisted 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.kogriv commentedon Nov 4, 2026
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, emptyHOME.graph.jsonnow has animportslinky.py → X(so cause B no longer means "no edge at all"). It has noimports_fromy.py → x.py, and noreverse_importstamp onx.py → y.py.find_import_cyclesreadsimports_from/re_exportsonly, so## Import Cyclessays "None detected."Control: with
from pkg.x import Xmoved to module level iny.py, the linkx.py → y.pygetsreverse_importand the report lists2-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_cyclesover 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-identicalgraph.jsonacross 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, adeferredstamp on animports_fromedge 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).
LuluaneS commentedon Nov 14, 2026
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"))).Non-
containsedges emitted for these files, verbatim:What that shows:
pkg/worker.pycallsedge toworker.runcontrol3.py(module-levelfrom pkg.worker import run)imports_from)local_import2.py(same import, inside the function)local_import.py(function-localfrom pkg import worker, thenworker.run())dynamic.py(importlib.import_module("pkg.worker"))importlibSo 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_modulecase is the same shape one step further: the target module name is a plain string literal, yet nothing connectsdynamic.pytopkg/worker.py, so "what depends onworker.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
deferredstamp suggested above: whenimportlib.import_module/__import__is called with a string literal that resolves to a scanned module, emit animports_fromedge stampeddeferred(ordynamic) 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.)