Repository navigation
refa: optimize knowledge compilation concurrency - #16933
Conversation
📝 WalkthroughWalkthroughDocument knowledge compilation now runs concurrent pooled LLM work, performs ordered batched local and Elasticsearch deduplication with alias rewriting, moves chain correction into merge orchestration, and filters compiled output rows from source chunk loading. ChangesKnowledge compilation pipeline
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Runner
participant LLMCallPool
participant Merge
participant Elasticsearch
Runner->>LLMCallPool: submit concurrent compilation calls
LLMCallPool-->>Runner: return compiled structures
Runner->>Merge: flush structures in commit order
Merge->>Elasticsearch: run batched deduplication and writes
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: 7
🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/structure.py (2)
1715-1721: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid the cubic
valid.index()lookup.The nested pair loop performs a linear search for every pair, making component construction O(n³).
Proposed fix
matrix = cosine_similarity([list(vectors[i]) for i in valid]) for left_offset, left in enumerate(valid): - for right in valid[left_offset + 1 :]: - right_offset = valid.index(right) + for right_offset in range(left_offset + 1, len(valid)): + right = valid[right_offset] if float(matrix[left_offset, right_offset]) >= similarity_threshold: union(left, right)🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 1715 - 1721, Replace the valid.index(right) lookup in the similarity union loop with an offset-based iteration that directly supplies both element indices, such as enumerating the suffix alongside its offset. Use those offsets to access matrix[left_offset, right_offset] while preserving the existing union threshold behavior.
1792-1800: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the dead single-document ES dedup path
rag/advanced_rag/knowlege_compile/structure.py:1792
_struct_es_dedup_onehas no callers and isn’t exported; deleting it will keep the ES dedup flow on one path and avoid drift.🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 1792 - 1800, Remove the unused private function _struct_es_dedup_one and its implementation, keeping the existing active ES deduplication path unchanged. Verify no references remain to this dead single-document helper.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/advanced_rag/knowlege_compile/runner.py`:
- Around line 294-321: The submission throttle must account for both active and
completed-but-uncommitted work. Update the pending-work bound in the surrounding
batch submission logic to use len(inflight) + len(completed) before creating
another task, preserving ordered commits through _commit_ready and existing task
handling.
- Around line 314-345: Propagate cancellation through the concurrent compilation
pipeline: in rag/advanced_rag/knowlege_compile/runner.py lines 314-345, poll the
existing cancellation check during batch/template submission and ensure every
exceptional exit cancels and awaits both inflight compile tasks and spawned
flush_tasks; in rag/advanced_rag/knowlege_compile/structure.py lines 1279-1288,
invoke cancel_check between the KNN, decision, merge, embedding, and write
stages.
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2291-2333: Update the correction flow around correct_batch and
keep_set so relations from separate batches cannot collectively violate the
strict-chain constraint. Either partition bad_edges into conflict-connected
components before correction, or revalidate the combined keep_set and run
correction on any remaining conflicts; preserve fail-open behavior for failed or
malformed corrections.
- Around line 980-981: Update the matched-row rebuild flow around
_struct_rebuild_es_doc() to resolve compilation_template_id and
compilation_template_kind from the original ES/base document before processing
the KNN result. Pass those preserved values into the rebuilt row, including the
analogous flow around the additional occurrence, so merged rows retain both
template metadata instead of using missing KNN fields.
- Around line 1416-1455: Change alias handling in the entity rebuild flows,
including merge_one_group and the additional paths at the referenced sections,
to stage aliases per entity group rather than updating the shared entity_aliases
immediately. Publish a group’s aliases only after its embedding and entity write
complete successfully; discard staged aliases on failure. Defer
_struct_rewrite_relation_doc and existing relation rewrites until the
corresponding canonical entity aliases have been successfully published, so
failed rebuilds cannot redirect relations.
- Around line 1563-1574: Move the return statement in the bulk-write flow
outside the loop over writes so every batch is processed and the function always
returns a tuple, including when writes is empty. Preserve the existing inserted
and updated count calculations and exception handling.
- Around line 63-71: Update AsyncPriorityLimiter.call so cancellation while
awaiting the condition removes that task’s ticket from _waiting and restores the
heap invariant, then notifies other waiters as needed. Preserve normal priority
ordering and active-count bookkeeping for successfully admitted calls.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 1715-1721: Replace the valid.index(right) lookup in the similarity
union loop with an offset-based iteration that directly supplies both element
indices, such as enumerating the suffix alongside its offset. Use those offsets
to access matrix[left_offset, right_offset] while preserving the existing union
threshold behavior.
- Around line 1792-1800: Remove the unused private function _struct_es_dedup_one
and its implementation, keeping the existing active ES deduplication path
unchanged. Verify no references remain to this dead single-document helper.
🪄 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: 67bd2cf6-4a7b-4504-aae0-07beac97ef6d
📒 Files selected for processing (4)
rag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/task_handler.py
wangq8
left a comment
There was a problem hiding this comment.
Review: PR #16933 — Optimize knowledge compilation concurrency
Files: 4 | +1117 / -135 | Author: @buua436 | State: Open
Overview
This PR significantly improves concurrency in the document knowledge compilation pipeline:
- Priority-queued LLM pool (
LLMCallPool) shared across compile batches, chain correction, and merge decisions - Concurrent batch compilation & ordered commits — async submission with bounded inflight tasks, sequential commit to maintain deterministic accumulator state
- Batched ES dedup replaces per-doc KNN+LLM with phased approach: parallel KNN → concurrent LLM decisions → grouped merges → batched embeddings & writes
- Entity alias resolution during local dedup — tracks canonical names and rewrites relation endpoints
- Parallel local dedup via cosine-connected component partitioning
- Parallel chain correction — splits bad edges into bounded batches for concurrent LLM correction
compile_kwdfilter — excludes compilation output rows from chunk loading queries to prevent offset-pagination drift
The architectural direction is good. However, several issues need attention before merging.
🔴 Critical: Early return in write loop drops data
File: rag/advanced_rag/knowlege_compile/structure.py (inside _struct_es_dedup_batch)
for start in range(0, len(writes), _ES_DEDUP_INSERT_BATCH_SIZE):
batch = writes[start : start + _ES_DEDUP_INSERT_BATCH_SIZE]
...
return inserted, updated + existing_relation_updates # ← inside loop bodyThe return is inside the for loop, so only the first write batch (up to 256 docs) is ever persisted. If len(writes) > 256, all subsequent batches are silently dropped. This is a data-loss bug.
Fix: Dedent return to be outside the for loop. Also the empty-batch continue is unreachable (range with positive step never yields empty slices) — can be cleaned up.
🔴 Cancellation leaves stale tickets in LLMCallPool
File: rag/advanced_rag/knowlege_compile/structure.py — LLMCallPool.call()
If a coroutine is cancelled while await self._condition.wait(), the ticket remains in self._waiting heap. This can:
- Block future slots if the stale ticket stays at the heap front
- Cause
self._active -= 1in thefinallyblock even though_activewas never incremented
Fix: Wrap the wait in a cancellable scope and remove the ticket from _waiting (restoring heap invariant) on cancellation.
🔴 No-op except BaseException: raise in _compile_batch
File: rag/advanced_rag/knowlege_compile/runner.py
async def _compile_batch(...):
try:
docs = await compile_structure_from_text(...)
return docs
except BaseException:
raiseThis bare except BaseException: raise is a no-op and should be removed entirely.
🟡 _struct_entity_candidate_groups — O(n³) index lookup
File: rag/advanced_rag/knowlege_compile/structure.py
for left_offset, left in enumerate(valid):
for right in valid[left_offset + 1 :]:
right_offset = valid.index(right) # O(n) linear search per pairvalid.index(right) is O(n) and called for every pair, making the connected-component construction O(n³). For large entity groups this is unnecessary overhead.
Fix: Use offset-based iteration instead:
for left_offset, left in enumerate(valid):
for right_offset in range(left_offset + 1, len(valid)):
right = valid[right_offset]
...🟡 Missing cancel_check inside ES dedup batch
File: rag/advanced_rag/knowlege_compile/structure.py — _struct_es_dedup_batch
The old per-doc code checked cancellation between every ES insert. The new batched equivalent checks cancel_check only before entering the batch. During a long ES dedup (parallel KNN → LLM decisions → merges → embeddings → bulk writes), cancellation is not checked at all for potentially minutes of wall time.
Fix: Insert cancel_check calls between the major stages (after KNN gathering, after LLM decisions, before merge jobs, before bulk writes).
🟡 Cross-batch chain correction conflicts
File: rag/advanced_rag/knowlege_compile/structure.py — correct_batch
Bad edges are partitioned into batches of _CHAIN_CORRECTION_MAX_RELATIONS (16). Each batch is corrected independently by the LLM. If two bad edges from different batches form a conflict chain (e.g., A→B and B→C), neither the LLM nor the post-processing sees the full connected component. This can produce a keep_set that still violates the strict-chain constraint, or drop more edges than necessary.
Consider: Partition by conflict-connected components instead of a fixed-size batch to ensure each LLM call sees the complete context.
🟡 Dead code: _struct_es_dedup_one is no longer called
File: rag/advanced_rag/knowlege_compile/structure.py
The function _struct_es_dedup_one is retained but has no callers after the switch to _struct_es_dedup_batch. Remove it to prevent drift.
🟢 Good practices observed
| Practice | Location |
|---|---|
| Fail-open pattern | Exception handlers in ES KNN, LLM decisions, chain correction gracefully degrade |
| Two-phase ES LLM dedup | Decision (read-only) → Merge (payload generation) — prevents write-before-read races |
| Ordered commits via sequence numbers | flush_sequence / next_es_sequence with asyncio.Condition — deterministic despite concurrent flushes |
must_not: exists for compile_kwd |
Clean approach — avoids adding a separate flag field just for filtering |
| Component partitioning for parallel local dedup | Cosine-connected groups allow safe concurrent dedup |
| Entity alias → relation rewrite dependency ordering | Entities deduped first, aliases collected, then relations rewritten & deduped |
| Bounded everything | Inflight tasks, LLM pool, KNN concurrency, LLM batch size, embed batch size, insert batch size — all configurable constants |
Summary
| Severity | Count | Items |
|---|---|---|
| 🔴 Critical | 3 | Write-loop early return (data loss), cancellation ticket leak, no-op try/except |
| 🟡 Should fix | 4 | O(n³) lookup, missing cancel_check inside ES batch, cross-batch chain conflicts, dead code |
| 🟢 Minor/cleanup | — | Various small improvements noted above |
Verdict: The concurrency model is well-designed and the PR represents meaningful progress. The early-return bug must be fixed before merge — it's a silent data loss bug. The cancellation issues should also be addressed for robustness.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16933 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
rag/advanced_rag/knowlege_compile/structure.py (3)
2374-2392: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winAlways release the ES slot and propagate cancellation.
After
es_waiter()succeeds, the cancellation check can raise before reachinges_releaser(), leaking the acquired slot.TaskCanceledExceptionraised during dedup is also swallowed by the broadexcept Exception. Put release infinallyand re-raise cancellation explicitly.Proposed lifecycle fix
if es_waiter is not None: await es_waiter() -_raise_if_canceled() try: - inserted, updated = await _struct_es_dedup_batch( - deduped, - chat_mdl, - embd_mdl, - tenant_id, - kb_id, - similarity_threshold, - timing_context=timing_context, - cancel_check=cancel_check, - ) -except Exception: - logging.exception("merge_compiled_structures: batched ES dedup failed") - inserted = updated = 0 -if es_releaser is not None: - await es_releaser() + _raise_if_canceled() + try: + inserted, updated = await _struct_es_dedup_batch( + deduped, + chat_mdl, + embd_mdl, + tenant_id, + kb_id, + similarity_threshold, + timing_context=timing_context, + cancel_check=cancel_check, + ) + except TaskCanceledException: + raise + except Exception: + logging.exception("merge_compiled_structures: batched ES dedup failed") + inserted = updated = 0 +finally: + if es_releaser is not None: + await es_releaser()🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 2374 - 2392, Update the ES slot lifecycle around _struct_es_dedup_batch so es_releaser always runs after a successful es_waiter, including when _raise_if_canceled or dedup raises. Move release into a finally block, and add an explicit TaskCanceledException handler that re-raises cancellation before the existing generic exception handling.
1504-1584: 🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy liftScope aliases to their document, compilation, and template.
successful_entity_aliasescollapses aliases from every graph into one mapping, which is then applied across every scope and all inserted relations. A merge such asApple → Apple Inc.in one document can therefore rewrite unrelated relations in another document. Key aliases by(doc_id, compile_kwd, template_id)and apply only the matching scope’s mapping.Also applies to: 1592-1603
🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 1504 - 1584, Update the alias aggregation and relation-rewrite flow around successful_entity_aliases so aliases are grouped by (doc_id, compile_kwd, template_id) instead of one global mapping. Record each successful entity’s aliases under its document/compilation/template scope, then select and apply only that scope’s mapping while iterating scopes and rewriting relation payloads and endpoint fields; preserve the existing successful-insert filtering and template handling.
2304-2327: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winKeep every result path on the same contract.
The normal result now includes
graphs, but empty input omits it. The docstring also still describes per-document updates and a three-key response. Returngraphs: 0early and document the batched upsert/four-key result.Proposed result fix
if not docs: - return {"inserted": 0, "updated": 0, "duplicates_dropped": 0} + return { + "inserted": 0, + "updated": 0, + "duplicates_dropped": 0, + "graphs": 0, + }As per coding guidelines, remove stale documentation and preserve valid behavior with focused tests.
Also applies to: 2414-2419
🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 2304 - 2327, Update the deduplication function’s empty-input return to include graphs: 0, matching the normal four-key result contract. Revise its docstring to describe batched upsert behavior and the inserted, updated, duplicates_dropped, and graphs fields, removing the stale per-document update and three-key descriptions. Add focused coverage for empty and non-empty result shapes.Source: Coding guidelines
🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/structure.py (2)
1592-1592: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winBatch relation-insert re-embedding.
The awaited list comprehension serializes one embedding call per relation and bypasses
_ES_DEDUP_EMBED_BATCH_SIZE. Reuse the batched payload/vector rebuild path used for existing relations.🤖 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/advanced_rag/knowlege_compile/structure.py` at line 1592, Update the relation handling around _struct_rewrite_relation_doc to collect relation documents and rebuild their embedding payloads/vectors through the existing batched path, honoring _ES_DEDUP_EMBED_BATCH_SIZE. Preserve non-relation documents unchanged and avoid awaiting one embedding call per relation.
60-87: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logging to the new LLM scheduling flow.
labelandcontextare accepted but never emitted, leaving queue admission, cancellation, and execution failures opaque. Add structured debug/error logs around those transitions.As per coding guidelines, “Add logging for new flows.”
🤖 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/advanced_rag/knowlege_compile/structure.py` around lines 60 - 87, Add structured debug/error logging to the scheduling flow in call, using the provided label and context to identify queue admission, cancellation, and execution failures. Log when a request is queued, admitted, and completed, record cancellation while waiting before removing its ticket, and log execution exceptions before re-raising them; preserve the existing scheduling and cleanup behavior.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.
Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2374-2392: Update the ES slot lifecycle around
_struct_es_dedup_batch so es_releaser always runs after a successful es_waiter,
including when _raise_if_canceled or dedup raises. Move release into a finally
block, and add an explicit TaskCanceledException handler that re-raises
cancellation before the existing generic exception handling.
- Around line 1504-1584: Update the alias aggregation and relation-rewrite flow
around successful_entity_aliases so aliases are grouped by (doc_id, compile_kwd,
template_id) instead of one global mapping. Record each successful entity’s
aliases under its document/compilation/template scope, then select and apply
only that scope’s mapping while iterating scopes and rewriting relation payloads
and endpoint fields; preserve the existing successful-insert filtering and
template handling.
- Around line 2304-2327: Update the deduplication function’s empty-input return
to include graphs: 0, matching the normal four-key result contract. Revise its
docstring to describe batched upsert behavior and the inserted, updated,
duplicates_dropped, and graphs fields, removing the stale per-document update
and three-key descriptions. Add focused coverage for empty and non-empty result
shapes.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Line 1592: Update the relation handling around _struct_rewrite_relation_doc to
collect relation documents and rebuild their embedding payloads/vectors through
the existing batched path, honoring _ES_DEDUP_EMBED_BATCH_SIZE. Preserve
non-relation documents unchanged and avoid awaiting one embedding call per
relation.
- Around line 60-87: Add structured debug/error logging to the scheduling flow
in call, using the provided label and context to identify queue admission,
cancellation, and execution failures. Log when a request is queued, admitted,
and completed, record cancellation while waiting before removing its ticket, and
log execution exceptions before re-raising them; preserve the existing
scheduling and cleanup behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f9b8258e-a318-40bd-b22d-e443da0c78b1
📒 Files selected for processing (2)
rag/advanced_rag/knowlege_compile/runner.pyrag/advanced_rag/knowlege_compile/structure.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/advanced_rag/knowlege_compile/runner.py
What problem does this PR solve?
Improve concurrency in the knowledge compilation pipeline:
Type of change