Skip to content

fix(guard): don't refuse a write when dedup folded a saved node into a twin (#4940) - #4952

Closed
Deepjyoti-Sarmah wants to merge 4 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4940-shrink-guard-dedup-merge
Closed

Deepjyoti-Sarmah wants to merge 4 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:fix/4940-shrink-guard-dedup-merge

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #4940.

The #479 write guard in to_json calls a saved node lost when its id is missing from the new graph. Entity dedup also removes ids. It folds a re-extracted node into a twin, and the content lives on under the twin's id. So an --update that re-extracted GLOSSARY.md alone was refused, and graph.json stayed stale. A full rebuild that merged the same twins was refused the same way.

This change has dedup report which ids it merged away, carries that map to to_json, and lets the guard count a merged id as present when its survivor is in the new graph:

  build_merge
    build
-     deduplicate_entities
+     deduplicate_entities(remap_out=remap)
+     G.graph["_dedup_remap"] = remap
  to_json
+   dedup_remap = take_dedup_remap(G)      # also keeps it out of graph.json
    _lost_saved_semantic_nodes(saved, new)
+     saved id in remap and survivor in new graph -> not lost
    node-count check
+     allowance: N merged ids = N-1 if the survivor is new, N if it is saved
saved:  claude_the_nudge   glossary_the_nudge
fresh:                     glossary_the_nudge   (GLOSSARY.md alone)
dedup:  glossary_the_nudge -> claude_the_nudge
guard:  before  "glossary_the_nudge missing"          -> refuse
        after   survivor claude_the_nudge is present  -> write

A survivor that is itself gone excuses nothing. A real loss next to a merge is still refused, and only that id is named.

The node-count check needed the same allowance. When two saved ids merge into one survivor that is new this run, the count drops by one with nothing lost, and the id check alone still refused it.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Evidence

Before: on upstream/v8 (32e5efe9), the issue's scenario.

[graphify] Deduplicated 2 node(s) (2 exact).
[graphify] WARNING: Refusing to overwrite — saved semantic node(s) are missing from the new graph: glossary_first_contact, glossary_the_nudge.
graph written: False
tests/test_shrink_guard_dedup_merge_4940.py
9 failed, 8 passed

After:

graph written: True, one node per concept,
an edge that pointed at the merged id now points at the survivor

tests/test_shrink_guard_dedup_merge_4940.py
17 passed

full suite
9405 passed, 18 skipped, 1 xfailed in 1689.87s

The full suite ran serially with PYTHONPATH=/var/tmp/wt-4940-fix, so subprocess CLI tests imported this worktree and not the installed package.

Verification & Invariants

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

The invariant: the guard may refuse a write, but only when content is gone, never because an id was merged into a twin that is still there.

The tests assert on what reaches graph.json and on whether to_json wrote, so they hold for any fix of this bug. They pin:

  • Re-extracting a doc alone writes when dedup folds it into the untouched twins.
  • An edge to the merged-away id is kept and rewired.
  • Same-file exact duplicates do not block the write.
  • Two saved ids folded into one new survivor write.
  • The updated graph has one node per concept.
  • A full rebuild that merges the same twins writes.
  • A real loss next to a merge is refused and only that id is named.
  • A survivor that is itself gone excuses nothing.
  • A saved node that vanished, and a re-extracted node dropped after the merge, are still refused. These two pass before and after.
  • The map is never written into graph.json.

I tried two other fixes against the same scenarios. Comparing against the pre-dedup node set turns the guard off, because build_merge's input already holds every saved node. Keeping dedup from dropping ids that graph.json holds leaves the twins unmerged, and the next full rebuild hits the same refusal.

Known limitations:

How was this tested?

PYTHONPATH=. .venv/bin/python -m pytest tests/test_shrink_guard_dedup_merge_4940.py -q
PYTHONPATH=. .venv/bin/python -m pytest tests -q -p no:cacheprovider --basetemp=/var/tmp/pt4940-full
.venv/bin/python -m ruff check graphify/build.py graphify/dedup.py graphify/export.py tests/test_shrink_guard_dedup_merge_4940.py

