Repository navigation
fix: improve incremental wiki compilation - #18164
Conversation
📝 WalkthroughWalkthroughThe wiki pipeline expands cleanup, repairs stale source chunks and MAP state, excludes disabled documents, adds telemetry, improves topic selection and routing, preserves link labels, and refreshes finalized page indexes. ChangesWiki compilation lifecycle
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant WikiGenerator
participant WikiRouter
participant WikiRefiner
participant PageIndex
WikiGenerator->>WikiRouter: route documents using candidate signals
WikiRouter->>WikiRefiner: pass page assignments and member evidence
WikiRefiner->>WikiGenerator: return generated pages and titles
WikiGenerator->>PageIndex: update pages and refresh index
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (1)
1364-1381: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTwo different key normalizations share one
seenset, so topics can duplicate.Lines 1371 uses
topic.casefold()for document topics. Line 1377 uses_normalize_key(topic)for the pool topics. If_normalize_keydoes more than case folding, the same topic produces two different keys and is appended twice.Use one normalization for both loops.
🔧 Proposed fix
topic = topic.strip() - key = topic.casefold() - if not topic or key == WIKI_TOPIC_FALLBACK.casefold() or key in seen: + key = _normalize_key(topic) + if not topic or key == _normalize_key(WIKI_TOPIC_FALLBACK) or key in seen: continue🤖 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 1364 - 1381, The topic collection logic uses inconsistent normalization before checking the shared seen set. Update both loops in the topic aggregation flow to use the same normalization helper, preferably _normalize_key, while preserving fallback filtering and deduplication behavior.
🧹 Nitpick comments (8)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (3)
3717-3737: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueBoth branches prepare the same topic state; hoist it above the
if.Lines 3717-3718 and 3736-3737 are identical. Move
topic_embeddingsandtopic_pool_lockbefore the mode dispatch.♻️ Proposed refactor
+ topic_embeddings = await _wiki_prepare_topic_embeddings(doc_topics, embd_mdl, list(topic_pool.values())) + topic_pool_lock = asyncio.Lock() if plan: - topic_embeddings = await _wiki_prepare_topic_embeddings(doc_topics, embd_mdl, list(topic_pool.values())) - topic_pool_lock = asyncio.Lock() summary = await _wiki_mode_b_run(🤖 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 3717 - 3737, Hoist the shared topic-state initialization out of the mode-dispatch branches: in the surrounding flow, call _wiki_prepare_topic_embeddings once and create topic_pool_lock once before the if/else, then remove both duplicate initializations from the branches while preserving the existing _wiki_mode_b_run arguments.
2079-2080: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the duplicate
thread_pool_execimport.
_wiki_refine_pagealready importsthread_pool_execat Line 1851. This second import inside the same function body is dead.As per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."
🤖 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 2079 - 2080, Remove the duplicate thread_pool_exec import from the import block near rag_tokenizer within _wiki_refine_page, preserving the existing earlier import and the rag_tokenizer import.Source: Coding guidelines
1990-2013: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
candidate_keysandnormalized_topic_candidatescompute the same set twice.Line 1996 builds
candidate_keys. Line 2012 rebuilds the same set asnormalized_topic_candidates, with only an extra falsy filter. Reuse one variable.🤖 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 1990 - 2013, Reuse the existing candidate-key set instead of recomputing it as normalized_topic_candidates. Update the topic_in_candidates check to use candidate_keys, preserving the current handling of falsy candidates and topic membership.rag/svr/task_executor_refactor/dataset_wiki_generator.py (1)
1906-1913: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winHandle a MAP-row deletion failure with a progress error.
_wiki_delete_map_rows_for_docsre-raises on failure (Line 345). This call site does not catch it, so the task aborts with an unhandled exception and the user sees no progress message. Every other failure path in this function reports throughprogress(-1, ...)or logs and continues.🔧 Proposed fix
- await _wiki_delete_map_rows_for_docs(ctx.tenant_id, ctx.kb_id, stale_doc_ids) + try: + await _wiki_delete_map_rows_for_docs(ctx.tenant_id, ctx.kb_id, stale_doc_ids) + except Exception: + progress(-1, "Failed to reset stale MAP state for wiki rebuild.") + return🤖 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 1906 - 1913, Wrap the _wiki_delete_map_rows_for_docs call in the surrounding incremental workflow with exception handling, report the deletion failure through progress(-1, ...) using an actionable error message, and prevent the exception from escaping as an unhandled task failure. Preserve the subsequent run_wiki_incremental behavior only when deletion succeeds.test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py (2)
1435-1456: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a case where
topic_embeddingsisNone.This test always supplies a populated
topic_embeddingsmap. The production default isNone, and on that path_wiki_rank_topic_candidatescurrently returns an empty list (see the comment onrag/advanced_rag/knowlege_compile/wiki_incremental.pyLines 1434-1480). A case withtopic_embeddings=Nonewould catch that regression.🤖 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 1435 - 1456, Extend test_topic_candidates_are_ranked_by_page_embedding with a case that calls _wiki_rank_topic_candidates using topic_embeddings=None, and assert it preserves the expected candidate-ranking behavior rather than returning an empty list. Keep the existing populated-embedding case unchanged and use the same page, evidence, candidates, and model setup.
1459-1464: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse a realistic pool key in the fixture.
The pool is
{"generated": "Generated topic"}. Production builds the pool with_normalize_key(topic)as the key, so the real key for this value would not be"generated"._wiki_topics_for_docsreads only.values(), so the test passes, but the fixture misrepresents the data shape and hides key-normalization defects.🤖 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 1459 - 1464, Update test_topics_for_docs_includes_global_topic_pool to use the normalized key produced by _normalize_key("Generated topic") for the global topic pool fixture instead of the hard-coded "generated" key, while preserving the expected topic values and assertion.api/apps/services/dataset_api_service.py (1)
4581-4583: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueConfirm that aborting the whole clear on a repair failure is intended.
If any exception occurs,
clear_wikireturns an error and deletes nothing. A user who wants a clean rebuild then has no way to clear the wiki while the repair keeps failing. Consider logging the failure and continuing with the deletion of genuine tracking rows only, or document why a hard abort is required.🤖 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 4581 - 4583, Update clear_wiki’s repair-exception handling so a failed legacy Wiki repair is logged but does not abort the clear operation; continue by deleting only genuine tracking rows and preserve the normal successful deletion result. Avoid returning the repair failure from this except block.rag/svr/task_executor_refactor/task_handler.py (1)
844-847: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog the recovery outcome.
The repair path logs only on exception. When rows are recovered it stays silent, so an operator cannot tell that legacy damage was found. The equivalent repair in
api/apps/services/dataset_api_service.py(Lines 4575-4580) logs a warning with the repaired count. Add the same signal here.As per coding guidelines: "Add logging for new flows".
🔧 Proposed fix
if recovered_batch: + logging.warning( + "load_chunks_for_doc: recovered %d source chunk(s) mislabeled as wiki_doc_page_source doc=%s", + len(recovered_batch), + doc_id, + ) yield recovered_batch🤖 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/task_handler.py` around lines 844 - 847, Add a warning log in the recovered_batch branch of the recovery path around load_chunks_for_doc, reporting the document identifier and number of repaired rows before yielding the batch. Match the warning-level repaired-count signal used by the equivalent dataset API repair flow, while preserving the existing exception logging and yield 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 4542-4574: Update the blocking doc-store operations in the
clear_wiki coroutine: wrap each settings.docStoreConn.search and
settings.docStoreConn.update call in the existing thread_pool_exec helper,
preserving the pagination and damaged-row cleanup behavior while keeping all
doc-store I/O off the event loop.
- Around line 4545-4567: Extract the duplicated scan-and-unmark behavior into a
shared repair helper, preserving pagination and consistent marker normalization,
then call it from api/apps/services/dataset_api_service.py:4545-4567 and
rag/svr/task_executor_refactor/task_handler.py:801-847 instead of maintaining
separate implementations. Document when this legacy helper can be deleted now
that the doc_id-based upsert fix in wiki_incremental.py:1745-1749 is in place.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1434-1480: Update _wiki_rank_topic_candidates to maintain a local
topic-to-embedding map initialized from topic_embeddings when provided, then
store newly encoded missing-topic vectors in that map regardless of whether the
caller supplied a cache. Use this local map when retrieving vectors for ranking,
while continuing to update topic_embeddings when it is not None.
- Around line 1142-1163: Update the graph fallback around _load_map_relations
and _wiki_load_pages_for_graph to reuse MAP relations already loaded during
compilation when available, avoiding a full wiki_map_extract scan on unchanged
graph loads. When loading relations is necessary, pass the same
disabled-document exclusion set used by the loader near the existing
excluded_doc_ids handling so disabled documents cannot contribute graph edges.
- Around line 1034-1036: Update the exclusion check in the field-map iteration
to normalize list-valued row["doc_id"] to its scalar element before converting
and comparing it with excluded_doc_ids. Preserve the existing handling for
scalar or missing doc_id values, and continue skipping rows whose normalized ID
is excluded.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1894-1914: Update _wiki_has_compiled_pages to distinguish “no
compiled pages” from probe failure, such as returning bool | None, and handle
the unknown result as a no-op at both call sites. In the recovery branch around
run_wiki_incremental, require a confirmed false probe and non-empty
existing_map_doc_ids before deleting rows or retrying MAP; preserve normal
behavior when pages exist or the probe fails.
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 809-820: The recovery query in the task handler currently limits
results to 1000 without handling additional pages. Update the recovery flow
around settings.docStoreConn.search to paginate through all available rows for
the document, aggregating each page so every marked chunk is restored and
visible to MAP; if pagination cannot be implemented, explicitly document the
1000-row cap at this call site.
- Around line 824-827: Normalize recovery_row’s compile_kwd value before the
marker comparison in the recovery-row processing flow: support both scalar and
list forms, extracting the scalar marker from a single-item list so
wiki_doc_page_source rows are accepted. Preserve the existing empty-content
filtering and continue behavior for non-matching markers.
---
Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1364-1381: The topic collection logic uses inconsistent
normalization before checking the shared seen set. Update both loops in the
topic aggregation flow to use the same normalization helper, preferably
_normalize_key, while preserving fallback filtering and deduplication behavior.
---
Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 4581-4583: Update clear_wiki’s repair-exception handling so a
failed legacy Wiki repair is logged but does not abort the clear operation;
continue by deleting only genuine tracking rows and preserve the normal
successful deletion result. Avoid returning the repair failure from this except
block.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 3717-3737: Hoist the shared topic-state initialization out of the
mode-dispatch branches: in the surrounding flow, call
_wiki_prepare_topic_embeddings once and create topic_pool_lock once before the
if/else, then remove both duplicate initializations from the branches while
preserving the existing _wiki_mode_b_run arguments.
- Around line 2079-2080: Remove the duplicate thread_pool_exec import from the
import block near rag_tokenizer within _wiki_refine_page, preserving the
existing earlier import and the rag_tokenizer import.
- Around line 1990-2013: Reuse the existing candidate-key set instead of
recomputing it as normalized_topic_candidates. Update the topic_in_candidates
check to use candidate_keys, preserving the current handling of falsy candidates
and topic membership.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1906-1913: Wrap the _wiki_delete_map_rows_for_docs call in the
surrounding incremental workflow with exception handling, report the deletion
failure through progress(-1, ...) using an actionable error message, and prevent
the exception from escaping as an unhandled task failure. Preserve the
subsequent run_wiki_incremental behavior only when deletion succeeds.
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 844-847: Add a warning log in the recovered_batch branch of the
recovery path around load_chunks_for_doc, reporting the document identifier and
number of repaired rows before yielding the batch. Match the warning-level
repaired-count signal used by the equivalent dataset API repair flow, while
preserving the existing exception logging and yield behavior.
In `@test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py`:
- Around line 1435-1456: Extend
test_topic_candidates_are_ranked_by_page_embedding with a case that calls
_wiki_rank_topic_candidates using topic_embeddings=None, and assert it preserves
the expected candidate-ranking behavior rather than returning an empty list.
Keep the existing populated-embedding case unchanged and use the same page,
evidence, candidates, and model setup.
- Around line 1459-1464: Update test_topics_for_docs_includes_global_topic_pool
to use the normalized key produced by _normalize_key("Generated topic") for the
global topic pool fixture instead of the hard-coded "generated" key, while
preserving the expected topic values and assertion.
🪄 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: 96479b92-e06b-451e-94ff-160e339ff93e
📒 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.pyrag/svr/task_executor_refactor/task_handler.pytest/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
| fields = ["id", "content_with_weight"] | ||
| offset = 0 | ||
| page_size = 1000 | ||
| damaged_row_ids: list[str] = [] | ||
| while True: | ||
| res = settings.docStoreConn.search( | ||
| fields, | ||
| [], | ||
| {"compile_kwd": ["wiki_doc_page_source"]}, | ||
| [], | ||
| OrderByExpr(), | ||
| offset, | ||
| page_size, | ||
| index_nm, | ||
| [dataset_id], | ||
| ) | ||
| rows = settings.docStoreConn.get_fields(res, fields) or {} | ||
| for row_id, row in rows.items(): | ||
| if row.get("content_with_weight"): | ||
| damaged_row_ids.append(row_id) | ||
| if len(rows) < page_size: | ||
| break | ||
| offset += page_size |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
The same legacy repair is implemented twice with different behavior. Both sites scan for rows mislabeled wiki_doc_page_source, keep the rows that still carry content_with_weight, and remove the marker. The shared root cause is the former doc_id-based upsert, which this PR already fixes at rag/advanced_rag/knowlege_compile/wiki_incremental.py#L1745-L1749. The two copies already differ: one paginates, one caps at 1000 rows; one compares the marker with str(...), one filters on truthiness. They will drift further.
api/apps/services/dataset_api_service.py#L4545-L4567: extract this scan-and-unmark logic into one shared helper, and call it from here.rag/svr/task_executor_refactor/task_handler.py#L801-L847: call the same shared helper instead of re-implementing the scan, so pagination and marker normalization are identical in both paths.
Because the underlying write bug is fixed, also record when the repair helper can be deleted. As per coding guidelines: "Treat legacy code as a liability rather than a compatibility target; prefer deletion over shims".
📍 Affects 2 files
api/apps/services/dataset_api_service.py#L4545-L4567(this comment)rag/svr/task_executor_refactor/task_handler.py#L801-L847
🤖 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 4545 - 4567, Extract
the duplicated scan-and-unmark behavior into a shared repair helper, preserving
pagination and consistent marker normalization, then call it from
api/apps/services/dataset_api_service.py:4545-4567 and
rag/svr/task_executor_refactor/task_handler.py:801-847 instead of maintaining
separate implementations. Document when this legacy helper can be deleted now
that the doc_id-based upsert fix in wiki_incremental.py:1745-1749 is in place.
Source: Coding guidelines
wangq8
left a comment
There was a problem hiding this comment.
This is a comprehensive and well-structured improvement to the incremental wiki compilation pipeline. The PR addresses multiple real issues and adds meaningful observability. Detailed review below.
Strengths
1. wiki_doc_page_source fix (critical)
The change from updating by {"doc_id": doc_id} to {"id": doc["id"]} in _wiki_update_doc_page_source is essential — the previous approach was corrupting source chunks that shared the same doc_id. This alone justifies the PR.
2. Repair logic in clear_wiki
The recovery block that scans for mislabeled source chunks and strips the wiki_doc_page_source compile keyword is well-designed: it preserves chunk content while allowing the real tracking rows to be cleared cleanly. The try/except with logging.exception and early-return on failure is correct.
3. Embedding-assisted topic ranking
_wiki_rank_topic_candidates uses embeddings only for candidate recall, letting the LLM remain the selector. The _wiki_topic_query_text builder composes query text from title, summary, evidence, and source chunks — a thoughtful approach that avoids superficial cosine similarity matches.
4. LLM page routing improvements
The new _wiki_expand_route_candidates with authority signals (current_owner → relation → cooccurrence → embedding → candidate_neighbor) is a clean way to bias routing toward authoritative page ownership. The 2-pass routing (initial LLM batch → confirm NEW results with expanded candidates) handles the common case where the LLM says NEW but graph evidence points to an existing page.
5. Multi-member page support
Adding member_evidence to prompts, TITLE line in LLM output, and build_member_evidence_block ensures the LLM cannot silently drop members from grouped pages. The display label preservation ([[target|display_text]]) during wikilink resolution prevents entity names from being overwritten by page slugs.
6. Observability
The _wiki_log_stats function provides machine-readable JSON logging at key decision points (MATCH, PLAN, ROUTE, TOPIC stages) — invaluable for debugging and monitoring.
7. Test coverage
347 lines of unit tests covering the new routing logic, merging behavior, and edge cases. The test for test_page_router_confirms_new_even_without_extra_neighbors tests the 2-pass routing behavior correctly.
8. Robustness
- Retry logic in
_wiki_llm_group_entities(2 attempts with fallback to single-entity groups instead of cluster fallback) - Retry missing items in
_wiki_llm_route_batcheswithout re-running the full batch refresh_idxcall after FINALIZE to ensure index consistency before graph materialization- Exclusion of disabled document IDs from MAP relation loading in incremental mode
Minor Observations (non-blocking)
LLM prompt format change
The new TITLE: line between SUMMARY: and TOPIC: is a breaking prompt format change. The system prompts are updated consistently, but any cached LLM responses or custom prompts in downstream forks would need updating. This is fine for the main repo — just flagging awareness.
Topic pool thread safety
The topic_pool_lock + setdefault pattern in _wiki_refine_page is correct, though setdefault itself is atomic in CPython due to the GIL. The lock is still warranted for the double-check pattern.
Dead link resolution
The dead link resolution now preserves display text: [[resolved|display_text]]. This is a nice touch — previously the display text was silently dropped on resolution.
Summary
No regressions, no security concerns, good test coverage, clear recovery paths. All 12 claimed improvements in the PR description are verifiable in the diff. Approved.
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/svr/task_executor_refactor/dataset_wiki_generator.py (3)
348-377: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winKeep the index-existence probe inside the tri-state error boundary.
_wiki_has_compiled_pagesdocumentsNonefor probe failures, butsettings.docStoreConn.index_existruns before thetryat Line [361]. If that call raises, the helper propagates instead of returningNone, andrun_wiki_incrementalaborts during the no-op check. ReturnFalseonly for a completed negative check, and returnNonefor every probe exception.Proposed fix
index = search.index_name(tenant_id) - if not settings.docStoreConn.index_exist(index, kb_id): - return False try: + if not settings.docStoreConn.index_exist(index, kb_id): + return False res = await thread_pool_exec(🤖 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 348 - 377, Move the index-existence check in _wiki_has_compiled_pages inside the existing try/except so exceptions from index_exist also return None after logging. Preserve False for a successful missing-index check, and retain the current search result handling for existing indexes.
1895-1906: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftDo not delete MAP resume rows after an unreported MAP failure.
all_map_resultscan be empty when every document has no fresh extract and when_produce_docor_map_workercatches an exception at Lines [1803]-[1805] and [1842]-[1843]. A transient failure for all MAP jobs can therefore satisfy this condition, delete persisted MAP rows for every eligible document, and trigger a full rebuild. Track MAP failures separately, and run this reset only after the MAP pass completes without errors.🤖 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 1895 - 1906, The reset guarded by existing_map_doc_ids, has_compiled_pages, and _map_rebuild_retry must not run when MAP processing encountered any document failure. Track failures from _produce_doc and _map_worker separately from all_map_results, and require the MAP pass to complete without errors before invalidating stale_doc_ids or triggering the one-time rebuild.
246-251: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winClean up Wiki state when a document becomes disabled.
run_wiki_incrementaldetects only deleted document IDs, so a transition to status"0"leaves existing Wiki rows searchable. Include disabled document IDs in cleanup or filter them from all Wiki read paths.🤖 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 246 - 251, Update run_wiki_incremental to include document IDs whose status transitions to "0" in the Wiki cleanup/deletion set, ensuring their existing Wiki rows are removed and no longer searchable. Preserve the current handling for deleted documents and the buildability check that skips disabled documents.
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/dataset_wiki_generator.py (1)
1907-1911: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPropagate MAP reset failures
If
_wiki_delete_map_rows_for_docsfails, re-raise the error after signaling failure.set_progress(..., prog=-1)swallows ordinary exceptions, so the worker recordsDONE_TASKSand stale MAP rows remain.🤖 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 1907 - 1911, Update the exception handler around _wiki_delete_map_rows_for_docs to signal failure with progress(-1, ...) and then re-raise the caught exception; remove the early return so the worker does not record completion and the MAP reset failure propagates.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.
Outside diff comments:
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 348-377: Move the index-existence check in
_wiki_has_compiled_pages inside the existing try/except so exceptions from
index_exist also return None after logging. Preserve False for a successful
missing-index check, and retain the current search result handling for existing
indexes.
- Around line 1895-1906: The reset guarded by existing_map_doc_ids,
has_compiled_pages, and _map_rebuild_retry must not run when MAP processing
encountered any document failure. Track failures from _produce_doc and
_map_worker separately from all_map_results, and require the MAP pass to
complete without errors before invalidating stale_doc_ids or triggering the
one-time rebuild.
- Around line 246-251: Update run_wiki_incremental to include document IDs whose
status transitions to "0" in the Wiki cleanup/deletion set, ensuring their
existing Wiki rows are removed and no longer searchable. Preserve the current
handling for deleted documents and the buildability check that skips disabled
documents.
---
Nitpick comments:
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1907-1911: Update the exception handler around
_wiki_delete_map_rows_for_docs to signal failure with progress(-1, ...) and then
re-raise the caught exception; remove the early return so the worker does not
record completion and the MAP reset failure propagates.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7699198e-db82-4b4a-b940-1322387ee4d6
📒 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.pyrag/svr/task_executor_refactor/task_handler.pytest/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
🚧 Files skipped from review as they are similar to previous changes (4)
- rag/svr/task_executor_refactor/task_handler.py
- api/apps/services/dataset_api_service.py
- test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py
- rag/advanced_rag/knowlege_compile/wiki_incremental.py
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py`:
- Around line 19-25: Add a test-local override in
test_finalize_links_via_map_relations for
DocumentService.get_disabled_doc_ids_by_kb_id to return {"map1"}, then assert
that _wiki_finalize writes no relation edge for the disabled document. Keep the
existing autouse fixture unchanged.
🪄 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: f5c0cbe7-541f-4737-8101-589ad4904dcd
📒 Files selected for processing (1)
test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py
| @pytest.fixture(autouse=True) | ||
| def _mock_disabled_document_lookup(monkeypatch): | ||
| """Keep knowledge-compile unit tests independent of the MySQL database.""" | ||
| from api.db.services.document_service import DocumentService | ||
|
|
||
| monkeypatch.setattr(DocumentService, "get_disabled_doc_ids_by_kb_id", MagicMock(return_value=set())) | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
root='test/unit_test/rag/advanced_rag/knowlege_compile'
rg -n -C 5 \
'get_disabled_doc_ids_by_kb_id|disabled.?document|disabled.?doc|_mock_disabled_document_lookup' \
"$root" || trueRepository: infiniflow/ragflow
Length of output: 1624
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
root='test/unit_test/rag/advanced_rag/knowlege_compile'
printf '%s\n' '--- files ---'
git ls-files "$root"
printf '%s\n' '--- test references in the directory ---'
rg -n -i -C 4 \
'disabled.?document|disabled.?doc|get_disabled_doc_ids_by_kb_id|DocumentService' \
"$root" || true
printf '%s\n' '--- production definition and callers ---'
rg -n -i -C 5 \
'def get_disabled_doc_ids_by_kb_id|get_disabled_doc_ids_by_kb_id\(' \
api rag test/unit_test || true
printf '%s\n' '--- conftest context ---'
cat -n "$root/conftest.py" | sed -n '1,80p'Repository: infiniflow/ragflow
Length of output: 5715
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
test_file='test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py'
service_file='api/db/services/document_service.py'
printf '%s\n' '--- test structure and relevant calls ---'
ast-grep outline "$test_file"
rg -n -C 8 \
'get_disabled_doc_ids_by_kb_id|disabled|compile|wiki|DocumentService' \
"$test_file" || true
printf '%s\n' '--- production method and repository callers ---'
cat -n "$service_file" | sed -n '40,55p'
rg -n -C 8 'get_disabled_doc_ids_by_kb_id\(' . || trueRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
python3 - <<'PY'
from pathlib import Path
needle = "get_disabled_doc_ids_by_kb_id"
for path in Path(".").rglob("*"):
if not path.is_file() or any(part in {".git", "node_modules", "build", "dist"} for part in path.parts):
continue
try:
text = path.read_text(errors="replace")
except OSError:
continue
for lineno, line in enumerate(text.splitlines(), 1):
if needle in line:
print(f"{path}:{lineno}:{line.strip()}")
PY
printf '%s\n' '--- direct DocumentService references in the target module ---'
rg -n 'DocumentService|get_disabled_doc_ids_by_kb_id' \
rag/advanced_rag/knowlege_compile/wiki_incremental.py \
test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py || trueRepository: infiniflow/ragflow
Length of output: 2266
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
prod='rag/advanced_rag/knowlege_compile/wiki_incremental.py'
tests='test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py'
printf '%s\n' '--- production callers ---'
cat -n "$prod" | sed -n '1138,1170p;3128,3155p;3480,3505p'
printf '%s\n' '--- test calls into likely caller paths ---'
rg -n \
'_wiki_(compile|run|finalize|mode_a_run|incremental|load_map|process)|wiki_compile|compile_wiki|DocumentService' \
"$tests" | tail -n 120
printf '%s\n' '--- fixture patch targets and scopes ---'
rg -n -C 3 \
'thread_pool_exec|_mock_disabled_document_lookup|autouse|scope=' \
'test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py'Repository: infiniflow/ragflow
Length of output: 7705
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
prod='rag/advanced_rag/knowlege_compile/wiki_incremental.py'
tests='test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_incremental.py'
printf '%s\n' '--- relation loader ---'
rg -n '^async def _load_map_relations|^def _load_map_relations|excluded_doc_ids|compile_kwd' "$prod" | head -n 60
cat -n "$prod" | sed -n '1030,1115p'
printf '%s\n' '--- relation-based test fixture ---'
cat -n "$tests" | sed -n '1240,1308p'
printf '%s\n' '--- finalize definition and relevant setup ---'
rg -n '^async def _wiki_finalize|^def _wiki_finalize|_load_map_relations\(' "$prod"Repository: infiniflow/ragflow
Length of output: 10436
Add disabled-document coverage for _wiki_finalize. The autouse fixture makes test_finalize_links_via_map_relations treat map1 as enabled. Add a test-local override that returns {"map1"} and assert that no relation edge is written.
🤖 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/conftest.py` around lines 19
- 25, Add a test-local override in test_finalize_links_via_map_relations for
DocumentService.get_disabled_doc_ids_by_kb_id to return {"map1"}, then assert
that _wiki_finalize writes no relation edge for the disabled document. Keep the
existing autouse fixture unchanged.
Source: Coding guidelines
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #18164 +/- ##
=======================================
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:
|
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this comprehensive PR. I reviewed the changes across all seven files and have the following observations:
Overall
This is a solid improvement to the incremental wiki pipeline. The changes address multiple real bugs (template kind mismatch, doc_id-based upsert damaging source chunks, incomplete cleanup state) while adding meaningful quality improvements to entity matching, page routing, topic selection, and graph restoration. The test coverage for the new routing behavior is appreciated.
Specific observations
Template kind fix (dataset_api_service.py L2170)
"artifacts" → "wiki" — correct. This was a bug where the wiki endpoint was checking the wrong template kind, making documents with the wiki template ineligible for wiki alteration.
_WIKI_COMPILE_KWDS expansion
Adding the five missing compile keywords ensures clear_wiki truly tears down all incremental state. The dependency order in the comment is preserved.
Source chunk repair in clear_wiki
The repair loop that scans for wiki_doc_page_source rows carrying actual content and strips the misapplied marker is a necessary defensive measure. The batching with page_size=1000 and the exception handling that returns a clear error message both look correct. One consideration: the repair only removes compile_kwd — if any of these damaged rows also had other wiki-specific fields written into them (unlikely since they were source chunks, but worth noting), those fields would remain.
Routing overhaul (wiki_incremental.py)
The removal of hardcoded thresholds (PAGE_ROUTER_DIRECT_THRESHOLD etc.) and replacement with signal-based candidate ranking + two-pass LLM confirmation is the right direction. Key strengths:
- Owner-based routing: entities already assigned to a page (
current_ownersignal) bypass the LLM entirely — correct and efficient. - Two-pass confirmation: entities the LLM marks as NEW get a second pass with expanded candidates (including graph neighbors). This is the fix for false NEW assignments that previously caused page proliferation.
_wiki_expand_route_candidates: merges embedding candidates with authoritative ownership, relation evidence, and chunk co-occurrence. The priority ordering (current_owner > relation > cooccurrence > embedding) is well-reasoned.- Retry-only-missing in
_wiki_llm_route_batches: avoids re-processing already-routed entities when one malformed item fails — good optimization.
Entity matching (llm_merge_pairs tracking)
The structured logging of LLM merge decisions via _wiki_log_stats is useful for debugging. The intra_build scope for merges within the same build iteration vs existing_canonical for merges into persisted entities is correctly distinguished.
wiki_doc_page_source upsert fix
Changing the update condition from {"doc_id": doc_id} to {"id": doc["id"]} is the critical fix. Using doc_id was a broad match that could stamp every row sharing that document ID (source chunks, MAP resume rows, etc.). Using the rows own unique id correctly targets only the tracking row.
MAP relation fallback in _wiki_load_pages_for_graph
Rebuilding graph outlinks from MAP relations when the LLM fails to generate wikilinks is a good fallback. The name-to-slug resolution (checking slug suffix, title, and entity_names) is thorough. One edge case: if two pages share a member name (e.g., same entity name across different pages), name_to_slug.setdefault picks the first page encountered — this is acceptable since the MAP relation endpoint ambiguity is inherently fuzzy, but a comment acknowledging this would help future readers.
Topic improvements
_wiki_rank_topic_candidates: embedding-based re-ranking of topic candidates before LLM selection is good. The function caches newly encoded topics back intotopic_embeddings(side effect) — this is intentional for amortization but worth documenting at the call site.- New topic pool: adds LLM-generated topics to the shared pool so subsequent pages can pick them up. The
topic_pool_lockusage is correct. - The
_wiki_prepare_topic_embeddingslist conversionlist(doc_topics.values())is necessary for concatenation with[extra_topics or []].
Member evidence in prompts
The _build_member_evidence_block and the ## Required Page Members section in both generate and modify system prompts are well-designed. The instruction "Do not silently omit or replace any member" addresses a real quality issue with multi-entity pages.
TITLE field in page output
Adding a TITLE line between SUMMARY and TOPIC is clear and backward-compatible since the parser strips unknown prefixes. The logic that single-member pages keep their original title while multi-entity pages get a synthesized title is correct (if len(member_names) <= 1: title = existing_title).
Wikilink pipe handling
Parsing [[slug|display text]] and keeping the display label in auto-links ([[target|name]]) prevents entity name collisions from being silently lost. The finalize step correctly strips the pipe portion when checking existing links and applies it when auto-linking.
refresh_idx after finalize
Calling refresh_idx after the batch of page updates ensures the search index sees the new outlinks before the caller reloads rows to materialize wiki_entity/wiki_relation. Without this, the graph could be built from a stale snapshot. Good catch.
Minor suggestions (non-blocking)
- The retry count in
_wiki_llm_group_entities(for attempt in range(2)) is hardcoded — consider a module-level constant alongside the other tunables. _wiki_rank_topic_candidatesmutatestopic_embeddingsas a side effect — a brief docstring note would help.- The
llm_page_grouplog could become verbose with large candidate sets — consider only logging whenlen(merged_groups) > 0.
Verdict
✅ Approved in spirit. No blocking issues. The changes are well-scoped, bug fixes are targeted, and the routing improvements are backed by tests.
What problem does this PR solve?
Improve incremental Wiki generation and fix multiple issues in entity matching, page planning, topic assignment, relationships, and clean rebuilds.
wiki_doc_page_sourceupdates overwriting source chunks sharing the samedoc_id.Type of change