graphify icon indicating copy to clipboard operation
graphify copied to clipboard

Node IDs collide for files sharing a basename (e.g. layout.py vs layout.ts)

Open shuff57 opened this issue 4 months ago • 7 comments

Summary

graphify.extract derives every node ID from path.stem (the extension-less basename). Two source files that share a basename therefore collapse into a single graph node — regardless of language or directory. This silently cross-wires unrelated code: edges from one file attach to another file's symbols.

Environment

  • graphify (PyPI graphifyy), current release as of 2026-07
  • Python 3.14, Windows; the bug is language-agnostic, not OS-specific

Reproduce

Two files sharing the basename layout:

  • a/layout.py — a Python class Layout
  • b/layout.ts — an unrelated TypeScript module
from graphify.extract import extract
from pathlib import Path
r = extract([Path("a/layout.py"), Path("b/layout.ts")])
ids = [n["id"] for n in r["nodes"]]
print("collisions:", len(ids) - len(set(ids)))   # > 0

Observed: both files map to the file node ID layout. The TS file's contains edges point at the Python Layout class/methods, and imports_from edges make the TS file appear to import Python modules.

Expected: each file gets a distinct node ID; edges stay within their own file.

Root cause

extract.py:

def _make_id(*parts: str) -> str:
    combined = "_".join(p.strip("_.") for p in parts if p)
    cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", combined)
    return cleaned.strip("_").lower()

# ...in each per-file extractor:
stem = path.stem            # no extension, no path -> collides
file_nid = _make_id(stem)

_make_id has no path/extension awareness, so stem is the only disambiguator and it isn't unique across files.

Suggested fix

Add a path-aware stem and use it wherever a file-scoped ID is built:

def _stem_id(path: Path) -> str:
    import hashlib
    rel = str(path).replace("\\", "/")
    h = hashlib.sha1(rel.encode("utf-8")).hexdigest()[:6]
    suffix = path.suffix.lstrip(".") or "noext"
    return f"{path.stem}_{suffix}_{h}"   # layout.py -> layout_py_acdcd1

Replace stem = path.stem -> stem = _stem_id(path) in every per-file extractor (and the Go extractor), and update the Python import-resolver's file-node exclusion check to _make_id(_stem_id(path)).

Do NOT change the import-resolver's module-name keys (Path(src).stem, {p.stem: p for p in paths}) — those must stay extensionless because they match Python import module names (from layout import X), which have no extension.

Impact / migration note

The fix changes every code node's ID, so existing persisted graphs won't merge on the next incremental --update; a full rebuild is needed once. Worth calling out in the release notes.

shuff57 avatar Jul 12 '26 17:07 shuff57

I could not reproduce this on the current v0.9.13 checkout (eec7a018).

I tested the reported case through graphify.extract.extract():

  • a/layout.py produced file node a_layout
  • b/layout.ts produced file node b_layout
  • there were no duplicate node IDs, and each contains edge remained attached to its own file

I also tested the harder same-directory case, same/layout.py + same/layout.ts. Those initially share the extensionless canonical stem, but the existing _disambiguate_colliding_node_ids() pass separated them using their source paths; no duplicate IDs or crossed contains edges remained.

The current implementation already has two relevant protections:

  1. _file_stem() preserves the full repo-relative path without the extension, rather than using only path.stem (graphify/extractors/base.py).
  2. _disambiguate_colliding_node_ids() rewrites remaining collisions using source-path identity, with a stable hash for residual normalized-path collisions (graphify/extractors/resolution.py).

Focused regression tests also pass: tests/test_file_node_id_spec.py, test_extract_disambiguates_duplicate_symbol_ids_by_source_path, test_separator_collision_paths_get_distinct_ids, and test_non_colliding_path_id_is_not_salted — 9 passed.

Could you share the output of graphify --version / the installed graphifyy version and the exact IDs/edges produced by the reproduction? The root-cause snippet in the report appears to describe an older implementation. Adding _stem_id() as proposed would change all code-node IDs and seems unnecessary with the current path-aware remap and collision pass.

fyzanshaik avatar Jul 12 '26 18:07 fyzanshaik

Checked the current source (`graphify/extractors/base.py` on the `v8` default branch) to follow up on @fyzanshaik's non-repro.

The originally-reported repro (cross-directory) is indeed fixed. `_file_stem` is now: ```python def _file_stem(path: Path) -> str: if not path.name: return "" return path.with_suffix("").as_posix() ``` This keeps the full relative path (all directory segments), only stripping the final suffix — the docstring even references this directly ("Using every segment — not just the immediate parent dir (#1504) — means same-named files in different directories get distinct IDs"). So `a/layout.py` → `a/layout` and `b/layout.ts` → `b/layout`, which matches @fyzanshaik's test (`a_layout` vs `b_layout`) and confirms the exact scenario in this issue's repro no longer collides.

However, a narrower version of the same defect looks like it should still reproduce: two files with the same basename and the same directory but different extensions. `path.with_suffix("")` drops only the extension, so:

  • `src/layout.py` → `src/layout`
  • `src/layout.ts` → `src/layout` (same directory — still collides)

This is a fairly common real-world pattern beyond the original `layout.py`/`layout.ts` example — e.g. C/C++ header+source pairs (`foo.h` + `foo.c`), or a hand-written `.d.ts` alongside its `.js`/`.ts` implementation in the same folder.

