Repository navigation
Refactor: refine wiki plan procedure. - #17579
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds plan-aware incremental wiki compilation with canonical entity matching, bounded MAP and REFINE concurrency, document-to-page tracking, deletion cleanup, expanded storage mappings, and template configuration controls. ChangesIncremental wiki compilation
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant TaskHandler
participant WikiGenerator
participant MapWorkers
participant IncrementalCompiler
participant CanonicalEntityIndex
participant DocumentStore
TaskHandler->>WikiGenerator: start wiki task with plan mode
WikiGenerator->>MapWorkers: process eligible document chunks
MapWorkers-->>WikiGenerator: return MAP results
WikiGenerator->>IncrementalCompiler: compile affected pages incrementally
IncrementalCompiler->>CanonicalEntityIndex: match and persist canonical entities
IncrementalCompiler->>DocumentStore: update pages and source tracking
Possibly related PRs
Suggested labels: 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: 14
🧹 Nitpick comments (5)
api/db/services/document_service.py (1)
683-687: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winReuse the shared page-source compile keyword.
wiki_incremental.pywrites these rows usingWIKI_DOC_PAGE_SOURCE_COMPILE_KWD, while this cleanup duplicates the literal. Import or re-export the owning constant so future keyword changes cannot silently disable deletion.🤖 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/db/services/document_service.py` around lines 683 - 687, Update the cleanup logic in the document service around the doc_page_kwd assignment to reuse the owning WIKI_DOC_PAGE_SOURCE_COMPILE_KWD constant instead of the duplicated "wiki_doc_page_source" literal. Import or re-export that shared constant from its defining module, then pass it through the existing search call unchanged.web/src/pages/user-setting/compilation-templates/create-next/utils.ts (1)
263-270: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse the
synthesis/planpassthrough branches. Both branches are byte-identical; a single membership check reads better and avoids the next passthrough key adding a third copy.♻️ Suggested consolidation
- if (key === 'synthesis') { - config[key] = value as ICompilationTemplateConfigRequest[string]; - return; - } - if (key === 'plan') { + if (key === 'synthesis' || key === 'plan') { config[key] = value as ICompilationTemplateConfigRequest[string]; 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 `@web/src/pages/user-setting/compilation-templates/create-next/utils.ts` around lines 263 - 270, Consolidate the identical passthrough branches in the configuration assignment logic by replacing the separate `key === 'synthesis'` and `key === 'plan'` checks with one membership check covering both keys. Preserve the existing assignment and early return behavior, and structure it so additional passthrough keys can be added without duplicating the branch.rag/svr/task_executor_refactor/dataset_wiki_generator.py (1)
1352-1382: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winDuplicate
get_by_kb_idscan. On the incremental path the full document list (with metadata joins) is fetched twice with identical arguments. Fetch once and reuse.♻️ Suggested change
- if is_incremental: - # Find deleted docs - all_docs, _ = await thread_pool_exec( - DocumentService.get_by_kb_id, - kb_id=ctx.kb_id, - page_number=0, - items_per_page=0, - orderby="create_time", - desc=False, - keywords="", - run_status=[], - types=[], - suffix=[], - ) - current_doc_ids = {str(d.get("id")) for d in all_docs or [] if d.get("id")} - deleted_doc_ids = existing_map_doc_ids - current_doc_ids - progress(0.02, f"Detected {len(deleted_doc_ids)} deleted document(s) ...") - - # 2. Pick eligible docs - all_docs, _ = await thread_pool_exec( + all_docs, _ = await thread_pool_exec( DocumentService.get_by_kb_id, kb_id=ctx.kb_id, page_number=0, items_per_page=0, orderby="create_time", desc=False, keywords="", run_status=[], types=[], suffix=[], ) + if is_incremental: + current_doc_ids = {str(d.get("id")) for d in all_docs or [] if d.get("id")} + deleted_doc_ids = existing_map_doc_ids - current_doc_ids + progress(0.02, f"Detected {len(deleted_doc_ids)} deleted document(s) ...")🤖 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 1352 - 1382, The incremental path invokes DocumentService.get_by_kb_id twice with identical arguments. Move the shared document fetch before the is_incremental block, then reuse all_docs for current_doc_ids and deleted-document detection while preserving the existing progress reporting and eligibility flow.rag/advanced_rag/knowlege_compile/wiki_incremental.py (2)
1090-1100: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
incrementalis accepted but never used in either mode runner. Dead parameters on a brand-new internal API; drop them (and the corresponding arguments inwiki_compile_incremental) unless a follow-up commit needs them.Also applies to: 1239-1249
🤖 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 1090 - 1100, Remove the unused incremental parameter from both wiki mode runner functions, including _wiki_mode_a_run and the corresponding runner near the second referenced section, then remove the matching arguments from wiki_compile_incremental and all internal call sites. Ensure the internal API signatures and invocations remain consistent without changing other behavior.
959-964: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSilent
except: passaround the progress callbacks, and private helpers in__all__. The three_progresshelpers swallow every exception without a log (Ruff S110/BLE001) — a persistently failing callback becomes invisible;logging.debug/exceptionthere costs nothing. And__all__exports six_-prefixed helpers (_wiki_reduce_entity,_wiki_page_router,_wiki_finalize, …), which contradicts keeping internal helpers private; export onlywiki_compile_incremental,wiki_handle_document_deleted, and the*_COMPILE_KWDconstants unless tests genuinely need more.As per coding guidelines: "reduce public surface area where helpers can be private or internal."
Also applies to: 1105-1110, 1254-1259, 1607-1619
🤖 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 959 - 964, Update all three _progress helpers to log callback failures with exception details before continuing, instead of silently swallowing them. Narrow __all__ to wiki_compile_incremental, wiki_handle_document_deleted, and the *_COMPILE_KWD constants; remove private underscore-prefixed helpers such as _wiki_reduce_entity, _wiki_page_router, and _wiki_finalize unless tests explicitly require their exports.Sources: Coding guidelines, 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.
Inline comments:
In `@api/db/services/document_service.py`:
- Around line 684-694: Update the docStoreConn.search call in
_wiki_update_doc_page_source to pass the dataset ID as a one-element list,
matching the expected final-argument shape used by other search callers. Keep
the existing doc.kb_id value and search behavior unchanged.
In `@conf/infinity_mapping.json`:
- Around line 70-75: Add the missing page_id and entity_names fields to the
Infinity schema in conf/infinity_mapping.json for the _wiki_update_plan_group
insert path. Match the existing ES mapping’s json/varchar types and preserve the
current defaults and field configuration conventions.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 888-924: Update the relation-map construction in the FINALIZE flow
to process only pages selected by page_ids, while preserving all pages when no
filter is provided. Replace the nested valid_ids substring scan with one regex
pass per page that extracts [[...]] wikilinks, keeps only IDs present in
valid_ids, excludes self-links, and retains the existing relation structure and
update behavior.
- Around line 1176-1197: The refine flow around _wiki_mode_a_refine incorrectly
rebuilds source_chunks and all_claims by iterating every delta for each page.
Replace that aggregation with data derived from the current entry, using
entry["additions"] to construct the page’s source chunks and claims while
preserving the existing fallback to entry["claims"], and remove the per-page
scan of deltas.
- Around line 1165-1213: The refine dispatch around _wiki_mode_a_refine
currently excludes refine_mode == "delete", leaving deletion handling and
pages_deleted accounting unreachable. Include the delete mode in the dispatch
and remove the redundant inner mode branch, or otherwise handle it outside the
guard, ensuring _wiki_mode_a_refine receives mode="delete" and deletions are
counted exactly once.
- Around line 234-246: Fix the existing-page lookup in _wiki_reduce_batch by
resolving each entity name to the page record keyed by slug, using
entity_names_kwd to build a name-to-page index or _wiki_derive_page_id(name)
before calling _wiki_reduce_entity. Preserve the existing page data for matching
entities so _wiki_reduce_entity can compute retractions, deletions, and deltas
instead of always taking the create path.
- Around line 252-304: The _wiki_update_doc_page_source function must preserve
existing source_chunk_hashes and map_checksum when chunk_hashes or map_checksum
is omitted: read the selected values from existing_map and use them as fallbacks
instead of "{}" and "". Replace the per-row update loop with one update call,
since the condition already targets doc_id and the row variable is unused.
- Around line 456-486: Update the page-building flow around source_doc_ids to
deserialize stored JSON strings, normalize missing or invalid values to a new
list, and append without mutating existing_pages or its existing record. Update
vec_col to derive the vector dimension from the embedding shape/value correctly,
using 768 only when the dimension cannot be determined.
- Around line 690-785: Update _wiki_page_router so threshold decisions use an
independent raw cosine similarity value rather than row["_score"], which may be
filtered, boosted, or combined with pagerank. Obtain that value through the
search result or compute it client-side from the query embedding and matched
page embedding, then compare it against PAGE_ROUTER_UPDATE_THRESHOLD and
PAGE_ROUTER_MAYBE_THRESHOLD while preserving the existing assignment and orphan
flows.
- Around line 1012-1033: The incremental affected-name calculation in the block
using _wiki_load_doc_page_source must handle newly added documents instead of
relying on the nonexistent entity_names field. Either persist and load
entity_names for doc_page_source, or derive affected_names from claims
associated with affected_doc_ids in map_results, ensuring pure additions
populate affected_names before _wiki_reduce_batch.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1501-1524: The run_wiki flow must explicitly remove stale MAP
state for every document in deleted_doc_ids before calling
wiki_compile_incremental. Reuse the existing _wiki_delete_deleted_doc_state
helper, ensuring wiki_map_extract rows and related deleted-document state are
swept so _wiki_existing_map_doc_ids and subsequent REDUCE processing no longer
include removed documents.
- Around line 1447-1462: Update the run_wiki template-processing flow to resolve
each document’s parser_cfg before starting _map_worker tasks, selecting
kb_chat_llm_id from the deterministic first eligible template rather than worker
dequeue order. Extend the map_queue tuple to carry parser_cfg and have
_map_worker reuse it instead of calling CompilationTemplateService.get_saved per
batch, removing the synchronous DB call from the event loop.
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 263-278: Update the plan parsing block in the task handler to
initialize plan_enabled to False and set it true only when a configured template
explicitly enables plan. Reuse the shared
_parser_config_compilation_template_ids(...) lookup used by
task_handler/dataset_wiki_generator instead of reading
pc.get("compilation_template_ids"), preserving no-plan behavior for false/no
values and lookup failures.
In
`@web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx`:
- Around line 199-207: The plan checkbox is not bound to form state because
RAGFlowFormItem does not support valuePropName. In both
web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx
lines 199-207 and
web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
lines 192-200, remove valuePropName and use a render-function child that maps
field.value to checked={!!field.value} and field.onChange to onCheckedChange,
preserving plan persistence in both flows.
---
Nitpick comments:
In `@api/db/services/document_service.py`:
- Around line 683-687: Update the cleanup logic in the document service around
the doc_page_kwd assignment to reuse the owning WIKI_DOC_PAGE_SOURCE_COMPILE_KWD
constant instead of the duplicated "wiki_doc_page_source" literal. Import or
re-export that shared constant from its defining module, then pass it through
the existing search call unchanged.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1090-1100: Remove the unused incremental parameter from both wiki
mode runner functions, including _wiki_mode_a_run and the corresponding runner
near the second referenced section, then remove the matching arguments from
wiki_compile_incremental and all internal call sites. Ensure the internal API
signatures and invocations remain consistent without changing other behavior.
- Around line 959-964: Update all three _progress helpers to log callback
failures with exception details before continuing, instead of silently
swallowing them. Narrow __all__ to wiki_compile_incremental,
wiki_handle_document_deleted, and the *_COMPILE_KWD constants; remove private
underscore-prefixed helpers such as _wiki_reduce_entity, _wiki_page_router, and
_wiki_finalize unless tests explicitly require their exports.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1352-1382: The incremental path invokes
DocumentService.get_by_kb_id twice with identical arguments. Move the shared
document fetch before the is_incremental block, then reuse all_docs for
current_doc_ids and deleted-document detection while preserving the existing
progress reporting and eligibility flow.
In `@web/src/pages/user-setting/compilation-templates/create-next/utils.ts`:
- Around line 263-270: Consolidate the identical passthrough branches in the
configuration assignment logic by replacing the separate `key === 'synthesis'`
and `key === 'plan'` checks with one membership check covering both keys.
Preserve the existing assignment and early return behavior, and structure it so
additional passthrough keys can be added without duplicating the branch.
🪄 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 Plus
Run ID: 0040b15d-c6ca-4cda-b246-ea905249a9c4
📒 Files selected for processing (12)
api/db/init_data/compilation_templates/wiki.yamlapi/db/services/document_service.pyconf/infinity_mapping.jsonrag/advanced_rag/knowlege_compile/wiki_incremental.pyrag/svr/task_executor_refactor/dataset_wiki_generator.pyrag/svr/task_executor_refactor/task_handler.pyweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsxweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsxweb/src/pages/user-setting/compilation-templates/edit-next/utils.ts
| res = settings.docStoreConn.search( | ||
| ["id"], | ||
| [], | ||
| {"compile_kwd": [doc_page_kwd], "doc_id": [doc.id]}, | ||
| [], | ||
| OrderByExpr(), | ||
| 0, | ||
| 10, | ||
| index, | ||
| doc.kb_id, | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Pass the dataset ID in the expected shape.
All supplied docStoreConn.search callers, including _wiki_update_doc_page_source, pass the final dataset argument as a one-element list. Passing doc.kb_id directly can make this lookup fail; because the exception is swallowed, the tracking row may remain after document deletion.
- doc.kb_id,
+ [doc.kb_id],📝 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.
| res = settings.docStoreConn.search( | |
| ["id"], | |
| [], | |
| {"compile_kwd": [doc_page_kwd], "doc_id": [doc.id]}, | |
| [], | |
| OrderByExpr(), | |
| 0, | |
| 10, | |
| index, | |
| doc.kb_id, | |
| ) | |
| res = settings.docStoreConn.search( | |
| ["id"], | |
| [], | |
| {"compile_kwd": [doc_page_kwd], "doc_id": [doc.id]}, | |
| [], | |
| OrderByExpr(), | |
| 0, | |
| 10, | |
| index, | |
| [doc.kb_id], | |
| ) |
🤖 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/db/services/document_service.py` around lines 684 - 694, Update the
docStoreConn.search call in _wiki_update_doc_page_source to pass the dataset ID
as a one-element list, matching the expected final-argument shape used by other
search callers. Keep the existing doc.kb_id value and search behavior unchanged.
There was a problem hiding this comment.
Actionable comments posted: 2
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)
1129-1172: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winPer-page claims get duplicated once per delta mapped to that page.
page_to_claims[page_id]already holds the aggregate for the page, but Line 1171extends it again for every delta routed to the samepage_id. With k deltas per page the REFINE prompt receives k copies of the same claim list (token blowup and skewed content), whilesource_chunkson Line 1172 is assigned idempotently — the two are inconsistent.🐛 Proposed fix
- "claims": [], + "claims": page_to_claims.get(page_id, []), "source_chunks": [], }, ) entry = concept_deltas[page_id] entry["additions"].extend(d.get("additions", [])) entry["retractions"].extend(d.get("retractions", [])) - entry["claims"].extend(page_to_claims.get(page_id, [])) entry["source_chunks"] = page_to_chunks.get(page_id, [])🤖 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 1129 - 1172, Update the concept_deltas aggregation around concept_deltas and page_to_claims so each page entry receives the aggregated claims exactly once, rather than extending the same page_to_claims list for every delta mapped to that page. Preserve the existing per-page additions and retractions aggregation, and keep source_chunks assignment idempotent like the corrected claims assignment.
♻️ Duplicate comments (1)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (1)
1024-1036: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
entity_namesstill isn't part of thedoc_page_sourcerecord, soaffected_namesis always empty. The new fallback now silently promotes every incremental run to a full rebuild overall_names— parallelizing the loads doesn't help because each load returns noentity_nameskey. Persistentity_names(and select it in_wiki_load_doc_page_source) or derive affected names frommap_resultsclaims foraffected_doc_ids.🤖 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 1024 - 1036, Fix the incremental affected-name calculation around `_wiki_load_doc_page_source` so loaded doc_page_source records provide `entity_names`, either by persisting and selecting that field or by deriving names from `map_results` claims for `affected_doc_ids`. Ensure `affected_names` is populated for impacted documents and reserve the `all_names` fallback for genuinely empty or unavailable incremental results.
🤖 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/wiki_incremental.py`:
- Around line 1259-1269: Update the serial doc_page_source apply loops around
_wiki_load_doc_page_source and _wiki_update_doc_page_source, including the
corresponding loop near the second referenced section, to preserve existing
source_chunk_hashes and map_checksum when writing updated page_ids. Pass the
retained metadata through the update call, or adjust
_wiki_update_doc_page_source defaults so omitted values do not overwrite stored
metadata.
- Around line 1531-1536: Expand the projection passed to _search_existing_pages
in the Mode A rewrite flow to include related_kb_pages_kwd and page_type_kwd.
Ensure _wiki_mode_a_refine receives and preserves these existing values when
modifying or re-synthesizing matching pages, rather than allowing the page dict
to overwrite them with missing data.
---
Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1129-1172: Update the concept_deltas aggregation around
concept_deltas and page_to_claims so each page entry receives the aggregated
claims exactly once, rather than extending the same page_to_claims list for
every delta mapped to that page. Preserve the existing per-page additions and
retractions aggregation, and keep source_chunks assignment idempotent like the
corrected claims assignment.
---
Duplicate comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1024-1036: Fix the incremental affected-name calculation around
`_wiki_load_doc_page_source` so loaded doc_page_source records provide
`entity_names`, either by persisting and selecting that field or by deriving
names from `map_results` claims for `affected_doc_ids`. Ensure `affected_names`
is populated for impacted documents and reserve the `all_names` fallback for
genuinely empty or unavailable incremental results.
🪄 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 Plus
Run ID: 9d11661e-c1c1-4e95-91f5-236609084f45
📒 Files selected for processing (1)
rag/advanced_rag/knowlege_compile/wiki_incremental.py
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/wiki_incremental.py (2)
281-305: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win
map_checksumis requested fromget_fieldsbut never selected in the search — the just-added preservation fix is a no-op for it.Line 283's search
select_fieldsis["id", "page_ids", "source_chunk_hashes"], but line 293'sget_fieldscall asks for"map_checksum"too. Since it was never in the projected field list,existing_maprows won't carry it, so the "preserve existingmap_checksumwhen omitted" logic (300-305) will consistently read empty/missing values and the metadata this was meant to protect keeps getting reset.🐛 Proposed fix
existing = await thread_pool_exec( settings.docStoreConn.search, - ["id", "page_ids", "source_chunk_hashes"], + ["id", "page_ids", "source_chunk_hashes", "map_checksum"], [], condition,🤖 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 281 - 305, Include "map_checksum" in the select_fields list passed to settings.docStoreConn.search within the existing metadata lookup, so get_fields can retrieve it and the preservation logic in the map_checksum block can reuse the stored value when the incoming value is omitted.
1050-1084: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
entity_namesis still never persisted, so deleted-doc name resolution remains broken.
_wiki_update_doc_page_source's write payload still only carriespage_ids/source_chunk_hashes/map_checksum— noentity_nameskey.dps.get("entity_names", [])at line 1066 is therefore always[]. The newnew_doc_idsloop (1071-1079) happens to cover every affected non-deleted doc, which papers over the "pure additions compile nothing" symptom, but it does not help for deleted documents: their claims are gone frommap_results, and thedps-based lookup that was meant to recover their previously-tracked entity names still yields nothing. Names owned exclusively by a deleted doc can be missed byaffected_names, so REDUCE may never compute their retraction/deletion here (any coverage would have to come entirely from the separate_wiki_delete_deleted_doc_statesweep indataset_wiki_generator.py).Persist
entity_namesondoc_page_sourcerows (as originally suggested) so this path actually works for deletions, not just as an accidental side effect of the additions fix.🤖 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 1050 - 1084, Update _wiki_update_doc_page_source to persist the document’s entity_names in each doc_page_source write payload alongside page_ids, source_chunk_hashes, and map_checksum. Ensure the stored names are available to the incremental compilation logic’s dps.get("entity_names", []) lookup, including for documents removed from map_results so deleted-only entities are marked affected.rag/svr/task_executor_refactor/task_handler.py (1)
280-281: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winSilently swallowed exception in a new flow.
except Exception: passdiscards any failure resolving the plan flag with no log trail, repeating the try/except/pass anti-pattern flagged by static analysis in the prior review round (S110/BLE001). As per coding guidelines, "Add logging for new flows" for**/*.py.🩹 Proposed fix
- except Exception: - pass # default to no-plan + except Exception: + logging.exception("wiki: plan-flag resolution failed for task %s; defaulting to no-plan", task_id)🤖 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 280 - 281, Update the exception handler in the plan-flag resolution flow of the task handler to log the caught exception before preserving the existing no-plan fallback. Replace the silent `except Exception: pass` behavior with the module’s established logging mechanism, including enough context and the exception details for diagnosis.Source: Coding guidelines
♻️ Duplicate comments (1)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (1)
1592-1661: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftDeletion-cleanup projection still omits
related_kb_pages_kwd/page_type_kwd.This still matches a previously-raised concern:
all_existing_pageshere is only projected with["slug_kwd","title_kwd","md_with_weight","claims","source_doc_ids","page_version_int","entity_names_kwd"], sorelated_kb_pages_kwd/page_type_kwdaren't loaded before themodify/deletecalls into_wiki_mode_a_refine. Whether this actually wipes those fields depends on whether the doc store'supdate()merges fields or replaces the document — worth confirming before deciding this is safe as-is.#!/bin/bash # Check whether docStoreConn.update() does a partial-field merge or full-document replace fd -a 'es_conn.py|infinity_conn.py|opensearch_conn.py|ob_conn.py' rag/utils | sed 's#^\./##' | while read -r f; do echo "== $f ==" rg -n 'def update' -A 25 "$f" done🤖 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 1592 - 1661, Update the deletion-cleanup projection used by all_existing_pages in the affected-page flow to also load related_kb_pages_kwd and page_type_kwd before calling _wiki_mode_a_refine. Preserve these fields through both the modify and delete paths, confirming the underlying update behavior if needed so existing metadata is not lost.
🧹 Nitpick comments (3)
rag/svr/task_executor_refactor/dataset_wiki_generator.py (1)
1385-1396: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winDuplicate template fetch per eligible doc.
CompilationTemplateService.get_saved(template_id, ...)is called once during eligibility filtering (line ~1391) and again for the sametemplate_idwhile pre-resolvingdoc_configs(line ~1438) — doubling DB round-trips across all eligible docs for no functional benefit.Capture the resolved config in the
eligibletuple during the first pass and reuse it here instead of re-fetching.Also applies to: 1434-1450
🤖 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 1385 - 1396, Avoid fetching each compilation template twice: in the eligibility loop, store the resolved template config alongside the document and template ID in eligible; update the later doc_configs pre-resolution flow to consume that stored config instead of calling CompilationTemplateService.get_saved again. Preserve the existing wiki filtering and downstream configuration behavior.rag/advanced_rag/knowlege_compile/wiki_incremental.py (2)
1131-1137: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift
_wiki_finalizegained apage_idsnarrowing filter but its only call site never uses it.
_wiki_finalizenow correctly restricts wikilink relation-building totarget_idswhenpage_idsis supplied, butwiki_compile_incrementalstill calls it asawait _wiki_finalize(tenant_id, kb_id, embd_mdl)with nopage_ids, so every incremental run still re-scans every page's markdown. Consider threading the set of pages actually touched by_wiki_mode_a_run/_wiki_mode_b_runthrough to this call to get the narrowing benefit this refactor enables.🤖 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 1131 - 1137, The incremental compile flow currently omits the new page narrowing filter when calling _wiki_finalize. Thread the set of pages touched by _wiki_mode_a_run/_wiki_mode_b_run through wiki_compile_incremental and pass it as page_ids to _wiki_finalize, preserving the existing finalize error handling.
1306-1324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDoc-page-source apply loop duplicated between Mode A and Mode B.
Both blocks independently load
existing_dps, mergepage_ids, and forwardchunk_hashes/map_checksum— nearly identical ~15-line sequences. This duplication already caused the same metadata-preservation fix to need applying twice (per the earlier "Also applies to: 1436-1445" note); extracting a shared_apply_doc_page_source_updates(tenant_id, kb_id, doc_updates)helper would remove that recurring risk.Also applies to: 1489-1507
🤖 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 1306 - 1324, Extract the duplicated doc_page_source merge-and-update logic from the Mode A and Mode B loops into a shared _apply_doc_page_source_updates(tenant_id, kb_id, doc_updates) helper. Preserve loading existing metadata, deduplicating page_ids, forwarding source_chunk_hashes and map_checksum, serial processing, and per-document exception logging; replace both inline blocks with calls to the helper.
🤖 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/wiki_incremental.py`:
- Around line 281-305: Include "map_checksum" in the select_fields list passed
to settings.docStoreConn.search within the existing metadata lookup, so
get_fields can retrieve it and the preservation logic in the map_checksum block
can reuse the stored value when the incoming value is omitted.
- Around line 1050-1084: Update _wiki_update_doc_page_source to persist the
document’s entity_names in each doc_page_source write payload alongside
page_ids, source_chunk_hashes, and map_checksum. Ensure the stored names are
available to the incremental compilation logic’s dps.get("entity_names", [])
lookup, including for documents removed from map_results so deleted-only
entities are marked affected.
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 280-281: Update the exception handler in the plan-flag resolution
flow of the task handler to log the caught exception before preserving the
existing no-plan fallback. Replace the silent `except Exception: pass` behavior
with the module’s established logging mechanism, including enough context and
the exception details for diagnosis.
---
Duplicate comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1592-1661: Update the deletion-cleanup projection used by
all_existing_pages in the affected-page flow to also load related_kb_pages_kwd
and page_type_kwd before calling _wiki_mode_a_refine. Preserve these fields
through both the modify and delete paths, confirming the underlying update
behavior if needed so existing metadata is not lost.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1131-1137: The incremental compile flow currently omits the new
page narrowing filter when calling _wiki_finalize. Thread the set of pages
touched by _wiki_mode_a_run/_wiki_mode_b_run through wiki_compile_incremental
and pass it as page_ids to _wiki_finalize, preserving the existing finalize
error handling.
- Around line 1306-1324: Extract the duplicated doc_page_source merge-and-update
logic from the Mode A and Mode B loops into a shared
_apply_doc_page_source_updates(tenant_id, kb_id, doc_updates) helper. Preserve
loading existing metadata, deduplicating page_ids, forwarding
source_chunk_hashes and map_checksum, serial processing, and per-document
exception logging; replace both inline blocks with calls to the helper.
In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 1385-1396: Avoid fetching each compilation template twice: in the
eligibility loop, store the resolved template config alongside the document and
template ID in eligible; update the later doc_configs pre-resolution flow to
consume that stored config instead of calling
CompilationTemplateService.get_saved again. Preserve the existing wiki filtering
and downstream configuration behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8ec104fb-46e8-4441-8c9e-0e73d8e6b915
📒 Files selected for processing (5)
rag/advanced_rag/knowlege_compile/wiki_incremental.pyrag/svr/task_executor_refactor/dataset_wiki_generator.pyrag/svr/task_executor_refactor/task_handler.pyweb/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsxweb/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17579 +/- ##
=======================================
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:
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (3)
1445-1524: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
page_ids(andembd_mdl) are now unused parameters, and the two wikilink-stripping branches are identical withdead_linksnever read. The docstring even states the filter is ignored. Per the guidelines on removing dead code, drop the unused parameters at the call sites and collapse Lines 1496-1502 into a singleelse, or actually usedead_links(e.g. log the count) if the diagnostics are wanted.♻️ Collapse the duplicate branches
- elif link in canonical_names: - # Entity reference (Mode A): remove [[]] keep plain text - content = content.replace(f"[[{link}]]", link, 1) else: - # Dead link: remove [[]] keep plain text + # Entity reference or dead link: remove [[]] keep plain text content = content.replace(f"[[{link}]]", link, 1) - dead_links.setdefault(pid, []).append(link) + if link not in canonical_names: + logging.debug("wiki: dropped dead wikilink %s on page %s", link, pid)As per coding guidelines: "During review, remove deprecated, legacy, and compatibility-only code; ... drop stale comments and documentation".
🤖 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 1445 - 1524, Remove the unused page_ids and embd_mdl parameters from _wiki_finalize and update every call site accordingly. Collapse the identical canonical-name and dead-link wikilink branches into one else path, and remove the unused dead_links collection and stale docstring references to the ignored filter.Source: Coding guidelines
452-527: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winIntra-build pairwise dedup is O(n²) with per-pair conversion, and
ENTITY_PAIRWISE_BATCH_SIZEis never used.ei/ejare re-converted withtolist()and re-normalized inside the inner loop for every pair. Normalize once into a matrix and take a singleA @ A.T(or chunk it with the declared batch size), which collapses the cost and removes the unused constant.confirmed_setin this block is also written but never read.♻️ Sketch
- ei = embeddings[i] - ej = embeddings[j] - if hasattr(ei, "tolist"): - ei = ei.tolist() - if hasattr(ej, "tolist"): - ej = ej.tolist() - sim = float(np.dot(ei, ej) / (np.linalg.norm(ei) * np.linalg.norm(ej) + 1e-10)) + sim = float(sim_matrix[i, j])with, before the loops:
mat = np.asarray([np.asarray(e).ravel() for e in embeddings], dtype=np.float32) mat /= np.linalg.norm(mat, axis=1, keepdims=True) + 1e-10 sim_matrix = mat @ mat.T🤖 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 452 - 527, Optimize the pairwise deduplication in the intra-build block around _find_parent by converting embeddings to a normalized NumPy matrix once and using matrix multiplication for similarities, chunked with ENTITY_PAIRWISE_BATCH_SIZE if appropriate; remove the per-pair tolist, norm, and dot calculations. Delete the unused confirmed_set variable while preserving concept exclusions, threshold handling, and merge behavior.
2410-2428: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAvoid exposing private helpers via
__all__. There are no outside-module imports for these underscore-prefixed helpers, so keep__all__limited to the real module entry points such aswiki_compile_incremental,wiki_handle_document_deleted, and the*_COMPILE_KWDconstants.🤖 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 2410 - 2428, Remove the underscore-prefixed helper names from __all__, including _wiki_reduce_entity and the other private functions, leaving only public module entry points such as wiki_compile_incremental, wiki_handle_document_deleted, and the *_COMPILE_KWD constants.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 `@conf/infinity_mapping.json`:
- Around line 89-92: Add the missing q_768_vec vector column definition to
conf/infinity_mapping.json, matching the existing q_{dim}_vec schema and the
expected 768-dimensional type used by _load_canonical_entities and
_save_canonical_entity, so canonical-entity reads and writes resolve the field.
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1849-1868: Replace the nested canonical_map traversal in the
concept enrichment block with a one-time chunk_id-to-text index built from
non-concept canonical claims, then intersect its keys with each page’s
concept_chunk_ids and append at most one source chunk per id. Preserve the
existing claim text fallback, and update the concept_deltas/canonical_map
iteration variables to avoid unused pid and cname symbols flagged by Ruff B007.
- Around line 409-448: The entity resolution flow should perform one KNN search
at ENTITY_AMBIGUOUS_LOW, classify each returned candidate by its score into
direct matches or maybe_pairs for LLM confirmation, and remove the redundant
_knn_search_canonical call and linear unmatched scan. Update the surrounding
zip-based entry/embedding handling and remove the unused score variable in the
enclosing logic, while preserving concept handling and still_unmatched behavior.
- Around line 114-159: Update _load_canonical_entities to request the vector
field matching the embedding dimension used by _save_canonical_entity, deriving
or reusing the model’s vector size instead of hardcoding q_768_vec. Also guard
JSON deserialization for aliases and source_doc_ids so malformed stored values
fall back safely without aborting the entire load. Preserve the existing
pagination and row aggregation behavior.
- Around line 189-211: Update the canonical artifact persistence flow around the
existing condition and docStoreConn.update call to include the same compile_kwd
constraint used when searching for the wiki record. Ensure updates target only
the WIKI_CANONICAL_ENTITY_COMPILE_KWD row for the entity, preventing graph-node
rows with the same entity_kwd from being overwritten.
- Around line 2260-2290: Update the canonical entity cleanup loop in the
deletion flow around _load_canonical_entities and _save_canonical_entity: remove
doc_id from source_doc_ids, then delete the canonical entity whenever the
resulting src_ids is empty. When sources remain, recompute mention_count_int
from the remaining source/claim data instead of decrementing mention_count_int
by one, and persist that recalculated count through _save_canonical_entity.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/wiki_incremental.py`:
- Around line 1445-1524: Remove the unused page_ids and embd_mdl parameters from
_wiki_finalize and update every call site accordingly. Collapse the identical
canonical-name and dead-link wikilink branches into one else path, and remove
the unused dead_links collection and stale docstring references to the ignored
filter.
- Around line 452-527: Optimize the pairwise deduplication in the intra-build
block around _find_parent by converting embeddings to a normalized NumPy matrix
once and using matrix multiplication for similarities, chunked with
ENTITY_PAIRWISE_BATCH_SIZE if appropriate; remove the per-pair tolist, norm, and
dot calculations. Delete the unused confirmed_set variable while preserving
concept exclusions, threshold handling, and merge behavior.
- Around line 2410-2428: Remove the underscore-prefixed helper names from
__all__, including _wiki_reduce_entity and the other private functions, leaving
only public module entry points such as wiki_compile_incremental,
wiki_handle_document_deleted, and the *_COMPILE_KWD constants.
🪄 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 Plus
Run ID: aac74169-f03e-4a8d-8327-77c3c3eaf13b
📒 Files selected for processing (2)
conf/infinity_mapping.jsonrag/advanced_rag/knowlege_compile/wiki_incremental.py
| "token_num": {"type": "integer", "default": 0}, | ||
|
|
||
| "aliases": {"type": "json", "default": "[]", "enabled": false}, | ||
| "aliases_flat_kwd": {"type": "varchar", "default": "", "analyzer": "whitespace-#"} |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
for f in entity_kwd entity_type_kwd aliases aliases_flat_kwd source_doc_ids mention_count_int compile_kwd page_id entity_names q_768_vec; do
printf '%-22s ' "$f"
rg -c "\"$f\"" conf/infinity_mapping.json || echo MISSING
doneRepository: infiniflow/ragflow
Length of output: 418
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate files =="
git ls-files | rg '(^|/)wiki_incremental\.py$|conf/infinity_mapping\.json$' || true
echo
echo "== infinity mapping lines == "
if [ -f conf/infinity_mapping.json ]; then
sed -n '1,140p' conf/infinity_mapping.json | cat -n
fi
echo
echo "== wiki_incremental occurrences =="
if [ -f rag/advanced_rag/knowlege_compile/wiki_incremental.py ]; then
echo "-- save/load relevant lines --"
rg -n "_save_canonical_entity|_load_canonical_entities|q_768_vec|entity_type_kwd|mention_count_int|page_id|source_doc_ids|compile_kwd|entity_kwd|aliases" rag/advanced_rag/knowlege_compile/wiki_incremental.py
echo "-- surrounding sections --"
line=$(rg -n "_save_canonical_entity|_load_canonical_entities" rag/advanced_rag/knowlege_compile/wiki_incremental.py | head -1 | cut -d: -f1 || true)
if [ -n "${line:-}" ]; then
start=$((line-25)); [ "$start" -lt 1 ] && start=1; end=$((line+90)); sed -n "${start},${end}p" rag/advanced_rag/knowlege_compile/wiki_incremental.py | cat -n
fi
fi
echo
echo "== all references to relevant symbols =="
rg -n "q_768_vec|entity_type_kwd|mention_count_int|_save_canonical_entity|_load_canonical_entities" -S .Repository: infiniflow/ragflow
Length of output: 35374
Declare the wiki incremental vector column in Infinity. _load_canonical_entities projects q_768_vec, and _save_canonical_entity can write q_768_vec as q_{dim}_vec, but conf/infinity_mapping.json has no q_768_vec column. Add it so canonical-entity inserts/selects don’t hit a missing-vector-field issue.
🤖 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 `@conf/infinity_mapping.json` around lines 89 - 92, Add the missing q_768_vec
vector column definition to conf/infinity_mapping.json, matching the existing
q_{dim}_vec schema and the expected 768-dimensional type used by
_load_canonical_entities and _save_canonical_entity, so canonical-entity reads
and writes resolve the field.
bb3a69c to
5617079
Compare
2. For no plan mode, both entity and concept will be build into a wiki
aa7313c to
6e4fe4a
Compare
fix: preserve wiki provenance and cache behavior
### Summary Refine wiki plan procedure. --------- Co-authored-by: Yingfeng Zhang <[email protected]> Co-authored-by: buua436 <[email protected]>
Summary
Refine wiki plan procedure.