Skip to content

Commit c29950f

Browse files
Deepjyoti-Sarmahsafishamsi
authored andcommitted
fix(extract): keep a symbol that spells a sibling's old file id on its own node (#4449)
extract() renames each file's old file-level id (its path with the extension, esquema_x_sql for x.sql) to the canonical one, on every node, edge endpoint and raw call that spells it. A symbol of another file can spell it too: const sql in x.mjs, so it took the file node's id and was dropped by dedup. The rename now follows only the file that minted the key, wherever another file's own symbol carries the same id; a file that only refers to the owner renames as before, so every key nobody contests behaves exactly as today. Swift extension nids and Objective-C field-table keys follow the same rule; the Objective-C path has no test that reaches it. (cherry picked from commit 2876a1e)
1 parent 5faa05c commit c29950f

2 files changed

Lines changed: 255 additions & 14 deletions

File tree

‎graphify/extract.py‎

Lines changed: 61 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9442,6 +9442,10 @@ def _describe_syntax_error(rel: str, line: "int | None", kept: int) -> str:
94429442
# subagents generate (#1033). Resolve before relativizing so paths passed in
94439443
# relative form still anchor to the (resolved) root.
94449444
id_remap: dict[str, str] = {}
9445+
# Input files that minted each old file-level id key (resolved paths) (#4449). A key
9446+
# names its owner's file node; a symbol of ANOTHER file that merely spells the same
9447+
# string (``const sql`` in x.mjs next to x.sql) must not follow it.
9448+
id_owner: dict[str, set[Path]] = {}
94459449
# A target OUTSIDE the scan root (an out-of-root ProjectReference/.sln/bash
94469450
# `source`/#include/relative import) can't be made relative to root; leaving
94479451
# it absolute leaked the scan path including the OS username into a
@@ -9598,13 +9602,15 @@ def _resolved(p: "str | Path") -> Path:
95989602
new_id = _file_node_id(rel)
95999603
if old_id != new_id:
96009604
id_remap[old_id] = new_id
9605+
id_owner.setdefault(old_id, set()).add(_resolved(path))
96019606
# Also register the absolute-resolved form of the file-level id so
96029607
# alias/workspace import targets (resolved via .resolve()) remap to
96039608
# canonical instead of orphaning (#1529).
96049609
path_abs = _resolved(path)
96059610
old_id_abs = _make_id(str(path_abs))
96069611
if old_id_abs != new_id:
96079612
id_remap[old_id_abs] = new_id
9613+
id_owner.setdefault(old_id_abs, set()).add(path_abs)
96089614
old_prefs: list[tuple[str, str]] = []
96099615
old_pref = _file_node_id(path)
96109616
if old_pref != new_id:
@@ -9634,15 +9640,50 @@ def _resolved(p: "str | Path") -> Path:
96349640
stem_forms[path_abs] = (
96359641
new_id, [old_pref_abs, old_pref, new_id]
96369642
)
9643+
# A key is contested when a node of a different file carries it as one of that
9644+
# file's OWN symbol ids (id starts with a stem prefix of its file). ``held`` lists
9645+
# the files that carry such a node. Every other key renames exactly as before
9646+
# (#1529, #2169, #2243) (#4449).
9647+
contested: set[str] = set()
9648+
held: dict[str, set[Path]] = {}
9649+
for _n in all_nodes:
9650+
_k, _sf = _n.get("id"), _n.get("source_file")
9651+
if _k in id_remap and _k in id_owner and _sf and _resolved(_sf) not in id_owner[_k]:
9652+
_forms = stem_forms.get(_resolved(_sf))
9653+
if _forms and any(_k.startswith(_f + "_") for _f in _forms[1]):
9654+
contested.add(_k)
9655+
held.setdefault(_k, set()).add(_resolved(_sf))
9656+
9657+
def _remapped(nid, owner_sf):
9658+
"""id_remap[nid], or None to keep nid. A contested key stays on an item whose
9659+
file holds its own node with that id and did not mint the key; everything else
9660+
(the owner's file, or a file that only REFERS to the owner) renames as before."""
9661+
new = id_remap.get(nid)
9662+
if new is None or nid not in contested:
9663+
return new
9664+
try:
9665+
if not owner_sf:
9666+
return new
9667+
f = _resolved(owner_sf)
9668+
if f in id_owner[nid]:
9669+
return new
9670+
return None if f in held[nid] else new
9671+
except (OSError, RuntimeError):
9672+
return new
9673+
96379674
if id_remap:
96389675
for n in all_nodes:
9639-
if n.get("id") in id_remap:
9640-
n["id"] = id_remap[n["id"]]
9676+
_new = _remapped(n.get("id"), n.get("source_file"))
9677+
if _new is not None:
9678+
n["id"] = _new
96419679
for e in all_edges:
9642-
if e.get("source") in id_remap:
9643-
e["source"] = id_remap[e["source"]]
9644-
if e.get("target") in id_remap:
9645-
e["target"] = id_remap[e["target"]]
9680+
_sf = e.get("source_file")
9681+
_new = _remapped(e.get("source"), _sf)
9682+
if _new is not None:
9683+
e["source"] = _new
9684+
_new = _remapped(e.get("target"), e.get("target_file") or _sf)
9685+
if _new is not None:
9686+
e["target"] = _new
96469687
# raw_calls carry caller_nid, consumed by the cross-file call pass far
96479688
# below (after this remap). A module-TOP-LEVEL indirect_call/callback
96489689
# records the FILE-level id as its caller — the id minted from the
@@ -9652,23 +9693,29 @@ def _resolved(p: "str | Path") -> Path:
96529693
# source and matches no node in the graph (#2231). Mirrors the
96539694
# sym_remap raw_calls rewrite in the prefix pass below.
96549695
for rc in all_raw_calls:
9655-
cn = rc.get("caller_nid")
9656-
if cn in id_remap:
9657-
rc["caller_nid"] = id_remap[cn]
9696+
_new = _remapped(rc.get("caller_nid"), rc.get("source_file"))
9697+
if _new is not None:
9698+
rc["caller_nid"] = _new
96589699
# swift_extensions[].nid is the same kind of id carrier as caller_nid
96599700
# above (cache.py remaps both), consumed by _merge_swift_extensions far
96609701
# below. Left stale it matches no node, so whether the extension merge
96619702
# runs at all depends on the FORM of the paths handed to extract() —
96629703
# relative input already yields the post-remap slug, absolute input does
96639704
# not (#2538). Remap it here so both agree.
9664-
for result in per_file:
9705+
for _path, result in zip(paths, per_file):
96659706
for ext in result.get("swift_extensions", []) or []:
9666-
en = ext.get("nid")
9667-
if en in id_remap:
9668-
ext["nid"] = id_remap[en]
9707+
_new = _remapped(ext.get("nid"), _path)
9708+
if _new is not None:
9709+
ext["nid"] = _new
96699710
# objc_field_types["tables"] is keyed BY class node id - the one bucket
96709711
# the #1529 rewrites missed (#3150).
9671-
_remap_objc_field_tables(per_file, id_remap)
9712+
if contested:
9713+
for _path, result in zip(paths, per_file):
9714+
_remap_objc_field_tables(
9715+
[result], {k: v for k, v in id_remap.items()
9716+
if k not in contested or _remapped(k, _path) is not None})
9717+
else:
9718+
_remap_objc_field_tables(per_file, id_remap)
96729719
if prefix_remap:
96739720
sym_remap: dict[str, str] = {}
96749721
edge_alias_candidates: dict[str, set[str]] = {}

