fix(extract): resolve Python module-qualified calls to calls edges (#1883)

`module.function()` where `module` is imported produced no calls edge,
while bare-name calls did. The member call was captured, but the shared
cross-file pass skips all member calls and _resolve_python_member_calls
only handled capitalized class receivers, so a lowercase module receiver
fell through. Add a module arm: a lowercase receiver naming a module
imported into the caller's file resolves to the single callable that
module contains. Keyed on stable node ids (imports edge source is the
caller file node; contains maps file -> children), not source_file
strings, so it holds under the cache_root id-remap relativization. Also
drop the no-classes early return that skipped the whole resolver when a
corpus had functions but no class methods.

Guards: only modules imported into the caller's own file match (so
self/obj/local instances never match), and a single-definition god-node
guard on the callable. Adds a positive test and a false-edge negative.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
safishamsi
2026-07-14 23:19:06 +01:00
co-authored by Claude Opus 4.8
parent 2795a18bda
commit 060dd6317f
3 changed files with 118 additions and 29 deletions
+2
View File
@@ -4,6 +4,8 @@ Full release notes with details on each version: [GitHub Releases](https://githu
## 0.9.16 (unreleased)
- Fix: Python qualified calls to an imported module (`module.function()`) now produce a `calls` edge, matching bare-name calls (#1883). The call was captured correctly but fell through a gap: the shared cross-file pass skips every member call (to avoid god-node blowups from bare method names), and the Python member-call resolver only handled capitalized class receivers (`ClassName.method()`), so a lowercase module receiver was dropped. The resolver now also resolves a lowercase receiver that names a module imported into the caller's file, linking to the single callable that module contains (guarded so `self`/`obj`/local instances and ambiguous names never create a false edge).
- Fix: `--exclude` patterns now survive into `update`/`watch`/git-hook rebuilds instead of applying only to the initial scan (#1886). The patterns were never persisted, so the first rebuild re-ran `detect()` without them and silently re-indexed the excluded paths. `extract` now records them in a `graphify-out/.graphify_build.json` sidecar and `_rebuild_code` re-applies them on every rebuild (they still layer after `.gitignore`/`.graphifyignore`/`.git/info/exclude`, so they keep winning). Graphs built before this release simply have no sidecar and behave as before.
- Fix: the dedup ID-collision warning now reports in proportion to what is actually lost, and an ID collision resolves to a deterministic survivor (#1851 / #1852, thanks @bchan84x). Two nodes can mint the same `<path>_<entity>` ID when a document merely references an entity defined elsewhere; the old code kept whichever arrived first and always printed a scary "two files with the same name" warning that overstated the loss (edges rewire to the survivor, so a reference collapse loses nothing). Now the node whose `source_file` actually defines the ID wins, a harmless reference collapse is silent, a same-file relabel is a quiet note, and only a genuine cross-file collision warns. The survivor is chosen by a total order (definer first, then the shorter/canonical label, then lexically) so it no longer depends on chunk arrival order, including when several same-file nodes co-define one ID.
+71 -29
View File
@@ -2162,9 +2162,9 @@ def _resolve_python_member_calls(
tnode = node_by_id.get(tgt)
if tnode is not None:
method_index[(src, _key(tnode.get("label", "")))] = tgt
if not class_def_nids:
return
# A class with N methods produced N entries; collapse to a unique set.
# A class with N methods produced N entries; collapse to a unique set. (No
# early return when there are no classes: the module arm below resolves
# `module.func()` where the callable is a plain function, not a method.)
for k in list(class_def_nids):
class_def_nids[k] = sorted(set(class_def_nids[k]))
@@ -2172,35 +2172,46 @@ def _resolve_python_member_calls(
for result in per_file:
all_raw_calls.extend(result.get("raw_calls", []))
# Module-alias arm index (#1883): `module.func()` where `module` is imported.
# Key on stable node ids, not source_file strings (source_file is relativized
# by the CLI id-remap pass but raw_calls keep their original path, so a string
# join would miss under an explicit cache_root). The `imports` edge's source
# is the caller's own file node; `contains` maps a file node to its children.
contains_children: dict[str, dict[str, list[str]]] = {}
file_of_node: dict[str, str] = {}
for e in all_edges:
if e.get("relation") == "contains":
src, tgt = e.get("source"), e.get("target")
tnode = node_by_id.get(tgt)
if tnode is not None:
contains_children.setdefault(src, {}).setdefault(
_key(tnode.get("label", "")), []).append(tgt)
file_of_node[tgt] = src
imported_by_filenode: dict[str, set[str]] = {}
for e in all_edges:
if e.get("relation") in ("imports", "imports_from"):
imported_by_filenode.setdefault(e.get("source"), set()).add(e.get("target"))
def _module_stem_key(nid: str) -> str:
n = node_by_id.get(nid)
if not n:
return ""
sf = n.get("source_file") or ""
stem = Path(sf).stem if sf else ""
return _key(stem or n.get("label", ""))
existing_pairs = {(e.get("source"), e.get("target")) for e in all_edges}
for rc in all_raw_calls:
if not rc.get("is_member_call"):
continue
receiver = rc.get("receiver")
callee = rc.get("callee")
caller = rc.get("caller_nid")
if not receiver or not callee or not caller:
continue
# Only a capitalized receiver is treated as a class reference, so an
# instance/module (`self`, `obj`, `config`) never collides with a
# same-spelled class via the case-folding key.
if not receiver[:1].isupper():
continue
class_nids = class_def_nids.get(_key(receiver), [])
if len(class_nids) != 1: # absent or ambiguous -> bail (god-node guard)
continue
method_nid = method_index.get((class_nids[0], _key(callee)))
if not method_nid or method_nid == caller:
continue
if (caller, method_nid) in existing_pairs:
continue
existing_pairs.add((caller, method_nid))
# EXTRACTED: a qualified `ClassName.method()` is an explicit, unambiguous
# static reference (unlike a bare instance member call), and the class
# resolved to exactly one definition that owns the method.
def _emit_call(caller: str, target_nid: "str | None", rc: dict) -> None:
if not target_nid or target_nid == caller or (caller, target_nid) in existing_pairs:
return
existing_pairs.add((caller, target_nid))
# EXTRACTED: a qualified call (`ClassName.method()` or `module.func()`) is
# an explicit, unambiguous static reference resolved to exactly one
# definition (each arm applies a single-definition god-node guard).
all_edges.append({
"source": caller,
"target": method_nid,
"target": target_nid,
"relation": "calls",
"context": "call",
"confidence": "EXTRACTED",
@@ -2210,6 +2221,37 @@ def _resolve_python_member_calls(
"weight": 1.0,
})
for rc in all_raw_calls:
if not rc.get("is_member_call"):
continue
receiver = rc.get("receiver")
callee = rc.get("callee")
caller = rc.get("caller_nid")
if not receiver or not callee or not caller:
continue
if receiver[:1].isupper():
# Class arm (#1446): a capitalized receiver is a class reference; an
# instance (`self`, `obj`) never collides with a same-spelled class.
class_nids = class_def_nids.get(_key(receiver), [])
if len(class_nids) != 1: # absent or ambiguous -> bail (god-node guard)
continue
_emit_call(caller, method_index.get((class_nids[0], _key(callee))), rc)
else:
# Module arm (#1883): a lowercase receiver may be an imported module.
# Resolve it against the modules imported into the caller's own file
# (so `self`/`obj`/local instances, which are not imported modules,
# never match), then to the single callable that module contains.
rkey = _key(receiver)
caller_file = file_of_node.get(caller)
mods = [t for t in imported_by_filenode.get(caller_file, ())
if t in contains_children and _module_stem_key(t) == rkey]
if len(mods) != 1: # not an imported module, or ambiguous -> bail
continue
children = contains_children[mods[0]].get(_key(callee), [])
if len(children) != 1: # absent or ambiguous callable -> bail
continue
_emit_call(caller, children[0], rc)
def _resolve_typescript_member_calls(
per_file: list[dict],
+45
View File
@@ -970,6 +970,51 @@ def test_python_qualified_class_method_call_resolves_extracted(tmp_path):
assert call_edges[0]["confidence"] == "EXTRACTED"
def test_python_module_qualified_call_resolves_extracted(tmp_path):
"""`module.func()` where `module` is imported resolves to the callable that
module contains, with an EXTRACTED `calls` edge (#1883). A lowercase module
receiver was previously dropped alongside instance calls."""
mathlib = tmp_path / "mathlib.py"
caller = tmp_path / "caller.py"
mathlib.write_text("def compute(x):\n return x * 2\n")
caller.write_text(
"import mathlib\n\n"
"def use_qualified(n):\n"
" return mathlib.compute(n)\n"
)
result = extract([caller, mathlib], cache_root=tmp_path)
nodes = {n["id"]: n for n in result["nodes"]}
edges = [
e for e in result["edges"]
if e["relation"] == "calls"
and "use_qualified" in nodes[e["source"]]["label"]
and "compute" in nodes[e["target"]]["label"]
and "mathlib.py" in (nodes[e["target"]].get("source_file") or "")
]
assert len(edges) == 1, f"expected one use_qualified->compute edge, got {edges}"
assert edges[0]["confidence"] == "EXTRACTED"
def test_python_module_qualified_call_requires_the_import(tmp_path):
"""A `module.func()` call must resolve only against a module the caller's own
file imports — a local instance `o.compute()` (o is a parameter) must NOT be
linked to a same-named function in some other module (#1883 false-edge guard)."""
mathlib = tmp_path / "mathlib.py"
caller = tmp_path / "caller.py"
mathlib.write_text("def compute(x):\n return x * 2\n")
# no `import mathlib`; `o` is just a parameter that happens to expose compute()
caller.write_text("def via_obj(o):\n return o.compute(3)\n")
result = extract([caller, mathlib], cache_root=tmp_path)
nodes = {n["id"]: n for n in result["nodes"]}
bad = [
e for e in result["edges"]
if e["relation"] == "calls"
and "via_obj" in nodes[e["source"]]["label"]
and "compute" in nodes[e["target"]]["label"]
]
assert bad == [], f"non-imported receiver must not link cross-file: {bad}"
def test_python_qualified_call_resolves_when_method_name_collides_with_caller(tmp_path):
"""The real #1446 shape: a viewset action `approve()` delegates to a SERVICE
action of the SAME name via `Service.approve()`. The bare-name in-file lookup