graphify icon indicating copy to clipboard operation
graphify copied to clipboard

[Bug] build_merge severs edges from UNCHANGED files into re-extracted files (−12% doc↔code in one update cycle): endpoint nodes are replaced, the surviving edges dangle, and the dangling-edge drop silently eats them

Open gkaganas-mparticle opened this issue 4 months ago • 1 comments

Version measured: graphifyy 0.8.46, one real incremental update on a 112,714-node / 258,776-edge monorepo graph. Code references below are against current v8 (0.9.8) — the mechanism is unchanged there. Note: the hyperedge half of what we measured was since fixed by #1574 (4f40967); this report is about the ordinary-edge half, plus one residual hyperedge gap.

What we observed (one --update cycle, 298 changed files)

Metric Before After Delta
doc↔code cross-edges 3,055 2,682 −12.2%
… lost 526 (of which 497 had an endpoint node replaced by the merge)
… gained 153
hyperedges (on 0.8.46, pre-#1574) 240 14 −94%; 182/240 had fully resolvable member sets in the merged graph

The worst losers were docs that did not change: e.g. one architecture doc went from 189 cross-edges to 68 purely because the code on the other end was re-extracted. Repeat updates compound this — each cycle erodes another slice of exactly the high-value cross-file linkage.

Mechanism

build_merge (v8 build.py ~735) implements replace-per-source: every source_file present in the new chunks is dropped from the loaded base — nodes and edges — before merging (~lines 816–820):

existing_nodes = [n for n in existing_nodes if _kept(n)]
existing_edges = [e for e in existing_edges if _kept(e)]

That filter is keyed on the edge's own source_file. An edge extracted from an unchanged doc (source_file = doc/foo.md) pointing at a node from src/bar.py survives the filter — correctly, its provenance didn't change. But src/bar.py was re-extracted, so its old nodes were dropped and its new nodes may carry different IDs (LLM extraction is not ID-stable across runs — see #1695 — and granularity/labels shift). The surviving doc edge now references a node ID that no longer exists.

Those dangling edges then die silently in build_from_json (v8 build.py ~562–567):

if src not in node_set:
    src = norm_to_id.get(_normalize_id(src), src)
...
if src not in node_set or tgt not in node_set:
    continue  # skip edges to external/stdlib nodes - expected, not an error

The norm_to_id remap only rescues casing/punctuation variants. A genuinely new ID for the same symbol (different qualifier, different chunk naming) is not rescued, and the drop is deliberately unlogged because the same code path legitimately absorbs stdlib/external references. So the erosion is invisible: no warning, node counts grow, and only a cross-edge count comparison exposes it. (This is the "local destruction while the graph grows globally" failure mode #1652 describes from the node side; here it's the edge side.)

Residual hyperedge gap (post-#1574)

#1574's fix carries forward hyperedges keyed on source_file — unchanged files' hyperedges survive, re-extracted files' are dropped on the expectation the new chunk re-emits them. Two gaps remain:

  1. A re-extracted file's new chunk frequently does not re-emit an equivalent hyperedge (same non-determinism as above) — the old one is dropped, nothing replaces it.
  2. A carried hyperedge's nodes list can reference replaced node IDs, so it survives as an orphan (or is dropped downstream), even when every member still exists under a new ID.

In our measured cycle, 182 of the 240 original hyperedges had member sets that were still fully resolvable in the merged graph — the information needed to keep them was present; only the identity linkage was lost.

Proposed fix

Preserve what provably survives, keyed on resolvability rather than provenance:

  1. Edge preservation pass in build_merge, after the merged node set is final: for each pre-existing edge that was kept by the source_file filter but now dangles, attempt to re-resolve each dead endpoint against the merged graph — exact ID, then _normalize_id, then the existing ghost-merge key (source_file basename, label) that build_from_json already uses for AST/LLM twin detection (v8 ~lines 435–470). Rewrite the endpoint and keep the edge if exactly one candidate matches; drop (and count) otherwise.
  2. Hyperedge preservation: for dropped/carried hyperedges, re-resolve member lists the same way; carry any hyperedge whose full member set survives (by resolved ID), id-deduped via the existing attach_hyperedges.
  3. Make the loss visible: build_merge already prints prune counts; print severed-edge and dropped-hyperedge counts too, so a 497-edge silent loss becomes one loud line. (Pairs with #1652's dry-run/alert proposal.)

Conservative matching (unique-candidate-only) keeps this from inventing edges; everything it rescues is an edge/hyperedge the graph had, whose both endpoints still exist.

Minimal repro sketch

from graphify.build import build, build_merge
from graphify.export import to_json

doc_chunk = {"nodes": [
    {"id": "payment_flow", "label": "Payment Flow", "file_type": "document",
     "source_file": "doc/payments.md"},
    {"id": "charge_card", "label": "charge_card", "file_type": "code",
     "source_file": "src/pay.py"}],
  "edges": [{"source": "payment_flow", "target": "charge_card",
             "relation": "references", "source_file": "doc/payments.md"}]}

G = build([doc_chunk]); to_json(G, "graphify-out/graph.json")
# assert: 1 doc→code edge

# Re-extract ONLY src/pay.py; same function, new node ID (qualified this time)
new_chunk = {"nodes": [
    {"id": "pay_charge_card", "label": "charge_card", "file_type": "code",
     "source_file": "src/pay.py"}], "edges": []}

G2 = build_merge([new_chunk])
# doc/payments.md was NOT re-extracted, charge_card still exists (as
# pay_charge_card, same label, same file) — but the doc→code edge is gone.

Same shape with a hyperedge whose nodes include the renamed ID reproduces the residual hyperedge gap post-#1574.

Related

  • #1574 (fixed) — hyperedge carry-forward by source_file; this report is the by-resolvability completion of it.
  • #1652 — dry-run / degree-drop alert; item 3 above is the minimal in-tree version of that visibility.
  • #1695 — extraction non-determinism is the amplifier here: the less ID-stable extraction is, the more the merge severs.
  • #1151 — a different way build_merge's source_file keying silently misbehaves.
  • #1710 — our native-update RFC folds this preservation pass into the proposed conductor's merge step; #1708 is the same committed-graph workflow this erosion degrades.

Offer

We have the forensic tooling (before/after cross-edge diff by source doc, endpoint-replacement classification) and are implementing the preservation pass downstream. Happy to contribute the PR with regression tests pinned to the mechanism (unchanged-doc edge into renamed code node survives; ambiguous candidate is dropped; counts are printed) if the approach works for you.

gkaganas-mparticle avatar Jul 07 '26 02:07 gkaganas-mparticle

Independent confirmation on a real corpus + the trigger condition, and a consequence that makes it non-self-healing

Reporting a measured data point from a production CI pipeline, since this issue currently has no reproduction outside the original one. I also want to flag a consequence I don't see mentioned yet: once these edges are eaten they never come back, because the surviving endpoint's file stays cached and is never re-dispatched.

Environment

  • Corporate SSOT documentation repo (robotics engineering specs), 938 files in the incremental manifest, ~96% Chinese Markdown + images, plus 14 Python files and 2 PDFs.
  • Latest published graph: 1,448 nodes / 1,186 links / 82 hyperedges.
  • GitLab CI runs graphify extract <root> --backend openai (OpenAI-compatible gateway) on every push to main, then commits graphify-out/ back. So every transition below is a warm incremental rebuild, not a cold build.
  • Backend model is a reasoning model (thinking enabled by default); graphify version was not pinned for the earlier part of the window (see the attribution caveat below).

Method

graphify's own dated backups make this measurable after the fact. graphify-out/<YYYY-MM-DD>/graph.json holds the graph as it stood before that day's run overwrote it, so consecutive backup dirs are a before/after pair — the same technique used in #2276.

For each consecutive pair I diffed the edge set keyed on (source, target, relation), and classified every lost edge by what happened to its endpoints. To detect the "endpoint nodes are replaced" half of the mechanism, I computed, per source_file, the set of node ids that disappeared and the set that appeared; a file with both non-empty is a file whose nodes were re-minted.

Measurement: the transition where the mechanism fires cleanly

2026-08-05 → 2026-08-12 backup pair:

nodes 945 → 961 (+16)
links 548 → 576 (+28 net)
links that disappeared 192
links that appeared 220
files whose node ids were re-minted 399
files that only lost nodes 12

Classification of the 192 lost edges:

count class
38 exactly this issue's signature — surviving endpoint belongs to a file whose node set is untouched, dead endpoint belongs to a file whose nodes were re-minted
139 both endpoints gone
9 dead endpoint in a shrink-only file
5 dead endpoint in a re-minted file, surviving endpoint has empty source_file
1 both endpoints alive, edge dropped anyway

The net +28 completely hides this: the summary line reads wrote graph.json: 961 nodes, 576 edges and the run exits 0. Nothing in the output says 192 edges were destroyed and 220 different ones created.

The 38 signature matches are disproportionately the cross-layer edges, which is the point the original report makes:

src_isaac_builder            --references-->              build_models_py            (target node gone)
src_config_loader            --references-->              build_models_py            (target node gone)
image_hw_sop_media_image10   --references-->              sop_procedure_document     (target node gone)
image_hw_sop_media_image111  --references-->              sop_procedure_document     (target node gone)
hip_perfect_mirrored_verificat --conceptually_related_to--> x1_29dof_hip_perfect_mirrored_ (target node gone)

requirements.txt → module --imports--> edges and README.md → README.md --references--> edges are hit the same way.

The consequence I'd like to add: it does not self-heal

The surviving endpoint's file was not re-extracted — that is the whole premise. On the next run it is a manifest/cache hit, so it is never re-dispatched, so nothing ever re-emits the edge against the new id of the target node. The edge is gone permanently, not merely until the next rebuild.

I checked this against the following transitions and it holds: the 38 signature edges from 08-05 → 08-12 are still absent nine rebuilds later, even though both endpoint files are still in the corpus and still in the graph.

Practical implication for anyone hitting this: re-running does not repair it. The only recovery I found is to force every file to be re-extracted in one consistent pass (drop graphify-out/graph.json and the whole graphify-out/cache/semantic/, so no file is served from cache), which re-mints all ids and re-emits all edges together. Clearing only the affected files is not enough — that just reproduces the asymmetry.

Attribution caveat, stated plainly because it limits how much weight this deserves

I could not establish which graphify version produced which snapshot. graph.json records built_at_commit but no graphify version, and our CI image tag was floating (...:…-graphify, i.e. latest) until we pinned it to 0.9.33 on 2026-08-05. So the 08-05 → 08-12 pair may straddle a version change, and a version change is itself a legitimate mass-remint trigger (a changed extraction prompt invalidates the prompt-fingerprinted semantic cache namespace, so every semantic file is re-dispatched and re-minted at once).

Two things I can say with confidence:

  1. The mechanism is exactly as described here — 399 files re-minted, 38 edges lost with an untouched source endpoint and a re-minted target endpoint, run exits 0, no message mentions edge removal.
  2. In pinned-version steady state it does not fire on this corpus. After pinning, five consecutive rebuilds retained 100% of edges, including one that added 187 new documents (+320 nodes, +538 links, 0 links lost).

So I am not claiming steady-state reproduction. I'm claiming the trigger is "any event that re-mints node ids for a subset of files while other files hold edges to the old ids" — which includes a version/prompt change, and also includes selectively re-extracting previously-cached files (e.g. retrying files that came back hollow). The second case is routine, not exceptional, which is why I think this is worth fixing rather than documenting.

Suggested direction

The reporter's framing is right and I'd add one constraint from the recovery cost above: because the loss is permanent, remapping beats dropping. When build_merge replaces the nodes of a re-extracted source_file, the edges from other files that pointed at the old ids should be remapped onto the new ids (by label/norm_label, which dedup.py already computes) rather than left to dangle and be swept. Dropping is only safe if the graph is going to be fully rebuilt, and nothing tells the operator which of the two situations they are in.

Cheaper partial mitigations, in increasing order of effort:

  1. Report the edge delta in the write summary when negative, and report dropped-as-dangling separately from not-emitted-this-run — currently both are invisible (this is #2276's suggestion 1, and the 192-vs-+28 gap above is why it matters).
  2. Stamp graphify_version into graph.json next to built_at_commit. Without it neither operators nor maintainers can separate "the tool ate my edges" from "an upgrade renamed my ids" — I hit this directly while preparing this report and had to reconstruct version boundaries from CI config git history.
  3. On a mass remint (prompt-fingerprint change), treat it as a full rebuild for edge purposes: don't carry forward edges whose endpoints were replaced, and say so.

joriwang avatar Sep 18 '26 01:09 joriwang