Skip to content

Commit 8d5b139

Browse files
Deepjyoti-Sarmahsafishamsi
authored andcommitted
fix(dedup): keep a dropped-folder doc next to a top-level same-id file (#4281)
With protocol.md next to docs/protocol.md and docs/firmware/protocol.md, all three minted `protocol` and the label tiebreak dropped a real document. A file whose full stem is the id now defines it and keeps the bare id; the other files are path-qualified when they have no other node spelled with their own full stem. If they do, the bare id may be a reference, so the file keeps today's collapse (known boundary). A genuine reference to the top-level file still collapses onto it. A bare path slice from a file that has its own page ranks as a reference, so the real file survives whatever the labels are. (cherry picked from commit a3fa3c4)
1 parent e8eb76e commit 8d5b139

2 files changed

Lines changed: 172 additions & 27 deletions

File tree

‎graphify/dedup.py‎

Lines changed: 67 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,10 @@ def _collision_rank(node: dict, root: Path | None = None,
464464
mention of a document rather than the document itself. Such a node ranks as a
465465
reference even though its id is a path slice, so a real document outranks it
466466
whatever the label lengths are (#4281). The set only ever contains path-slice
467-
ids, so the survivor of every other collision is chosen exactly as before.
467+
ids, so the survivor of every other collision is chosen exactly as before. It
468+
also holds a shorter path-slice id from a file that has its own page
469+
(``_slice_references``), so a bare ``protocol`` inside docs/protocol.md cannot
470+
outrank the real top-level protocol.md on label length.
468471
"""
469472
label = node.get("label") or ""
470473
rank_path = _rank_path(node.get("source_file") or "", root)
@@ -524,6 +527,43 @@ def key(sf):
524527
return found
525528

526529

530+
def _own_page_files(nodes: list[dict], root: Path | None) -> set[str]:
531+
"""Root-relative files that have a node spelled with their own full stem (#4281).
532+
533+
Such a file already has its page, so a shorter path-slice id it also mints
534+
(``protocol`` inside docs/protocol.md, next to ``docs_protocol``) may be a
535+
reference to another file rather than that file's own page."""
536+
from graphify.build import _is_abs # local: build imports dedup
537+
538+
files: set[str] = set()
539+
for node in nodes:
540+
nid, sf = node.get("id"), node.get("source_file")
541+
if not nid or not isinstance(nid, str) or not sf or not isinstance(sf, str):
542+
continue
543+
k = _rank_path(sf, root)
544+
if _is_abs(k):
545+
continue
546+
full = _full_stem(k)
547+
if nid == full or nid.startswith(f"{full}_"):
548+
files.add(k)
549+
return files
550+
551+
552+
def _slice_references(nodes: list[dict], root: Path | None) -> set[tuple[str, str]]:
553+
"""``(id, file)`` of nodes whose id is a SHORTER path slice of a file that has its
554+
own page (#4281). They rank as references, like a ``_mentions`` entry."""
555+
own_page = _own_page_files(nodes, root)
556+
found: set[tuple[str, str]] = set()
557+
for node in nodes:
558+
nid, sf = node.get("id"), node.get("source_file")
559+
if not nid or not isinstance(nid, str) or not sf or not isinstance(sf, str):
560+
continue
561+
k = _rank_path(sf, root)
562+
if k in own_page and nid in _id_prefixes(k) and nid != _full_stem(k):
563+
found.add((nid, k))
564+
return found
565+
566+
527567
def _same_source_entity(survivor: dict, duplicate: dict) -> bool:
528568
"""True when exact-ID records came from the same source file.
529569
@@ -709,10 +749,6 @@ def _path_qualify_dropped_collisions(
709749
location cannot leak into an id;
710750
- a group acts only when its files have at least two distinct full stems; a
711751
lone candidate is left to ``build_from_json``'s semantic id remap;
712-
- a group is skipped when ANY node in the input comes from the file whose
713-
full stem is the id's shorter prefix (``protocol`` while ``protocol.md``
714-
exists): that file is the one the bare id names, so the id may be a genuine
715-
reference to it and stays on the definer-wins collapse-and-warn path;
716752
- a node read as a MENTION of a document (``_mentions``: a path-slice id that
717753
another node of its own file ``references``) is not a candidate, so it is not
718754
renamed onto the mentioning file's own page. That reading is inferred from LLM
@@ -721,9 +757,15 @@ def _path_qualify_dropped_collisions(
721757
collapses as it did before. If two or more other files also mint the mention's
722758
id it cannot be pointed at any one of them, so it stays on the bare id and
723759
``build_from_json`` then folds it into its own file's page;
724-
- a top-level file that mints the same id (``protocol.md`` next to
725-
``docs/protocol.md``) is a separate collision this pass does not resolve: the
726-
group is skipped and the label tiebreak drops one of the real documents;
760+
- a file whose full stem IS the id (``protocol.md`` for ``protocol``) defines it,
761+
keeps the bare id, and counts toward the collision, so ``docs/protocol.md``
762+
next to it is still renamed. A candidate whose bare id names another input
763+
file is renamed only if its own file has no other node spelled with its own
764+
full stem. If it has one (``docs_protocol`` next to ``protocol``), the bare id
765+
may be a reference, so it stays on the definer-wins collapse-and-warn path as
766+
before. Known boundary: when the LLM drops the folder AND also emits another
767+
node spelled with the file's full stem, the file counts as having its own page
768+
and falls back to the collapse it got before this change (#4281);
727769
- a reference to the bare id from ANOTHER file cannot be attributed to one
728770
file, so it is left unresolved (one warning per id) rather than guessed;
729771
- if the new id is already used by a node of a different file, or two files
@@ -777,20 +819,32 @@ def qualified_id(node: dict) -> tuple[str, str] | None:
777819
else:
778820
by_id[nid].append(node)
779821

822+
# Files with a node spelled with their own full stem: their page already exists,
823+
# so a shorter-prefix id from such a file may be a reference to another file.
824+
own_page = _own_page_files(nodes, root)
825+
780826
renames: dict[tuple[str, str], str] = {}
781827
claimed: dict[str, str] = {}
782828
for nid in sorted(by_id):
783829
members = by_id[nid]
784-
if len({key(m["source_file"]) for m in members}) < 2:
785-
continue
786-
if len({_full_stem(key(m["source_file"])) for m in members}) < 2:
830+
# The file whose full stem IS the id defines it; it keeps the bare id and
831+
# counts toward the collision even though it is not a candidate.
832+
definers = {o for o in owners[nid] if o and not _is_abs(o) and _full_stem(o) == nid}
833+
files = {key(m["source_file"]) for m in members} | definers
834+
if len(files) < 2:
787835
continue
788-
if any((qualified_id(m) or ("", ""))[1] in named_files for m in members):
836+
if len({_full_stem(f) for f in files}) < 2:
789837
continue
790838
for m in sorted(members, key=lambda m: key(m["source_file"])):
791839
k = key(m["source_file"])
792840
if (nid, k) in renames or (nid, k) in kept_bare:
793841
continue
842+
# The bare id names another input file (``protocol`` while protocol.md
843+
# exists). It is this file's own page only if the file has no other
844+
# page node; otherwise it may be a reference, so leave it to collapse.
845+
if (qualified_id(m) or ("", ""))[1] in named_files and k in own_page:
846+
kept_bare.add((nid, k))
847+
continue
794848
qualified = qualified_id(m)
795849
new_id = qualified[0] if qualified else None
796850
if (new_id is None
@@ -938,7 +992,7 @@ def deduplicate_entities(
938992
# Genuine cross-file ID collisions stay isolated and are reported below (#1504).
939993
nodes, edges = _disambiguate_defining_collisions(nodes, edges, hyperedges, root_resolved)
940994
nodes, edges = _path_qualify_dropped_collisions(nodes, edges, hyperedges, root_resolved)
941-
mentions = _mentions(nodes, edges, root_resolved)
995+
mentions = _mentions(nodes, edges, root_resolved) | _slice_references(nodes, root_resolved)
942996
seen_ids: dict[str, dict] = {}
943997
dropped: dict[str, list[dict]] = defaultdict(list)
944998
for node in nodes:

‎tests/test_dedup.py‎

Lines changed: 105 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1604,20 +1604,28 @@ def test_bare_id_across_different_paths_is_path_qualified(capsys):
16041604
assert "minted by two different files" not in capsys.readouterr().err
16051605

16061606

1607-
def test_bare_id_naming_an_existing_file_is_not_renamed(capsys):
1608-
"""`protocol.md` exists, so a bare `protocol` may be a genuine reference to it:
1609-
the group is not path-qualified and takes the definer-wins collapse path."""
1610-
nodes = [
1607+
def _three_bare_protocols():
1608+
return [
16111609
{"id": "protocol", "label": "protocol", "file_type": "document",
16121610
"source_file": "protocol.md"},
16131611
{"id": "protocol", "label": "protocol (docs)", "file_type": "document",
16141612
"source_file": "docs/protocol.md"},
16151613
{"id": "protocol", "label": "protocol (firmware)", "file_type": "document",
16161614
"source_file": "docs/firmware/protocol.md"},
16171615
]
1618-
result_nodes, _ = deduplicate_entities(nodes, [], communities={})
1619-
assert [(n["id"], n["source_file"]) for n in result_nodes] == [("protocol", "protocol.md")]
1620-
assert "WARNING" in capsys.readouterr().err
1616+
1617+
1618+
def test_bare_ids_in_three_files_keep_one_node_per_file(capsys):
1619+
"""protocol.md exists and the other two files each have only a bare `protocol`.
1620+
Neither has a page of its own, so the bare id is their page: protocol.md keeps
1621+
`protocol` and the others are path-qualified. Nothing is dropped (#4281)."""
1622+
result_nodes, _ = deduplicate_entities(_three_bare_protocols(), [], communities={})
1623+
assert {(n["id"], n["source_file"]) for n in result_nodes} == {
1624+
("protocol", "protocol.md"),
1625+
("docs_protocol", "docs/protocol.md"),
1626+
("docs_firmware_protocol", "docs/firmware/protocol.md"),
1627+
}
1628+
assert "minted by two different files" not in capsys.readouterr().err
16211629

16221630

16231631
def test_build_with_absolute_edge_paths_moves_edges_to_renamed_node(tmp_path):
@@ -1961,17 +1969,100 @@ def test_mention_without_an_edge_gives_the_same_two_documents():
19611969
assert list(G.edges) == []
19621970

19631971

1964-
def test_top_level_collision_keeps_todays_result():
1965-
"""Case R_toplevel. KNOWN LIMITATION, pinned so a change is noticed: with a
1966-
top-level protocol.md that also mints `protocol`, the three files collide and the
1967-
label tiebreak drops the top-level document's node. This is a separate genuine
1968-
collision from the mention rule and is not fixed here (#4281)."""
1972+
def test_top_level_file_keeps_its_own_node_next_to_dropped_folder_docs():
1973+
"""Case R_toplevel. protocol.md, docs/protocol.md and docs/firmware/protocol.md
1974+
all mint `protocol`. Each file keeps its own node, and the firmware reference
1975+
lands on the top-level `protocol` node (#4281)."""
19691976
from graphify.build import build
19701977

19711978
G = build([_protocol_reference_input(top_level=True)])
1972-
assert sorted(G.nodes) == ["docs_firmware_protocol", "docs_protocol"]
1979+
assert sorted(G.nodes) == ["docs_firmware_protocol", "docs_protocol", "protocol"]
19731980
assert {frozenset(e) for e in G.edges} == {
1974-
frozenset(("docs_firmware_protocol", "docs_protocol"))}
1981+
frozenset(("docs_firmware_protocol", "protocol"))}
1982+
1983+
1984+
def _reference_to_top_level(*, edge=True, docs_label="protocol", top_label="Protocol"):
1985+
docs = "docs/protocol.md"
1986+
nodes = [_mention_node("docs_protocol", "Docs protocol", docs),
1987+
_mention_node("protocol", docs_label, docs),
1988+
_mention_node("protocol", top_label, "protocol.md")]
1989+
edges = [_mention_edge("docs_protocol", "protocol", docs)] if edge else []
1990+
return nodes, edges
1991+
1992+
1993+
def test_genuine_reference_to_top_level_file_still_collapses():
1994+
"""docs/protocol.md has its own `docs_protocol` page and a `protocol` it
1995+
references. That bare id is the top-level file, not a second page of docs/:
1996+
it collapses onto protocol.md's node and the edge ends there (#4281)."""
1997+
nodes, edges = _reference_to_top_level()
1998+
kept, kept_edges = deduplicate_entities(nodes, edges, communities={})
1999+
assert {(n["id"], n["source_file"]) for n in kept} == {
2000+
("docs_protocol", "docs/protocol.md"), ("protocol", "protocol.md")}
2001+
assert [(e["source"], e["target"]) for e in kept_edges] == [("docs_protocol", "protocol")]
2002+
2003+
2004+
def test_reference_to_top_level_file_without_an_edge_still_collapses():
2005+
"""Same input with no `references` edge: the docs `protocol` still collapses
2006+
into protocol.md's node, because docs/protocol.md has its own page (#4281)."""
2007+
nodes, edges = _reference_to_top_level(edge=False)
2008+
kept, kept_edges = deduplicate_entities(nodes, edges, communities={})
2009+
assert {(n["id"], n["source_file"]) for n in kept} == {
2010+
("docs_protocol", "docs/protocol.md"), ("protocol", "protocol.md")}
2011+
assert kept_edges == []
2012+
2013+
2014+
def test_top_level_file_survives_whatever_the_labels_are():
2015+
"""Case R_toplevel, label-swap. The bare `protocol` from docs/protocol.md has the
2016+
SHORTER label. docs/protocol.md has its own page, so that node is a reference and
2017+
protocol.md's node survives; the docs_protocol edge ends on it (#4281)."""
2018+
nodes, edges = _reference_to_top_level(docs_label="Protocol", top_label="Protocol (top-level)")
2019+
kept, kept_edges = deduplicate_entities(nodes, edges, communities={})
2020+
assert {(n["id"], n["label"], n["source_file"]) for n in kept} == {
2021+
("docs_protocol", "Docs protocol", "docs/protocol.md"),
2022+
("protocol", "Protocol (top-level)", "protocol.md")}
2023+
assert [(e["source"], e["target"]) for e in kept_edges] == [("docs_protocol", "protocol")]
2024+
2025+
2026+
def test_top_level_file_survives_without_a_references_edge():
2027+
"""Same label-swap input with no `references` edge, so `_mentions` has no
2028+
evidence. The ranking alone must keep protocol.md's node: a bare slice from a
2029+
file that has its own page is a reference, whatever the labels (#4281)."""
2030+
nodes, _ = _reference_to_top_level(edge=False, docs_label="Protocol",
2031+
top_label="Protocol (top-level)")
2032+
for order in (nodes, list(reversed(nodes))):
2033+
kept, _ = deduplicate_entities([dict(n) for n in order], [], communities={})
2034+
survivor = next(n for n in kept if n["id"] == "protocol")
2035+
assert (survivor["label"], survivor["source_file"]) == ("Protocol (top-level)", "protocol.md")
2036+
2037+
2038+
def test_top_level_collision_result_does_not_depend_on_input_order():
2039+
"""The three-file case fed in reverse order keeps the same nodes (#4281)."""
2040+
nodes = _three_bare_protocols()
2041+
fwd, _ = deduplicate_entities([dict(n) for n in nodes], [], communities={})
2042+
rev, _ = deduplicate_entities([dict(n) for n in reversed(nodes)], [], communities={})
2043+
assert {(n["id"], n["source_file"]) for n in fwd} == {
2044+
(n["id"], n["source_file"]) for n in rev}
2045+
2046+
2047+
def test_dropped_folder_doc_with_own_stem_entity_falls_back_to_collapse():
2048+
"""KNOWN BOUNDARY, pinned so a change is noticed. docs/protocol.md emits `protocol`
2049+
AND `docs_protocol_header` (an entity spelled with its full stem), so the file
2050+
counts as having its own page and the bare id may be a reference. It collapses
2051+
into protocol.md's node, as before this change (#4281)."""
2052+
nodes = [_mention_node("protocol", "protocol", "docs/protocol.md"),
2053+
_mention_node("docs_protocol_header", "Header", "docs/protocol.md"),
2054+
_mention_node("protocol", "Protocol", "protocol.md")]
2055+
kept, _ = deduplicate_entities(nodes, [], communities={})
2056+
assert {(n["id"], n["source_file"]) for n in kept} == {
2057+
("docs_protocol_header", "docs/protocol.md"), ("protocol", "protocol.md")}
2058+
2059+
2060+
def test_lone_bare_id_without_a_top_level_file_is_left_to_build():
2061+
"""A single `protocol` from docs/protocol.md and no protocol.md anywhere: this
2062+
pass does not act, the id stays `protocol` for build's remap (#4281)."""
2063+
nodes = [_mention_node("protocol", "Protocol", "docs/protocol.md")]
2064+
kept, _ = deduplicate_entities(nodes, [], communities={})
2065+
assert [n["id"] for n in kept] == ["protocol"]
19752066

19762067

19772068
def test_entity_described_in_two_documents_collapses_to_one_node(capsys):

0 commit comments

Comments
 (0)