‎tests/test_ext_tagged_id_clash.py‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
"""#4449: a symbol must not take a same-stem sibling's file id.
2+
3+
``extract()`` renames every file's OLD file-level id (its path WITH the extension,
4+
``esquema_x_sql`` for ``esquema/x.sql``) to the canonical one (``esquema_x``). A symbol of
5+
another file can spell the same string: ``const sql`` in ``x.mjs`` is minted
6+
``{stem}_{name}`` = ``esquema_x_sql``. The rename used to hit it too, so the symbol took
7+
the file node's id, was salted next to it, and dedup kept one of the two: the file node
8+
of ``x.mjs`` ended up labelled ``sql`` and ``graphify explain "x.mjs"`` found nothing.
9+
Edges and calls that named the symbol followed the wrong rename.
10+
11+
These tests pin the cause (a key is renamed only for the file that minted it, wherever
12+
another file's own symbol spells it) and the controls that must not move.
13+
"""
14+
from __future__ import annotations
15+
16+
from pathlib import Path
17+
18+
import pytest
19+
20+
from graphify.build import build
21+
from graphify.extract import extract, extract_js
22+
23+
ISSUE_MJS = (
24+
'import postgres from "postgres";\n'
25+
"const sql = postgres(process.env.U);\n"
26+
"async function prueba(){ return sql`select 1` }\n"
27+
)
28+
SQL = "create table t(a int);\n"
29+
30+
31+
def _write(root: Path, rel: str, text: str) -> Path:
32+
path = root / rel
33+
path.parent.mkdir(parents=True, exist_ok=True)
34+
path.write_text(text, encoding="utf-8")
35+
return path
36+
37+
38+
def _run(root: Path, files: dict[str, str], monkeypatch, *, absolute: bool = False) -> dict:
39+
"""Write ``files`` under ``root`` and run extract() on them, relative or absolute."""
40+
for rel, text in files.items():
41+
_write(root, rel, text)
42+
if absolute:
43+
return extract([root / rel for rel in files], root=root, cache_root=root / "c")
44+
monkeypatch.chdir(root)
45+
return extract([Path(rel) for rel in files], root=Path("."), cache_root=root / "c")
46+
47+
48+
def _node(result: dict, label: str, source_file: str) -> dict:
49+
found = [n for n in result["nodes"] if n.get("label") == label and n.get("source_file") == source_file]
50+
assert len(found) == 1, f"expected one node {label!r} from {source_file}; got {found}"
51+
return found[0]
52+
53+
54+
def _edges(result: dict, relation: str) -> list[tuple[str, str]]:
55+
return [(e["source"], e["target"]) for e in result["edges"] if e.get("relation") == relation]
56+
57+
58+
def _assert_unique_ids(result: dict) -> None:
59+
ids = [n["id"] for n in result["nodes"]]
60+
assert len(ids) == len(set(ids)), f"an id is used by two nodes: {sorted(i for i in ids if ids.count(i) > 1)}"
61+
62+
63+
@pytest.mark.parametrize("absolute", [False, True], ids=["relative", "absolute"])
64+
def test_variable_named_like_the_sibling_extension_keeps_its_own_node(tmp_path, monkeypatch, absolute):
65+
"""The issue: x.mjs with ``const sql`` next to x.sql. Both nodes survive, apart."""
66+
result = _run(tmp_path, {"esquema/x.mjs": ISSUE_MJS, "esquema/x.sql": SQL}, monkeypatch, absolute=absolute)
67+
68+
file_node = _node(result, "x.mjs", "esquema/x.mjs")
69+
variable = _node(result, "sql", "esquema/x.mjs")
70+
sql_file = _node(result, "x.sql", "esquema/x.sql")
71+
assert len({file_node["id"], variable["id"], sql_file["id"]}) == 3
72+
_assert_unique_ids(result)
73+
74+
75+
def test_the_file_node_is_still_found_by_label_after_build(tmp_path, monkeypatch):
76+
"""What ``graphify explain "x.mjs"`` needs: build() must not drop the file node."""
77+
result = _run(tmp_path, {"esquema/x.mjs": ISSUE_MJS, "esquema/x.sql": SQL}, monkeypatch)
78+
labels = {d.get("label") for _, d in build([result]).nodes(data=True)}
79+
assert {"x.mjs", "sql", "x.sql"} <= labels
80+
81+
82+
def test_edges_follow_the_right_node_when_x_mjs_also_imports_x_sql(tmp_path, monkeypatch):
83+
"""One id string, three meanings: the import (stamped with target_file) ends on the
84+
x.sql FILE node; ``contains`` and ``calls`` end on the ``sql`` VARIABLE; no self-loop."""
85+
mjs = 'import raw from "./x.sql";\n' + ISSUE_MJS
86+
result = _run(tmp_path, {"esquema/x.mjs": mjs, "esquema/x.sql": SQL}, monkeypatch)
87+
file_node = _node(result, "x.mjs", "esquema/x.mjs")["id"]
88+
variable = _node(result, "sql", "esquema/x.mjs")["id"]
89+
sql_file = _node(result, "x.sql", "esquema/x.sql")["id"]
90+
prueba = _node(result, "prueba()", "esquema/x.mjs")["id"]
91+
92+
assert (file_node, sql_file) in _edges(result, "imports_from")
93+
assert (file_node, variable) in _edges(result, "contains")
94+
assert (prueba, variable) in _edges(result, "calls")
95+
assert not [e for e in result["edges"] if e["source"] == e["target"]]
96+
97+
98+
def test_a_sibling_without_nodes_still_keeps_the_variable_apart(tmp_path, monkeypatch):
99+
"""x.ts + x.css: x.css yields no nodes, so nothing is salted. ``css`` still must not
100+
take x.ts's file id. (collect_files skips .css; a Python caller passes it explicitly.)"""
101+
ts = "function makeCss(){ return 1 }\nexport const css = makeCss();\nexport function g(){ return css }\n"
102+
result = _run(tmp_path, {"web/x.ts": ts, "web/x.css": "a { color: red }\n"}, monkeypatch)
103+
assert _node(result, "x.ts", "web/x.ts")["id"] != _node(result, "css", "web/x.ts")["id"]
104+
_assert_unique_ids(result)
105+
106+
107+
def test_a_variable_keeps_the_id_the_extractor_gave_it_next_to_a_js_map(tmp_path, monkeypatch):
108+
"""x.js + x.js.map: ``js_map`` was renamed to x.js.map's file id (a node that does not exist)."""
109+
js = "function mk(){ return 1 }\nconst js_map = mk();\nfunction g(){ return js_map }\n"
110+
result = _run(tmp_path, {"web/x.js": js, "web/x.js.map": '{"version":3}\n'}, monkeypatch)
111+
minted = {n["label"]: n["id"] for n in extract_js(Path("web/x.js"))["nodes"]}
112+
assert _node(result, "js_map", "web/x.js")["id"] == minted["js_map"]
113+
114+
115+
def test_a_python_function_named_like_the_sibling_extension_keeps_its_calls(tmp_path, monkeypatch):
116+
"""def sql() in x.py next to x.sql: the function survives and its call edge starts at it,
117+
not at the file node (a caller id that followed the file-level rename)."""
118+
files = {
119+
"pyfn/__init__.py": "",
120+
"pyfn/util.py": "def helper():\n return 1\n",
121+
"pyfn/x.py": "from pyfn.util import helper\n\n\ndef sql():\n return helper()\n",
122+
"pyfn/x.sql": SQL,
123+
}
124+
result = _run(tmp_path, files, monkeypatch)
125+
function = _node(result, "sql()", "pyfn/x.py")["id"]
126+
file_node = _node(result, "x.py", "pyfn/x.py")["id"]
127+
helper = _node(result, "helper()", "pyfn/util.py")["id"]
128+
assert function != file_node
129+
assert (function, helper) in _edges(result, "calls")
130+
assert (file_node, function) in _edges(result, "contains")
131+
_assert_unique_ids(result)
132+
133+
134+
def test_an_unstamped_import_on_a_contested_key_ends_where_it_ends_without_the_variable(tmp_path, monkeypatch):
135+
"""Pascal ``uses util`` makes an edge with no target_file to util.pas's old file id. A JS
136+
variable ``pas`` in util.js spells that id. The edge must end exactly where the same
137+
edge ends when no such variable exists, never on the variable."""
138+
pas = {"uses/util.pas": "unit util;\ninterface\nimplementation\nend.\n",
139+
"uses/main.pas": "unit main;\ninterface\nuses util;\nimplementation\nend.\n"}
140+
contested = _run(tmp_path / "contested", {**pas, "uses/util.js": "function mk(){ return 1 }\nconst pas = mk();\n"}, monkeypatch)
141+
control = _run(tmp_path / "control", {**pas, "uses/util.js": "function mk(){ return 1 }\nconst other = mk();\n"}, monkeypatch)
142+
143+
(target,) = [t for s, t in _edges(contested, "imports") if s == _node(contested, "main", "uses/main.pas")["id"]]
144+
(control_target,) = [t for s, t in _edges(control, "imports") if s == _node(control, "main", "uses/main.pas")["id"]]
145+
assert target == control_target
146+
assert target != _node(contested, "pas", "uses/util.js")["id"]
147+
148+
149+
@pytest.mark.parametrize("name,mjs,expect", [
150+
("other name", 'import postgres from "postgres";\nconst db = postgres(1);\nfunction prueba(){ return db }\n',
151+
{"x.mjs": "esquema_x_mjs_esquema_x", "db": "esquema_x_db", "x.sql": "esquema_x_sql_esquema_x"}),
152+
("literal", "const sql = 1;\nfunction prueba(){ return sql }\n",
153+
{"x.mjs": "esquema_x_mjs_esquema_x", "x.sql": "esquema_x_sql_esquema_x"}),
154+
])
155+
def test_controls_with_a_sibling_keep_todays_ids(tmp_path, monkeypatch, name, mjs, expect):
156+
result = _run(tmp_path, {"esquema/x.mjs": mjs, "esquema/x.sql": SQL}, monkeypatch)
157+
got = {n["label"]: n["id"] for n in result["nodes"] if n["label"] in expect}
158+
assert got == expect, name
159+
160+
161+
@pytest.mark.parametrize("sibling", [None, "esquema/y.sql"], ids=["no sibling", "other-stem sibling"])
162+
def test_the_variable_beside_no_same_stem_sibling_keeps_todays_ids(tmp_path, monkeypatch, sibling):
163+
files = {"esquema/x.mjs": 'import postgres from "postgres";\nconst sql = postgres(1);\nfunction prueba(){ return sql }\n'}
164+
if sibling:
165+
files[sibling] = SQL
166+
result = _run(tmp_path, files, monkeypatch)
167+
assert _node(result, "x.mjs", "esquema/x.mjs")["id"] == "esquema_x"
168+
assert _node(result, "sql", "esquema/x.mjs")["id"] == "esquema_x_sql"
169+
170+
171+
def test_a_stub_from_a_different_stem_keeps_todays_ids(tmp_path, monkeypatch):
172+
"""A Lazarus package names a unit with the unit file's old id. Its stem differs
173+
from the unit's, so the key is not contested and nothing moves."""
174+
lpk = ('<?xml version="1.0"?>\n<CONFIG><Package Version="5"><Name Value="P"/><Files Count="1"><Item1>'
175+
'<Filename Value="b.pas"/><UnitName Value="b"/></Item1></Files></Package></CONFIG>\n')
176+
result = _run(tmp_path, {"lazarus/a.lpk": lpk, "lazarus/b.pas": "unit b;\ninterface\nimplementation\nend.\n"}, monkeypatch)
177+
assert _node(result, "b", "lazarus/a.lpk")["id"] == "lazarus_a_lpk_lazarus_b"
178+
assert _node(result, "b.pas", "lazarus/b.pas")["id"] == "lazarus_b_pas_lazarus_b"
179+
180+
181+
def test_a_swift_type_named_like_the_sibling_extension_keeps_both_file_nodes(tmp_path, monkeypatch):
182+
"""struct sql and ``extension sql`` in x.swift next to x.sql. The recorded extension nid must
183+
follow the type node. If it follows the file-level rename instead, _merge_swift_extensions
184+
removes every node with that id, and both file nodes go with it."""
185+
files = {"sw/x.swift": "struct sql {\n func run() {}\n}\n\nextension sql {\n func extra() {}\n}\n",
186+
"sw/x.sql": SQL}
187+
result = _run(tmp_path, files, monkeypatch)
188+
189+
swift_file = _node(result, "x.swift", "sw/x.swift")["id"]
190+
sql_file = _node(result, "x.sql", "sw/x.sql")["id"]
191+
type_node = _node(result, "sql", "sw/x.swift")["id"]
192+
assert len({swift_file, sql_file, type_node}) == 3
193+
run, extra = _node(result, ".run()", "sw/x.swift")["id"], _node(result, ".extra()", "sw/x.swift")["id"]
194+
assert {(type_node, run), (type_node, extra)} <= set(_edges(result, "method"))

0 commit comments

Comments
 (0)