Skip to content

fix(export): index (label, id) before the graph DB push upsert loop - #3957

Closed
Yi-111-a wants to merge 1 commit into
Graphify-Labs:v8from
Yi-111-a:fix/graphdb-index-before-merge
Closed

Yi-111-a wants to merge 1 commit into
Graphify-Labs:v8from
Yi-111-a:fix/graphdb-index-before-merge

Conversation

@Yi-111-a

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes the O(n²) node-upsert loop in the graph DB exporters by creating an index on the MERGE match pattern before any node is written.

Both push_to_falkordb and push_to_neo4j upsert every node with:

MERGE (n:<Label> {id: $id}) SET n += $props

That matches on (label, id), but neither path created an index on that pattern first. Without one, the engine scans every node already carrying the label to decide whether the node already exists, so each upsert costs O(nodes with that label) and the whole push degrades to O(n²) in nodes-per-label. In the report on #3804 (167,428 nodes / 209,215 edges across 6 labels) throughput collapsed from ~10,000 node upserts/60s to ~100 upserts/300s partway through, with FalkorDB at ~97% CPU and a multi-hour total wall time.

The change creates one index per distinct label up front, before the upsert loop:

-- FalkorDB
CREATE INDEX FOR (n:<Label>) ON (n.id)

-- Neo4j
CREATE INDEX IF NOT EXISTS FOR (n:<Label>) ON (n.id)

_distinct_node_labels() derives the label set exactly the way the two push loops derive ftype (.capitalize(), then [^A-Za-z0-9_] stripped, falling back to Entity), so every label a MERGE matches against is covered — including the fallback label a node with an unusable file_type would be written under.

Refs #3804.

Type of change

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

Verification & Invariants

The invariant: no MERGE in either push path may run before its label is indexed. Without it a bulk push silently costs a full label scan per node, and the only symptom is throughput — the push still reports success.

  • 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 regression tests assert against the Cypher that reaches the server, using fake falkordb / neo4j clients, so they need no database and run in the default CI:

  • One index per distinct label is issued, and the last index precedes the first MERGE.
  • Stated as the property itself rather than a fixed call order: scanning the recorded Cypher, every MERGE (n:<Label> must have seen a CREATE INDEX for that label earlier in the stream.
  • _distinct_node_labels() cannot emit a label the MERGE loop would never write (an all-punctuation file_type collapses to the Entity fallback, matching _safe_label).
  • A CREATE INDEX that raises does not abort the push — every node and edge is still upserted.

Against the unpatched graphdb.py all 5 tests fail, and one reports the failure in the shape of the bug itself:

E  AssertionError: MERGE on unindexed label Code: MERGE (n:Code {id: $id}) SET n += $props

Limitations / unsupported cases:

  • Neo4j index creation uses IF NOT EXISTS so re-pushes stay idempotent. FalkorDB's CREATE INDEX has no such clause, so a re-push against an already-indexed graph gets an error back. That is caught and ignored deliberately: a redundant index is a performance detail, and failing an otherwise valid push over it would be worse. The push is unchanged in that case apart from the (already-optimized) query cost.
  • Creating an index on a large, already-populated graph is itself not free. That cost is paid once and is bounded per label, which is the trade this issue is asking for.
  • Only the index statements are new. Node/edge property payloads, label sanitization, community attachment, and the MERGE-based idempotency of the push itself are untouched.

How was the tested?

Commands actually run:

uvx [email protected] check --config pyproject.toml graphify/exporters/graphdb.py tests/test_graphdb_push_indexes.py
# All checks passed!

python -m pytest tests/test_graphdb_push_indexes.py -q
# 5 passed

# Prove the regression test demonstrates the old failure:
git stash push graphify/exporters/graphdb.py
python -m pytest tests/test_graphdb_push_indexes.py -q
# 5 failed
git stash pop
python -m pytest tests/test_graphdb_push_indexes.py -q
# 5 passed

# No regression in the surrounding export suites (baseline is identical with and
# without the change; those failures are pre-existing in this environment):
python -m pytest tests/test_cli_export.py -q
# 47 failed, 5 passed  — both with and without the change

Notes on the environment: pyright reports only reportMissingImports for neo4j, falkordb and pytest — optional dependencies that are not installed here. There are no type errors in the changed code.

tests/test_falkordb_integration.py skips here (no FalkorDB server reachable), which is why the new tests use fake clients rather than adding to that file — they need to run in CI, which starts no external services.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. — No skill fragments touched.
  • 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). — Labels are passed through the same [^A-Za-z0-9_] allowlist the push loops already apply to ftype, so nothing new is interpolated into Cypher.
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

