Skip to content

Commit c08d9af

Browse files
ousamabenyounesclaude
authored andcommitted
fix(extract): attribute cross-file INFERRED uses edges to the referencing symbol (#2652)
Rewrites Pass 2 of the Python cross-file import resolver so an INFERRED `uses` edge anchors on the symbol whose body actually references the imported name (a class as a unit, or a module-level function) at the real reference line, instead of fanning out from the import statement line to every class in the importing file. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 0302bfa commit c08d9af

2 files changed

Lines changed: 172 additions & 78 deletions

File tree

‎graphify/extractors/resolution.py‎

Lines changed: 112 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1935,25 +1935,31 @@ def _resolve_cross_file_imports(
19351935
if src_path.stem not in bare_to_qualified:
19361936
bare_to_qualified[src_path.stem] = fq_stem
19371937

1938-
# Pass 2: for each file, find `from .X import A, B, C` and resolve
1938+
# Pass 2: for each file, find `from .X import A, B, C`, then attribute the
1939+
# `uses` edge to the specific local symbol (class OR function) whose body
1940+
# actually references the imported name — not to every class that merely
1941+
# shares the file (#2652). The edge is anchored at the real reference, not
1942+
# the import line, so `source_location` points at genuine corroboration.
19391943
new_edges: list[dict] = []
1940-
stem_to_path: dict[str, Path] = {_file_stem(p): p for p in paths}
19411944

19421945
for file_result, path in zip(per_file, paths):
1943-
stem = _file_stem(path)
19441946
str_path = str(path)
19451947

1946-
# Find all classes defined in this file (the importers).
1947-
# Excludes rationale nodes whose labels happen not to end in ")" or ".py"
1948-
# but which must never be treated as importing entities (#563).
1949-
local_classes = [
1950-
n["id"] for n in file_result.get("nodes", [])
1951-
if n.get("source_file") == str_path
1952-
and not n["label"].endswith((")", ".py"))
1953-
and n["id"] != _make_id(stem) # exclude file-level node
1954-
and n.get("file_type") != "rationale"
1955-
]
1956-
if not local_classes:
1948+
# Map each local symbol (class or function) to its node id, keyed by the
1949+
# bare symbol name. Function labels end in "()"; the file node ends in
1950+
# ".py"; rationale nodes never import (#563). First writer wins on a
1951+
# name collision (inherently ambiguous within a file).
1952+
name_to_nid: dict[str, str] = {}
1953+
for n in file_result.get("nodes", []):
1954+
if n.get("source_file") != str_path or n.get("file_type") == "rationale":
1955+
continue
1956+
label = n.get("label", "")
1957+
if not label or label.endswith(".py"):
1958+
continue
1959+
sym_name = label[:-2] if label.endswith("()") else label
1960+
if sym_name and sym_name not in name_to_nid:
1961+
name_to_nid[sym_name] = n["id"]
1962+
if not name_to_nid:
19571963
continue
19581964

19591965
# Parse imports from this file
@@ -1963,75 +1969,103 @@ def _resolve_cross_file_imports(
19631969
except Exception:
19641970
continue
19651971

1966-
def walk_imports(node) -> None:
1967-
if node.type == "import_from_statement":
1968-
# Find the module name - handles both absolute and relative imports.
1969-
# Relative: `from .models import X` → relative_import → dotted_name
1970-
# Absolute: `from models import X` → module_name field
1971-
# target_fq is the directory-qualified stem used as the key in
1972-
# stem_to_entities. Relative imports are resolved exactly via the
1973-
# importing file's directory; absolute imports fall back to the
1974-
# bare-stem secondary index (first-writer-wins when names collide).
1975-
target_fq: str | None = None
1976-
for child in node.children:
1977-
if child.type == "relative_import":
1978-
for sub in child.children:
1979-
if sub.type == "dotted_name":
1980-
raw = source[sub.start_byte:sub.end_byte].decode("utf-8", errors="replace")
1981-
bare = raw.split(".")[-1]
1982-
# Resolve relative import to exact qualified stem.
1983-
candidate = path.parent / f"{bare}.py"
1984-
target_fq = _file_stem(candidate)
1985-
break
1986-
break
1987-
if child.type == "dotted_name" and target_fq is None:
1988-
raw = source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
1989-
bare = raw.split(".")[-1]
1990-
target_fq = bare_to_qualified.get(bare)
1972+
# local_name -> target node id (local_name honours `import X as Y`, so a
1973+
# reference to the alias in the body still attributes correctly).
1974+
import_targets: dict[str, str] = {}
1975+
# referenced name -> {source symbol nid: first reference line}
1976+
ref_sources: dict[str, dict[str, int]] = {}
1977+
1978+
def _text(n) -> str:
1979+
return source[n.start_byte:n.end_byte].decode("utf-8", errors="replace")
1980+
1981+
def resolve_import(node) -> None:
1982+
# Find the module name - handles both absolute and relative imports.
1983+
# Relative: `from .models import X` → relative_import → dotted_name
1984+
# Absolute: `from models import X` → module_name field
1985+
# target_fq is the directory-qualified stem used as the key in
1986+
# stem_to_entities. Relative imports are resolved exactly via the
1987+
# importing file's directory; absolute imports fall back to the
1988+
# bare-stem secondary index (first-writer-wins when names collide).
1989+
target_fq: str | None = None
1990+
for child in node.children:
1991+
if child.type == "relative_import":
1992+
for sub in child.children:
1993+
if sub.type == "dotted_name":
1994+
bare = _text(sub).split(".")[-1]
1995+
candidate = path.parent / f"{bare}.py"
1996+
target_fq = _file_stem(candidate)
1997+
break
1998+
break
1999+
if child.type == "dotted_name" and target_fq is None:
2000+
bare = _text(child).split(".")[-1]
2001+
target_fq = bare_to_qualified.get(bare)
19912002

1992-
if not target_fq or target_fq not in stem_to_entities:
1993-
return
2003+
if not target_fq or target_fq not in stem_to_entities:
2004+
return
19942005

1995-
# Collect imported names: dotted_name children of import_from_statement
1996-
# that come AFTER the 'import' keyword token.
1997-
imported_names: list[str] = []
1998-
past_import_kw = False
1999-
for child in node.children:
2000-
if child.type == "import":
2001-
past_import_kw = True
2002-
continue
2003-
if not past_import_kw:
2004-
continue
2005-
if child.type == "dotted_name":
2006-
imported_names.append(
2007-
source[child.start_byte:child.end_byte].decode("utf-8", errors="replace")
2008-
)
2009-
elif child.type == "aliased_import":
2010-
# `import X as Y` - take the original name
2011-
name_node = child.child_by_field_name("name")
2012-
if name_node:
2013-
imported_names.append(
2014-
source[name_node.start_byte:name_node.end_byte].decode("utf-8", errors="replace")
2015-
)
2006+
# Imported names come AFTER the 'import' keyword token. For
2007+
# `import X as Y` the target is found via X but the body uses Y.
2008+
past_import_kw = False
2009+
for child in node.children:
2010+
if child.type == "import":
2011+
past_import_kw = True
2012+
continue
2013+
if not past_import_kw:
2014+
continue
2015+
imported_name: str | None = None
2016+
local_name: str | None = None
2017+
if child.type == "dotted_name":
2018+
imported_name = local_name = _text(child)
2019+
elif child.type == "aliased_import":
2020+
name_node = child.child_by_field_name("name")
2021+
alias_node = child.child_by_field_name("alias")
2022+
if name_node is not None:
2023+
imported_name = _text(name_node)
2024+
local_name = _text(alias_node) if alias_node is not None else imported_name
2025+
if not imported_name or not local_name:
2026+
continue
2027+
tgt_nid = stem_to_entities[target_fq].get(imported_name)
2028+
if tgt_nid:
2029+
import_targets[local_name] = tgt_nid
20162030

2017-
line = node.start_point[0] + 1
2018-
for name in imported_names:
2019-
tgt_nid = stem_to_entities[target_fq].get(name)
2020-
if tgt_nid:
2021-
for src_class_nid in local_classes:
2022-
new_edges.append({
2023-
"source": src_class_nid,
2024-
"target": tgt_nid,
2025-
"relation": "uses",
2026-
"confidence": "INFERRED",
2027-
"source_file": str_path,
2028-
"source_location": f"L{line}",
2029-
"weight": 0.8,
2030-
})
2031+
def visit(node, current_nid: str | None) -> None:
2032+
# Identifiers inside an import statement are the import itself, not a
2033+
# real use — resolve the import here and don't descend into it.
2034+
if node.type == "import_from_statement":
2035+
resolve_import(node)
2036+
return
2037+
# Attribute references to the top-level symbol that contains them: a
2038+
# class is a unit (a reference inside one of its methods counts for
2039+
# the class, matching the documented DigestAuth->Response edge), and
2040+
# a module-level function is its own source. Only set at module scope
2041+
# (current_nid is None) so nested defs never override the container.
2042+
if current_nid is None and node.type in ("class_definition", "function_definition"):
2043+
name_node = node.child_by_field_name("name")
2044+
if name_node is not None:
2045+
mapped = name_to_nid.get(_text(name_node))
2046+
if mapped is not None:
2047+
current_nid = mapped
2048+
if node.type == "identifier" and current_nid is not None:
2049+
slot = ref_sources.setdefault(_text(node), {})
2050+
slot.setdefault(current_nid, node.start_point[0] + 1)
20312051
for child in node.children:
2032-
walk_imports(child)
2052+
visit(child, current_nid)
2053+
2054+
visit(tree.root_node, None)
20332055

2034-
walk_imports(tree.root_node)
2056+
for name, tgt_nid in import_targets.items():
2057+
for src_nid, line in ref_sources.get(name, {}).items():
2058+
if src_nid == tgt_nid:
2059+
continue
2060+
new_edges.append({
2061+
"source": src_nid,
2062+
"target": tgt_nid,
2063+
"relation": "uses",
2064+
"confidence": "INFERRED",
2065+
"source_file": str_path,
2066+
"source_location": f"L{line}",
2067+
"weight": 0.8,
2068+
})
20352069

20362070
return new_edges
20372071

‎tests/test_extract.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3434,3 +3434,63 @@ def test_extract_emits_posix_source_file_for_relative_inputs(tmp_path):
34343434
assert {sf for _, sf in carriers} == {
34353435
"src/lib/content.ts", "src/pages/index.astro",
34363436
}
3437+
3438+
3439+
def _inferred_uses(result):
3440+
"""(source, target) pairs of every INFERRED cross-file `uses` edge."""
3441+
return {
3442+
(e["source"], e["target"])
3443+
for e in result["edges"]
3444+
if e.get("relation") == "uses" and e.get("confidence") == "INFERRED"
3445+
}
3446+
3447+
3448+
def test_inferred_uses_edge_attributes_to_the_referencing_symbol(tmp_path):
3449+
"""A cross-file INFERRED `uses` edge binds to the symbol that actually
3450+
references the import — a function is a valid source and a co-located class
3451+
that never touches the import gets no edge (#2652)."""
3452+
(tmp_path / "helpers.py").write_text("class Helper:\n pass\n", encoding="utf-8")
3453+
(tmp_path / "api.py").write_text(
3454+
"from helpers import Helper\n\n\n"
3455+
"class Request:\n x: int = 0\n\n\n"
3456+
"def handler(req):\n return Helper()\n",
3457+
encoding="utf-8",
3458+
)
3459+
3460+
result = extract([tmp_path / "api.py", tmp_path / "helpers.py"], cache_root=tmp_path)
3461+
uses = _inferred_uses(result)
3462+
3463+
# handler() references Helper -> it is the source.
3464+
assert ("api_handler", "helpers_helper") in uses
3465+
# Request never references Helper -> no false edge from the co-located class.
3466+
assert ("api_request", "helpers_helper") not in uses
3467+
3468+
3469+
def test_inferred_uses_edge_kept_when_the_class_body_references_the_import(tmp_path):
3470+
"""Positive control: a class that genuinely uses the imported symbol still
3471+
gets its class-level INFERRED `uses` edge (the DigestAuth->Response case)."""
3472+
(tmp_path / "models.py").write_text("class Response:\n pass\n", encoding="utf-8")
3473+
(tmp_path / "auth.py").write_text(
3474+
"from models import Response\n\n\n"
3475+
"class DigestAuth:\n def build(self):\n return Response()\n",
3476+
encoding="utf-8",
3477+
)
3478+
3479+
result = extract([tmp_path / "auth.py", tmp_path / "models.py"], cache_root=tmp_path)
3480+
3481+
assert ("auth_digestauth", "models_response") in _inferred_uses(result)
3482+
3483+
3484+
def test_inferred_uses_edge_follows_an_import_alias(tmp_path):
3485+
"""`from helpers import Helper as H` attributes via the local alias `H`, so a
3486+
body that only ever names `H` still resolves to the imported target (#2652)."""
3487+
(tmp_path / "helpers.py").write_text("class Helper:\n pass\n", encoding="utf-8")
3488+
(tmp_path / "api.py").write_text(
3489+
"from helpers import Helper as H\n\n\n"
3490+
"def handler(req):\n return H()\n",
3491+
encoding="utf-8",
3492+
)
3493+
3494+
result = extract([tmp_path / "api.py", tmp_path / "helpers.py"], cache_root=tmp_path)
3495+
3496+
assert ("api_handler", "helpers_helper") in _inferred_uses(result)

0 commit comments

Comments
 (0)