Branch fix/4940-shrink-guard-dedup-merge is based on upstream/v8 (32e5efe9). It has four commits:

54423fc2 test(guard): pin that the #479 write guard still refuses a real loss (#4940)
89f34e14 feat(dedup): report which ids deduplicate_entities merged away (#4940)
268513af feat(build): carry the dedup merge map on the built graph (#4940)
4c3b38ba fix(guard): a saved node dedup folded into a twin is not a lost node (#4940)

Merge Danger

Door: Two-way.

The default path is unchanged when dedup merges nothing. No cache schema bump and no graph format change. Reverting restores the old guard.

Blast Radius: Write guard.

Every graph written through to_json passes this guard, so a mistake here either blocks a good write or lets a bad one through. The guard excuses an id only when its survivor is in the new graph, and the control tests pin the refusals. After merge, a graph that dedup has already shrunk by merging twins is written instead of refused, so an --update that was stuck on a stale graph.json now lands. Extraction, ignore rules and secret filtering are unchanged.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. No source fragments changed.
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

… a real loss (Graphify-Labs#4940)

The guard compares saved semantic ids against the new graph. A fix for
Graphify-Labs#4940 must excuse ids that entity dedup folded into a twin without
excusing ids that are simply gone. These three cases pass today and
fence the guard's existing job before it is touched: an update with
nothing merged or lost writes; a saved node that vanished is refused and
named; a re-extracted node dropped after the merge is refused.
…ify-Labs#4940)

The write guard has to know whether a saved id disappeared because dedup
folded it into a survivor or because the node was lost, and dedup is the
only place that knows. Add an optional remap_out dict that is filled with
{merged-away id: surviving id}. Callers that do not pass it see no change.
…abs#4940)

build() passes remap_out to entity dedup and stashes the result on
G.graph['_dedup_remap'], next to the existing _dedup_collapsed count.
take_dedup_remap() reads and removes it. to_json drops it before
node_link_data runs, because that would otherwise write G.graph into
graph.json. Nothing reads the map yet.
…raphify-Labs#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
Graphify-Labs#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.
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Nov 2, 2026

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

View in Graphify

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 2 advisory finding(s) below merit a look before merge.

Not checked: tests were not run; formal verification proved 0 of 4 changed function(s) (2 sampled, not proven, 2 not verified).

Formal verification. PR-changed functions: 2/4 verified (0 proven, 2 may-equivalent, 0 distinguished) · 2 not verified (2 vacuous).

Not verified on this run: build (vacuous: never exercised), deduplicate\_entities (vacuous: never exercised).


Graphify review — findings

Fixes the #479 shrink guard refusing --update writes when entity dedup had folded saved nodes into a twin. deduplicate_entities now reports each {merged-away id: survivor id} pair through remap_out, build stashes that map on the graph, and to_json reads it and strips it before serialization. The lost-node check and the node-count check then both treat a saved id folded into a surviving node as one node rather than a loss, while a missing survivor still counts as lost. The count allowance from _dedup_shrink_allowance matches saved ids by exact membership, whereas the lost-node check tolerates renames, so the two can disagree. The remap is also consumed at the top of to_json, before the guard can refuse the write.

Worth a look

  • to_json consumes dedup remap before a failed write — graphify/export.py:310 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • Shrink allowance uses exact id membership while the lost-node check tolerates renames — graphify/build.py:191 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 2226 functions depend on the 286 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: deduplicate_entities() — 121 callers, 32 callees
  • worse: build_merge() — 104 callers, 16 callees
  • worse: to_json() — 94 callers, 13 callees
  • worse: build() — 90 callers, 6 callees
  • worse: _lost_saved_semantic_nodes() — 19 callers, 6 callees
  • new: _merge_and_write() — 9 callers, 4 callees

Verification — 2226 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 1590 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

144 of 490 test file(s) selected (29%) via static blast radius.

  • tests/test_4874_jvm_resolution.py — impact
  • tests/test_affected_cli.py — impact
  • tests/test_affected_path_file_node.py — impact
  • tests/test_affected_seed_reference_forms.py — impact
  • tests/test_alias_folding.py — impact
  • tests/test_analyze.py — impact
  • tests/test_atomic_canvas_export.py — impact
  • tests/test_atomic_writes.py — impact
  • tests/test_backend_opt_in.py — impact
  • tests/test_benchmark.py — impact
  • tests/test_benchmark_raw_graph.py — impact
  • tests/test_benchmark_real_query.py — impact
  • tests/test_build.py — impact
  • tests/test_build_located_semantic_identity.py — impact
  • tests/test_build_merge_dedup_scope.py — impact
  • tests/test_build_merge_hyperedges_and_prune.py — impact
  • tests/test_build_merge_shrink_guard.py — impact
  • tests/test_c_include_resolution.py — impact
  • tests/test_carried_hyperedge_remap.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_claude_cli_backend.py — impact
  • tests/test_cli_export.py — impact
  • tests/test_cluster.py — impact
  • tests/test_community_labels_skill.py — impact
  • tests/test_compact_graph_json.py — impact
  • tests/test_confidence.py — impact
  • tests/test_confidence_score_output.py — impact
  • tests/test_corrupt_graph_json.py — impact
  • tests/test_cpp_objc_cross_file_calls.py — impact
  • tests/test_cross_extension_reexport_self_cycle.py — impact
  • tests/test_cross_repo_external_call_guards.py — impact
  • tests/test_csharp_method_owner_labels.py — impact
  • tests/test_csharp_object_creation.py — impact
  • tests/test_dedup.py — impact
  • tests/test_dedup_remaps_hyperedges.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_dedup_survivor_richness.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_duplicate_annotation_edges.py — impact
  • tests/test_edge_also_seen.py — impact
  • tests/test_evidence_binding.py — impact
  • tests/test_export.py — impact
  • tests/test_export_control_characters.py — impact
  • tests/test_export_direction.py — impact
  • tests/test_export_idempotent_writes.py — impact
  • tests/test_export_path_length.py — impact
  • tests/test_ext_tagged_id_clash.py — impact
  • tests/test_external_stub_endpoints.py — impact
  • tests/test_extract.py — impact
  • … and 94 more

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

No difference found (not proven): No behavior difference found in \_lost\_saved\_semantic\_nodes (not a proof).

The verifier ran both versions of \_lost\_saved\_semantic\_nodes on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

Could not verify: Could not verify build.

The verifier did not have enough to check build, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 9 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly AttributeError — names the real obstacle, not a sampling gap)

Could not verify: Could not verify deduplicate\_entities.

The verifier did not have enough to check deduplicate\_entities, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 11 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly TypeError — names the real obstacle, not a sampling gap)

No difference found (not proven): No behavior difference found in to\_json (not a proof).

The verifier ran both versions of to\_json on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

· 2 grounded finding(s) anchored inline below; 4 more finding(s) on lines outside this diff (see the check run).

Comment thread graphify/export.py
@@ -303,7 +303,10 @@ def existing_graph_node_count(path: "str | Path"):
def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *, force: bool = False, built_at_commit: str | None = None, community_labels: dict[int, str] | None = None, original_links: "list[dict] | None" = None) -> bool:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — to_json()

fans out to 13 callees (efferent coupling); 94 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

to_json(G, {0: [n["id"] for n in nodes]}, str(path), force=True)


def _merge_and_write(tmp_path, saved, fresh, saved_edges=(), tamper=None):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — _merge_and_write()

9 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.101 (published to PyPI), cherry-picked with your authorship preserved. Fixes #4940. Thanks @Deepjyoti-Sarmah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shrink-guard refuses a valid merge when exact-duplicate dedup drops nodes the saved cache references

2 participants