Skip to content

Commit 27c57c7

Browse files
Deepjyoti-Sarmahsafishamsi
authored andcommitted
fix(dedup): path-qualify semantic ids that dropped the directory (#4281)
Semantic extraction sometimes mints an id from the bare filename stem, so a/x.md and b/x.md both emit `x`. Dedup then collapsed them into one node and one file's node was lost. _semantic_id_remap in build.py knows how to rebuild the full-path id, but it runs after dedup and is keyed by id alone, so it cannot send one id to two files. Add _path_qualify_dropped_collisions next to the extension pass. When two or more files with different full path stems mint the same shorter-stem id, rename each node to its own full-path id (keyed by id and source file) and move edges by their source_file. References from other files cannot be attributed, so they are left unresolved with a warning. Boundaries: a group is skipped when the file the bare id names is in the input (a genuine reference); absolute source_files are never qualified, so checkout paths cannot leak into ids; AST-tier nodes are untouched. This reverses the collapse pinned in #1504/#4282 for path-dropped ids: the #1504 test now uses a non-shorter-stem id and the protocol test now expects both files to be path-qualified. (cherry picked from commit 58f844e)
1 parent 364b258 commit 27c57c7

2 files changed

Lines changed: 340 additions & 8 deletions

File tree

‎graphify/dedup.py‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,142 @@ def key(sf):
633633
return out_nodes, edges
634634

635635

636+
def _path_qualify_dropped_collisions(
637+
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
638+
root: Path | None,
639+
) -> tuple[list[dict], list[dict]]:
640+
"""Path-qualify semantic ids that dropped the directory, per file (#4281).
641+
642+
Semantic extraction sometimes mints an id from the bare filename stem, so
643+
``a/x.md`` and ``b/x.md`` both emit ``x``. This is the sibling of
644+
``_disambiguate_defining_collisions`` for different directories rather than
645+
different extensions. Every colliding node is renamed to
646+
``<full path stem><rest of id>``, computed from the node's OWN source_file;
647+
no file keeps the bare id, because picking one would be a guess.
648+
649+
Heuristic boundary:
650+
- only ids spelled with a SHORTER-than-full path stem of the node's own file
651+
are candidates (an id already carrying the full stem is left alone), and
652+
AST-tier nodes are never touched;
653+
- a source_file that is still absolute after rooting (no root, outside the
654+
root, or the other platform's form) is never qualified, so the checkout
655+
location cannot leak into an id;
656+
- a group acts only when its files have at least two distinct full stems; a
657+
lone candidate is left to ``build_from_json``'s semantic id remap;
658+
- a group is skipped when ANY node in the input comes from the file whose
659+
full stem is the id's shorter prefix (``protocol`` while ``protocol.md``
660+
exists): that file is the one the bare id names, so the id may be a genuine
661+
reference to it and stays on the definer-wins collapse-and-warn path;
662+
- a reference to the bare id from ANOTHER file cannot be attributed to one
663+
file, so it is left unresolved (one warning per id) rather than guessed;
664+
- if the new id is already used by a node of a different file, or two files
665+
of a group map to the same new id, the first file in sorted order keeps it
666+
and the rest stay on the bare id and take the collapse-and-warn path.
667+
"""
668+
from graphify.build import _is_abs, _is_ast_tier # local: build imports dedup
669+
670+
def key(sf):
671+
return _rank_path(sf, root) if sf and isinstance(sf, str) else ""
672+
673+
def qualified_id(node: dict) -> tuple[str, str] | None:
674+
"""``(new id, matched shorter prefix)`` for a candidate node, else None."""
675+
nid = node.get("id")
676+
sf = node.get("source_file")
677+
if not nid or not isinstance(nid, str) or not sf or not isinstance(sf, str):
678+
return None
679+
if _is_ast_tier(node):
680+
return None
681+
rel = key(sf)
682+
if _is_abs(rel):
683+
# No root to relativize against: never bake an on-disk path into an id.
684+
return None
685+
full = _full_stem(rel)
686+
matching = [p for p in _id_prefixes(rel) if nid == p or nid.startswith(f"{p}_")]
687+
if not full or not matching:
688+
return None
689+
longest = max(matching, key=len)
690+
if longest == full:
691+
return None
692+
return full + nid[len(longest):], longest
693+
694+
named_files = {
695+
_full_stem(key(n["source_file"])) for n in nodes
696+
if isinstance(n.get("source_file"), str) and n["source_file"]
697+
}
698+
by_id: dict[str, list[dict]] = defaultdict(list)
699+
owners: dict[str, set[str]] = defaultdict(set)
700+
for node in nodes:
701+
nid = node.get("id")
702+
if not nid or not isinstance(nid, str):
703+
continue
704+
owners[nid].add(key(node.get("source_file")))
705+
if qualified_id(node):
706+
by_id[nid].append(node)
707+
708+
renames: dict[tuple[str, str], str] = {}
709+
kept_bare: set[tuple[str, str]] = set()
710+
claimed: dict[str, str] = {}
711+
for nid in sorted(by_id):
712+
members = by_id[nid]
713+
if len({key(m["source_file"]) for m in members}) < 2:
714+
continue
715+
if len({_full_stem(key(m["source_file"])) for m in members}) < 2:
716+
continue
717+
if any((qualified_id(m) or ("", ""))[1] in named_files for m in members):
718+
continue
719+
for m in sorted(members, key=lambda m: key(m["source_file"])):
720+
k = key(m["source_file"])
721+
if (nid, k) in renames or (nid, k) in kept_bare:
722+
continue
723+
qualified = qualified_id(m)
724+
new_id = qualified[0] if qualified else None
725+
if (new_id is None
726+
or any(o != k for o in owners.get(new_id, ()))
727+
or claimed.get(new_id, k) != k):
728+
kept_bare.add((nid, k))
729+
continue
730+
claimed[new_id] = k
731+
renames[(nid, k)] = new_id
732+
if not renames:
733+
return nodes, edges
734+
735+
out_nodes = []
736+
for node in nodes:
737+
new_id = renames.get((str(node.get("id") or ""), key(node.get("source_file"))))
738+
out_nodes.append(dict(node, id=new_id) if new_id else node)
739+
renamed_ids = {nid for nid, _ in renames}
740+
unattributed: dict[str, int] = defaultdict(int)
741+
for coll in (edges, hyperedges or []):
742+
for item in coll:
743+
if not isinstance(item, dict):
744+
continue
745+
k = key(item.get("source_file"))
746+
refs = [item.get("source"), item.get("target")]
747+
members = item.get("nodes")
748+
if isinstance(members, list):
749+
refs += members
750+
for ref in refs:
751+
if (isinstance(ref, str) and ref in renamed_ids
752+
and (ref, k) not in renames and (ref, k) not in kept_bare):
753+
unattributed[ref] += 1
754+
for end in ("source", "target"):
755+
ref = item.get(end)
756+
new_id = renames.get((ref, k)) if isinstance(ref, str) else None
757+
if new_id:
758+
item[end] = new_id
759+
if isinstance(members, list):
760+
item["nodes"] = [renames.get((m, k), m) if isinstance(m, str) else m
761+
for m in members]
762+
for nid in sorted(unattributed):
763+
print(
764+
f"[graphify] WARNING: node '{nid}' was minted by several files and "
765+
f"renamed per file; {unattributed[nid]} reference(s) from other files "
766+
f"could not be attributed and were left unresolved.",
767+
file=sys.stderr,
768+
)
769+
return out_nodes, edges
770+
771+
636772
# ── main entry point ──────────────────────────────────────────────────────────
637773

638774
def _remap_hyperedge_members(hyperedges: list[dict], remap: dict[str, str]) -> None:
@@ -730,6 +866,7 @@ def deduplicate_entities(
730866
# retained so AST structure and semantic enrichment can coexist (#2091).
731867
# Genuine cross-file ID collisions stay isolated and are reported below (#1504).
732868
nodes, edges = _disambiguate_defining_collisions(nodes, edges, hyperedges, root_resolved)
869+
nodes, edges = _path_qualify_dropped_collisions(nodes, edges, hyperedges, root_resolved)
733870
seen_ids: dict[str, dict] = {}
734871
dropped: dict[str, list[dict]] = defaultdict(list)
735872
for node in nodes:

‎tests/test_dedup.py‎

Lines changed: 203 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -444,11 +444,13 @@ def test_dedup_still_merges_crossfile_true_duplicates():
444444
def test_cross_chunk_id_collision_emits_warning(capsys):
445445
"""When two nodes share the same ID but come from different source files
446446
(a cross-chunk LLM ID collision), a WARNING must be printed to stderr
447-
and only the first node survives (#1504)."""
447+
and only the first node survives (#1504). The id is not a shorter-stem mint
448+
of either path, so this covers a collision the path-qualify pass cannot
449+
attribute (#4281)."""
448450
nodes = [
449-
{"id": "readme_booking_service", "label": "Booking Service",
451+
{"id": "booking_service", "label": "Booking Service",
450452
"file_type": "concept", "source_file": "module-a/README.md"},
451-
{"id": "readme_booking_service", "label": "Booking Service",
453+
{"id": "booking_service", "label": "Booking Service",
452454
"file_type": "concept", "source_file": "module-b/README.md"},
453455
]
454456
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
@@ -458,7 +460,7 @@ def test_cross_chunk_id_collision_emits_warning(capsys):
458460

459461
captured = capsys.readouterr()
460462
assert "WARNING" in captured.err
461-
assert "readme_booking_service" in captured.err
463+
assert "booking_service" in captured.err
462464
assert "module-b/README.md" in captured.err
463465
assert "module-a/README.md" in captured.err
464466

@@ -1582,17 +1584,34 @@ def test_extension_rename_is_order_independent():
15821584
assert {(n["source_file"], n["id"]) for n in n1} == {(n["source_file"], n["id"]) for n in n2}
15831585

15841586

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."""
1587+
def test_bare_id_across_different_paths_is_path_qualified(capsys):
1588+
"""A bare `protocol` shared by docs/protocol.md and docs/firmware/protocol.md,
1589+
with no protocol.md anywhere: neither file is named by the bare id, so both are
1590+
definers and each gets its own path-qualified id (#4281 remaining case)."""
15881591
nodes = [
15891592
{"id": "protocol", "label": "protocol", "file_type": "document",
15901593
"source_file": "docs/protocol.md"},
15911594
{"id": "protocol", "label": "protocol (top-level)", "file_type": "document",
15921595
"source_file": "docs/firmware/protocol.md"},
15931596
]
15941597
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1595-
assert len(result_nodes) == 1
1598+
assert {n["id"] for n in result_nodes} == {"docs_protocol", "docs_firmware_protocol"}
1599+
assert "minted by two different files" not in capsys.readouterr().err
1600+
1601+
1602+
def test_bare_id_naming_an_existing_file_is_not_renamed(capsys):
1603+
"""`protocol.md` exists, so a bare `protocol` may be a genuine reference to it:
1604+
the group is not path-qualified and takes the definer-wins collapse path."""
1605+
nodes = [
1606+
{"id": "protocol", "label": "protocol", "file_type": "document",
1607+
"source_file": "protocol.md"},
1608+
{"id": "protocol", "label": "protocol (docs)", "file_type": "document",
1609+
"source_file": "docs/protocol.md"},
1610+
{"id": "protocol", "label": "protocol (firmware)", "file_type": "document",
1611+
"source_file": "docs/firmware/protocol.md"},
1612+
]
1613+
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1614+
assert [(n["id"], n["source_file"]) for n in result_nodes] == [("protocol", "protocol.md")]
15961615
assert "WARNING" in capsys.readouterr().err
15971616

15981617

@@ -1693,3 +1712,179 @@ def test_build_from_subdirectory_moves_edges_to_renamed_node(tmp_path, monkeypat
16931712
assert "firmware_lib_portal" in G and "firmware_lib_portal_html" in G
16941713
assert G.has_edge("firmware_lib_portal_html", "card_a")
16951714
assert not G.has_edge("firmware_lib_portal", "card_a")
1715+
1716+
1717+
# ── #4281: path-dropped doc ids (a/x.md vs b/x.md both mint `x`) ──────────────
1718+
1719+
def _path_dropped_input():
1720+
"""Two docs whose semantic ids dropped the directory: both mint `x`/`x_intro`."""
1721+
nodes = [
1722+
{"id": "x", "label": "X A", "file_type": "document", "source_file": "a/x.md"},
1723+
{"id": "x_intro", "label": "Intro A", "file_type": "document",
1724+
"source_file": "a/x.md"},
1725+
{"id": "x", "label": "X B", "file_type": "document", "source_file": "b/x.md"},
1726+
{"id": "x_intro", "label": "Intro B", "file_type": "document",
1727+
"source_file": "b/x.md"},
1728+
]
1729+
edges = [
1730+
{"source": "x", "target": "x_intro", "relation": "references",
1731+
"confidence": "EXTRACTED", "source_file": "a/x.md"},
1732+
{"source": "x", "target": "x_intro", "relation": "references",
1733+
"confidence": "EXTRACTED", "source_file": "b/x.md"},
1734+
]
1735+
return nodes, edges
1736+
1737+
1738+
def test_path_dropped_doc_id_keeps_both_files(capsys):
1739+
"""a/x.md and b/x.md both mint `x`; neither may be dropped, and each file's
1740+
edge stays inside its own file (#4281)."""
1741+
nodes, edges = _path_dropped_input()
1742+
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
1743+
1744+
assert len(result_nodes) == 4
1745+
assert {n["id"] for n in result_nodes} == {"a_x", "a_x_intro", "b_x", "b_x_intro"}
1746+
by_file = {e["source_file"]: (e["source"], e["target"]) for e in result_edges}
1747+
assert by_file == {"a/x.md": ("a_x", "a_x_intro"), "b/x.md": ("b_x", "b_x_intro")}
1748+
assert "minted by two different files" not in capsys.readouterr().err
1749+
1750+
1751+
def test_path_dropped_rename_is_order_independent():
1752+
"""Guards determinism of the new pass: reversed input must give the same result.
1753+
Expected to pass pre-fix too, since the old collapse is deterministic as well."""
1754+
nodes, edges = _path_dropped_input()
1755+
n1, e1 = deduplicate_entities([dict(n) for n in nodes], [dict(e) for e in edges],
1756+
communities={})
1757+
n2, e2 = deduplicate_entities([dict(n) for n in reversed(nodes)],
1758+
[dict(e) for e in reversed(edges)], communities={})
1759+
assert {(n["source_file"], n["id"]) for n in n1} == {(n["source_file"], n["id"]) for n in n2}
1760+
assert {(e["source_file"], e["source"], e["target"]) for e in e1} == \
1761+
{(e["source_file"], e["source"], e["target"]) for e in e2}
1762+
1763+
1764+
def test_path_dropped_foreign_reference_is_not_guessed(capsys):
1765+
"""c.md points at the bare `x`. It cannot be attributed to a/x.md or b/x.md, so
1766+
it is left unresolved with one warning rather than guessed (#4281)."""
1767+
nodes, edges = _path_dropped_input()
1768+
nodes.append({"id": "c_note", "label": "Note C", "file_type": "document",
1769+
"source_file": "c.md"})
1770+
edges.append({"source": "c_note", "target": "x", "relation": "references",
1771+
"confidence": "INFERRED", "source_file": "c.md"})
1772+
result_nodes, result_edges = deduplicate_entities(nodes, edges, communities={})
1773+
1774+
assert {n["id"] for n in result_nodes} == {
1775+
"a_x", "a_x_intro", "b_x", "b_x_intro", "c_note"}
1776+
foreign = next(e for e in result_edges if e["source_file"] == "c.md")
1777+
assert foreign["target"] == "x"
1778+
warning = ("[graphify] WARNING: node 'x' was minted by several files and renamed "
1779+
"per file; 1 reference(s) from other files could not be attributed "
1780+
"and were left unresolved.")
1781+
assert capsys.readouterr().err.count(warning) == 1
1782+
1783+
1784+
@pytest.mark.parametrize("a, b, leaked", [
1785+
("/home/u/a/x.md", "/home/u/b/x.md", "home_u"),
1786+
("C:\\r\\a\\x.md", "C:\\r\\b\\x.md", "c_r"),
1787+
])
1788+
def test_path_dropped_absolute_paths_are_not_qualified(a, b, leaked, capsys):
1789+
"""With no root to relativize against, a stored absolute path (POSIX or
1790+
Windows) must not be baked into an id: the checkout location would leak into
1791+
persisted ids. Such files stay on the collapse-and-warn path (#4281)."""
1792+
nodes = [
1793+
{"id": "x", "label": "X A", "file_type": "document", "source_file": a},
1794+
{"id": "x", "label": "X B", "file_type": "document", "source_file": b},
1795+
]
1796+
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1797+
assert not any(leaked in n["id"] for n in result_nodes)
1798+
assert "minted by two different files" in capsys.readouterr().err
1799+
1800+
1801+
def test_single_path_dropped_id_left_alone():
1802+
"""A lone path-dropped id has no collision; build_from_json's remap handles it."""
1803+
nodes = [
1804+
{"id": "x", "label": "X A", "file_type": "document", "source_file": "a/x.md"},
1805+
{"id": "other", "label": "Other", "file_type": "document", "source_file": "a/y.md"},
1806+
]
1807+
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1808+
assert {n["id"] for n in result_nodes} == {"x", "other"}
1809+
1810+
1811+
def test_path_dropped_through_build(tmp_path):
1812+
"""The full build path (dedup runs before build_from_json) keeps both files'
1813+
nodes and edges, with absolute semantic paths as real extractions carry (#4281)."""
1814+
from graphify.build import build
1815+
1816+
root = tmp_path
1817+
a = str(root / "a" / "x.md")
1818+
b = str(root / "b" / "x.md")
1819+
ext = {
1820+
"nodes": [
1821+
{"id": "x", "label": "X A", "file_type": "document", "source_file": a},
1822+
{"id": "x_intro", "label": "Intro A", "file_type": "document", "source_file": a},
1823+
{"id": "x", "label": "X B", "file_type": "document", "source_file": b},
1824+
{"id": "x_intro", "label": "Intro B", "file_type": "document", "source_file": b},
1825+
],
1826+
"edges": [
1827+
{"source": "x", "target": "x_intro", "relation": "references",
1828+
"confidence": "EXTRACTED", "source_file": a},
1829+
{"source": "x", "target": "x_intro", "relation": "references",
1830+
"confidence": "EXTRACTED", "source_file": b},
1831+
],
1832+
}
1833+
G = build([ext], root=str(root))
1834+
1835+
assert set(G.nodes) == {"a_x", "a_x_intro", "b_x", "b_x_intro"}
1836+
assert G.has_edge("a_x", "a_x_intro")
1837+
assert G.has_edge("b_x", "b_x_intro")
1838+
assert not G.has_edge("a_x", "b_x_intro")
1839+
assert not G.has_edge("b_x", "a_x_intro")
1840+
1841+
1842+
def test_path_dropped_rebuild_is_idempotent():
1843+
"""Round-tripping a built graph through build() again must not keep renaming
1844+
the fix's own output (#4281)."""
1845+
import copy
1846+
from networkx.readwrite import json_graph
1847+
from graphify.build import build
1848+
1849+
nodes, edges = _path_dropped_input()
1850+
G1 = build([copy.deepcopy({"nodes": nodes, "edges": edges})])
1851+
G2 = build([json_graph.node_link_data(G1, edges="edges")])
1852+
1853+
expected = ["a_x", "a_x_intro", "b_x", "b_x_intro"]
1854+
assert sorted(G1.nodes) == sorted(G2.nodes) == expected
1855+
assert {frozenset(e) for e in G2.edges} == {
1856+
frozenset(("a_x", "a_x_intro")), frozenset(("b_x", "b_x_intro"))}
1857+
1858+
1859+
def test_path_dropped_id_stays_qualified_after_collision_disappears():
1860+
"""Once b/x.md leaves the corpus there is no collision, but a/x.md must keep
1861+
`a_x` rather than flip back to the bare `x` (#4281)."""
1862+
from graphify.build import build
1863+
1864+
nodes, edges = _path_dropped_input()
1865+
only_a = {"nodes": [n for n in nodes if n["source_file"] == "a/x.md"],
1866+
"edges": [e for e in edges if e["source_file"] == "a/x.md"]}
1867+
G = build([only_a])
1868+
1869+
assert sorted(G.nodes) == ["a_x", "a_x_intro"]
1870+
assert G.has_edge("a_x", "a_x_intro")
1871+
1872+
1873+
def test_path_dropped_foreign_reference_edge_is_dropped_by_build(capsys):
1874+
"""c.md's reference to the bare `x` cannot be attributed, so build() ends up
1875+
with no node `x` and drops the edge, and the warning says so (#4281)."""
1876+
from graphify.build import build
1877+
1878+
nodes, edges = _path_dropped_input()
1879+
nodes.append({"id": "c_note", "label": "Note C", "file_type": "document",
1880+
"source_file": "c.md"})
1881+
edges.append({"source": "c_note", "target": "x", "relation": "references",
1882+
"confidence": "INFERRED", "source_file": "c.md"})
1883+
G = build([{"nodes": nodes, "edges": edges}])
1884+
1885+
assert sorted(G.nodes) == ["a_x", "a_x_intro", "b_x", "b_x_intro", "c_note"]
1886+
assert G.degree("c_note") == 0
1887+
assert not G.has_edge("c_note", "a_x")
1888+
assert not G.has_edge("c_note", "b_x")
1889+
assert ("node 'x' was minted by several files and renamed per file; "
1890+
"1 reference(s)") in capsys.readouterr().err

0 commit comments

Comments
 (0)