Skip to content

perf: batch-embed entity/edge names in set_graph() to fix stall on large graphs (#16205) - #16472

Merged
yingfeng merged 3 commits into
infiniflow:mainfrom
OSHA-B:fix/issue-16205-batch-embed-set-graph
Jul 1, 2026
Merged

yingfeng merged 3 commits into
infiniflow:mainfrom
OSHA-B:fix/issue-16205-batch-embed-set-graph

Conversation

@OSHA-B

@OSHA-B OSHA-B commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Problem

When building or updating a knowledge graph with a large number of entities and edges, set_graph() in rag/graphrag/utils.py creates one asyncio task per entity and one per edge, each calling embd_mdl.encode([single_name]) — a single-item HTTP request to the embedding server.

For a graph with 17,000+ nodes and edges (real case reported in #16205), this generates 34,000+ individual embedding API round-trips instead of ~266 batched calls at the default _INSERT_BULK_SIZE=128. The asyncio gather over thousands of tasks makes the embedding server the bottleneck; under load, a single slow/failed call aborts all remaining tasks, causing the pipeline to stall and never complete.

Closes #16205. Related: #15921.

Root Cause

# Before (in set_graph, node loop):
tasks = [asyncio.create_task(graph_node_to_chunk(n, ...)) for n in nodes]
# Each task calls embd_mdl.encode([single_name]) — 1 HTTP call per node

graph_node_to_chunk checks the embed cache first, but the cache is cold on first build, so every task makes a live API call.

Fix

Pre-warm the embedding cache with batched calls before spawning tasks. Each batch pre-warm calls embd_mdl.encode(batch_of_128) once, populating the cache. Then every individual task hits the cache and makes zero embedding API calls.

  • Only encodes names not already in cache (no-op on warm cache / small incremental updates)
  • Uses existing project idioms: thread_pool_exec, chat_limiter, _INSERT_BULK_SIZE, get_embed_cache, set_embed_cache
  • Mirrors the ENABLE_TIMEOUT_ASSERTION timeout pattern from graph_node_to_chunk
  • Zero behavior change: per-task encode logic remains as a correct fallback

Result

Graph size Before After
17,576 edges ~17,576 embedding calls → stall ~138 batched calls
17,509 nodes ~17,509 embedding calls → stall ~137 batched calls
Total ~35,000 calls ~275 calls

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

set_graph in rag/graphrag/utils.py now pre-warms Redis embedding cache entries for updated nodes and edges before chunk conversion tasks run. It also adds batched cache lookup/write helpers and expanded docstrings across utility functions.

Changes

GraphRAG Bulk Embedding Cache Pre-warming

Layer / File(s) Summary
Utility docstrings
rag/graphrag/utils.py
Adds docstrings across cache, graph, parsing, and helper utilities without changing runtime behavior.
Batched cache helpers
rag/graphrag/utils.py
Adds internal helpers for batched Redis miss detection and synchronous batch writes of embeddings back to the cache.
Node embedding pre-warm
rag/graphrag/utils.py
Updates set_graph to detect missing node embeddings in one batched pass, encode missing entity names in bulk batches, write them to Redis, and report node batch progress.
Edge embedding pre-warm
rag/graphrag/utils.py
Updates set_graph to detect missing edge embeddings in one batched pass, encode uncached relation texts in bulk batches, write them to Redis, and report edge batch progress.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

Poem

🐇 Hop to the cache, so bright and neat,
Nodes and edges now batch their treat.
Misses wake, then zip away,
Redis hums at the end of day,
The graph runs fast with a happy beat.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed It clearly describes batching entity/edge embedding in set_graph() to fix large-graph stalls.
Description check ✅ Passed It includes a clear problem, root cause, fix, and result, so it is mostly complete despite not using the exact template heading.
Linked Issues check ✅ Passed The PR batches cache lookup and embedding for entities and edges, addressing the one-by-one embedding stall described in #16205.
Out of Scope Changes check ✅ Passed The changes stay within set_graph() performance work; only docstring updates appear outside the main logic change.
Docstring Coverage ✅ Passed Docstring coverage is 96.43% which is sufficient. The required threshold is 80.00%.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
rag/graphrag/utils.py (1)

555-579: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add server-side logging for the new pre-warm phases.

These are new execution paths, but they only emit optional callback messages. When callback is absent, there is no trace for batch counts, timing, or failures in the pre-warm flow, which makes production stalls harder to diagnose. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 599-627

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/graphrag/utils.py` around lines 555 - 579, The batch pre-warm entity
embedding flow in the embedding cache warmup path only reports via the optional
callback, so add server-side logging around the new pre-warm phases. Instrument
the batch loop that uses asyncio.wait_for, thread_pool_exec, and embd_mdl.encode
to log when pre-warming starts, each batch size/count, elapsed time, and any
timeout or encode failures, and keep the existing callback as a secondary
notification only. Use the existing symbols in this flow (chat_limiter,
_uncached_node_names, _INSERT_BULK_SIZE, set_embed_cache) to place the logs in
the right spots so production runs have traceability even when callback is
missing.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/graphrag/utils.py`:
- Around line 559-562: The cache-miss discovery in `set_graph()` is still doing
synchronous `get_embed_cache()` calls per node/edge before batching, which
blocks the event loop. Update the `_uncached_node_names` and corresponding edge
miss discovery paths to batch these Redis reads, or move the miss-check work off
the event loop using `thread_pool_exec`; keep the existing batching in
`encode()` but ensure the prefiltering no longer performs per-item
`REDIS_CONN.get()` calls.

---

Nitpick comments:
In `@rag/graphrag/utils.py`:
- Around line 555-579: The batch pre-warm entity embedding flow in the embedding
cache warmup path only reports via the optional callback, so add server-side
logging around the new pre-warm phases. Instrument the batch loop that uses
asyncio.wait_for, thread_pool_exec, and embd_mdl.encode to log when pre-warming
starts, each batch size/count, elapsed time, and any timeout or encode failures,
and keep the existing callback as a secondary notification only. Use the
existing symbols in this flow (chat_limiter, _uncached_node_names,
_INSERT_BULK_SIZE, set_embed_cache) to place the logs in the right spots so
production runs have traceability even when callback is missing.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33322705-7deb-42cc-a0b1-f7bd82be6f65

📥 Commits

Reviewing files that changed from the base of the PR and between 5276baf and 381c759.

📒 Files selected for processing (1)
  • rag/graphrag/utils.py

Comment thread rag/graphrag/utils.py Resolved
…read pool

- Replace per-item get_embed_cache() list comprehensions with
  _batch_embed_cache_misses() which issues a single REDIS_CONN.mget()
  call, avoiding N synchronous Redis GETs blocking the event loop.
- Add _write_embed_cache_batch() and call it via thread_pool_exec so
  the set_embed_cache() loop after each encode batch also runs off the
  event loop.
- Add logging.debug() instrumentation for both the node and edge
  pre-warm phases (batch count, miss count, elapsed info).
- Add docstring to set_graph() describing its overall contract.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 30, 2026
@yingfeng yingfeng added the ci Continue Integration label Jul 1, 2026
@yingfeng
yingfeng marked this pull request as draft July 1, 2026 08:57
@yingfeng
yingfeng marked this pull request as ready for review July 1, 2026 08:57
Adds one-line docstrings to the 24 public functions in
rag/graphrag/utils.py that were missing them.  Pushes the file's
docstring coverage from ~60% to 100%, satisfying the pre-merge
coverage check flagged by CodeRabbit.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
rag/graphrag/utils.py (1)

340-341: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

Insecure-hash lint on md5 (pre-existing, non-security use).

compute_args_hash uses md5 purely as a cache-key hash, not for security purposes, so the risk is low. Since Python 3.9+ supports usedforsecurity=False to suppress this class of finding (and satisfy FIPS-restricted environments), consider passing it explicitly.

♻️ Proposed fix
 def compute_args_hash(*args):
     """Return a hex MD5 digest of the string representation of *args* (used as a cache key)."""
-    return md5(str(args).encode()).hexdigest()
+    return md5(str(args).encode(), usedforsecurity=False).hexdigest()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/graphrag/utils.py` around lines 340 - 341, The cache-key hash in
compute_args_hash is using md5 without explicitly marking it as non-security
use, which triggers the lint and can fail in FIPS-restricted environments.
Update the md5 call in rag/graphrag/utils.py’s compute_args_hash helper to pass
usedforsecurity=False explicitly while keeping the existing cache-key behavior
unchanged.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@rag/graphrag/utils.py`:
- Around line 340-341: The cache-key hash in compute_args_hash is using md5
without explicitly marking it as non-security use, which triggers the lint and
can fail in FIPS-restricted environments. Update the md5 call in
rag/graphrag/utils.py’s compute_args_hash helper to pass usedforsecurity=False
explicitly while keeping the existing cache-key behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a90a272a-4066-49d3-8312-a9cdf94fdbdc

📥 Commits

Reviewing files that changed from the base of the PR and between 0fd66d9 and 3c946d7.

📒 Files selected for processing (1)
  • rag/graphrag/utils.py

@codecov

codecov Bot commented Jul 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (643cb47) to head (3c946d7).
⚠️ Report is 189 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16472   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng merged commit b0e6007 into infiniflow:main Jul 1, 2026
4 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GraphRAG set_graph() extremely slow due to per-entity/relation embedding (10-50x slower than batch)

2 participants