Repository navigation
perf: batch-embed entity/edge names in set_graph() to fix stall on large graphs (#16205) - #16472
Conversation
📝 WalkthroughWalkthrough
ChangesGraphRAG Bulk Embedding Cache Pre-warming
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
rag/graphrag/utils.py (1)
555-579: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd server-side logging for the new pre-warm phases.
These are new execution paths, but they only emit optional
callbackmessages. Whencallbackis 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
📒 Files selected for processing (1)
rag/graphrag/utils.py
…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.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
rag/graphrag/utils.py (1)
340-341: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueInsecure-hash lint on
md5(pre-existing, non-security use).
compute_args_hashusesmd5purely as a cache-key hash, not for security purposes, so the risk is low. Since Python 3.9+ supportsusedforsecurity=Falseto 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
📒 Files selected for processing (1)
rag/graphrag/utils.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Problem
When building or updating a knowledge graph with a large number of entities and edges,
set_graph()inrag/graphrag/utils.pycreates oneasynciotask per entity and one per edge, each callingembd_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
graph_node_to_chunkchecks 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.thread_pool_exec,chat_limiter,_INSERT_BULK_SIZE,get_embed_cache,set_embed_cacheENABLE_TIMEOUT_ASSERTIONtimeout pattern fromgraph_node_to_chunkResult