Skip to content

Commit fb6e7c7

Browse files
bitwizard25safishamsi
authored andcommitted
fix(dedup): keep distinct files that mint the same node id (#4281)
Landed from PR #4282 (squashed, authorship preserved). Covers the extension-drop collision (x.py vs x.html); the path-dropped doc-id case in #4281 remains open.
1 parent 4b8be21 commit fb6e7c7

3 files changed

Lines changed: 166 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ A correctness batch picked directly from open issues, plus an OpenCode plugin fi
1313
- Fix: **Python** a bare `import logging` is no longer captured by a loose same-named module (`scripts/logging.py`) in a non-package directory — it resolves to the stdlib module. Guarded by a vendored, deterministic stdlib-name set across the module resolver, the sibling-repoint pass, and the build-time stem-alias index; a deliberate package shadow (`logging/__init__.py`) still resolves (#4261).
1414
- Fix: **Python** a qualified external annotation (`httpx.Response`) no longer binds to an unrelated private local class (`_Response`). The stub-rewire match key now preserves underscores, so `_Response` and `Response` are distinct identifiers (#4269).
1515
- Fix: **C#** an external type the corpus references but never declares (`List<T>`, `System.Type`, Unity's `VisualElement`) now gets one shared, name-keyed placeholder instead of a separate per-file stub (`a_cs_list`, `b_cs_list`), so a query returns one node and the files sharing the type connect through it (#4247).
16+
- Fix: two files that differ only by extension (`portal.py` / `portal.html`) no longer collapse into one node. They derive the same extension-stripped id; the best-ranked file keeps it, the other gets an extension-qualified id (`…_portal_html`), and its edges follow it (matched by root-relative `source_file`, so absolute semantic paths work). A bare id shared across different paths still collapses with the warning (#4281).
1617
- Internal: added regression coverage locking in cross-module binding of a singly-defined type through re-export chains and the unique-stub rewire; the reported failure (#4262) no longer reproduces on this line.
1718

1819
## 0.9.83 (2026-10-09)

‎graphify/dedup.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,98 @@ def _report_id_collision(nid: str, survivor: dict, losers: list[dict]) -> None:
512512
)
513513

514514

515+
def _full_stem(source_file: str) -> str:
516+
"""The extension-stripped, slugified full-path stem a file's own IDs start with."""
517+
stem = _EXTENSION.sub("", source_file.replace("\\", "/"))
518+
return "_".join(s for s in (normalize_id(p) for p in stem.split("/")) if s)
519+
520+
521+
def _extension_qualified_id(node: dict) -> str | None:
522+
"""``x.html``'s own spelling of an ID it shares with ``x.py`` (#4281).
523+
524+
Only applies when the ID is spelled with the node's FULL path stem, i.e.
525+
the ID collides because the extension was stripped. Returns None for an ID
526+
that only matches a trailing path slice (a bare ``protocol``): that is a
527+
reference to another file's entity, not a distinct entity, and is left to
528+
the collapse-and-warn path.
529+
"""
530+
nid = node.get("id") or ""
531+
source_file = node.get("source_file") or ""
532+
ext_match = _EXTENSION.search(source_file.replace("\\", "/"))
533+
full = _full_stem(source_file)
534+
if not (nid and full and ext_match):
535+
return None
536+
if nid != full and not nid.startswith(f"{full}_"):
537+
return None
538+
return f"{full}_{normalize_id(ext_match.group(0))}{nid[len(full):]}"
539+
540+
541+
def _disambiguate_defining_collisions(
542+
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
543+
root: Path | None,
544+
) -> tuple[list[dict], list[dict]]:
545+
"""Keep ``x.py`` and ``x.html`` apart when both derive the same ID (#4281).
546+
547+
The ID is built from the extension-stripped path, so two files that differ
548+
only by extension mint the same ID. The best-ranked file keeps it; the
549+
others get an extension-qualified ID. Edges and hyperedges follow the
550+
renamed node by ``source_file``, compared in root-relative form because
551+
semantic edges can still carry an absolute path here while nodes were
552+
already made relative. Anything else (an ID no file derives from its own
553+
path, or a bare ID shared across different paths) is left to the existing
554+
collapse-and-warn path.
555+
"""
556+
def key(sf):
557+
return _rank_path(sf, root) if sf else ""
558+
559+
by_id: dict[str, list[dict]] = defaultdict(list)
560+
for node in nodes:
561+
nid = node.get("id")
562+
if nid and node.get("source_file") and _extension_qualified_id(node):
563+
by_id[nid].append(node)
564+
taken = {n.get("id") for n in nodes if n.get("id")}
565+
renames: dict[tuple[str, str], str] = {}
566+
for nid, definers in by_id.items():
567+
if len({key(d["source_file"]) for d in definers}) < 2:
568+
continue
569+
winner = min(definers, key=lambda d: _collision_rank(d, root))
570+
for d in sorted(definers, key=lambda d: key(d["source_file"])):
571+
k = key(d["source_file"])
572+
if k == key(winner["source_file"]) or (nid, k) in renames:
573+
continue
574+
# Same full stem only: x.py vs x.html, never a/x vs b/x.
575+
if _full_stem(d["source_file"]) != _full_stem(winner["source_file"]):
576+
continue
577+
# The extension is what tells them apart; same-extension slug twins
578+
# (pkg/service.py vs pkg_service.py) stay on the collapse-and-warn path.
579+
if _EXTENSION.search(d["source_file"]) and _EXTENSION.search(winner["source_file"]) and _EXTENSION.search(d["source_file"]).group(0).lower() == _EXTENSION.search(winner["source_file"]).group(0).lower():
580+
continue
581+
new_id = _extension_qualified_id(d)
582+
if new_id and new_id not in taken:
583+
taken.add(new_id)
584+
renames[(nid, k)] = new_id
585+
if not renames:
586+
return nodes, edges
587+
out_nodes = [
588+
dict(node, id=renames[(node.get("id"), key(node.get("source_file")))])
589+
if (node.get("id"), key(node.get("source_file"))) in renames else node
590+
for node in nodes
591+
]
592+
for coll in (edges, hyperedges or []):
593+
for item in coll:
594+
if not isinstance(item, dict):
595+
continue
596+
k = key(item.get("source_file"))
597+
for end in ("source", "target"):
598+
new_id = renames.get((item.get(end), k))
599+
if new_id:
600+
item[end] = new_id
601+
members = item.get("nodes")
602+
if isinstance(members, list):
603+
item["nodes"] = [renames.get((m, k), m) if isinstance(m, str) else m for m in members]
604+
return out_nodes, edges
605+
606+
515607
# ── main entry point ──────────────────────────────────────────────────────────
516608

517609
def _remap_hyperedge_members(hyperedges: list[dict], remap: dict[str, str]) -> None:
@@ -608,6 +700,7 @@ def deduplicate_entities(
608700
# passing cross-reference's. Missing attributes from same-source records are
609701
# retained so AST structure and semantic enrichment can coexist (#2091).
610702
# Genuine cross-file ID collisions stay isolated and are reported below (#1504).
703+
nodes, edges = _disambiguate_defining_collisions(nodes, edges, hyperedges, root_resolved)
611704
seen_ids: dict[str, dict] = {}
612705
dropped: dict[str, list[dict]] = defaultdict(list)
613706
for node in nodes:

‎tests/test_dedup.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1550,3 +1550,75 @@ def test_reads_as_file_entity_trusts_the_node_kind_stamp_only():
15501550
del unstamped["node_kind"]
15511551
assert not _reads_as_file_entity(stamped)
15521552
assert _reads_as_file_entity(unstamped)
1553+
1554+
1555+
# ── #4281: same stem, different extension keeps both nodes ────────────────────
1556+
1557+
def test_same_stem_different_extension_keeps_both_nodes(capsys):
1558+
"""x.py and x.html share an extension-stripped stem; neither may be dropped."""
1559+
nodes = [
1560+
{"id": "firmware_lib_portal", "label": "portal.py",
1561+
"file_type": "code", "source_file": "firmware/lib/portal.py"},
1562+
{"id": "firmware_lib_portal", "label": "Brick provisioning portal (portal.html)",
1563+
"file_type": "document", "source_file": "firmware/lib/portal.html"},
1564+
]
1565+
edges = [{"source": "firmware_lib_portal", "target": "firmware_lib_portal",
1566+
"relation": "serves", "source_file": "firmware/lib/portal.html"}]
1567+
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
1568+
1569+
ids = {n["source_file"]: n["id"] for n in result_nodes}
1570+
assert len(result_nodes) == 2
1571+
assert ids["firmware/lib/portal.py"] == "firmware_lib_portal"
1572+
assert ids["firmware/lib/portal.html"] == "firmware_lib_portal_html"
1573+
assert result_edges[0]["source"] == result_edges[0]["target"] == "firmware_lib_portal_html"
1574+
assert "WARNING" not in capsys.readouterr().err
1575+
1576+
1577+
def test_extension_rename_is_order_independent():
1578+
a = {"id": "x", "label": "x", "file_type": "code", "source_file": "x.py"}
1579+
b = {"id": "x", "label": "x page", "file_type": "document", "source_file": "x.html"}
1580+
n1, _ = deduplicate_entities([dict(a), dict(b)], [], communities={})
1581+
n2, _ = deduplicate_entities([dict(b), dict(a)], [], communities={})
1582+
assert {(n["source_file"], n["id"]) for n in n1} == {(n["source_file"], n["id"]) for n in n2}
1583+
1584+
1585+
def test_bare_id_across_different_paths_still_collapses_with_warning(capsys):
1586+
"""A bare `protocol` shared by docs/protocol.md and docs/firmware/protocol.md is
1587+
a reference to another file's entity, not a second entity: it is not renamed."""
1588+
nodes = [
1589+
{"id": "protocol", "label": "protocol", "file_type": "document",
1590+
"source_file": "docs/protocol.md"},
1591+
{"id": "protocol", "label": "protocol (top-level)", "file_type": "document",
1592+
"source_file": "docs/firmware/protocol.md"},
1593+
]
1594+
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1595+
assert len(result_nodes) == 1
1596+
assert "WARNING" in capsys.readouterr().err
1597+
1598+
1599+
def test_build_with_absolute_edge_paths_moves_edges_to_renamed_node(tmp_path):
1600+
"""Semantic edges reach dedup with an ABSOLUTE source_file while nodes are already
1601+
root-relative; the renamed node must still receive its edges (#4281)."""
1602+
from graphify.build import build
1603+
1604+
root = tmp_path
1605+
py = str(root / "firmware" / "lib" / "portal.py")
1606+
html = str(root / "firmware" / "lib" / "portal.html")
1607+
ext = {
1608+
"nodes": [
1609+
{"id": "firmware_lib_portal", "label": "portal.py", "file_type": "code",
1610+
"source_file": py},
1611+
{"id": "firmware_lib_portal", "label": "Portal page", "file_type": "document",
1612+
"source_file": html},
1613+
{"id": "card_a", "label": "Card A", "file_type": "document", "source_file": html},
1614+
],
1615+
"edges": [
1616+
{"source": "firmware_lib_portal", "target": "card_a", "relation": "references",
1617+
"confidence": "EXTRACTED", "source_file": html},
1618+
],
1619+
}
1620+
G = build([ext], root=str(root))
1621+
1622+
assert "firmware_lib_portal" in G and "firmware_lib_portal_html" in G
1623+
assert G.has_edge("firmware_lib_portal_html", "card_a")
1624+
assert not G.has_edge("firmware_lib_portal", "card_a")

0 commit comments

Comments
 (0)