fix(guard): a saved node dedup folded into a twin is not a lost node (#4940)

to_json refused a valid --update when entity dedup merged a re-extracted
node into a twin: the saved id was no longer in the new graph, so the
#479 guard called it lost and the previous graph.json stayed on disk.

Treat a saved id as present when dedup folded it into a survivor that is
in the new graph. A survivor that is itself gone excuses nothing, so a
real loss beside a merge is still refused and only it is named. The
node-count check gets the same allowance, counting N merged ids as N - 1
when the survivor is new this run and N when it is a saved id.

Full rebuilds were refused the same way and are fixed by the same change.

(cherry picked from commit 4c3b38ba6e)
This commit is contained in:
Deepjyoti-Sarmah authored and safishamsi committed 2026-11-02 19:03:49 +00:00
1 parent 4c81e6f5a9
commit 7566615de3
3 files changed
+141 -4

No files matched your search

+28
View File
@@ -71,6 +71,7 @@ def _lost_saved_semantic_nodes(
new_nodes: list,
deleted_sources: set[str] | None = None,
folded: dict[str, str] | None = None,
dedup_remap: dict[str, str] | None = None,
) -> list[dict]:
"""Saved semantic nodes whose ids are absent from the new graph.
@@ -85,6 +86,11 @@ def _lost_saved_semantic_nodes(
``folded`` (when given) maps each saved node id that build_from_json merged
into an AST twin to that twin's id, so a caller comparing node counts can
discount it.
``dedup_remap`` is the ``{merged-away id: survivor id}`` map entity dedup
produced this run (#4940). A saved id it folded into a survivor that is in
the new graph is one node, not a lost one. A survivor that is itself gone
excuses nothing: the content went with it.
"""
deleted = {
norm
@@ -145,6 +151,10 @@ def _lost_saved_semantic_nodes(
continue
if isinstance(node_id, str) and _renamed_present(node_id):
continue
if dedup_remap:
survivor = dedup_remap.get(node_id)
if isinstance(survivor, str) and _renamed_present(survivor):
continue
sf_val = node.get("source_file")
source = _norm_source_file(sf_val) if isinstance(sf_val, str) else None
lbl = str(node.get("label", "")).strip()
@@ -168,6 +178,24 @@ def _lost_saved_semantic_nodes(
return lost
def _dedup_shrink_allowance(saved_ids: set, new_ids: set, dedup_remap: dict[str, str]) -> int:
"""How many fewer nodes the graph may have because dedup merged saved ids (#4940).
Merging N saved ids into one survivor removes N - 1 nodes when the survivor
is new this run, and N when it is itself a saved id (that one stays in the
count of the old graph). Only merges whose survivor is in the new graph
count: a missing survivor is a loss, not a merge.
"""
losers_by_survivor: dict[str, int] = {}
for loser, survivor in dedup_remap.items():
if loser in saved_ids and survivor in new_ids:
losers_by_survivor[survivor] = losers_by_survivor.get(survivor, 0) + 1
return sum(
count if survivor in saved_ids else count - 1
for survivor, count in losers_by_survivor.items()
)
# Relations that say only "these two symbols appear together", with no claim about
# HOW. An extractor that finds a specific fact for a pair — a call, an import, an
# inheritance — routinely emits one of these for the same pair as well, so when the
+12 -4
View File
@@ -304,8 +304,9 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
# Drop #3774 accounting before any write. Extract pops these first; every
# other caller of to_json (the documented build_merge persist path) does not.
from graphify.build import take_dedup_remap, take_shrink_accounting
# Not persisted: node_link_data would write G.graph into graph.json (#4940).
take_dedup_remap(G)
# The guard below reads it; it is removed here so node_link_data cannot
# write it into graph.json (#4940).
dedup_remap = take_dedup_remap(G)
take_shrink_accounting(G)
# Safety check: refuse to silently shrink an existing graph (#479)
existing_path = Path(output_path)
@@ -353,13 +354,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
)
return False
new_n = G.number_of_nodes()
from graphify.build import _lost_saved_semantic_nodes
from graphify.build import _dedup_shrink_allowance, _lost_saved_semantic_nodes
new_node_list = [
{"id": node_id, **{key: value for key, value in attrs.items() if key != "id"}}
for node_id, attrs in G.nodes(data=True)
]
folded: dict[str, str] = {}
missing = _lost_saved_semantic_nodes(existing_nodes, new_node_list, set(), folded)
missing = _lost_saved_semantic_nodes(
existing_nodes, new_node_list, set(), folded, dedup_remap=dedup_remap,
)
if missing:
import sys as _sys
ids = ", ".join(str(node.get("id")) for node in missing)
@@ -374,6 +377,11 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
# A twin new to this run does not offset some other node's loss.
existing_ids = {n.get("id") for n in existing_nodes if isinstance(n, dict)}
merged = sum(twin in existing_ids for twin in folded.values())
# Ids entity dedup folded into a survivor are not lost either (#4940).
if dedup_remap:
merged += _dedup_shrink_allowance(
existing_ids, set(G.nodes), dedup_remap,
)
if new_n < existing_n - merged:
import sys as _sys
print(
+101
View File
@@ -135,3 +135,104 @@ def test_the_dedup_map_is_never_written_into_graph_json(tmp_path):
out = tmp_path / "graph.json"
assert to_json(G, cluster(G), str(out)) is True
assert "_dedup_remap" not in json.dumps(json.loads(out.read_text()))
# The bug: a merge dedup performed read as a loss.
TWINS = [_node("claude_the_nudge", "The nudge", "CLAUDE.md"),
_node("claude_first_contact", "First contact", "CLAUDE.md"),
_node("glossary_the_nudge", "The nudge", "GLOSSARY.md"),
_node("glossary_first_contact", "First contact", "GLOSSARY.md")]
GLOSSARY_ALONE = [_node("glossary_the_nudge", "The nudge", "GLOSSARY.md"),
_node("glossary_first_contact", "First contact", "GLOSSARY.md")]
def test_re_extracting_a_doc_alone_writes_when_dedup_folds_it_into_its_twins(tmp_path):
# The issue: GLOSSARY.md is re-extracted alone, dedup merges its concepts
# into the untouched CLAUDE.md twins, and the saved glossary_* ids vanish.
written, disk = _merge_and_write(tmp_path, TWINS, GLOSSARY_ALONE)
assert written is True
assert sorted(n["label"] for n in disk["nodes"]) == ["First contact", "The nudge"]
def test_an_edge_to_the_merged_away_id_is_kept_and_rewired(tmp_path):
hub = _node("claude_hub", "Hub", "CLAUDE.md")
written, disk = _merge_and_write(
tmp_path, TWINS + [hub], GLOSSARY_ALONE,
saved_edges=[_edge("claude_hub", "glossary_the_nudge", "CLAUDE.md")],
)
ids = {n["id"] for n in disk["nodes"]}
links = disk.get("links", disk.get("edges", []))
assert written is True
assert [link for link in links if "claude_hub" in (link["source"], link["target"])]
assert all(link["source"] in ids and link["target"] in ids for link in links)
def test_same_file_exact_duplicates_do_not_block_the_write(tmp_path):
saved = [_node("glossary_the_nudge", "The nudge", "GLOSSARY.md"),
_node("glossary_the_nudge_2", "The nudge", "GLOSSARY.md"),
_node("claude_x", "X thing", "CLAUDE.md")]
written, disk = _merge_and_write(tmp_path, saved, saved[:2])
assert written is True
assert "The nudge" in {n["label"] for n in disk["nodes"]}
def test_two_saved_ids_folded_into_one_new_survivor_write(tmp_path):
# The node count drops by one although nothing was lost: both saved ids
# live on in a survivor that is new this run.
saved = [_node("glossary_the_nudge_c1", "The nudge", "GLOSSARY.md"),
_node("glossary_the_nudge_c2", "The nudge", "GLOSSARY.md"), ALPHA]
fresh = [_node("glossary_nudge", "The nudge", "GLOSSARY.md"), saved[0], saved[1]]
written, disk = _merge_and_write(tmp_path, saved, fresh)
assert written is True
assert sorted(n["label"] for n in disk["nodes"]) == ["Alpha concept", "The nudge"]
def test_the_updated_graph_has_one_node_per_concept(tmp_path):
_, disk = _merge_and_write(tmp_path, TWINS, GLOSSARY_ALONE)
labels = [n["label"] for n in disk["nodes"]]
assert len(labels) == len(set(labels))
def test_full_rebuild_that_merges_the_same_twins_writes(tmp_path):
from graphify.build import build
graph_path = tmp_path / "graph.json"
_seed(graph_path, TWINS)
G = build([{"nodes": [dict(n) for n in TWINS], "edges": [], "hyperedges": []}],
root=str(tmp_path))
assert G.number_of_nodes() < len(TWINS)
assert to_json(G, cluster(G), str(graph_path)) is True
# The guard must not go blind to a real loss that sits beside a merge.
def test_a_real_loss_next_to_a_merge_is_refused_and_only_it_is_named(tmp_path, capsys):
written, _ = _merge_and_write(
tmp_path, TWINS, GLOSSARY_ALONE,
tamper=lambda G: G.remove_node("claude_first_contact"),
)
named = capsys.readouterr().err.split("missing from the new graph:")[-1]
assert written is False
assert "claude_first_contact" in named
assert "glossary_the_nudge" not in named
def test_a_survivor_that_is_itself_gone_excuses_nothing():
from graphify.build import _lost_saved_semantic_nodes
saved = [_node("loser", "The nudge", "GLOSSARY.md")]
assert _lost_saved_semantic_nodes(saved, [], set(), dedup_remap={"loser": "winner"}) == saved
kept = [_node("winner", "The nudge", "GLOSSARY.md")]
assert _lost_saved_semantic_nodes(saved, kept, set(), dedup_remap={"loser": "winner"}) == []
def test_the_allowance_counts_only_merges_whose_survivor_is_present():
from graphify.build import _dedup_shrink_allowance
remap = {"a": "w", "b": "w", "c": "gone"}
# w is new this run: two saved ids became one node, so the graph may be one smaller.
assert _dedup_shrink_allowance({"a", "b", "c"}, {"w"}, remap) == 1
# w is itself a saved id: both losers are accounted for.
assert _dedup_shrink_allowance({"a", "b", "w"}, {"w"}, remap) == 2
assert _dedup_shrink_allowance({"a"}, set(), remap) == 0