Skip to content

fix(dedup): keep distinct files that mint the same node id (#4281) - #4282

Closed
bitwizard25 wants to merge 2 commits into
Graphify-Labs:v8from
bitwizard25:fix/4281-node-id-collisions
Closed

bitwizard25 wants to merge 2 commits into
Graphify-Labs:v8from
bitwizard25:fix/4281-node-id-collisions

Conversation

@bitwizard25

@bitwizard25 bitwizard25 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4281

What does this PR do?

Two distinct files can derive the same node id (portal.py/portal.html, or a bare protocol from docs/protocol.md and docs/firmware/protocol.md). Dedup collapsed them to one node with a warning, losing a real entity on every rebuild. Now each file keeps its own node: the best-ranked file keeps the id, the others get a path- or extension-qualified id (firmware_lib_portal_html), and their edges follow. Ids no file derives from its own path still collapse with the existing warning.

Type of change

  • Bug fix

How was this tested?

  • tests/test_dedup.py (107 passed), including new tests for both cases and order-independence; two old tests that asserted the "one entity is lost" behavior were updated
  • Full suite: only pre-existing failures (test_hooks shebang test fails without this change; some test_extract tests fail under -n 4 with or without it)
  • Checked through build() with semantic nodes matching the issue

…Labs#4281)

Two files that both derive the same id (x.py/x.html, or a bare id that is a
trailing path slice of docs/x.md and docs/sub/x.md) were collapsed to one
node with a warning, losing a real entity. The best-ranked file keeps the id;
the others get a path- or extension-qualified id and their edges follow.
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @bitwizard25. 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.

@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.

Graphify reviewed this change.

Code graph out of date: Health delta baseline: last indexed commit 2cb81c6, 1 commit(s) behind this PR's base. Impact and hotspot numbers below may be wrong.

No verdict: the code graph is out of date. Static checks found no blocking issues, but they compared against an outdated graph. The next push after the repository re-indexes gets a full review.

Not checked: tests were not run; formal verification proved 0 of 1 changed function(s) (1 not verified).

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

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


Graphify review — findings

Fixes deduplicate_entities so two distinct files that mint the same node id (portal.py/portal.html, or a bare protocol from two protocol.md paths) each keep a node instead of one being dropped with a warning. _disambiguate_defining_collisions lets the best-ranked file keep the id and renames the others to a full-path id, or the full-path-plus-extension form if that's taken. Edges and hyperedges carrying the renamed file's source_file follow it, while unattributed references stay on the winner; ids no file derives from its own path, or with no free alternative, still collapse with the #1504 warning.

No blocking issues surfaced. 2 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 800 functions depend on the 472 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: deduplicate_entities() — 85 callers, 27 callees
  • worse: _collision_rank() — 4 callers, 3 callees

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

Health delta baseline: last indexed commit 2cb81c6, 1 commit(s) behind this PR's base.

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: 594 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

361 of 361 test file(s) selected (100%) via static blast radius.

Escalated to a full run for safety — the selection is not trustworthy on its own (see below). CI should run the whole suite.

  • tests/test_affected_cli.py — full-run-safety
  • tests/test_affected_member_seed.py — full-run-safety
  • tests/test_agents_platform.py — full-run-safety
  • tests/test_analyze.py — full-run-safety
  • tests/test_anthropic_custom_endpoint.py — full-run-safety
  • tests/test_antigravity_install.py — full-run-safety
  • tests/test_apm_fallback_version.py — full-run-safety
  • tests/test_architecture_doc.py — full-run-safety
  • tests/test_astro_extraction.py — full-run-safety
  • tests/test_astro_import_ids.py — full-run-safety
  • tests/test_atomic_canvas_export.py — full-run-safety
  • tests/test_atomic_version_stamp.py — full-run-safety
  • tests/test_atomic_writes.py — full-run-safety
  • tests/test_backend_env_isolation.py — full-run-safety
  • tests/test_backend_extras.py — full-run-safety
  • tests/test_benchmark.py — full-run-safety
  • tests/test_benchmark_raw_graph.py — full-run-safety
  • tests/test_blade_extractor.py — full-run-safety
  • tests/test_build.py — impact, full-run-safety
  • tests/test_build_located_semantic_identity.py — impact, full-run-safety
  • tests/test_build_merge_dedup_scope.py — impact, full-run-safety
  • tests/test_build_merge_hyperedges_and_prune.py — impact, full-run-safety
  • tests/test_build_merge_shrink_guard.py — impact, full-run-safety
  • tests/test_builtin_global_type_refs.py — full-run-safety
  • tests/test_cache.py — full-run-safety
  • tests/test_cache_stale_import_target.py — full-run-safety
  • tests/test_callflow_html.py — full-run-safety
  • tests/test_cargo_introspect.py — full-run-safety
  • tests/test_cargo_missing_manifest.py — full-run-safety
  • tests/test_carried_hyperedge_remap.py — impact, full-run-safety
  • tests/test_case_sensitive_resolution.py — full-run-safety
  • tests/test_charmap_encoding.py — full-run-safety
  • tests/test_chunking.py — full-run-safety
  • tests/test_cjs_module_extension.py — full-run-safety
  • tests/test_claude_cli_backend.py — full-run-safety
  • tests/test_claude_md.py — full-run-safety
  • tests/test_cli_broken_pipe.py — full-run-safety
  • tests/test_cli_export.py — full-run-safety
  • tests/test_cli_help.py — full-run-safety
  • tests/test_cloud_cta.py — full-run-safety
  • tests/test_cluster.py — full-run-safety
  • tests/test_cluster_ambiguous_scale.py — full-run-safety
  • tests/test_cluster_exclude_hubs.py — full-run-safety
  • tests/test_cobol_extractor.py — full-run-safety
  • tests/test_codebuddy.py — full-run-safety
  • tests/test_community_hub_labels.py — full-run-safety
  • tests/test_community_labels_skill.py — full-run-safety
  • tests/test_confidence.py — full-run-safety
  • tests/test_corrupt_graph_json.py — impact, full-run-safety
  • tests/test_cpp_method_declarations.py — full-run-safety
  • … and 311 more

non-code file(s) changed (CHANGELOG.md) → running the full suite for safety (a code graph can't see config/fixture/data deps)

changed code file(s) with no mapped test (CHANGELOG.md) — a coverage gap or a missing link — running the full suite rather than only the selected tests

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

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)

· 2 more finding(s) on lines outside this diff (see the check run).

@gmos

gmos commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Thanks for picking this up so quickly. I ran an A/B test of this PR on the repository where I hit the warnings. It removes the warnings, but the restored nodes come back with no edges, so in practice little changes compared to before.

Setup

  • Corpus: a mixed repo (MicroPython firmware, an HTML page, Markdown docs), ~1,500 nodes, 39 semantic files. Paths and IDs below are shortened, as in the issue.
  • extract --backend claude-cli --token-budget 4500, then cluster-only.
  • Both runs replayed the same semantic cache (39 hit / 0 miss, 0 re-extracted), so the extraction output was identical between runs.
  • Baseline: 2cb81c6 (this PR's parent, identical to the 0.9.84 release). PR: ddf0460b. Each was installed in its own venv and started from the same graphify-out/cache.
  • For reference I also compared against my committed graph from 0.9.83. That comparison includes the 0.9.83→0.9.84 changes; the baseline-vs-PR pair is the clean comparison.

Results

"minted by two different files" warnings nodes edges
0.9.83 (committed graph) n/a 1524 2558
baseline 2cb81c6 (0.9.84) 2 1523 2558
PR ddf0460b 0 1525 2558

The only differences between baseline and PR are the two new nodes. The edge set is identical, no existing ID, label or source_file changed, and there are no new warnings or dangling edges.

Problem 1: edges don't follow the renamed node

node source_file edges
firmware_lib_portal (kept) firmware/lib/portal.py 16
firmware_lib_portal_html (new) firmware/lib/portal.html 0

In the cache, the HTML node has three references edges to card nodes on the same page. With the PR, those edges still start from the .py node, exactly as on the baseline.

The cause is a path-form mismatch. Semantic nodes and edges reach build() with an absolute source_file. I confirmed this for a cache hit: load_cached re-anchors them to absolute (cache.py ~1138-1142, "the same absolute-path shape that a fresh in-process extraction produces"). Before calling deduplicate_entities, build() makes only the node source_file repo-relative (build.py ~1757-1760 in 0.9.84). Edges stay absolute until build_from_json runs after dedup. _disambiguate_defining_collisions keys renames on (id, node source_file) and looks edges up by (endpoint, edge source_file), so no edge ever matches. The new unit tests call deduplicate_entities directly, with nodes and edges sharing one relative path, so they don't cover this. Comparing normalised paths in the rename, or normalising edge source_file in build() before dedup, should fix it. A test that goes through build() with absolute paths would catch it.

Problem 2: the doc case yields an orphan near-duplicate

node source_file edges
docs_firmware_protocol (existing) docs/firmware/protocol.md 7
docs_firmware_protocol_md (new) docs/firmware/protocol.md 0
  • The new test expects docs_firmware_protocol, but on a real corpus that ID already belongs to the file's own document node. The fallback therefore gives docs_firmware_protocol_md: a second node for the same file.
  • The dropped node ("protocol (top-level)") is not a separate entity. It is the firmware doc's wikilink to the top-level docs/protocol.md, and its only edge (docs_firmware_protocol references protocol) already resolves to that document's node. Restoring it creates an orphan duplicate, and for this case the old drop was arguably the right outcome. My issue overstated this case, sorry about that. The genuine loss is the extension case (x.py / x.html).

Suggestion

  • Keep the rename for the "same stem, different extension" case, but make edges follow it under the path forms build() actually passes to dedup.
  • For a bare ID that only collides because a file refers to another file's entity, merging into the existing node (or skipping it) may be better than minting a new one.

… twins (Graphify-Labs#4281)

Edges reach dedup with an absolute source_file while nodes are already
root-relative, so the exact-path match never found them and the renamed node
came back without edges. Compare root-relative keys instead.

Also restrict the rename to files with the same full stem and a different
extension (x.py / x.html). A bare id shared across different paths is a
reference to another file's entity, so it stays on the collapse-and-warn path.
@gmos

gmos commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Thanks, da923e9 works on our corpus: re-running the same A/B, the html node now gets its own ID and its three edges, and nothing else in the graph changes. The only warning left is the bare protocol one, as intended.

One remaining edge case: key() calls _rank_path, which resolves a relative path against the CWD. Node paths are already root-relative at that point, so when graphify is started from a subdirectory of the scan root, node and edge keys no longer match and the edges stay on the .py node. On our corpus, da923e9 started from a subdirectory gives the html node 0 edges again. With the patch below it is identical to a run from outside the root.

The patch only relativizes absolute paths in key(). It also tidies the extension comparison, which was one 254-character line (a lost line continuation?), and adds a regression test that fails on da923e9:

diff --git a/graphify/dedup.py b/graphify/dedup.py
--- a/graphify/dedup.py
+++ b/graphify/dedup.py
@@ -518,6 +518,12 @@ def _full_stem(source_file: str) -> str:
     return "_".join(s for s in (normalize_id(p) for p in stem.split("/")) if s)
 
 
+def _extension(source_file: str) -> str:
+    """The lowercased extension of ``source_file`` (``.html``), or ``""`` if it has none."""
+    m = _EXTENSION.search(source_file.replace("\\", "/"))
+    return m.group(0).lower() if m else ""
+
+
 def _extension_qualified_id(node: dict) -> str | None:
     """``x.html``'s own spelling of an ID it shares with ``x.py`` (#4281).
 
@@ -554,7 +560,13 @@ def _disambiguate_defining_collisions(
     collapse-and-warn path.
     """
     def key(sf):
-        return _rank_path(sf, root) if sf else ""
+        if not sf:
+            return ""
+        sf = sf.replace("\\", "/")
+        # Nodes are already root-relative here; only an absolute (semantic edge)
+        # path needs relativizing. Resolving a relative one would anchor it at
+        # the CWD, which differs from the root when run from a subdirectory.
+        return _rank_path(sf, root) if Path(sf).is_absolute() else sf
 
     by_id: dict[str, list[dict]] = defaultdict(list)
     for node in nodes:
@@ -576,7 +588,7 @@ def _disambiguate_defining_collisions(
                 continue
             # The extension is what tells them apart; same-extension slug twins
             # (pkg/service.py vs pkg_service.py) stay on the collapse-and-warn path.
-            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():
+            if _extension(d["source_file"]) == _extension(winner["source_file"]):
                 continue
             new_id = _extension_qualified_id(d)
             if new_id and new_id not in taken:
@@ -600,7 +612,9 @@ def _disambiguate_defining_collisions(
                     item[end] = new_id
             members = item.get("nodes")
             if isinstance(members, list):
-                item["nodes"] = [renames.get((m, k), m) if isinstance(m, str) else m for m in members]
+                item["nodes"] = [
+                    renames.get((m, k), m) if isinstance(m, str) else m for m in members
+                ]
     return out_nodes, edges
 
 
diff --git a/tests/test_dedup.py b/tests/test_dedup.py
--- a/tests/test_dedup.py
+++ b/tests/test_dedup.py
@@ -1622,3 +1622,33 @@ def test_build_with_absolute_edge_paths_moves_edges_to_renamed_node(tmp_path):
     assert "firmware_lib_portal" in G and "firmware_lib_portal_html" in G
     assert G.has_edge("firmware_lib_portal_html", "card_a")
     assert not G.has_edge("firmware_lib_portal", "card_a")
+
+
+def test_build_moves_edges_to_renamed_node_when_cwd_is_inside_root(tmp_path, monkeypatch):
+    """A repo-relative node path must not be resolved against the CWD: run from a
+    subdirectory of the scan root, the renamed node still receives its edges (#4281)."""
+    from graphify.build import build
+
+    root = tmp_path
+    (root / "firmware").mkdir()
+    monkeypatch.chdir(root / "firmware")
+    py = str(root / "firmware" / "lib" / "portal.py")
+    html = str(root / "firmware" / "lib" / "portal.html")
+    ext = {
+        "nodes": [
+            {"id": "firmware_lib_portal", "label": "portal.py", "file_type": "code",
+             "source_file": py},
+            {"id": "firmware_lib_portal", "label": "Portal page", "file_type": "document",
+             "source_file": html},
+            {"id": "card_a", "label": "Card A", "file_type": "document", "source_file": html},
+        ],
+        "edges": [
+            {"source": "firmware_lib_portal", "target": "card_a", "relation": "references",
+             "confidence": "EXTRACTED", "source_file": html},
+        ],
+    }
+    G = build([ext], root=str(root))
+
+    assert "firmware_lib_portal" in G and "firmware_lib_portal_html" in G
+    assert G.has_edge("firmware_lib_portal_html", "card_a")
+    assert not G.has_edge("firmware_lib_portal", "card_a")

test_dedup.py passes (109), and the full suite shows no new failures. ruff is clean.

safishamsi pushed a commit that referenced this pull request Oct 10, 2026
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.
@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.85 (now on PyPI) via authorship-preserving cherry-pick, covering the extension-drop collision (x.py vs x.html). Thank you, @bitwizard25! Note: #4281 stays open for the remaining path-dropped doc-id case (a/x.md vs b/x.md), which this PR intentionally doesn't cover.

@safishamsi safishamsi closed this Oct 10, 2026
Deepjyoti-Sarmah added a commit to Deepjyoti-Sarmah/graphify that referenced this pull request Oct 12, 2026
…phify-Labs#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 Graphify-Labs#1504/Graphify-Labs#4282 for path-dropped ids:
the Graphify-Labs#1504 test now uses a non-shorter-stem id and the protocol test now
expects both files to be path-qualified.
safishamsi pushed a commit that referenced this pull request Oct 12, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Node IDs drop the file extension (and doc IDs the path), so distinct entities in x.py/x.html or a/x.md/b/x.md collide and one is lost

3 participants