fix(python): resolve calls through injected fields and method results

Carry unchanged typed bindings through self.field assignments and associate
method-result receivers with the exact resolved producer call. Preserve
INFERRED provenance, fail closed on ambiguous or rebound values, and retain
return-type context during incremental CLI and watch rebuilds.

Bump the AST cache schema and cover the four missing task-service calls,
cache reuse, incremental rebuilds, and negative resolution cases.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
(cherry picked from commit 9f42b5eca9)
This commit is contained in:
keny11300 authored and safishamsi committed 2026-10-25 17:25:50 +00:00
1 parent f1a11d33ac
commit a5ea8bbd6b
6 files changed
+284 -15

No files matched your search

+10
View File
@@ -124,6 +124,16 @@ classes under different parents retain separate definitions, methods, and
containment edges; top-level class ids are unchanged. AST cache schema 7 prevents
older cached definitions from retaining the collapsed identities.
Python injected fields retain an unchanged parameter/local's declared class
through `self.field = value`. A local assigned a member-call result can use the
resolved method's single scalar return-type reference. The link uses the exact
producer call's byte span, not a same-line argument or a bare method name.
Unknown types, conflicting assignments, shadowed names, container returns, and
ambiguous return references emit no inferred call. Resulting call edges remain
`INFERRED`. Changed-caller rebuilds carry unchanged methods' return-type references
as resolver context. Changes to a producer's return annotation require a full
rebuild to recompute unchanged callers' inferred relationships.
C# partial types merge across files by their path inside the namespace,
enclosing types first and each with its arity (`` Outer`1.Inner ``), within one
assembly. Nested halves merge only under the same enclosing chain, and `Foo` and
+5 -2
View File
@@ -4382,7 +4382,7 @@ def dispatch_command(cmd: str) -> None:
"_rust_impl_key", "_rust_declaration_count",
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture",
"_py_fixture", "_py_return_type",
):
if _node.get(_marker):
_ctx_node[_marker] = _node[_marker]
@@ -4420,7 +4420,8 @@ def dispatch_command(cmd: str) -> None:
if _edge.get("relation") not in (
"contains", "method", "inherits", "imports", "imports_from"
):
continue
if not (_edge.get("relation") == "references" and _edge.get("context") == "return_type"):
continue
if not _ctx_is_ast_tier(_edge):
continue
_sf = _edge.get("source_file")
@@ -4432,6 +4433,8 @@ def dispatch_command(cmd: str) -> None:
"relation": _edge.get("relation"),
"source_file": _sf,
}
if _edge.get("context") == "return_type":
_ctx_edge["context"] = "return_type"
_edge_metadata = _edge.get("metadata")
if (
isinstance(_edge_metadata, dict)
+39 -1
View File
@@ -4949,10 +4949,12 @@ def _resolve_python_member_calls(
parent = nid = up
return None
resolved_call_sites: dict[tuple[str, tuple[int, ...]], set[str]] = {}
def _emit_call(
caller: str, target_nid: "str | None", rc: dict, inferred: bool = False
) -> None:
if not target_nid or target_nid == caller or (caller, target_nid) in existing_pairs:
if not target_nid or target_nid == caller:
return
target_file = node_by_id.get(target_nid, {}).get("source_file")
if target_file and not _is_python_file(target_file):
@@ -4968,6 +4970,13 @@ def _resolve_python_member_calls(
label = str(target.get("label", "")).strip().lstrip(".").removesuffix("()")
if not target.get("_py_property") or label != rc.get("callee"):
return
elif rc.get("_python_call_site"):
# Record the precise producer before pair deduplication. A same-line
# argument call must never stand in for the assigned factory itself.
site = (caller, tuple(rc["_python_call_site"]))
resolved_call_sites.setdefault(site, set()).add(target_nid)
if (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
@@ -5041,6 +5050,7 @@ def _resolve_python_member_calls(
cls = base
return None
factory_receivers: list[dict] = []
for rc in all_raw_calls:
if rc.get("_ambiguous_python_import"):
continue
@@ -5074,6 +5084,9 @@ def _resolve_python_member_calls(
continue
if not receiver or not callee or not caller:
continue
if rc.get("_python_receiver_factory"):
factory_receivers.append(rc)
continue
# External modules have no parsed member definition. The extractor's
# present-false lexical fact and one exact plain import are both needed;
# older cached facts, from-imports, and ambiguous bindings fail closed.
@@ -5157,6 +5170,31 @@ def _resolve_python_member_calls(
continue
_emit_call(caller, children[0], rc)
# A local bound to a uniquely resolved method call may take the method's
# scalar return annotation. Container/union/unknown return types do not name
# one class here, and rebinding/shadowing was already rejected by the extractor.
return_classes: dict[str, set[str]] = {}
class_ids = {nid for group in class_def_nids.values() for nid in group}
for edge in all_edges:
if edge.get("relation") == "references" and edge.get("context") == "return_type":
# The AST must also identify one scalar class. Looking only at
# reference edges would misread `Task | int` as Task: builtins have
# no class node and are deliberately omitted from type references.
if not node_by_id.get(edge["source"], {}).get("_py_return_type"):
continue
return_classes.setdefault(edge["source"], set()).add(edge["target"])
for rc in factory_receivers:
site = (rc["caller_nid"], tuple(rc["_python_receiver_factory"]))
producers = resolved_call_sites.get(site, set())
if len(producers) != 1:
continue
classes = return_classes.get(next(iter(producers)), set())
if len(classes) != 1:
continue
cls = next(iter(classes))
if cls in class_ids:
_emit_call(rc["caller_nid"], method_index.get((cls, _key(rc["callee"]))), rc, inferred=True)
# Every suffix the TS/JS extractors claim, so a pure-ESM (`.mjs`) repo still activates
# the member-call resolver below.
+41 -10
View File
@@ -2690,11 +2690,13 @@ def _python_self_attr(node, source: bytes) -> str | None:
return None
return _read_text(attr, source)
def _python_self_attr_bindings(body, source: bytes):
def _python_self_attr_bindings(body, source: bytes, local_types: dict[str, str | None] | None = None):
"""Yield ``(attr, type_name)`` for every ``self.attr = ...`` in a method body
(#2860). ``type_name`` is the annotation (``self.attr: T = ...``) or the bare
class of ``self.attr = Ctor(...)``, and None for any other value so the
caller can poison the field; ``self.attr = None`` binds nothing."""
caller can poison the field; ``self.attr = None`` binds nothing. An unchanged
typed parameter/local also carries its class through ``self.attr = value``."""
local_types = local_types or {}
stack = list(body.named_children)
while stack:
node = stack.pop()
@@ -2705,11 +2707,14 @@ def _python_self_attr_bindings(body, source: bytes):
if left is None:
continue
value, right = node.child_by_field_name("type"), node.child_by_field_name("right")
bound_type = None
if value is None and right is not None:
if right.type == "none":
continue
if right.type == "identifier":
bound_type = local_types.get(_read_text(right, source))
value = right.child_by_field_name("function") if right.type == "call" else None
name = _read_text(value, source) if value is not None else ""
name = _read_text(value, source) if value is not None else (bound_type or "")
typed = name.isidentifier() and name[:1].isupper()
for target in (left.named_children if left.type == "pattern_list" else [left]):
attr = _python_self_attr(target, source)
@@ -5375,7 +5380,9 @@ def _python_class_ref(node, source: bytes) -> str | None:
return _python_class_ref(right, source)
return None
def _python_local_class_bindings(body_node, source: bytes) -> dict[str, str | None]:
def _python_local_class_bindings(
body_node, source: bytes, *, factory_bindings: dict[str, list[int]] | None = None,
) -> dict[str, str | None]:
"""Map ``name -> ClassName`` for the parameters and locals of one Python function.
Typed from a class annotation on a parameter or local (``request: Request``,
@@ -5389,10 +5396,12 @@ def _python_local_class_bindings(body_node, source: bytes) -> dict[str, str | No
inside a lambda or a nested class body are attributed to this function, so
every name those bind is poisoned rather than typed.
"""
bindings: dict[str, str | None] = {}
# A member-call result is not a known class in this file. Keep only its exact
# AST call span for the corpus resolver; the same poison rules apply to it.
bindings: dict[str, str | tuple[int, int] | None] = {}
poison_only = False
def bind(name: str, cls: str | None) -> None:
def bind(name: str, cls: str | tuple[int, int] | None) -> None:
if poison_only or cls is None or bindings.get(name, cls) != cls:
bindings[name] = None
elif name not in bindings:
@@ -5462,7 +5471,12 @@ def _python_local_class_bindings(body_node, source: bytes) -> dict[str, str | No
if annotation is not None:
bind(name, _python_class_ref(annotation, source))
elif right is not None and right.type == "call":
bind(name, _python_class_ref(right.child_by_field_name("function"), source))
fn = right.child_by_field_name("function")
cls = _python_class_ref(fn, source)
if cls is None and factory_bindings is not None and fn is not None and fn.type == "attribute":
bind(name, (right.start_byte, right.end_byte))
else:
bind(name, cls)
else:
bindings[name] = None
else:
@@ -5492,7 +5506,10 @@ def _python_local_class_bindings(body_node, source: bytes) -> dict[str, str | No
visit(child)
visit(body_node)
return bindings
if factory_bindings is not None:
factory_bindings.update({name: list(value) for name, value in bindings.items()
if isinstance(value, tuple)})
return {name: value if isinstance(value, str) else None for name, value in bindings.items()}
def _ruby_local_class_bindings(body_node, source: bytes) -> dict[str, str | None]:
"""Map ``local_var -> ClassName`` for ``var = ClassName.new`` within one Ruby
@@ -9938,10 +9955,14 @@ def _extract_generic(
_py_type = python_var_types.get(caller_nid, {}).get(member_receiver)
if _py_type:
rc_entry["receiver_type"] = _py_type
elif member_receiver in python_factory_bindings.get(caller_nid, {}):
rc_entry["_python_receiver_factory"] = python_factory_bindings[caller_nid][member_receiver]
elif member_receiver in python_fixture_params.get(caller_nid, ()):
# A fixture parameter: typed by the resolver from the
# fixture pytest would pick for it.
rc_entry["_python_fixture_param"] = True
if config.ts_module == "tree_sitter_python":
rc_entry["_python_call_site"] = [node.start_byte, node.end_byte]
# `super(Cls, obj).m()` starts the MRO after Cls, not after the
# caller's class; only bare `super()` may walk the caller's bases.
if member_receiver == "super" and config.ts_module == "tree_sitter_python":
@@ -10302,11 +10323,19 @@ def _extract_generic(
# `self.X.m()` can resolve corpus-side (#2860). Conflicting or untypable
# bindings poison the field to None.
python_attr_types: dict[str, dict[str, str | None]] = {}
python_factory_bindings: dict[str, dict[str, list[int]]] = {}
if config.ts_module == "tree_sitter_python":
for caller_nid, body_node in function_bodies:
factories: dict[str, list[int]] = {}
python_var_types[caller_nid] = _python_local_class_bindings(
body_node, source, factory_bindings=factories,
)
python_factory_bindings[caller_nid] = factories
if caller_nid in method_owner:
fields = python_attr_types.setdefault(method_owner[caller_nid], {})
for attr, type_name in _python_self_attr_bindings(body_node, source):
for attr, type_name in _python_self_attr_bindings(
body_node, source, python_var_types[caller_nid],
):
fields[attr] = type_name if fields.get(attr, type_name) == type_name else None
if config.ts_module == "tree_sitter_ruby":
@@ -10318,10 +10347,12 @@ def _extract_generic(
_py_node_by_id = {n["id"]: n for n in nodes}
_py_test_module = _python_is_test_module(str_path)
for caller_nid, body_node in function_bodies:
python_var_types[caller_nid] = _python_local_class_bindings(body_node, source)
func = getattr(body_node, "parent", None)
if func is None or func.type != "function_definition":
continue
return_class = _python_class_ref(func.child_by_field_name("return_type"), source)
if caller_nid in _py_node_by_id and return_class:
_py_node_by_id[caller_nid]["_py_return_type"] = return_class
if caller_nid in _py_node_by_id and _python_is_property(func, source):
_py_node_by_id[caller_nid]["_py_property"] = True
if not _py_test_module:
+5 -2
View File
@@ -2319,7 +2319,7 @@ def _rebuild_code(
"_rust_impl_key", "_rust_declaration_count",
"_ts_public_twin", "_py_property", "_java_ret",
"_ts_fields", "_ts_static_fields",
"_py_fixture",
"_py_fixture", "_py_return_type",
):
if node.get(marker):
ctx_node[marker] = node[marker]
@@ -2364,7 +2364,8 @@ def _rebuild_code(
if edge.get("relation") not in (
"contains", "method", "inherits", "imports", "imports_from"
):
continue
if not (edge.get("relation") == "references" and edge.get("context") == "return_type"):
continue
if not _is_ast_tier(edge):
continue
source_file = edge.get("source_file")
@@ -2376,6 +2377,8 @@ def _rebuild_code(
"relation": edge.get("relation"),
"source_file": source_file,
}
if edge.get("context") == "return_type":
context_edge["context"] = "return_type"
edge_metadata = edge.get("metadata")
if (
isinstance(edge_metadata, dict)
+184
View File
@@ -0,0 +1,184 @@
"""Calls through injected fields and annotated method results keep provenance."""
from pathlib import Path
import pytest
from graphify.extract import extract
FILES = {
"models.py": (
"class Task:\n"
" def complete(self): pass\n"
),
"repository.py": (
"from models import Task\n"
"class TaskRepository:\n"
" def add(self, title) -> Task: return Task()\n"
" def get(self, key) -> Task: return Task()\n"
" def all(self) -> list[Task]: return []\n"
),
"services.py": (
"from models import Task\n"
"from repository import TaskRepository\n"
"class TaskService:\n"
" def __init__(self, repository: TaskRepository):\n"
" self.repository = repository\n"
" def create_task(self, title):\n"
" return self.repository.add(title)\n"
" def complete_task(self, key):\n"
" task = self.repository.get(key)\n"
" task.complete()\n"
" def pending_tasks(self):\n"
" return self.repository.all()\n"
),
}
def _project(root: Path, overrides=None):
files = {**FILES, **(overrides or {})}
for name, text in files.items():
(root / name).write_text(text, encoding="utf-8")
return extract([root / name for name in files], root=root, cache_root=root, parallel=False)
def _edge(result, source, target):
return next((edge for edge in result["edges"]
if edge["source"] == source and edge["target"] == target
and edge["relation"] == "calls"), None)
@pytest.mark.parametrize(("caller", "callee", "line"), [
("create_task", "add", "L7"),
("complete_task", "get", "L9"),
("pending_tasks", "all", "L12"),
])
def test_injected_parameter_types_reach_member_calls(tmp_path, caller, callee, line):
result = _project(tmp_path)
edge = _edge(result, f"services_taskservice_{caller}", f"repository_taskrepository_{callee}")
assert edge is not None
assert edge["confidence"] == "INFERRED"
assert edge["source_location"] == line
assert edge["source_file"].endswith("services.py")
def test_annotated_method_result_types_the_local_receiver(tmp_path):
result = _project(tmp_path)
edge = _edge(result, "services_taskservice_complete_task", "models_task_complete")
assert edge is not None
assert edge["confidence"] == "INFERRED"
assert edge["source_location"] == "L10"
@pytest.mark.parametrize("body", [
" task = self.repository.get(key)\n task = unknown()\n task.complete()\n",
" task = wrap(self.repository.get(key))\n task.complete()\n",
" task = unknown.get(self.repository.get(key))\n task.complete()\n",
" task = self.repository.get(key)\n return lambda task: task.complete()\n",
" task = self.repository.get(key)\n task = self.repository.get(key)\n task.complete()\n",
])
def test_unknown_rebound_and_shadowed_results_do_not_guess(tmp_path, body):
service = FILES["services.py"].split(" def complete_task")[0]
service += " def complete_task(self, key):\n" + body
result = _project(tmp_path, {"services.py": service})
assert _edge(result, "services_taskservice_complete_task", "models_task_complete") is None
@pytest.mark.parametrize("replacement", ["repository", "repository: TaskRepository"])
def test_untyped_or_rebound_injection_stays_unknown(tmp_path, replacement):
service = FILES["services.py"].replace("repository: TaskRepository", replacement)
if ": TaskRepository" in replacement:
service = service.replace(" self.repository = repository", " repository = unknown()\n self.repository = repository")
result = _project(tmp_path, {"services.py": service})
assert _edge(result, "services_taskservice_create_task", "repository_taskrepository_add") is None
@pytest.mark.parametrize("annotation", ["", " -> list[Task]", " -> Task | Other", " -> Task | int", " -> Task | Unknown"])
def test_return_annotations_must_name_one_scalar_class(tmp_path, annotation):
repository = FILES["repository.py"].replace(
" def get(self, key) -> Task:", f" def get(self, key){annotation}:"
)
repository += "class Other:\n def complete(self): pass\n"
result = _project(tmp_path, {"repository.py": repository})
assert _edge(result, "services_taskservice_complete_task", "models_task_complete") is None
def test_cache_and_changed_file_rebuild_preserve_calls(tmp_path):
cold = _project(tmp_path)
warm = _project(tmp_path)
key = lambda r: sorted((e["source"], e["target"], e["confidence"]) # noqa: E731
for e in r["edges"] if e["relation"] == "calls")
assert key(cold) == key(warm)
assert _edge(warm, "services_taskservice_complete_task", "models_task_complete") is not None
service = tmp_path / "services.py"
service.write_text(service.read_text() + "\n# changed\n")
context_nodes = [n for n in cold["nodes"] if n.get("source_file") != "services.py"]
context_edges = [e for e in cold["edges"] if e.get("source_file") != "services.py"]
changed = extract(
[service], root=tmp_path, cache_root=tmp_path, parallel=False,
resolution_context_nodes=context_nodes, resolution_context_edges=context_edges,
)
for caller, target in [
("create_task", "repository_taskrepository_add"),
("complete_task", "repository_taskrepository_get"),
("complete_task", "models_task_complete"),
("pending_tasks", "repository_taskrepository_all"),
]:
assert _edge(changed, f"services_taskservice_{caller}", target) is not None
def test_changed_file_watch_rebuild_keeps_unchanged_return_annotations(tmp_path):
import json
from graphify.watch import _rebuild_code
_project(tmp_path)
assert _rebuild_code(tmp_path, no_cluster=True, acquire_lock=False, force=True)
service = tmp_path / "services.py"
service.write_text(service.read_text() + "\n# changed\n")
assert _rebuild_code(tmp_path, changed_paths=[service], no_cluster=True, acquire_lock=False)
graph = json.loads((tmp_path / "graphify-out/graph.json").read_text())
assert _edge({"edges": graph.get("links", graph.get("edges", []))}, "services_taskservice_complete_task", "models_task_complete") is not None
def test_changed_file_cli_extract_keeps_unchanged_return_annotations(tmp_path):
import json
import os
import subprocess
import sys
_project(tmp_path)
command = [sys.executable, "-m", "graphify", "extract", str(tmp_path), "--code-only", "--no-cluster"]
env = dict(os.environ, GRAPHIFY_BACKEND="none")
for changed in (False, True):
if changed:
service = tmp_path / "services.py"
service.write_text(service.read_text() + "\n# changed\n")
run = subprocess.run(command, cwd=tmp_path, env=env, capture_output=True, text=True)
assert run.returncode == 0, run.stderr[-2000:]
graph = json.loads((tmp_path / "graphify-out/graph.json").read_text())
assert _edge({"edges": graph.get("links", graph.get("edges", []))}, "services_taskservice_complete_task", "models_task_complete") is not None
def test_schema_change_retires_cached_calls_without_type_provenance(tmp_path, monkeypatch):
import graphify.cache as cache
from graphify.cache import save_cached
from graphify.extract import extract_python
_project(tmp_path)
schema = cache._AST_CACHE_SCHEMA
monkeypatch.setattr(cache, "_EXTRACTOR_VERSION", "same-version")
monkeypatch.setattr(cache, "_AST_CACHE_SCHEMA", 25)
monkeypatch.setattr(cache, "_cleaned_ast_dirs", set())
for path in sorted(tmp_path.glob("*.py")):
result = extract_python(path, root=tmp_path)
for node in result["nodes"]:
node.pop("_py_return_type", None)
for call in result.get("raw_calls", []):
for marker in ("_python_self_attr_type", "_python_receiver_factory", "_python_call_site"):
call.pop(marker, None)
save_cached(path, result, root=tmp_path, cache_root=tmp_path, kind="ast")
monkeypatch.setattr(cache, "_AST_CACHE_SCHEMA", schema)
result = extract(sorted(tmp_path.glob("*.py")), root=tmp_path, cache_root=tmp_path, parallel=False)
assert _edge(result, "services_taskservice_complete_task", "models_task_complete") is not None