I haven't been able to verify this against a live run (installing the package to reproduce wasn't something I wanted to do without checking in first, per this session's tooling permissions), so this is source-reading analysis only, not a confirmed repro — flagging it in case it's useful, rather than asserting it as fact. If it does hold up, the original suggested fix (make the stem extension-aware, e.g. append path.suffix before hashing/normalizing) would need to land in `_file_stem` itself rather than per-extractor, since every extractor already goes through this shared helper.

STiFLeR7 avatar Jul 16 '26 05:07 STiFLeR7

I tried to reproduce this on the current release (graphifyy 0.9.18 / v8) and couldn't — node ids stay distinct and no edge crosses between the two files, both for the different-directory example in the report and for the harder same-directory variant.

Repro:

from pathlib import Path
from graphify.extract import extract

def check(label, paths):
    r = extract([Path(p) for p in paths])
    ids = [n["id"] for n in r["nodes"]]
    node_sf = {n["id"]: n.get("source_file") for n in r["nodes"]}
    leaks = [
        e for e in r["edges"]
        if node_sf.get(e["source"]) and node_sf.get(e["target"])
        and node_sf[e["source"]] != node_sf[e["target"]]
    ]
    print(f"{label}: id collisions = {len(ids) - len(set(ids))}, cross-file edges = {len(leaks)}")

# different dirs (the report's example)
check("different dirs", ["a/layout.py", "b/layout.ts"])
# same dir, same basename, different extension (the harder case)
check("same dir      ", ["pkg/layout.py", "pkg/layout.ts"])

Output on 0.9.18:

different dirs: id collisions = 0, cross-file edges = 0
same dir      : id collisions = 0, cross-file edges = 0

For different directories the path-preserving id stem already keeps them apart (a_layout vs b_layout). For the same directory both files do collapse onto one pre-extension stem, but _disambiguate_colliding_node_ids (#550 / #1522) salts the two file nodes — and every symbol they contain — apart, so the contains / imports_from edges stay within their own file. That matches the "expected" behavior in the report.

So this looks already fixed on v8. If it still reproduces for you, could you share your graphify version and the exact input? Otherwise this can probably be closed.

Happy to send a small regression test that pins the same-directory case (distinct file-node ids + no cross-file edge) if you'd find it useful as a guard.

alphanury avatar Jul 17 '26 19:07 alphanury

Thanks for the actual repro, @alphanury — you're right, and I traced it on v8 too. My analysis stopped at _file_stem in extractors/base.py and missed the _disambiguate_colliding_node_ids post-pass (extractors/resolution.py:578, called from extract.py). That pass groups nodes by id, and for any id shared across ≥2 distinct source_files it re-salts each one with its source path — so even the same-directory pkg/layout.py / pkg/layout.ts case collapses to one pre-extension stem in _file_stem but then gets split back apart before edges are wired, keeping contains/imports_from within each file. That's exactly what your cross-file edges = 0 output shows.

So this is already handled on v8 — agreed it can be closed. And yes, a small regression test pinning the same-directory variant (distinct file-node ids + zero cross-file edges) would be a worthwhile guard against a future _file_stem change silently regressing it, since the collision is invisible until the disambiguation pass is bypassed. Happy to defer to you on that since you already have the repro wired up.

STiFLeR7 avatar Jul 20 '26 09:07 STiFLeR7

Another instance of this, with a trigger that is guaranteed rather than incidental: systemd units.

foo.service and foo.timer are the standard naming convention for a paired unit — a timer and the service it activates are expected to share a basename. Since _file_stem drops the extension, every such pair collapses into one node, and the timer --activates--> service edge becomes a self-loop or disappears.

Unlike layout.py vs layout.ts, this is not a coincidence a repo might avoid by naming discipline: it is the convention systemd documents, so any repo tracking its units hits it 100% of the time, once per pair.

config/systemd/sl-daily-audit.service  ->  _file_stem -> config/systemd/sl-daily-audit
config/systemd/sl-daily-audit.timer    ->  _file_stem -> config/systemd/sl-daily-audit   # same id

We hit it building an out-of-tree pass for these files (units are in no extension set — filed separately as #2848) and had to mint ids that retain the extension (config_systemd_sl_daily_audit_service vs …_timer) to keep the pair distinct. Worth noting the other half held up fine: normalize_id is stable and reproducible from outside the library, so referencing already-extracted nodes by predicted id worked everywhere except where two files share a stem.

Not asking for anything — just adding a case where the collision is structural rather than accidental, in case it helps weigh the fix.

nathanschram avatar Aug 18 '26 09:08 nathanschram

Already fixed on current v8.

Reproduced the repro shape: a/layout.py and b/layout.ts (different directories, same basename, different language), plus a same-directory variant src/layout.py/src/layout.ts. File node ids come out as a_layout_py/b_layout_ts and src_layout_py/src_layout_ts respectively — distinct in both cases, no collision.

_file_node_id in graphify/extract.py builds the id from {parent_dir}_{stem} plus the extension folded in via the file stem, so two files that only share a basename across languages no longer collide at the file-node level.

ayushcodes10 avatar Sep 16 '26 09:09 ayushcodes10

This looks fixed on the v8 branch by fb6e7c78 (fix(dedup): keep distinct files that mint the same node id (#4281)). Could a maintainer confirm and close?

omsenjalia avatar Oct 18 '26 09:10 omsenjalia