From f67113361b99500f2cbd36e36ea6e7a60ba74da3 Mon Sep 17 00:00:00 2001 From: safishamsi Date: Tue, 28 Jul 2026 10:18:01 +0100 Subject: [PATCH] fix(extract): close the absolute-path node-id leak class (#2231, #2243) Absolute/machine-slug ids still leaked into edge endpoints from producers the target_file-stamp loop didn't reach. Three fixes: apply id_remap to raw_calls caller_nid so module-top-level indirect_call sources canonicalize (#2231); a general backstop in the final relativization pass that learns _make_id(abs source_file) -> canonical id for every node and rewrites all node ids and edge endpoints (in-root -> _file_node_id, out-of-root -> ext_), suffix-aware for __entry; and target_file stamps on bash source/entry edges so they ride the same canonicalization. No node id or edge endpoint now carries the scan-root slug for any file in the batch. Builds on #2250. Co-Authored-By: Claude Opus 4.8 (1M context) --- graphify/extract.py | 145 ++++++++++++++++++++++++------- graphify/extractors/bash.py | 27 ++++-- tests/test_extract.py | 2 + tests/test_node_id_canonical.py | 149 ++++++++++++++++++++++++++++++++ 4 files changed, 288 insertions(+), 35 deletions(-) create mode 100644 tests/test_node_id_canonical.py diff --git a/graphify/extract.py b/graphify/extract.py index 6e23894..b834fb4 100644 --- a/graphify/extract.py +++ b/graphify/extract.py @@ -4803,6 +4803,17 @@ def extract( id_remap[_make_id(str(_tp))] = ext_new_id if _raw_tp != _tp: id_remap[_make_id(str(_raw_tp))] = ext_new_id + # Bash entrypoint endpoints suffix the file-level id with + # "__entry" (script-invocation `calls` edges, + # extractors/bash.py); register the suffixed forms too so + # an out-of-root invoked script canonicalizes instead of + # keeping the absolute scan-path slug (#2243). + id_remap.setdefault( + _make_id(str(_tp)) + "__entry", ext_new_id + "__entry") + if _raw_tp != _tp: + id_remap.setdefault( + _make_id(str(_raw_tp)) + "__entry", + ext_new_id + "__entry") except OSError: pass continue @@ -4851,6 +4862,21 @@ def extract( old_pref_abs = _file_node_id(path.resolve()) if old_pref_abs != new_id and old_pref_abs != old_pref: old_prefs.append((old_pref_abs, new_id)) + # Bash entrypoint node ids append "__entry" to the file-level id + # (extractors/bash.py), so a script-invocation edge endpoint minted + # from an out-of-batch target path keeps a suffixed absolute-derived + # id neither the plain id_remap key above nor the source_file-gated + # prefix pass below (nodes only) can reach on an incremental run + # (#2243). Register the suffixed forms, preserving the extension tail + # exactly as the prefix remap yields for in-batch entry nodes + # (`c.sh` -> `c_sh__entry`): new prefix + the tail of the minted id. + for _old, _pref in ((old_id, old_pref), (old_id_abs, old_pref_abs)): + if not _old.startswith(_pref): + continue + _entry_new = new_id + _old[len(_pref):] + "__entry" + _entry_old = _old + "__entry" + if _entry_old != _entry_new: + id_remap.setdefault(_entry_old, _entry_new) if old_prefs: prefix_remap[path.resolve()] = old_prefs # Absolute form first: it is the longest, so prefix decomposition can @@ -4867,6 +4893,18 @@ def extract( e["source"] = id_remap[e["source"]] if e.get("target") in id_remap: e["target"] = id_remap[e["target"]] + # raw_calls carry caller_nid, consumed by the cross-file call pass far + # below (after this remap). A module-TOP-LEVEL indirect_call/callback + # records the FILE-level id as its caller — the id minted from the + # absolute input path that this very remap just rewrote on the file + # node. Without rewriting the raw_calls too, the emitted + # indirect_call edge keeps the machine-specific absolute-derived + # source and matches no node in the graph (#2231). Mirrors the + # sym_remap raw_calls rewrite in the prefix pass below. + for rc in all_raw_calls: + cn = rc.get("caller_nid") + if cn in id_remap: + rc["caller_nid"] = id_remap[cn] if prefix_remap: sym_remap: dict[str, str] = {} edge_alias_candidates: dict[str, set[str]] = {} @@ -5444,6 +5482,52 @@ def extract( # portable id and rewrite the edge endpoints that reference it. # ``_portable_out_of_root_sf`` is defined above, by ``id_remap`` (#2243). ext_id_remap: dict[str, str] = {} + # General backstop closing the absolute-id leak CLASS (#2231/#2243): any + # producer that minted an id or edge endpoint as _make_id() + # and was reached by no earlier remap (module-top-level raw_calls before + # #2231, unstamped edges, regex-rescue stubs #2195, ...) still leaks the + # machine/scan-path slug here. Instead of pattern-matching only the item's + # OWN id, LEARN the absolute-derived key forms (as-written and resolved) + # of every file that appears in the batch from the nodes' source_file, map + # them to the file's canonical id — _file_node_id(rel) in-root, the + # #1899/#2250 "ext" recipe out-of-root — and rewrite every node id and + # edge endpoint through that map. Only absolute-derived ids are renamed to + # their canonical form; a key already owned by a real (differently-minted) + # node is never remapped, so no edge is fabricated toward a node it did + # not already reference. + owned_ids = {n.get("id") for n in all_nodes} + # sf string -> (relativized source_file, canonical id, absolute-derived + # key forms). Cached so the path work (resolve() hits the filesystem) + # runs once per file, not once per node. + _sf_forms: dict[str, tuple[str, str, tuple[str, ...]]] = {} + + def _sf_entry(sf: str, sf_path: Path) -> tuple[str, str, tuple[str, ...]]: + cached = _sf_forms.get(sf) + if cached is not None: + return cached + try: + rel = sf_path.relative_to(root) + except ValueError: + portable = _portable_out_of_root_sf(sf_path) + canonical_id = _make_id("ext", portable) + new_sf = portable + else: + # In-root: the same canonical repo-relative form the real file + # node uses (_file_node_id), so the scan root can never leak into + # a persisted id. Real file nodes were already remapped by the + # #2169 pass, so only leftover absolute-derived ids match below + # (belt-and-braces for #2195 regex-rescue stubs and friends). + canonical_id = _file_node_id(rel) + new_sf = rel.as_posix() + try: + sf_resolved = sf_path.resolve() + except (OSError, RuntimeError): + sf_resolved = sf_path + keys = tuple({_make_id(str(sf_path)), _make_id(str(sf_resolved))}) + entry = (new_sf, canonical_id, keys) + _sf_forms[sf] = entry + return entry + for item in all_nodes + all_edges: sf = item.get("source_file") if not sf: @@ -5451,40 +5535,41 @@ def extract( sf_path = Path(sf) if not sf_path.is_absolute(): continue - try: - rel = sf_path.relative_to(root) - except ValueError: - pass - else: - # Belt-and-braces for #2195: a stub node minted by the Svelte/ - # Astro/Vue regex rescue from an ABSOLUTE input path keeps an - # absolute-path-derived id when no earlier pass learned it (the - # target never resolved to a real file, so the edge carried no - # target_file stamp for the #2169 remap). Mirror the out-of-root - # check below: remap it to the same canonical repo-relative form - # the real file node would use (_file_node_id) so the scan root - # can never leak into a persisted id. Real file nodes were - # already remapped by the #2169 pass, so only leftover stubs - # match here. - if item.get("id") == _make_id(str(sf_path)): - ext_id_remap[item["id"]] = _file_node_id(rel) - item["source_file"] = rel.as_posix() - continue - portable = _portable_out_of_root_sf(sf_path) - # A node whose id was minted from this absolute path also leaks it. - if "id" in item and item.get("id") == _make_id(str(sf_path)): - ext_id_remap[item["id"]] = _make_id("ext", portable) - item["source_file"] = portable + new_sf, canonical_id, keys = _sf_entry(str(sf), sf_path) + if "id" in item: + for key in keys: + if key == canonical_id or key in ext_id_remap: + continue + if key in owned_ids and item.get("id") != key: + # The key is a real node's id minted some other way — + # renaming it (or edges onto it) would corrupt the graph. + # The node that owns it registers it itself when its own + # id IS the absolute-derived form (#2195 stub). + continue + ext_id_remap[key] = canonical_id + item["source_file"] = new_sf if ext_id_remap: + # Bash entrypoint ids are the file-level id + "__entry" + # (extractors/bash.py); rewrite the suffixed form of any learned key + # the same way so a script-invocation endpoint can't keep the slug. + _ENTRY = "__entry" + + def _canon(nid: str) -> str: + if nid in ext_id_remap: + return ext_id_remap[nid] + if nid.endswith(_ENTRY) and nid[: -len(_ENTRY)] in ext_id_remap: + return ext_id_remap[nid[: -len(_ENTRY)]] + _ENTRY + return nid + for n in all_nodes: - if n.get("id") in ext_id_remap: - n["id"] = ext_id_remap[n["id"]] + if n.get("id"): + n["id"] = _canon(n["id"]) for e in all_edges: - if e.get("source") in ext_id_remap: - e["source"] = ext_id_remap[e["source"]] - if e.get("target") in ext_id_remap: - e["target"] = ext_id_remap[e["target"]] + if e.get("source"): + e["source"] = _canon(e["source"]) + if e.get("target"): + e["target"] = _canon(e["target"]) # origin_file is an internal disambiguation hint (#1462): the colliding-id pass # above reads it to keep same-named cross-file stubs distinct, after which nothing diff --git a/graphify/extractors/bash.py b/graphify/extractors/bash.py index 4aa9a4d..984676b 100644 --- a/graphify/extractors/bash.py +++ b/graphify/extractors/bash.py @@ -112,7 +112,8 @@ def extract_bash(path: Path) -> dict: def add_edge(src: str, tgt: str, relation: str, line: int, confidence: str = "EXTRACTED", weight: float = 1.0, - context: str | None = None) -> None: + context: str | None = None, + target_file: str | None = None) -> None: if not src or not tgt or src == tgt: return edge = {"source": src, "target": tgt, "relation": relation, @@ -120,6 +121,13 @@ def extract_bash(path: Path) -> dict: "source_location": f"L{line}", "weight": weight} if context: edge["context"] = context + # Transient resolved-target hint (#1814/#2169), mirroring the Python/ + # markdown extractors: lets the extract() id-remap pass canonicalize a + # target minted from an absolute path even when the target file is not + # in the batch (incremental run) or lives out of root (#2243). Popped + # before anything persists, never shipped into graph.json. + if target_file is not None: + edge["target_file"] = target_file edges.append(edge) file_nid = _make_id(str(path)) @@ -266,7 +274,8 @@ def extract_bash(path: Path) -> dict: if resolved.exists(): tgt_nid = _make_id(str(resolved)) add_edge(file_nid, tgt_nid, "imports_from", line, - context="import") + context="import", + target_file=str(resolved)) # Record the sourced file so resolve_bash_source_edges # can bind calls into its functions (#2141). Gated on # existence like the edge above, so crafted traversal @@ -301,7 +310,8 @@ def extract_bash(path: Path) -> dict: if resolved.is_file(): add_edge(file_nid, _make_id(str(resolved)), "imports_from", line, - confidence="INFERRED", context="import") + confidence="INFERRED", context="import", + target_file=str(resolved)) # Integration (#2141 + #2079): record the resolved # sourced file so calls into its functions resolve # too, not just the source edge. target_path is @@ -335,7 +345,8 @@ def extract_bash(path: Path) -> dict: # is a heuristic, so mark it INFERRED (#2171). add_edge(file_nid, _make_id(str(sibling)), "imports_from", line, - confidence="INFERRED", context="import") + confidence="INFERRED", context="import", + target_file=str(sibling)) bash_sources.append({ "target_path": raw, "source_file": str_path, @@ -360,9 +371,15 @@ def extract_bash(path: Path) -> dict: except ValueError: pass caller_nid = entry_nid if parent_nid == file_nid else parent_nid + # target_file lets the extract() remap loop learn + # this script's canonical id even when it is not in + # the batch; the "__entry"-suffixed endpoint is + # rewritten there via the suffix-aware entry + # registration (#2243). add_edge(caller_nid, _make_id(str(target_path)) + "__entry", "calls", node.start_point[0] + 1, - context="script_invocation") + context="script_invocation", + target_file=str(target_path)) return if t == "declaration_command": diff --git a/tests/test_extract.py b/tests/test_extract.py index 488bdcf..da7a615 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -1765,6 +1765,8 @@ def test_extract_bash_emits_script_invocation_calls(tmp_path, command): "source_location": "L2", "weight": 1.0, "context": "script_invocation", + # Transient canonicalization hint (#2243); popped before persist. + "target_file": str(helpers.resolve()), }] diff --git a/tests/test_node_id_canonical.py b/tests/test_node_id_canonical.py new file mode 100644 index 0000000..6b0c9ea --- /dev/null +++ b/tests/test_node_id_canonical.py @@ -0,0 +1,149 @@ +"""Node-id / edge-endpoint canonicalization: no absolute-path (machine/temp +slug) leaks (#2231, #2243). + +Every producer that mints ids from ``_make_id(str(absolute_path))`` must end +up canonicalized by the time ``extract()`` returns: after extraction, no node +id and no edge endpoint may contain the absolute scan-root slug for any file +that appears in the batch — on full scans AND on incremental (changed-files +only) runs. +""" +from __future__ import annotations + +import os +from pathlib import Path + +from graphify.extract import extract, _make_id + + +def _real(tmp_path: Path) -> Path: + # macOS pytest tmp dirs live under a /var -> /private/var symlink; resolve + # so "absolute input path" and "resolved path" agree deterministically. + return Path(os.path.realpath(tmp_path)) + + +def _slug(root: Path) -> str: + # The tmp-root directory name is unique per test run; an id or endpoint + # containing it can only have been minted from the absolute path. + return _make_id(root.name) + + +def _assert_no_slug(result: dict, slug: str) -> None: + leaked_nodes = [n["id"] for n in result["nodes"] if slug in n["id"].lower()] + assert not leaked_nodes, f"absolute-slug node ids leaked: {leaked_nodes}" + leaked_edges = [ + (e["source"], e["target"], e["relation"]) + for e in result["edges"] + if slug in e["source"].lower() or slug in e["target"].lower() + ] + assert not leaked_edges, f"absolute-slug edge endpoints leaked: {leaked_edges}" + + +def test_module_level_dispatch_indirect_call_source_is_canonical(tmp_path): + """#2231: a module-TOP-LEVEL dispatch table (`HANDLERS = {'a': handle_a}`) + records the FILE node as the raw_call caller. The emitted indirect_call + edge's source must be the canonical file node id, not the id minted from + the absolute input path.""" + root = _real(tmp_path) + (root / "handlers.py").write_text("def handle_a():\n return 1\n") + (root / "disp.py").write_text( + "from handlers import handle_a\n\nHANDLERS = {'a': handle_a}\n" + ) + + result = extract( + [root / "disp.py", root / "handlers.py"], cache_root=tmp_path, root=root + ) + + indirect = [e for e in result["edges"] if e["relation"] == "indirect_call"] + assert indirect, "module-level dispatch must emit an indirect_call edge" + node_ids = {n["id"] for n in result["nodes"]} + for e in indirect: + assert e["source"] == "disp", ( + f"indirect_call source must be the canonical file node id, got {e['source']}" + ) + assert e["source"] in node_ids, "indirect_call source must be a real node" + assert e["target"] == "handlers_handle_a" + _assert_no_slug(result, _slug(root)) + + +def test_bash_source_incremental_target_canonicalizes(tmp_path): + """#2243 (bash): `source ./b.sh` mints the target from the resolved + absolute path. On an incremental run (only the sourcing script in the + batch) the target_file stamp must still canonicalize it to the same id the + full scan produces, with no tmp-root slug.""" + root = _real(tmp_path) + (root / "a.sh").write_text("#!/bin/bash\nsource ./b.sh\nbash ./c.sh\n") + (root / "b.sh").write_text("#!/bin/bash\nhello() { echo hi; }\n") + (root / "c.sh").write_text("#!/bin/bash\necho run\n") + + full = extract( + [root / "a.sh", root / "b.sh", root / "c.sh"], cache_root=tmp_path, root=root + ) + _assert_no_slug(full, _slug(root)) + full_imports = { + (e["source"], e["target"]) for e in full["edges"] + if e["relation"] == "imports_from" + } + assert ("a", "b") in full_imports + full_invocations = { + (e["source"], e["target"]) for e in full["edges"] + if e["relation"] == "calls" and e.get("context") == "script_invocation" + } + assert ("a_sh__entry", "c_sh__entry") in full_invocations + + # Incremental: only the CHANGED sourcing script is re-extracted; b.sh and + # c.sh are not in the batch, so their canonical ids must be learned from + # the target_file stamps. + incr = extract([root / "a.sh"], cache_root=tmp_path, root=root) + _assert_no_slug(incr, _slug(root)) + incr_imports = { + (e["source"], e["target"]) for e in incr["edges"] + if e["relation"] == "imports_from" + } + assert ("a", "b") in incr_imports, ( + f"incremental imports_from target must canonicalize; got {incr_imports}" + ) + incr_invocations = { + (e["source"], e["target"]) for e in incr["edges"] + if e["relation"] == "calls" and e.get("context") == "script_invocation" + } + assert ("a_sh__entry", "c_sh__entry") in incr_invocations, ( + "incremental script-invocation __entry endpoint must match the entry " + f"node id the full scan mints; got {incr_invocations}" + ) + # The transient stamp must never ship out of extract(). + assert not any("target_file" in e for e in incr["edges"]) + assert not any("target_file" in e for e in full["edges"]) + + +def test_extract_invariant_no_absolute_root_slug_anywhere(tmp_path): + """General invariant: extracting a mixed corpus (python module-level + dispatch + bash source + a normal import) from ABSOLUTE input paths leaves + no node id and no edge endpoint containing the absolute-root slug.""" + root = _real(tmp_path) + (root / "handlers.py").write_text("def handle_a():\n return 1\n") + (root / "disp.py").write_text( + "from handlers import handle_a\n\nHANDLERS = {'a': handle_a}\n" + ) + (root / "main.py").write_text("import handlers\n\nhandlers.handle_a()\n") + (root / "run.sh").write_text("#!/bin/bash\nsource ./lib.sh\n./tool.sh\n") + (root / "lib.sh").write_text("#!/bin/bash\ngreet() { echo hi; }\n") + (root / "tool.sh").write_text("#!/bin/bash\necho tool\n") + + paths = [ + root / "disp.py", root / "handlers.py", root / "main.py", + root / "run.sh", root / "lib.sh", root / "tool.sh", + ] + result = extract(paths, cache_root=tmp_path, root=root) + + slug = _slug(root) + assert not any(slug in n["id"].lower() for n in result["nodes"]), [ + n["id"] for n in result["nodes"] if slug in n["id"].lower() + ] + assert not any( + slug in ep.lower() + for e in result["edges"] + for ep in (e["source"], e["target"]) + ), [ + (e["source"], e["target"]) for e in result["edges"] + if slug in e["source"].lower() or slug in e["target"].lower() + ]