Skip to content

fix: improve incremental wiki compilation - #18130

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
buua436:b155
Aug 11, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
buua436:b155

Conversation

@buua436

@buua436 buua436 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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:

  • preserves source document and chunk provenance throughout entity matching, reduction, page generation, and deletion;
  • uses embeddings to retrieve candidates and the LLM to make final page grouping and incremental routing decisions;
  • batches embedding and LLM operations with bounded concurrency and deterministic fallbacks;
  • selects source-scoped topic candidates with embeddings before the page LLM chooses the final topic;
  • rebuilds Wiki state when the compilation mode or embedding model changes;
  • normalizes Wiki array fields returned by the API and retains entities without relations in graph responses.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Aug 11, 2026
@buua436 buua436 added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. 🌈 python Pull requests that update Python code size:XXL This PR changes 1000+ lines, ignoring generated files. 🧪 test Pull requests that update test cases. labels Aug 11, 2026
@buua436 buua436 assigned wangq8 and unassigned wangq8 Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Incremental 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.

Changes

Incremental wiki compilation

Layer / File(s) Summary
Entity evidence and canonical persistence
rag/advanced_rag/knowlege_compile/wiki_incremental.py, test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
Entity extraction and canonical records retain aliases, claims, source documents, and source chunks.
Page refinement and topic selection
rag/advanced_rag/knowlege_compile/wiki_incremental.py, test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
Page refinement uses evidence and topic candidates, parses selected topics, deduplicates claims, and preserves provenance.
LLM-assisted page routing and clustering
rag/advanced_rag/knowlege_compile/wiki_incremental.py, test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
Mode B retrieves candidate pages, applies LLM routing, and groups unrouted entities with capacity-constrained clustering.
Page membership reconciliation and splitting
rag/advanced_rag/knowlege_compile/wiki_incremental.py
Mode B reconciles moves and deletions, updates plan groups and document mappings, and splits unstable pages.
Compilation state compatibility
rag/svr/task_executor_refactor/dataset_wiki_generator.py
Incremental compilation stores embedding fingerprints and resets state when the plan mode or embedding model changes.
Wiki API normalization and graph responses
api/apps/services/dataset_api_service.py, test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py
List-valued wiki fields are normalized, and graph responses include entities without relations.

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
Loading

Possibly related PRs

Suggested labels: 🐞 bug, 🌈 python, size:XXL

Suggested reviewers: kevinhush, lynn-inf

Poem

A rabbit guards each source chunk tight,
And routes wiki pages left and right.
Claims bloom, topics find their tune,
Clusters dance beneath the moon.
Graphs show every entity bright—
Hop, hop, the records now align!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: improving incremental Wiki compilation.
Description check ✅ Passed The description clearly explains the problems, summarizes the main changes, and provides relevant background, despite using a different heading than the template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@buua436
buua436 requested a review from wangq8 August 11, 2026 11:39

@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: 3

🧹 Nitpick comments (5)
test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py (1)

1382-1399: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The concurrency assertion depends on two module constants.

max_active == 2 holds only while WIKI_GROUP_LLM_CANDIDATE_SIZE is 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 example math.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 win

Sort the document IDs before you derive topic candidates.

entry["source_doc_ids"] is a set. _wiki_topics_for_docs iterates it in insertion-independent order, so the candidate topic list and the resulting prompt differ between runs. Line 3470 already sorts the same set for source_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_ids is 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 win

Consider a fallback when the embedding matrix has an unexpected shape.

_wiki_cluster_entities raises ValueError for a non-2-D matrix. _wiki_llm_group_entities and _wiki_page_router call it without a guard, so one malformed embedding batch aborts the whole Mode B run. _wiki_match_entities handles 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 value

The 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 current empty_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 than target_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 win

Add 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 in entities.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ef6e45 and 9f54e17.

📒 Files selected for processing (5)
  • api/apps/services/dataset_api_service.py
  • rag/advanced_rag/knowlege_compile/wiki_incremental.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py
  • test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py

Comment on lines +4397 to 4399
"entities": list(entities.values()),
"relations": relations,
}

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.

📐 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

Comment on lines +1691 to +1694
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)

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.

🗄️ 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.

Suggested change
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.

Comment on lines +1695 to +1706
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)

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.

📐 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

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (fbcb865) to head (9f54e17).
⚠️ Report is 7 commits behind head on main.

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.
📢 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.

@JinHai-CN
JinHai-CN merged commit 0cfd8f4 into infiniflow:main Aug 11, 2026
15 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Aug 12, 2026
2 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants