Repository navigation
fix: improve incremental wiki compilation - #18130
Conversation
# Conflicts: # api/apps/services/dataset_api_service.py
📝 WalkthroughWalkthroughIncremental wiki compilation now preserves source chunks and aliases, selects document-scoped topics during refinement, uses LLM-assisted page routing and constrained clustering, reconciles page membership, tracks embedding compatibility, and returns normalized wiki API data. ChangesIncremental wiki compilation
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant Compiler
participant PageRouter
participant EmbeddingSearch
participant ChatModel
participant PageRefinement
participant PlanGroupStorage
Compiler->>PageRouter: Submit entity evidence
PageRouter->>EmbeddingSearch: Retrieve page candidates
EmbeddingSearch-->>PageRouter: Return candidates and scores
PageRouter->>ChatModel: Request page routing
ChatModel-->>PageRouter: Return page assignments
PageRouter->>PageRefinement: Send grouped evidence
PageRefinement-->>Compiler: Return refined pages
Compiler->>PlanGroupStorage: Persist final membership
Possibly related PRs
Suggested labels: Suggested reviewers: 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: 3
🧹 Nitpick comments (5)
test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py (1)
1382-1399: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe concurrency assertion depends on two module constants.
max_active == 2holds only whileWIKI_GROUP_LLM_CANDIDATE_SIZEis 24 and the fixture has 48 entities, which produces exactly two candidate communities. A change to the constant makes this test fail for a reason unrelated to concurrency. Derive the expected value from the constant, for examplemath.ceil(len(entities) / _wiki.WIKI_GROUP_LLM_CANDIDATE_SIZE).🤖 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 `@test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py` around lines 1382 - 1399, The concurrency assertion in test_llm_page_grouping_partitions_candidate_communities_concurrently should derive its expected value from WIKI_GROUP_LLM_CANDIDATE_SIZE rather than hard-coding 2. Update the max_active assertion using the ceiling of len(entities) divided by _wiki.WIKI_GROUP_LLM_CANDIDATE_SIZE.rag/advanced_rag/knowlege_compile/wiki_incremental.py (3)
3470-3471: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winSort the document IDs before you derive topic candidates.
entry["source_doc_ids"]is aset._wiki_topics_for_docsiterates it in insertion-independent order, so the candidate topic list and the resulting prompt differ between runs. Line 3470 already sorts the same set forsource_doc_ids. Use the sorted list for both.♻️ Proposed change
- source_doc_ids=sorted(entry["source_doc_ids"]), - topic_candidates=_wiki_topics_for_docs(entry["source_doc_ids"], doc_topics), + source_doc_ids=sorted(entry["source_doc_ids"]), + topic_candidates=_wiki_topics_for_docs(sorted(entry["source_doc_ids"]), doc_topics),The same applies to line 3791, where
page_source_doc_idsis also a set.🤖 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/wiki_incremental.py` around lines 3470 - 3471, Update the wiki compilation flows around source_doc_ids and page_source_doc_ids so each set is sorted once and that same sorted list is passed to both the source ID field and _wiki_topics_for_docs. Apply the change at both referenced construction sites, preserving the existing topic derivation behavior while making its input deterministic.
2531-2533: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider a fallback when the embedding matrix has an unexpected shape.
_wiki_cluster_entitiesraisesValueErrorfor a non-2-D matrix._wiki_llm_group_entitiesand_wiki_page_routercall it without a guard, so one malformed embedding batch aborts the whole Mode B run._wiki_match_entitieshandles the same condition at lines 754-761 by logging and skipping. Align the behavior, for example by returning one group per entity.🤖 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/wiki_incremental.py` around lines 2531 - 2533, Update _wiki_cluster_entities to handle invalid embedding matrix shapes without raising ValueError: log the condition consistently with _wiki_match_entities and return one group per entity as the fallback. Preserve normal clustering for valid two-dimensional matrices so _wiki_llm_group_entities and _wiki_page_router can continue processing malformed batches.
2589-2598: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueThe empty-cluster repair can leave a new empty cluster.
The loop iterates cluster ids in increasing order. A move can reduce a donor cluster to size 0 only when
sizes[...] > 1, so the donor stays non-empty. However, a cluster that becomes empty is never re-checked if its id is lower than the currentempty_cid. The next iteration of the outer k-means loop usually repairs this, and the final cluster list drops empty clusters, so the impact is limited to a smaller page count thantarget_count.🤖 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/wiki_incremental.py` around lines 2589 - 2598, The empty-cluster repair around the loop over empty cluster IDs must ensure every cluster remains represented after each move. Update the repair logic using the existing assignments, sizes, and stable_order symbols so newly emptied clusters are rechecked rather than skipped due to increasing empty_cid order, and preserve the requirement that each repaired cluster receives one member while maintaining deterministic selection.api/apps/services/dataset_api_service.py (1)
4397-4399: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winAdd regression tests for isolated graph entities.
The supplied test change covers
_string_list, but not this new click-mode and overview-mode contract. Add focused tests that assert an entity with no relation remains inentities.As per coding guidelines, preserve still-valid behavior with focused tests.
Also applies to: 4506-4508
🤖 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 `@api/apps/services/dataset_api_service.py` around lines 4397 - 4399, Add focused regression tests for the click-mode and overview-mode response paths that build the payload containing "entities" and "relations", verifying an entity with no relations remains in the returned entities list. Cover both locations associated with the relevant service methods while preserving existing relation and _string_list 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.
Inline comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 4397-4399: The graph response documentation is stale and must
reflect that entities are returned even when they have no relations. Update the
service docstring near the graph response in the relevant dataset API method and
the REST handler documentation near its graph response description, removing the
claim that only relation-referenced entities are included.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1695-1706: The incremental compatibility flow around
_wiki_reset_all_wiki_state and _wiki_save_mode_plan lacks a normal-flow log. Add
a log recording whether existing state was reused or reset, include the
applicable reset reason, and report only non-sensitive embedding fingerprint
status; preserve the existing reset behavior and avoid logging raw sensitive
values.
- Around line 1691-1694: Update the incremental reset logic around
_wiki_load_embedding_fingerprint and embedding_changed: when is_incremental is
true, treat a missing stored fingerprint or any mismatch with the current
fingerprint as requiring a reset. Do not treat an empty current fingerprint as
compatible; stop the build or derive and use a stable embedding identity before
recording state.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 4397-4399: Add focused regression tests for the click-mode and
overview-mode response paths that build the payload containing "entities" and
"relations", verifying an entity with no relations remains in the returned
entities list. Cover both locations associated with the relevant service methods
while preserving existing relation and _string_list behavior.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 3470-3471: Update the wiki compilation flows around source_doc_ids
and page_source_doc_ids so each set is sorted once and that same sorted list is
passed to both the source ID field and _wiki_topics_for_docs. Apply the change
at both referenced construction sites, preserving the existing topic derivation
behavior while making its input deterministic.
- Around line 2531-2533: Update _wiki_cluster_entities to handle invalid
embedding matrix shapes without raising ValueError: log the condition
consistently with _wiki_match_entities and return one group per entity as the
fallback. Preserve normal clustering for valid two-dimensional matrices so
_wiki_llm_group_entities and _wiki_page_router can continue processing malformed
batches.
- Around line 2589-2598: The empty-cluster repair around the loop over empty
cluster IDs must ensure every cluster remains represented after each move.
Update the repair logic using the existing assignments, sizes, and stable_order
symbols so newly emptied clusters are rechecked rather than skipped due to
increasing empty_cid order, and preserve the requirement that each repaired
cluster receives one member while maintaining deterministic selection.
In `@test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py`:
- Around line 1382-1399: The concurrency assertion in
test_llm_page_grouping_partitions_candidate_communities_concurrently should
derive its expected value from WIKI_GROUP_LLM_CANDIDATE_SIZE rather than
hard-coding 2. Update the max_active assertion using the ceiling of
len(entities) divided by _wiki.WIKI_GROUP_LLM_CANDIDATE_SIZE.
🪄 Autofix
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 Plus
Run ID: f78a8fbe-76c0-42b1-9136-02ddca7b02d0
📒 Files selected for processing (5)
api/apps/services/dataset_api_service.pyrag/advanced_rag/knowlege_compile/wiki_incremental.pyrag/svr/task_executor_refactor/dataset_wiki_generator.pytest/unit_test/api/apps/services/test_dataset_api_service_list_datasets.pytest/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
| "entities": list(entities.values()), | ||
| "relations": relations, | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Update the graph response documentation.
These returns now include entities without relations. The service docstring still says that only relation-referenced entities are returned. The REST handler in api/apps/restful_apis/dataset_api.py repeats that statement in Lines 673-687. Update both descriptions to match the new payload.
As per coding guidelines, remove stale documentation instead of preserving it.
Also applies to: 4506-4508
🤖 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 `@api/apps/services/dataset_api_service.py` around lines 4397 - 4399, The graph
response documentation is stale and must reflect that entities are returned even
when they have no relations. Update the service docstring near the graph
response in the relevant dataset API method and the REST handler documentation
near its graph response description, removing the claim that only
relation-referenced entities are included.
Source: Coding guidelines
| previous_embedding = await _wiki_load_embedding_fingerprint(ctx.tenant_id, ctx.kb_id) | ||
| current_embedding = _wiki_embedding_fingerprint(embedding_model) | ||
| mode_changed = prev_plan is not None and bool(prev_plan) != bool(plan) | ||
| embedding_changed = bool(previous_embedding and current_embedding and previous_embedding != current_embedding) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Reset legacy state with no embedding fingerprint.
Line 1694 treats a missing embedding_model_kwd as compatible. Existing incremental Wiki state created before this field was added will not reset. Line 1706 then records the current fingerprint while old embedding-space data remains. This can mix incompatible vectors during page candidate retrieval.
If is_incremental is true, reset when the stored fingerprint is absent or differs from the current fingerprint. If the current fingerprint is empty, stop the build or derive a stable identity instead of treating the state as compatible.
Proposed fix
previous_embedding = await _wiki_load_embedding_fingerprint(ctx.tenant_id, ctx.kb_id)
current_embedding = _wiki_embedding_fingerprint(embedding_model)
mode_changed = prev_plan is not None and bool(prev_plan) != bool(plan)
- embedding_changed = bool(previous_embedding and current_embedding and previous_embedding != current_embedding)
+ if is_incremental and not current_embedding:
+ logging.error("wiki: cannot determine embedding fingerprint for kb=%s", ctx.kb_id)
+ progress(-1, "Cannot verify Wiki embedding compatibility.")
+ return
+ embedding_changed = is_incremental and previous_embedding != current_embedding📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| previous_embedding = await _wiki_load_embedding_fingerprint(ctx.tenant_id, ctx.kb_id) | |
| current_embedding = _wiki_embedding_fingerprint(embedding_model) | |
| mode_changed = prev_plan is not None and bool(prev_plan) != bool(plan) | |
| embedding_changed = bool(previous_embedding and current_embedding and previous_embedding != current_embedding) | |
| previous_embedding = await _wiki_load_embedding_fingerprint(ctx.tenant_id, ctx.kb_id) | |
| current_embedding = _wiki_embedding_fingerprint(embedding_model) | |
| mode_changed = prev_plan is not None and bool(prev_plan) != bool(plan) | |
| if is_incremental and not current_embedding: | |
| logging.error("wiki: cannot determine embedding fingerprint for kb=%s", ctx.kb_id) | |
| progress(-1, "Cannot verify Wiki embedding compatibility.") | |
| return | |
| embedding_changed = is_incremental and previous_embedding != current_embedding |
🤖 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/svr/task_executor_refactor/dataset_wiki_generator.py` around lines 1691 -
1694, Update the incremental reset logic around _wiki_load_embedding_fingerprint
and embedding_changed: when is_incremental is true, treat a missing stored
fingerprint or any mismatch with the current fingerprint as requiring a reset.
Do not treat an empty current fingerprint as compatible; stop the build or
derive and use a stable embedding identity before recording state.
| if is_incremental and (mode_changed or embedding_changed): | ||
| if mode_changed: | ||
| reason = f"Mode switched (plan: {'on' if prev_plan else 'off'} -> {'on' if plan else 'off'})" | ||
| else: | ||
| reason = "Embedding model changed" | ||
| progress(0.05, f"{reason}; rebuilding wiki from scratch...") | ||
| await _wiki_reset_all_wiki_state(ctx.tenant_id, ctx.kb_id) | ||
| # Everything is gone; this is now a first build. | ||
| is_incremental = False | ||
| existing_map_doc_ids = set() | ||
| deleted_doc_ids = set() | ||
| await _wiki_save_mode_plan(ctx.tenant_id, ctx.kb_id, bool(plan)) | ||
| await _wiki_save_mode_plan(ctx.tenant_id, ctx.kb_id, bool(plan), current_embedding) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Log the embedding compatibility decision.
Add a normal-flow log that records whether the build reused state or reset it, with the reset reason and non-sensitive fingerprint status. The new compatibility flow currently logs only failures.
As per coding guidelines, **/*.py: 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/svr/task_executor_refactor/dataset_wiki_generator.py` around lines 1695 -
1706, The incremental compatibility flow around _wiki_reset_all_wiki_state and
_wiki_save_mode_plan lacks a normal-flow log. Add a log recording whether
existing state was reused or reset, include the applicable reset reason, and
report only non-sensitive embedding fingerprint status; preserve the existing
reset behavior and avoid logging raw sensitive values.
Source: Coding guidelines
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18130 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Incremental Wiki compilation could lose provenance for claim-light entities, produce unstable page groups across embedding models, route entities to unrelated pages, and assign topics without sufficient page-level context. Document removals and page membership changes could also leave stale Wiki state.
This PR:
Type of change