`push_to_falkordb` and `push_to_neo4j` upsert every node with
`MERGE (n:<Label> {id: $id}) SET n += $props`, which matches on (label, id).
Neither path created an index on that pattern first, so the engine had to
scan every node already carrying the label to decide whether the node is
already there. Each upsert then costs O(nodes with that label) and a full push
degrades to O(n^2): on the graph in #3804 (167,428 nodes / 209,215 edges
across 6 labels) throughput collapsed from ~10,000 node upserts/60s to
~100 upserts/300s partway through, with the database at ~97% CPU.

Create one index per distinct label up front, before the upsert loop. The
label set is derived exactly as the push loops derive it, so every label a
MERGE matches against is covered. Neo4j uses IF NOT EXISTS to stay idempotent
across re-pushes; FalkorDB's CREATE INDEX has no such clause, so a re-push
against an already-indexed graph is tolerated rather than failing an
otherwise valid push.

Refs #3804

Co-Authored-By: opencode space-bunny-free <[email protected]>
@github-actions

Copy link
Copy Markdown

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

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

Formal verification. No changes could be formally verified in this run.


Graphify review — findings

Fixes the O(n²) slowdown in push_to_falkordb and push_to_neo4j by creating an (n.id) index for every node label before the MERGE upsert loop runs, so each upsert no longer scans every existing node with that label. _distinct_node_labels derives those labels exactly as the push loops do. Neo4j uses IF NOT EXISTS; FalkorDB has no such clause, so index-creation errors on a re-push are swallowed and the push continues.

Worth a look

  • Swallowed Neo4j index error can resurface on the first MERGE — graphify/exporters/graphdb.py:63 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 41 functions depend on the 39 functions this change touches.

Health — this change adds coupling hotspots:

  • new: push_to_falkordb() — 7 callers, 4 callees
  • new: push_to_neo4j() — 3 callers, 4 callees

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

Test selection

Test selection

2 of 309 test file(s) selected (1%) via static blast radius.

  • tests/test_falkordb_integration.py — impact
  • tests/test_graphdb_push_indexes.py — impact, changed-test

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.

Docs that may be stale (advisory)

…and 10 more.

Formal verification

Could not verify: Could not verify push\_to\_falkordb.

The verifier did not have enough to check push\_to\_falkordb, 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 200 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly ImportError — names the real obstacle, not a sampling gap)

Could not verify: Could not verify push\_to\_neo4j.

The verifier did not have enough to check push\_to\_neo4j, 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 200 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly ImportError — names the real obstacle, not a sampling gap)

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

return sorted(labels)


def push_to_neo4j(

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 — push_to_neo4j()

high coupling complexity (Ca·Ce = 12).

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

safishamsi added a commit that referenced this pull request Sep 30, 2026
Solidity free functions (#3906), VB.NET qualified calls (#3909), Astro
frontmatter-only AST pass (#3902), surprise bonus/reason alignment (#3934),
exclude-hubs stranded-neighbour (#3933), graph-DB push index (#3957),
label retry keep-named (#3956), stale-hook status (#3951), virtual-workspace
Cargo.toml skip (#3930), and symlinked-instructions install/uninstall
handling (#3950/#3953).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.73 (now on PyPI) via an authorship-preserving cherry-pick, so your commit keeps contributor-graph credit. Thanks @Yi-111-a!

Release: https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.73

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.

2 participants