Skip to content

Refactor: refine wiki plan procedure. - #17579

Merged
KevinHuSh merged 33 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search10
Aug 3, 2026
Merged

KevinHuSh merged 33 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search10

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

Refine wiki plan procedure.

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jul 30, 2026
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Incremental wiki compilation

Layer / File(s) Summary
Template plan configuration
api/db/init_data/compilation_templates/wiki.yaml, web/src/locales/*, web/src/pages/user-setting/compilation-templates/...
Adds plan defaults, artifact-only checkbox controls, payload handling, and localized labels.
Incremental task execution
rag/svr/task_executor_refactor/task_handler.py, rag/svr/task_executor_refactor/dataset_wiki_generator.py
Resolves plan mode, selects eligible documents, runs bounded MAP processing, and invokes incremental compilation.
Canonical entities and page compilation
rag/advanced_rag/knowlege_compile/wiki_incremental.py, conf/infinity_mapping.json, rag/advanced_rag/knowlege_compile/wiki.py
Adds canonical entity matching, affected-scope reduction, concurrent refinement, metadata preservation, routing, link finalization, and storage fields.
Document deletion cleanup
api/db/services/document_service.py, rag/advanced_rag/knowlege_compile/wiki_incremental.py
Updates canonical entities and affected pages, removes document-scoped tracking rows, and runs cleanup finalization.

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
Loading

Possibly related PRs

Suggested labels: 🌈 python, 🐖api

Poem

A rabbit plans pages beneath moonlight bright,
Canonical names hop into sight.
MAP gathers clues, REFINE takes flight,
Sources leave trails, then cleanup feels right.
Hop, hop—the wiki grows!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and related to the main change, though somewhat broad.
Description check ✅ Passed The description includes the required Summary section and is adequate for this template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jul 30, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

🧹 Nitpick comments (5)
api/db/services/document_service.py (1)

683-687: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Reuse the shared page-source compile keyword.

wiki_incremental.py writes these rows using WIKI_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 value

Collapse the synthesis/plan passthrough 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 win

Duplicate get_by_kb_id scan. 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

incremental is accepted but never used in either mode runner. Dead parameters on a brand-new internal API; drop them (and the corresponding arguments in wiki_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 value

Silent except: pass around the progress callbacks, and private helpers in __all__. The three _progress helpers swallow every exception without a log (Ruff S110/BLE001) — a persistently failing callback becomes invisible; logging.debug/exception there costs nothing. And __all__ exports six _-prefixed helpers (_wiki_reduce_entity, _wiki_page_router, _wiki_finalize, …), which contradicts keeping internal helpers private; export only wiki_compile_incremental, wiki_handle_document_deleted, and the *_COMPILE_KWD constants 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7af51f9 and 2385cbb.

📒 Files selected for processing (12)
  • api/db/init_data/compilation_templates/wiki.yaml
  • api/db/services/document_service.py
  • conf/infinity_mapping.json
  • rag/advanced_rag/knowlege_compile/wiki_incremental.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • rag/svr/task_executor_refactor/task_handler.py
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/create-next/utils.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/utils.ts

Comment on lines +684 to +694
res = settings.docStoreConn.search(
["id"],
[],
{"compile_kwd": [doc_page_kwd], "doc_id": [doc.id]},
[],
OrderByExpr(),
0,
10,
index,
doc.kb_id,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

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.

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

Comment thread conf/infinity_mapping.json Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Per-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 1171 extends it again for every delta routed to the same page_id. With k deltas per page the REFINE prompt receives k copies of the same claim list (token blowup and skewed content), while source_chunks on 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_names still isn't part of the doc_page_source record, so affected_names is always empty. The new fallback now silently promotes every incremental run to a full rebuild over all_names — parallelizing the loads doesn't help because each load returns no entity_names key. Persist entity_names (and select it in _wiki_load_doc_page_source) or derive affected names from map_results claims for affected_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

📥 Commits

Reviewing files that changed from the base of the PR and between 2385cbb and eb6d7ec.

📒 Files selected for processing (1)
  • rag/advanced_rag/knowlege_compile/wiki_incremental.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_checksum is requested from get_fields but never selected in the search — the just-added preservation fix is a no-op for it.

Line 283's search select_fields is ["id", "page_ids", "source_chunk_hashes"], but line 293's get_fields call asks for "map_checksum" too. Since it was never in the projected field list, existing_map rows won't carry it, so the "preserve existing map_checksum when 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_names is still never persisted, so deleted-doc name resolution remains broken.

_wiki_update_doc_page_source's write payload still only carries page_ids/source_chunk_hashes/map_checksum — no entity_names key. dps.get("entity_names", []) at line 1066 is therefore always []. The new new_doc_ids loop (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 from map_results, and the dps-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 by affected_names, so REDUCE may never compute their retraction/deletion here (any coverage would have to come entirely from the separate _wiki_delete_deleted_doc_state sweep in dataset_wiki_generator.py).

Persist entity_names on doc_page_source rows (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 win

Silently swallowed exception in a new flow.

except Exception: pass discards 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 lift

Deletion-cleanup projection still omits related_kb_pages_kwd/page_type_kwd.

This still matches a previously-raised concern: all_existing_pages here is only projected with ["slug_kwd","title_kwd","md_with_weight","claims","source_doc_ids","page_version_int","entity_names_kwd"], so related_kb_pages_kwd/page_type_kwd aren't loaded before the modify/delete calls into _wiki_mode_a_refine. Whether this actually wipes those fields depends on whether the doc store's update() 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 win

Duplicate template fetch per eligible doc.

CompilationTemplateService.get_saved(template_id, ...) is called once during eligibility filtering (line ~1391) and again for the same template_id while pre-resolving doc_configs (line ~1438) — doubling DB round-trips across all eligible docs for no functional benefit.

Capture the resolved config in the eligible tuple 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_finalize gained a page_ids narrowing filter but its only call site never uses it.

_wiki_finalize now correctly restricts wikilink relation-building to target_ids when page_ids is supplied, but wiki_compile_incremental still calls it as await _wiki_finalize(tenant_id, kb_id, embd_mdl) with no page_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_run through 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 win

Doc-page-source apply loop duplicated between Mode A and Mode B.

Both blocks independently load existing_dps, merge page_ids, and forward chunk_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

📥 Commits

Reviewing files that changed from the base of the PR and between eb6d7ec and 585b79b.

📒 Files selected for processing (5)
  • rag/advanced_rag/knowlege_compile/wiki_incremental.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • rag/svr/task_executor_refactor/task_handler.py
  • web/src/pages/user-setting/compilation-templates/create-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx

@yingfeng yingfeng added the ci Continue Integration label Jul 30, 2026
@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (29287ef) to head (d5337ff).
⚠️ Report is 37 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/wiki_incremental.py (3)

1445-1524: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

page_ids (and embd_mdl) are now unused parameters, and the two wikilink-stripping branches are identical with dead_links never 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 single else, or actually use dead_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 win

Intra-build pairwise dedup is O(n²) with per-pair conversion, and ENTITY_PAIRWISE_BATCH_SIZE is never used. ei/ej are re-converted with tolist() and re-normalized inside the inner loop for every pair. Normalize once into a matrix and take a single A @ A.T (or chunk it with the declared batch size), which collapses the cost and removes the unused constant. confirmed_set in 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 value

Avoid 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 as wiki_compile_incremental, wiki_handle_document_deleted, and the *_COMPILE_KWD constants.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 585b79b and 0be9e6c.

📒 Files selected for processing (2)
  • conf/infinity_mapping.json
  • rag/advanced_rag/knowlege_compile/wiki_incremental.py

Comment on lines +89 to +92
"token_num": {"type": "integer", "default": 0},

"aliases": {"type": "json", "default": "[]", "enabled": false},
"aliases_flat_kwd": {"type": "varchar", "default": "", "analyzer": "whitespace-#"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 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
done

Repository: 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.

@yingfeng
yingfeng force-pushed the feat/agentic_search10 branch from bb3a69c to 5617079 Compare July 30, 2026 17:20
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jul 31, 2026
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 31, 2026
@yingfeng yingfeng added ci Continue Integration and removed ci Continue Integration labels Jul 31, 2026
@yingfeng
yingfeng force-pushed the feat/agentic_search10 branch from aa7313c to 6e4fe4a Compare July 31, 2026 15:55
@KevinHuSh
KevinHuSh merged commit 3b4a96d into infiniflow:main Aug 3, 2026
5 checks passed
yuzhichang pushed a commit to yuzhichang/ragflow that referenced this pull request Aug 3, 2026
### Summary

Refine wiki plan procedure.

---------

Co-authored-by: Yingfeng Zhang <[email protected]>
Co-authored-by: buua436 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants