fix(elixir): guard nested-module capture and same-file contains clobber (#3603 follow-up)
#3603 resolves cross-file alias/import/require/use targets onto the real defmodule node. Two guards ported from the competing #3566 so the resolver does not over-reach: - Only top-level modules are indexed as resolution targets. extract_elixir marks them with _elixir_module; a nested defmodule (labeled with its bare inner name) is left unmarked so an unrelated `use <Name>` from another file cannot latch onto it. The marker rides through incremental rebuilds via the resolution-context allow-list in watch.py and cli.py, so the fix does not decay on the `graphify update` / watch path. - A same-file alias is left unresolved: the import edge's source is the file node, which already `contains` that module, so retargeting would duplicate the pair as a weaker `imports` and clobber `contains` in the non-multi graph. Adds regression tests for both guards plus an incremental-rebuild test that routes through the real watch._rebuild_code builder (the path #3566's own test bypassed). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b117a6e420
commit
e3535e942a
5 files changed
+133
-19
No files matched your search
+1
-1
@@ -3818,7 +3818,7 @@ def dispatch_command(cmd: str) -> None:
|
||||
"file_type": _node.get("file_type"),
|
||||
"type": _node.get("type"),
|
||||
}
|
||||
for _marker in ("_callable", "_callable_class"):
|
||||
for _marker in ("_callable", "_callable_class", "_elixir_module"):
|
||||
if _node.get(_marker):
|
||||
_ctx_node[_marker] = _node[_marker]
|
||||
_metadata = _node.get("metadata")
|
||||
|
||||
+26
-7
@@ -4863,19 +4863,26 @@ def _resolve_elixir_import_targets(
|
||||
two files each defining the same module name, most likely a genuine
|
||||
corpus oddity) also leaves the edge alone rather than guessing.
|
||||
"""
|
||||
# Index only top-level modules. extract_elixir marks them with
|
||||
# `_elixir_module`; a nested `defmodule` (labeled with its bare inner name)
|
||||
# is left unmarked so it cannot capture an unrelated `use <Name>` from
|
||||
# another file (#3603 follow-up). The marker is carried across incremental
|
||||
# rebuilds via the resolution-context allow-list in watch.py / cli.py, so
|
||||
# this gate keeps working on the `graphify update` / watch path.
|
||||
node_by_id: dict[str, dict] = {}
|
||||
module_nids_by_bare_id: dict[str, list[str]] = {}
|
||||
for n in all_nodes:
|
||||
sf = str(n.get("source_file") or "")
|
||||
if not sf.endswith((".ex", ".exs")):
|
||||
node_by_id[n["id"]] = n
|
||||
if not n.get("_elixir_module"):
|
||||
continue
|
||||
label = str(n.get("label") or "")
|
||||
if not label or label.endswith("()"):
|
||||
continue # function nodes are labeled "name()"; modules are not
|
||||
if not label:
|
||||
continue
|
||||
module_nids_by_bare_id.setdefault(_make_id(label), []).append(n["id"])
|
||||
if not module_nids_by_bare_id:
|
||||
return
|
||||
|
||||
node_ids = {n["id"] for n in all_nodes}
|
||||
node_ids = set(node_by_id)
|
||||
for e in all_edges:
|
||||
if (
|
||||
e.get("relation") != "imports"
|
||||
@@ -4887,8 +4894,20 @@ def _resolve_elixir_import_targets(
|
||||
if tgt in node_ids:
|
||||
continue # already resolves (e.g. a module referring to itself)
|
||||
candidates = module_nids_by_bare_id.get(tgt, [])
|
||||
if len(candidates) == 1:
|
||||
e["target"] = candidates[0]
|
||||
if len(candidates) != 1:
|
||||
continue
|
||||
target_nid = candidates[0]
|
||||
# A module aliasing/importing another module defined in the SAME file
|
||||
# would retarget the `file -> target` import edge onto a node the file
|
||||
# already `contains`, and the non-multi graph keeps one edge per pair,
|
||||
# silently overwriting the structural `contains` edge (#3603 follow-up).
|
||||
# Leave those alone.
|
||||
target_node = node_by_id.get(target_nid)
|
||||
if target_node is not None and str(target_node.get("source_file") or "") == str(
|
||||
e.get("source_file") or ""
|
||||
):
|
||||
continue
|
||||
e["target"] = target_nid
|
||||
|
||||
|
||||
# Kotlin import-target resolution runs EARLY (directly in extract(), before the
|
||||
|
||||
@@ -31,11 +31,13 @@ def extract_elixir(path: Path) -> dict:
|
||||
seen_ids: set[str] = set()
|
||||
function_bodies: list[tuple[str, Any]] = []
|
||||
|
||||
def add_node(nid: str, label: str, line: int) -> None:
|
||||
def add_node(nid: str, label: str, line: int, **attrs) -> None:
|
||||
if nid not in seen_ids:
|
||||
seen_ids.add(nid)
|
||||
nodes.append({"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"})
|
||||
node = {"id": nid, "label": label, "file_type": "code",
|
||||
"source_file": str_path, "source_location": f"L{line}"}
|
||||
node.update(attrs)
|
||||
nodes.append(node)
|
||||
|
||||
def add_edge(src: str, tgt: str, relation: str, line: int,
|
||||
confidence: str = "EXTRACTED", weight: float = 1.0,
|
||||
@@ -117,7 +119,14 @@ def extract_elixir(path: Path) -> dict:
|
||||
if not module_name:
|
||||
return
|
||||
module_nid = _make_id(stem, module_name)
|
||||
add_node(module_nid, module_name, line)
|
||||
# Only a top-level module is a safe cross-file resolution target
|
||||
# (#3603 follow-up): a nested `defmodule Supervisor` is labeled with
|
||||
# its bare inner name and would otherwise capture an unrelated
|
||||
# `use Supervisor` from another file. Mark just the top-level ones;
|
||||
# the marker rides through incremental rebuilds via the
|
||||
# resolution-context allow-list in watch.py / cli.py.
|
||||
add_node(module_nid, module_name, line,
|
||||
**({"_elixir_module": True} if parent_module_nid is None else {}))
|
||||
add_edge(file_nid, module_nid, "contains", line)
|
||||
if do_block_node:
|
||||
for child in do_block_node.children:
|
||||
|
||||
+1
-1
@@ -1687,7 +1687,7 @@ def _rebuild_code(
|
||||
# #2438: the persisted callability markers are the only
|
||||
# thing that lets an unchanged target pass the
|
||||
# indirect_call guard — never re-derived from the label.
|
||||
for marker in ("_callable", "_callable_class"):
|
||||
for marker in ("_callable", "_callable_class", "_elixir_module"):
|
||||
if node.get(marker):
|
||||
ctx_node[marker] = node[marker]
|
||||
metadata = node.get("metadata")
|
||||
|
||||
@@ -10,6 +10,7 @@ the entire internal module dependency graph.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extract import extract
|
||||
@@ -73,10 +74,15 @@ def test_alias_resolves_to_the_module_declared_in_another_file(tmp_path: Path):
|
||||
assert accounts in node_ids, "the import target must be a real, non-dangling node"
|
||||
|
||||
|
||||
def test_same_file_module_reference_is_unaffected(tmp_path: Path):
|
||||
"""Negative control: a module importing something declared in the SAME
|
||||
file already resolved before this fix (both ids share the same stem)
|
||||
and must keep working exactly as before."""
|
||||
def test_same_file_module_reference_does_not_clobber_contains(tmp_path: Path):
|
||||
"""A module aliasing another module declared in the SAME file must be left
|
||||
unresolved. The alias `imports` edge's source is the FILE node, which
|
||||
already `contains` that module, so retargeting it would duplicate the
|
||||
file->module pair with a weaker relation and -- in the non-multi build
|
||||
graph, where `imports` and `contains` are both specific relations -- clobber
|
||||
the structural `contains` edge (#3603 follow-up guard). Cross-file
|
||||
resolution is covered by the repro test above; here the same-file case must
|
||||
fail closed."""
|
||||
result = _extract(tmp_path, {
|
||||
"lib/demo.ex": (
|
||||
"defmodule Demo.Inner do\n"
|
||||
@@ -92,12 +98,21 @@ def test_same_file_module_reference_is_unaffected(tmp_path: Path):
|
||||
})
|
||||
demo_file = _find_file(result, "demo.ex")
|
||||
inner = _find(result, "Demo.Inner")
|
||||
imports = {
|
||||
contains = {
|
||||
(e["source"], e["target"])
|
||||
for e in result["edges"]
|
||||
if e["relation"] == "contains"
|
||||
}
|
||||
resolved_imports = {
|
||||
(e["source"], e["target"])
|
||||
for e in result["edges"]
|
||||
if e["relation"] == "imports"
|
||||
}
|
||||
assert (demo_file, inner) in imports
|
||||
# The structural containment edge is intact ...
|
||||
assert (demo_file, inner) in contains
|
||||
# ... and the same-file alias was NOT retargeted onto Inner's node (which
|
||||
# would duplicate that pair as a weaker `imports` and clobber `contains`).
|
||||
assert (demo_file, inner) not in resolved_imports
|
||||
|
||||
|
||||
def test_ambiguous_module_name_across_files_yields_no_resolution(tmp_path: Path):
|
||||
@@ -154,3 +169,74 @@ def test_genuinely_external_module_stays_unresolved(tmp_path: Path):
|
||||
}
|
||||
assert import_targets
|
||||
assert not (import_targets & node_ids)
|
||||
|
||||
|
||||
def test_nested_module_does_not_capture_foreign_use(tmp_path: Path):
|
||||
"""A nested `defmodule` is labeled with its bare inner name, so an unrelated
|
||||
`use <Name>` / `alias <Name>` from another file must NOT latch onto it
|
||||
(#3603 follow-up guard). Only top-level modules are indexed as targets."""
|
||||
result = _extract(tmp_path, {
|
||||
"lib/app/application.ex": (
|
||||
"defmodule MyApp.Application do\n"
|
||||
" defmodule Supervisor do\n"
|
||||
" def child_spec(_), do: %{}\n"
|
||||
" end\n"
|
||||
"end\n"
|
||||
),
|
||||
"lib/app/worker.ex": (
|
||||
"defmodule MyApp.Worker do\n"
|
||||
" use Supervisor\n"
|
||||
"end\n"
|
||||
),
|
||||
})
|
||||
nested = _find(result, "Supervisor")
|
||||
resolved_targets = {
|
||||
e["target"] for e in result["edges"] if e["relation"] == "imports"
|
||||
}
|
||||
# The `use Supervisor` in worker.ex must not resolve onto the nested module
|
||||
# (it means the stdlib/behaviour Supervisor, which is genuinely external).
|
||||
assert nested not in resolved_targets
|
||||
|
||||
|
||||
def test_resolution_survives_incremental_rebuild(tmp_path: Path):
|
||||
"""The cross-file alias must stay resolved on the real `graphify update` /
|
||||
watch path, where the unchanged target module arrives as a resolution-context
|
||||
node. This only holds if the `_elixir_module` marker rides through the
|
||||
context builder's allow-list -- the exact path #3566's own test bypassed."""
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
corpus = tmp_path / "corpus"
|
||||
corpus.mkdir()
|
||||
(corpus / "accounts.ex").write_text(
|
||||
"defmodule Demo.Accounts do\n def list_users, do: []\nend\n", encoding="utf-8"
|
||||
)
|
||||
caller = corpus / "web.ex"
|
||||
|
||||
def _caller(extra: str = "") -> str:
|
||||
body = " def index, do: Accounts.list_users()\n" + extra
|
||||
return f"defmodule Demo.Web do\n alias Demo.Accounts\n{body}end\n"
|
||||
|
||||
caller.write_text(_caller(), encoding="utf-8")
|
||||
graph_path = corpus / "graphify-out" / "graph.json"
|
||||
|
||||
def resolves() -> bool:
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
accounts = next(
|
||||
(n["id"] for n in data["nodes"] if n.get("label") == "Demo.Accounts"), None
|
||||
)
|
||||
if accounts is None:
|
||||
return False
|
||||
return any(
|
||||
e.get("relation") == "imports" and e.get("target") == accounts
|
||||
for e in data["links"]
|
||||
)
|
||||
|
||||
assert _rebuild_code(corpus, no_cluster=True, acquire_lock=False) is True
|
||||
assert resolves(), "full build resolves the cross-file alias"
|
||||
|
||||
# Change ONLY the caller: accounts.ex is unchanged, so its top-level module
|
||||
# node is fed back as a resolution-context node. The alias must still resolve.
|
||||
caller.write_text(_caller(" def dup, do: Accounts.list_users()\n"), encoding="utf-8")
|
||||
assert _rebuild_code(corpus, changed_paths=[caller], no_cluster=True,
|
||||
acquire_lock=False) is True
|
||||
assert resolves(), "alias stays resolved after an incremental rebuild"
|
||||
Reference in new issue
Block a user