feat(extract): resolve cross-file indirect dispatch as indirect_call

#1565 captured a function passed by name as a call argument
(executor.submit(fn), Thread(target=fn), map(fn, xs)) only when the
callback was defined in the SAME file — it resolved through the in-file
label map. But the dominant real-world shape is cross-module: the callback
is imported (`from .handlers import on_event; pool.submit(on_event)`), so
the same-file map can't see it and the edge was dropped — exactly the
caller a blast-radius query must not miss.

When the argument identifier isn't defined in-file (and isn't shadowed by
a param/local — that guard already ran), emit an `indirect` raw_call and
let the existing cross-file resolution pass handle it, branching to a
distinct indirect_call/INFERRED edge instead of calls. It rides the same
single-definition god-node guard and import-evidence disambiguation as
direct calls (parity: when a direct call resolves, so does the indirect
one; when the name is ambiguous, both bail). Two added safeguards: the
target must be a real callable def (per-file callable_nids unioned across
the corpus) so an imported data constant can never become a dispatch
target, and an existing direct `calls` edge for the pair pre-empts it.

Smoke-verified: imported single-def callback resolves; ambiguous name
bails (same as direct); imported data constant rejected; direct+indirect
to the same target keeps only the direct edge; cross-file keyword
target=cb resolves. Full suite 2710 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
safishamsi
2026-06-30 22:08:14 +01:00
co-authored by Claude Opus 4.8
parent 19e7a31343
commit cf747abeaf
3 changed files with 140 additions and 3 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu
## Unreleased
- Feat: capture indirect dispatch as `indirect_call` edges so `graphify affected` (blast radius) catches callers that pass a function by name as a call argument — `executor.submit(fn)`, `Thread(target=fn)`, `map(fn, xs)`, callbacks (#1565, thanks @sheik-hiiobd). Kept as a distinct INFERRED relation separate from `calls` (strict call-graph queries stay precise) and added to the affected relation set. Hardened against false edges: the argument name must resolve to a callable definition and must NOT be shadowed by a parameter or local binding in the enclosing function — so the idiomatic `def via(pool, handler): pool.submit(handler)` (handler is the param) and a data variable sharing a function's name produce no edge. Python only for now.
- Feat: capture indirect dispatch as `indirect_call` edges so `graphify affected` (blast radius) catches callers that pass a function by name as a call argument — `executor.submit(fn)`, `Thread(target=fn)`, `map(fn, xs)`, callbacks (#1565, thanks @sheik-hiiobd). Kept as a distinct INFERRED relation separate from `calls` (strict call-graph queries stay precise) and added to the affected relation set. Hardened against false edges: the argument name must resolve to a callable definition and must NOT be shadowed by a parameter or local binding in the enclosing function — so the idiomatic `def via(pool, handler): pool.submit(handler)` (handler is the param) and a data variable sharing a function's name produce no edge. Now also resolves cross-file: a callback imported from another module (`from .handlers import on_event; pool.submit(on_event)`) routes through the same cross-file resolver as direct calls — single-definition god-node guard, callable-target-only, staying INFERRED — closing the gap where #1565 saw only same-file callbacks (the common real-world shape is cross-module). Python only for now.
## 0.9.3 (2026-06-30)
+56 -1
View File
@@ -4453,8 +4453,27 @@ def _extract_generic(
# 1. shadowing: a param / local binding is not the module fn
if ident_name in enclosing_locals:
continue
if ident_name in ("self", "cls"):
continue # never a module-level callable reference
ref_nid = label_to_nid.get(ident_name)
if not ref_nid or ref_nid == caller_nid:
if ref_nid is None:
# Callback defined in ANOTHER file (e.g. `from .h import fn;
# pool.submit(fn)`). The in-file label map can't see it, so
# defer to the cross-file resolvers, which apply the same
# single-definition god-node guard plus a callable-target
# check before emitting an INFERRED `indirect_call`. The
# shadowing guard above has already run, so a parameter /
# local binding never reaches here.
raw_calls.append({
"caller_nid": caller_nid,
"callee": ident_name,
"is_member_call": False,
"indirect": True,
"source_file": str_path,
"source_location": f"L{ident.start_point[0] + 1}",
})
continue
if ref_nid == caller_nid:
continue
# 2. callable target only: never an arbitrary data/same-named node
if ref_nid not in callable_def_nids:
@@ -4654,6 +4673,12 @@ def _extract_generic(
clean_edges.append(edge)
result = {"nodes": nodes, "edges": clean_edges, "raw_calls": raw_calls}
if callable_def_nids:
# Function / method / class def ids in this file. The cross-file
# indirect_call resolvers use the union of these to ensure a callback
# passed by name resolves only to a real callable, never a same-named
# data symbol (mirrors the in-file `callable_def_nids` guard).
result["callable_nids"] = sorted(callable_def_nids)
if swift_extensions:
result["swift_extensions"] = swift_extensions
if type_table:
@@ -14780,10 +14805,15 @@ def extract(
all_nodes: list[dict] = []
all_edges: list[dict] = []
all_raw_calls: list[dict] = []
# Union of every file's function / method / class def ids. The cross-file
# indirect_call pass resolves a callback passed by name only to one of these,
# so a same-named data symbol can never become an indirect-dispatch target.
callable_nids: set[str] = set()
for result in per_file:
all_nodes.extend(result.get("nodes", []))
all_edges.extend(result.get("edges", []))
all_raw_calls.extend(result.get("raw_calls", []))
callable_nids.update(result.get("callable_nids", ()))
_augment_symbol_resolution_edges(paths, all_nodes, all_edges, root)
@@ -15069,6 +15099,31 @@ def extract(
continue
has_import_evidence = False
if tgt != caller and (caller, tgt) not in existing_pairs:
if rc.get("indirect"):
# Cross-file indirect dispatch: a callback passed BY NAME
# (`from .h import fn; pool.submit(fn)`). Resolved through the
# same single-definition / import-evidence candidate logic as a
# direct call, but emitted as a distinct INFERRED `indirect_call`
# and ONLY when the target is a real callable def — never a
# same-named data symbol. Stays INFERRED even with import
# evidence: the name is referenced as a value here, not invoked.
# An existing direct `calls` edge for this pair already pre-empts
# it via the existing_pairs guard above.
if tgt not in callable_nids:
continue
existing_pairs.add((caller, tgt))
all_edges.append({
"source": caller,
"target": tgt,
"relation": "indirect_call",
"context": "argument",
"confidence": "INFERRED",
"confidence_score": 0.8,
"source_file": rc.get("source_file", ""),
"source_location": rc.get("source_location"),
"weight": 1.0,
})
continue
existing_pairs.add((caller, tgt))
# Promote to EXTRACTED when there's a direct import edge from the
# caller's file pointing at either the callee symbol itself or the
+83 -1
View File
@@ -9,10 +9,13 @@ They also pin the soundness guards: an argument that is a PARAMETER or a LOCAL b
enclosing function is a local value, not the module-level function it shares a name with, and a
non-callable same-named node is never a dispatch target — neither may manufacture an edge.
"""
import os
from pathlib import Path
import networkx as nx
from graphify.affected import affected_nodes
from graphify.extract import extract_python
from graphify.extract import extract, extract_python
SRC = '''\
import threading
@@ -172,3 +175,82 @@ def test_genuine_module_function_still_emits_indirect_call(tmp_path):
r, nid = _extract(tmp_path, REAL_PASS)
indirect = _rels(r, "indirect_call")
assert (nid["via"], nid["handler"]) in indirect
# ── Cross-file indirect dispatch ──────────────────────────────────────────────
# The dominant real-world shape: the callback is defined in ANOTHER module and
# imported. The in-file label map can't see it, so it is deferred to the
# cross-file resolver, which emits a distinct INFERRED `indirect_call` only when
# the name resolves to exactly one real callable (the single-definition guard).
def _extract_dir(tmp_path, files: dict[str, str]):
base = tmp_path / "pkg"
base.mkdir()
for name, body in files.items():
(base / name).write_text(body)
old = os.getcwd()
try:
os.chdir(tmp_path)
r = extract(
[Path("pkg") / name for name in files],
cache_root=Path(".cache"), parallel=False,
)
finally:
os.chdir(old)
nid = {n["label"].rstrip("()"): n["id"] for n in r["nodes"]}
return r, nid
def test_cross_file_imported_callback_emits_indirect_call(tmp_path):
r, nid = _extract_dir(tmp_path, {
"handlers.py": "def on_event(x):\n return x\n",
"scheduler.py": (
"from handlers import on_event\n\n\n"
"def schedule(pool):\n"
" pool.submit(on_event)\n" # callback imported from another module
),
})
indirect = _rels(r, "indirect_call")
calls = _rels(r, "calls")
assert (nid["schedule"], nid["on_event"]) in indirect
# never leaks into the precise `calls` relation
assert (nid["schedule"], nid["on_event"]) not in calls
# and it is INFERRED (a referenced value, not an invocation here)
for e in r["edges"]:
if e["relation"] == "indirect_call" and e["target"] == nid["on_event"]:
assert e["confidence"] == "INFERRED"
def test_cross_file_affected_includes_importing_dispatcher(tmp_path):
r, nid = _extract_dir(tmp_path, {
"handlers.py": "def on_event(x):\n return x\n",
"scheduler.py": (
"from handlers import on_event\n\n\n"
"def schedule(pool):\n"
" pool.submit(on_event)\n"
),
})
g = nx.DiGraph()
for n in r["nodes"]:
g.add_node(n["id"], **n)
for e in r["edges"]:
g.add_edge(e["source"], e["target"], **e)
affected = {h.node_id for h in affected_nodes(g, nid["on_event"])}
# editing on_event now flags the cross-module dispatcher — the gap #1565
# left open (it only saw same-file callbacks).
assert nid["schedule"] in affected
def test_cross_file_param_shadow_emits_no_indirect_call(tmp_path):
"""Soundness carries across files: an imported name shadowed by a parameter
is the local value, so no cross-file indirect edge is manufactured."""
r, nid = _extract_dir(tmp_path, {
"handlers.py": "def on_event(x):\n return x\n",
"scheduler.py": (
"from handlers import on_event\n\n\n"
"def schedule(pool, on_event):\n" # on_event is the PARAMETER here
" pool.submit(on_event)\n"
),
})
indirect = _rels(r, "indirect_call")
assert (nid["schedule"], nid["on_event"]) not in indirect