Skip to content

Feat: refine the tree navigation during compilations - #17140

Merged
yingfeng merged 20 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search4
Jul 23, 2026
Merged

yingfeng merged 20 commits into
infiniflow:mainfrom
KevinHuSh:feat/agentic_search4

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

Refine the tree navigations druing compilations

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 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

Adds dataset-scoped structure graphs, navigation generation and management APIs, wiki alteration detection, provenance-aware artifact cleanup, compiled skill deletion, safer vector handling, invalid structure filtering, and compiler template-group normalization.

Changes

Dataset structure and management

Layer / File(s) Summary
Structure validation and dataset-scope merging
rag/advanced_rag/knowlege_compile/structure.py, rag/advanced_rag/knowlege_compile/_common.py
Filters invalid structure payloads, supports dataset-scope graph merging with locking, migrates storage helpers, and persists dataset structure graphs.
Compilation and navigation generation
rag/advanced_rag/knowlege_compile/runner.py, rag/advanced_rag/knowlege_compile/dataset_nav.py
Rebuilds dataset and page-index graphs, coordinates merge sequencing, upserts navigation, hardens vector handling, and generates readable deterministic navigation names.
Wiki provenance and artifact cleanup
rag/advanced_rag/knowlege_compile/wiki.py, rag/svr/task_executor_refactor/dataset_wiki_generator.py, api/db/services/document_service.py, rag/utils/infinity_conn.py
Persists source document provenance through wiki products, removes stale or unshared derived rows, and stores provenance fields as keyword-like values.
Wiki eligibility and skill management
rag/svr/task_executor_refactor/dataset_wiki_generator.py, api/apps/services/dataset_api_service.py, rag/flow/compiler/compiler.py
Resolves wiki templates from parser and pipeline configuration, reports document alterations, normalizes template-group inputs, and deletes compiled skills.
Dataset navigation and artifact APIs
api/apps/services/dataset_api_service.py, api/apps/restful_apis/dataset_api.py
Adds structure, wiki alteration, navigation listing/deletion, and skill deletion operations with standardized REST responses.
Compilation and retrieval behavior
rag/advanced_rag/knowlege_compile/raptor.py, rag/nlp/search.py
Preserves tuple-shaped tree compilation exits and updates fused retrieval weights.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant StructureCompiler
  participant DatasetGraphRebuilder
  participant DatasetNavigation
  StructureCompiler->>DatasetGraphRebuilder: rebuild dataset structure graph
  DatasetGraphRebuilder-->>StructureCompiler: return graph and compile keywords
  StructureCompiler->>DatasetNavigation: upsert page-index summaries
Loading

Suggested reviewers: buua436, lynn-inf, wangq8

Poem

I’m a rabbit with routes in my paws,
Sorting nav trees by readable laws.
Skills may vanish, nodes gently part,
Safe vectors hop from chart to chart.
“-1” slips away unseen—
While provenance keeps paths clean!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description only repeats a vague summary and lacks useful background or specifics beyond the required heading. Expand the Summary with the problem context, key changes, and the intended impact of the compilation navigation update.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title matches a real part of the PR and concisely points to the navigation changes, even though the PR is broader than tree navigation.

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.

@JinHai-CN JinHai-CN changed the title Feat: refine the tree navigations druing compilations Feat: refine the tree navigations during compilations Jul 21, 2026
@JinHai-CN JinHai-CN changed the title Feat: refine the tree navigations during compilations Feat: refine the tree navigation during compilations Jul 21, 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: 1

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/dataset_nav.py (1)

319-349: 🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift

_make_nav_doc_row's new hash-based name breaks _maybe_split_cluster's doc-leaf lookup.

name used to equal doc_id for nav_doc rows; now it's f"{parent_kwd}_{hash(summary)}" (Line 336), while doc_id is still stored separately in the doc_id field. That's fine for reads that use row.get("doc_id") first (e.g. _nav_item in dataset_api_service.py, search_dataset_nav below), but _maybe_split_cluster (unchanged code, same file) derives the row id for doc children as cid = _nav_doc_id(kn) where kn is the row's name (see the for kn in kid_names: loops around the description-aggregation and reparenting steps). Since _nav_doc_id expects a doc_id (confirmed by _store_get(tenant_id, kb_id, _nav_doc_id(doc_id)) in upsert_dataset_nav_doc), and kn is no longer the doc_id, _store_get will not find the row for any nav_doc child. Effect: whenever a cluster's fanout triggers a split, document leaves under it are silently skipped from the new sub-cluster's doc_ids/description aggregation, and are never reparented — they stay attached to the pre-split parent, orphaned/duplicated in the tree view. This isn't a rare edge case; it fires on every fanout-triggered split.

(Side note, same root cause: the comment in search_dataset_nav at "Leaf: name == the document id" is now stale — worth updating for clarity even though the fallback there still works.)

🛠️ Proposed fix: resolve doc-leaf ids via `doc_id`, not `name`
     child_details = await _store_search(
         tenant_id,
         kb_id,
         child_cond,
-        ["id", "name", "type_kwd", "content_with_weight", vf],
+        ["id", "name", "type_kwd", "content_with_weight", "doc_id", vf],
         limit=200,
     )
     embeddings = []
     names = []
     name_to_type: dict[str, str] = {}
+    name_to_doc_id: dict[str, str] = {}
     for c in child_details:
         stored = c.get(vf)
         if stored:
             embeddings.append(stored)
             names.append(c.get("name", ""))
         cn = c.get("name", "")
         if cn:
             name_to_type[cn] = c.get("type_kwd", "nav_cluster")
+            if c.get("type_kwd") == "nav_doc":
+                name_to_doc_id[cn] = c.get("doc_id", "")

Then, in both for kn in kid_names: loops later in _maybe_split_cluster:

-            is_doc = name_to_type.get(kn) == "nav_doc"
-            cid = _nav_doc_id(kn) if is_doc else _nav_cluster_id(kb_id, kn)
+            is_doc = name_to_type.get(kn) == "nav_doc"
+            cid = _nav_doc_id(name_to_doc_id.get(kn, kn)) if is_doc else _nav_cluster_id(kb_id, kn)
🤖 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/dataset_nav.py` around lines 319 - 349,
Update both kid_names loops in _maybe_split_cluster to resolve nav_doc leaves
using the row’s doc_id field before deriving _nav_doc_id, rather than treating
name as the document identifier. Preserve cluster handling and ensure document
leaves are included in description/doc_ids aggregation and reparented during
splits. Also update the stale search_dataset_nav comment to state that nav_doc
name is not the document id.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 2047-2063: Update the JSON parsing exception handler in _nav_item
to log the caught parse failure using the service’s existing logging pattern,
then retain payload = {} as the fallback so malformed content still produces a
valid UI node. Match the logging approach used by the sibling _nav_search
implementation.

---

Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/dataset_nav.py`:
- Around line 319-349: Update both kid_names loops in _maybe_split_cluster to
resolve nav_doc leaves using the row’s doc_id field before deriving _nav_doc_id,
rather than treating name as the document identifier. Preserve cluster handling
and ensure document leaves are included in description/doc_ids aggregation and
reparented during splits. Also update the stale search_dataset_nav comment to
state that nav_doc name is not the document id.
🪄 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

Run ID: 6785f85c-b3cc-467d-ae0b-5d7d03475fca

📥 Commits

Reviewing files that changed from the base of the PR and between 161d2f0 and 18a1ae4.

📒 Files selected for processing (7)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/init_data/compilation_templates/empty.yaml
  • rag/advanced_rag/knowlege_compile/dataset_nav.py
  • rag/advanced_rag/knowlege_compile/raptor.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
💤 Files with no reviewable changes (1)
  • api/db/init_data/compilation_templates/empty.yaml

Comment on lines +2047 to +2063
def _nav_item(row: dict) -> dict:
"""Shape one nav row into a UI node: name, description, doc count, type."""
try:
payload = json.loads(row.get("content_with_weight") or "{}")
except Exception:
payload = {}
is_cluster = (row.get("type_kwd") or payload.get("type")) == "nav_cluster"
return {
"name": row.get("name") or "",
"description": payload.get("description") or "",
# doc_id count under this node: the cluster's tally, or 1 for a leaf.
"doc_count": int(row.get("doc_count_int") or 0) if is_cluster else 1,
"type": "cluster" if is_cluster else "doc",
"doc_id": None if is_cluster else (row.get("doc_id") or row.get("name")),
"has_children": is_cluster,
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Log the parse failure instead of swallowing it silently.

_nav_item's except Exception: payload = {} (flagged by Ruff BLE001) drops the error entirely, unlike the sibling _nav_search which logs failures. A malformed content_with_weight would silently degrade the UI (empty description) with no trace. As per coding guidelines, **/*.py: "Add logging for new flows".

🩹 Proposed fix
     try:
         payload = json.loads(row.get("content_with_weight") or "{}")
-    except Exception:
+    except Exception:
+        logging.exception("dataset_nav: failed to parse content_with_weight for row id=%s", row.get("id"))
         payload = {}
📝 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
def _nav_item(row: dict) -> dict:
"""Shape one nav row into a UI node: name, description, doc count, type."""
try:
payload = json.loads(row.get("content_with_weight") or "{}")
except Exception:
payload = {}
is_cluster = (row.get("type_kwd") or payload.get("type")) == "nav_cluster"
return {
"name": row.get("name") or "",
"description": payload.get("description") or "",
# doc_id count under this node: the cluster's tally, or 1 for a leaf.
"doc_count": int(row.get("doc_count_int") or 0) if is_cluster else 1,
"type": "cluster" if is_cluster else "doc",
"doc_id": None if is_cluster else (row.get("doc_id") or row.get("name")),
"has_children": is_cluster,
}
def _nav_item(row: dict) -> dict:
"""Shape one nav row into a UI node: name, description, doc count, type."""
try:
payload = json.loads(row.get("content_with_weight") or "{}")
except Exception:
logging.exception("dataset_nav: failed to parse content_with_weight for row id=%s", row.get("id"))
payload = {}
is_cluster = (row.get("type_kwd") or payload.get("type")) == "nav_cluster"
return {
"name": row.get("name") or "",
"description": payload.get("description") or "",
# doc_id count under this node: the cluster's tally, or 1 for a leaf.
"doc_count": int(row.get("doc_count_int") or 0) if is_cluster else 1,
"type": "cluster" if is_cluster else "doc",
"doc_id": None if is_cluster else (row.get("doc_id") or row.get("name")),
"has_children": is_cluster,
}
🧰 Tools
🪛 Ruff (0.15.21)

[warning] 2051-2051: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 2047 - 2063, Update
the JSON parsing exception handler in _nav_item to log the caught parse failure
using the service’s existing logging pattern, then retain payload = {} as the
fallback so malformed content still produces a valid UI node. Match the logging
approach used by the sibling _nav_search implementation.

Sources: Coding guidelines, Linters/SAST tools

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

codecov Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17140   +/-   ##
=======================================
  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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rag/flow/compiler/compiler.py`:
- Around line 53-57: Update Compiler.check to normalize
compilation_template_group_ids before calling check_empty: convert a string to a
trimmed value or list form, and discard or reject blank IDs consistently with
the existing normalizers. Then validate the normalized result with check_empty,
preserving validation for non-string inputs.
🪄 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

Run ID: 04243fa6-1381-4a65-b349-a4750ae806ea

📥 Commits

Reviewing files that changed from the base of the PR and between 18a1ae4 and d0c53b4.

📒 Files selected for processing (1)
  • rag/flow/compiler/compiler.py

Comment on lines 53 to +57
def check(self):
super().check()
self.check_empty(self.compilation_template_group_ids, "Compilation Template Groups")
if isinstance(self.compilation_template_group_ids, str):
self.compilation_template_group_ids = [self.compilation_template_group_ids]

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize before validating template group IDs.

Line 55 calls check_empty before the string is converted, and the conversion does not trim whitespace. A value such as " " can therefore become [" "] and pass validation if check_empty checks truthiness, while related normalizers already trim and discard empty IDs. Move normalization before check_empty and reject blank strings.

Proposed fix
     def check(self):
         super().check()
-        self.check_empty(self.compilation_template_group_ids, "Compilation Template Groups")
         if isinstance(self.compilation_template_group_ids, str):
-            self.compilation_template_group_ids = [self.compilation_template_group_ids]
+            group_id = self.compilation_template_group_ids.strip()
+            self.compilation_template_group_ids = [group_id] if group_id else []
+        self.check_empty(self.compilation_template_group_ids, "Compilation Template Groups")
📝 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
def check(self):
super().check()
self.check_empty(self.compilation_template_group_ids, "Compilation Template Groups")
if isinstance(self.compilation_template_group_ids, str):
self.compilation_template_group_ids = [self.compilation_template_group_ids]
def check(self):
super().check()
if isinstance(self.compilation_template_group_ids, str):
group_id = self.compilation_template_group_ids.strip()
self.compilation_template_group_ids = [group_id] if group_id else []
self.check_empty(self.compilation_template_group_ids, "Compilation Template Groups")
🤖 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/flow/compiler/compiler.py` around lines 53 - 57, Update Compiler.check to
normalize compilation_template_group_ids before calling check_empty: convert a
string to a trimmed value or list form, and discard or reject blank IDs
consistently with the existing normalizers. Then validate the normalized result
with check_empty, preserving validation for non-string inputs.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
api/apps/services/dataset_api_service.py (3)

2351-2376: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Same blocking-call issue as _nav_search (see consolidated comment).

delete_nav calls settings.docStoreConn.delete(...) directly from an async function without offloading.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 2351 - 2376, The async
delete_nav function performs the blocking docStoreConn.delete call directly.
Offload that delete operation to the project’s established worker-thread or
async execution mechanism, preserving its arguments, exception handling, and
deleted-count response.

2379-2442: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Same blocking-call issue, compounded by up to 64 sequential blocking searches per request.

delete_nav_node's subtree-collection loop performs up to 64 sequential, unoffloaded settings.docStoreConn.search calls (plus the final unoffloaded .delete), all inside an async request handler. This is the most severe instance of the pattern flagged in the consolidated comment below, since it multiplies event-loop blocking time by tree depth.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 2379 - 2442, The async
delete_nav_node function performs blocking doc-store search and delete
operations directly on the event loop, potentially repeating searches up to 64
times. Offload each settings.docStoreConn.search and the final
settings.docStoreConn.delete to the project’s established async/thread execution
mechanism, preserving the existing subtree traversal, error handling, and return
behavior.

2280-2323: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Blocking docStoreConn.search call not offloaded, unlike get_wiki_alteration above.

_nav_search calls settings.docStoreConn.search(...) synchronously inside an async def. This blocks the event loop for every list_nav_clusters/list_nav_children request. get_wiki_alteration in this same file already establishes the correct pattern (await thread_pool_exec(settings.docStoreConn.search, ...)) for the identical call. See the consolidated comment below covering this and the sibling delete_nav/delete_nav_node functions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 2280 - 2323, The
synchronous settings.docStoreConn.search call in _nav_search blocks the async
event loop. Match the established get_wiki_alteration pattern by invoking the
search through thread_pool_exec and awaiting it, while preserving the existing
arguments, result handling, and exception behavior; apply the same offloading to
the sibling delete_nav and delete_nav_node search calls if present.
🧹 Nitpick comments (4)
rag/svr/task_executor_refactor/dataset_wiki_generator.py (2)

168-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

LGTM overall; conceptually overlaps with dataset_api_service.py's pipeline-wiki helpers.

_pipeline_compilation_template_ids resolves the same pipeline-DSL → group-ids → template-ids chain that _pipeline_has_wiki_compiler/_group_has_wiki_template in api/apps/services/dataset_api_service.py re-implement for a boolean check. Not a strict duplicate, but worth factoring into the same shared module suggested below.

🤖 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 168 -
189, Factor the shared pipeline DSL-to-compilation-template resolution into a
common helper module, and update _pipeline_compilation_template_ids plus
_pipeline_has_wiki_compiler/_group_has_wiki_template to reuse it. Preserve the
existing tenant scoping, deduplication, and boolean-check behavior while
removing the duplicated resolution logic.

756-776: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Eligibility merge logic looks correct; consider caching CompilationTemplateService.get_saved per template id.

The merge/dedup of parser-config and pipeline-derived template ids is correct. However, the subsequent for template_id in template_ids: template = CompilationTemplateService.get_saved(...) loop (just below, unchanged) now has a larger candidate set per doc and still does one DB lookup per template id per doc with no cache, unlike the sibling pipeline_template_ids_cache. For KBs where many docs share the same template/group, this repeats identical lookups across docs.

♻️ Proposed fix
     eligible = []
     pipeline_template_ids_cache: dict[str, list[str]] = {}
+    template_kind_cache: dict[str, str] = {}
     for d in all_docs or []:
         for template_id in template_ids:
-            template = CompilationTemplateService.get_saved(template_id, ctx.tenant_id)
-            config = template.get("config") if template else {}
-            kind = _compilation_template_kind(config.get("kind") if isinstance(config, dict) else "")
+            if template_id not in template_kind_cache:
+                template = CompilationTemplateService.get_saved(template_id, ctx.tenant_id)
+                config = template.get("config") if template else {}
+                template_kind_cache[template_id] = _compilation_template_kind(config.get("kind") if isinstance(config, dict) else "")
+            kind = template_kind_cache[template_id]
             if kind == "artifacts":
                 eligible.append((d, template_id))
                 break
🤖 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 756 -
776, Cache CompilationTemplateService.get_saved results by template ID while
processing template_ids in the surrounding document-generation flow. Reuse the
cached result for repeated IDs across documents, including missing results if
applicable, and preserve the existing template processing behavior after
retrieval; keep the existing pipeline_template_ids_cache unchanged.
api/apps/services/dataset_api_service.py (2)

1567-1622: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

LGTM logic-wise; part of the same overlapping "resolve pipeline → wiki eligibility" surface.

_template_is_wiki, _group_has_wiki_template, _parser_config_has_wiki_template, and _pipeline_has_wiki_compiler are correctly cached and reuse the shared _parser_config_compilation_template_ids from chunk_post_processor, which is good. They do, however, re-derive the same "pipeline DSL → compiler group ids" chain that dataset_wiki_generator.py's _pipeline_compilation_template_ids already implements — see consolidated duplication comment.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 1567 - 1622, Reuse the
existing pipeline DSL-to-compiler-group resolution implemented by
dataset_wiki_generator.py’s _pipeline_compilation_template_ids instead of
re-deriving it in _pipeline_has_wiki_compiler. Update that helper to call the
shared resolver while preserving its existing caching and wiki-template
eligibility checks.

1505-1511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse the shared kind normalizer This repeats the same normalization used in api.apps.restful_apis.chunk_api._compilation_template_kind; extract it into one shared helper and reuse it here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 1505 - 1511, Extract
the normalization logic from _compilation_template_kind into a shared helper,
then update both api.apps.restful_apis.chunk_api._compilation_template_kind and
this _compilation_template_kind to delegate to it. Preserve the existing
handling for non-string values, trimming, lowercasing, hyphen conversion, and
timeline aliases.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1514-1528: The dataset service duplicates
_normalize_compilation_template_group_ids and
_extract_pipeline_compiler_group_ids from dataset_wiki_generator.py; remove the
duplicate implementations and reuse the existing shared definitions or extract
them into a common module, updating callers to import that single source.
- Around line 1693-1727: Update the search loop in the get_wiki_alteration flow
so failures from settings.docStoreConn.search or get_fields do not continue as
an empty successful result. Propagate the exception to the caller (while
preserving the existing logging if appropriate), ensuring removed_doc_ids is not
computed from incomplete wiki-involved document data.

In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 115-129: Remove the duplicated
_normalize_compilation_template_group_ids and
_extract_pipeline_compiler_group_ids implementations from dataset_api_service.py
and reuse the canonical definitions from dataset_wiki_generator.py through the
existing shared import/module boundary. Update callers as needed while
preserving their current normalization and extraction behavior.

---

Outside diff comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 2351-2376: The async delete_nav function performs the blocking
docStoreConn.delete call directly. Offload that delete operation to the
project’s established worker-thread or async execution mechanism, preserving its
arguments, exception handling, and deleted-count response.
- Around line 2379-2442: The async delete_nav_node function performs blocking
doc-store search and delete operations directly on the event loop, potentially
repeating searches up to 64 times. Offload each settings.docStoreConn.search and
the final settings.docStoreConn.delete to the project’s established async/thread
execution mechanism, preserving the existing subtree traversal, error handling,
and return behavior.
- Around line 2280-2323: The synchronous settings.docStoreConn.search call in
_nav_search blocks the async event loop. Match the established
get_wiki_alteration pattern by invoking the search through thread_pool_exec and
awaiting it, while preserving the existing arguments, result handling, and
exception behavior; apply the same offloading to the sibling delete_nav and
delete_nav_node search calls if present.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1567-1622: Reuse the existing pipeline DSL-to-compiler-group
resolution implemented by dataset_wiki_generator.py’s
_pipeline_compilation_template_ids instead of re-deriving it in
_pipeline_has_wiki_compiler. Update that helper to call the shared resolver
while preserving its existing caching and wiki-template eligibility checks.
- Around line 1505-1511: Extract the normalization logic from
_compilation_template_kind into a shared helper, then update both
api.apps.restful_apis.chunk_api._compilation_template_kind and this
_compilation_template_kind to delegate to it. Preserve the existing handling for
non-string values, trimming, lowercasing, hyphen conversion, and timeline
aliases.

In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 168-189: Factor the shared pipeline DSL-to-compilation-template
resolution into a common helper module, and update
_pipeline_compilation_template_ids plus
_pipeline_has_wiki_compiler/_group_has_wiki_template to reuse it. Preserve the
existing tenant scoping, deduplication, and boolean-check behavior while
removing the duplicated resolution logic.
- Around line 756-776: Cache CompilationTemplateService.get_saved results by
template ID while processing template_ids in the surrounding document-generation
flow. Reuse the cached result for repeated IDs across documents, including
missing results if applicable, and preserve the existing template processing
behavior after retrieval; keep the existing pipeline_template_ids_cache
unchanged.
🪄 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

Run ID: 97e7f7ec-c60c-4fc7-9313-7fecb330d3d6

📥 Commits

Reviewing files that changed from the base of the PR and between d0c53b4 and 52d52d6.

📒 Files selected for processing (3)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/dataset_api.py

Comment on lines +1514 to +1528
def _normalize_compilation_template_group_ids(raw) -> list[str]:
if isinstance(raw, str):
raw = [raw]
if not isinstance(raw, list):
return []
ids: list[str] = []
seen: set[str] = set()
for group_id in raw:
if not isinstance(group_id, str):
continue
group_id = group_id.strip()
if group_id and group_id not in seen:
seen.add(group_id)
ids.append(group_id)
return ids

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Duplicated verbatim from rag/svr/task_executor_refactor/dataset_wiki_generator.py.

_normalize_compilation_template_group_ids (1514-1528) and _extract_pipeline_compiler_group_ids (1531-1564) are byte-for-byte copies of the functions of the same name added in rag/svr/task_executor_refactor/dataset_wiki_generator.py (lines 115-129 and 132-165). See the consolidated comment below.

Also applies to: 1531-1564

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 1514 - 1528, The
dataset service duplicates _normalize_compilation_template_group_ids and
_extract_pipeline_compiler_group_ids from dataset_wiki_generator.py; remove the
duplicate implementations and reuse the existing shared definitions or extract
them into a common module, updating callers to import that single source.

Source: Coding guidelines

Comment on lines +1693 to +1727
offset = 0
page_size = 1000
while True:
try:
res = await thread_pool_exec(
settings.docStoreConn.search,
select_fields=select_fields,
highlight_fields=[],
condition={"compile_kwd": [WIKI_PAGE_COMPILE_KWD]},
match_expressions=[],
order_by=OrderByExpr(),
offset=offset,
limit=page_size,
index_names=index_nm,
knowledgebase_ids=[dataset_id],
)
rows = settings.docStoreConn.get_fields(res, select_fields) or {}
except Exception:
logging.exception("get_wiki_alteration: docStore search failed for kb=%s", dataset_id)
rows = {}

if not rows:
break
for row in rows.values():
source_doc_ids = row.get("source_doc_ids")
if isinstance(source_doc_ids, str):
source_doc_ids = [source_doc_ids]
if not isinstance(source_doc_ids, list):
continue
wiki_involved_doc_ids.update(str(doc_id) for doc_id in source_doc_ids if doc_id)

offset += page_size
total = settings.docStoreConn.get_total(res)
if not total or offset >= int(total):
break

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 | 🟡 Minor | ⚡ Quick win

Search failure silently degrades to "no wiki-involved docs" instead of surfacing the error.

On exception, rows = {} and the loop immediately breaks via if not rows: break. If this happens on the very first page, wiki_involved_doc_ids stays empty for the whole run, so removed_doc_ids (wiki_involved_doc_ids - current_doc_ids) silently reports 0 instead of reflecting the actual (unknown) state. Callers using this endpoint to decide whether to re-run the wiki pipeline could wrongly conclude there's no drift.

🩹 Proposed fix
             try:
                 res = await thread_pool_exec(...)
                 rows = settings.docStoreConn.get_fields(res, select_fields) or {}
             except Exception:
                 logging.exception("get_wiki_alteration: docStore search failed for kb=%s", dataset_id)
-                rows = {}
+                return False, "Failed to compute wiki alteration."
📝 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
offset = 0
page_size = 1000
while True:
try:
res = await thread_pool_exec(
settings.docStoreConn.search,
select_fields=select_fields,
highlight_fields=[],
condition={"compile_kwd": [WIKI_PAGE_COMPILE_KWD]},
match_expressions=[],
order_by=OrderByExpr(),
offset=offset,
limit=page_size,
index_names=index_nm,
knowledgebase_ids=[dataset_id],
)
rows = settings.docStoreConn.get_fields(res, select_fields) or {}
except Exception:
logging.exception("get_wiki_alteration: docStore search failed for kb=%s", dataset_id)
rows = {}
if not rows:
break
for row in rows.values():
source_doc_ids = row.get("source_doc_ids")
if isinstance(source_doc_ids, str):
source_doc_ids = [source_doc_ids]
if not isinstance(source_doc_ids, list):
continue
wiki_involved_doc_ids.update(str(doc_id) for doc_id in source_doc_ids if doc_id)
offset += page_size
total = settings.docStoreConn.get_total(res)
if not total or offset >= int(total):
break
offset = 0
page_size = 1000
while True:
try:
res = await thread_pool_exec(
settings.docStoreConn.search,
select_fields=select_fields,
highlight_fields=[],
condition={"compile_kwd": [WIKI_PAGE_COMPILE_KWD]},
match_expressions=[],
order_by=OrderByExpr(),
offset=offset,
limit=page_size,
index_names=index_nm,
knowledgebase_ids=[dataset_id],
)
rows = settings.docStoreConn.get_fields(res, select_fields) or {}
except Exception:
logging.exception("get_wiki_alteration: docStore search failed for kb=%s", dataset_id)
return False, "Failed to compute wiki alteration."
if not rows:
break
for row in rows.values():
source_doc_ids = row.get("source_doc_ids")
if isinstance(source_doc_ids, str):
source_doc_ids = [source_doc_ids]
if not isinstance(source_doc_ids, list):
continue
wiki_involved_doc_ids.update(str(doc_id) for doc_id in source_doc_ids if doc_id)
offset += page_size
total = settings.docStoreConn.get_total(res)
if not total or offset >= int(total):
break
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 1693 - 1727, Update
the search loop in the get_wiki_alteration flow so failures from
settings.docStoreConn.search or get_fields do not continue as an empty
successful result. Propagate the exception to the caller (while preserving the
existing logging if appropriate), ensuring removed_doc_ids is not computed from
incomplete wiki-involved document data.

Comment on lines +115 to +129
def _normalize_compilation_template_group_ids(raw) -> list[str]:
if isinstance(raw, str):
raw = [raw]
if not isinstance(raw, list):
return []
ids: list[str] = []
seen: set[str] = set()
for group_id in raw:
if not isinstance(group_id, str):
continue
group_id = group_id.strip()
if group_id and group_id not in seen:
seen.add(group_id)
ids.append(group_id)
return ids

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Duplicated verbatim in api/apps/services/dataset_api_service.py.

_normalize_compilation_template_group_ids and _extract_pipeline_compiler_group_ids are copied identically into api/apps/services/dataset_api_service.py (lines 1514-1528 and 1531-1564). See the consolidated comment below for the proposed fix.

Also applies to: 132-165

🤖 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 115 -
129, Remove the duplicated _normalize_compilation_template_group_ids and
_extract_pipeline_compiler_group_ids implementations from dataset_api_service.py
and reuse the canonical definitions from dataset_wiki_generator.py through the
existing shared import/module boundary. Update callers as needed while
preserving their current normalization and extraction behavior.

Source: Coding guidelines

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 22, 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: 3

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/structure.py (1)

2559-2598: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Dataset merge lock can expire before _struct_es_dedup_batch() finishes. In rag/advanced_rag/knowlege_compile/structure.py:2559-2598, the lock is held across KNN/LLM/embedding/insertion work, but valkey.lock.Lock does not auto-renew. A merge that runs past _STRUCT_MERGE_LOCK_TIMEOUT_S = 60 can lose the lock while still active, let another worker enter, and reintroduce duplicates. The acquire-failure path also falls back to unlocked execution.

🤖 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/structure.py` around lines 2559 - 2598, The
dataset lock in merge_compiled_structures must remain held for the entire
_struct_es_dedup_batch operation and must not permit unlocked fallback. Add lock
renewal/watchdog handling for RedisDistributedLock so it cannot expire during
KNN/LLM/embedding work, and ensure acquisition failure aborts or safely skips
the merge instead of proceeding without the lock. Preserve release cleanup for
successfully acquired locks.
🧹 Nitpick comments (1)
rag/advanced_rag/knowlege_compile/runner.py (1)

488-529: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift

Dataset-graph rebuild is repeated on every document-parse completion.

This block runs a full KB-wide rebuild for each dataset-scope template on every document parse, and each rebuild_dataset_structure_graph_json reads all entities/relations across the whole KB and rewrites the dataset_graph row. As the comment notes, only the last document to finish produces the authoritative graph, so with N documents this is ~O(N × KB-size) of redundant reads/writes. Consider debouncing this to fire once after the final flush for the KB (e.g. a dedicated post-parse job or a per-kb "rebuild pending" flag) rather than per document.

Also note _struct_rebuild_graph_json caps the ES read at 10000 rows, so a large dataset graph may be silently truncated.

🤖 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/runner.py` around lines 488 - 529, Move the
dataset-scope rebuild currently performed in the per-document completion flow
around rebuild_dataset_structure_graph_json out of that loop and schedule it
once after the final KB flush, using a per-KB pending flag or dedicated
post-parse job. Preserve cancellation, progress reporting, template/kind
resolution, and best-effort error handling while ensuring multiple documents
cannot trigger duplicate rebuilds. Also update _struct_rebuild_graph_json to
read all entity/relation rows rather than truncating at 10,000.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 1785-1788: Update the JSON parsing block for content_with_weight
to catch the relevant JSON input exception explicitly, log the row’s tid and
malformed-payload context, then continue skipping that row. Preserve the
existing fallback for missing content and the current graph-processing flow for
valid payloads.

In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 503-506: Update the template-loading path around
CompilationTemplateService.get_saved to execute the synchronous database call
through thread_pool_exec, while preserving the existing template_id and
tenant_id arguments and saved_template handling. Keep the surrounding async flow
and structure_kind derivation unchanged.

In `@rag/nlp/search.py`:
- Line 210: Update the FusionExpr configuration in the search flow to use
weights "0.001,0.999" instead of "0.001,1", ensuring lexical relevance retains a
0.001 boost while vector similarity receives 0.999.

---

Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 2559-2598: The dataset lock in merge_compiled_structures must
remain held for the entire _struct_es_dedup_batch operation and must not permit
unlocked fallback. Add lock renewal/watchdog handling for RedisDistributedLock
so it cannot expire during KNN/LLM/embedding work, and ensure acquisition
failure aborts or safely skips the merge instead of proceeding without the lock.
Preserve release cleanup for successfully acquired locks.

---

Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/runner.py`:
- Around line 488-529: Move the dataset-scope rebuild currently performed in the
per-document completion flow around rebuild_dataset_structure_graph_json out of
that loop and schedule it once after the final KB flush, using a per-KB pending
flag or dedicated post-parse job. Preserve cancellation, progress reporting,
template/kind resolution, and best-effort error handling while ensuring multiple
documents cannot trigger duplicate rebuilds. Also update
_struct_rebuild_graph_json to read all entity/relation rows rather than
truncating at 10,000.
🪄 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

Run ID: a5575d3a-53c7-4fbf-b9f8-04b5fce22f85

📥 Commits

Reviewing files that changed from the base of the PR and between 52d52d6 and be3c7b8.

📒 Files selected for processing (5)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/nlp/search.py

Comment on lines +1785 to +1788
try:
graph = json.loads(row.get("content_with_weight") or "{}")
except Exception:
continue

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

ruff check api/apps/services/dataset_api_service.py --select S112,BLE001

Repository: infiniflow/ragflow

Length of output: 8157


🏁 Script executed:

sed -n '1768,1795p' api/apps/services/dataset_api_service.py

Repository: infiniflow/ragflow

Length of output: 1261


Log malformed content_with_weight payloads before skipping them. A bad row is dropped silently here, so partial structure responses are hard to trace. Catch the JSON input errors explicitly and log tid before continuing.

🧰 Tools
🪛 Ruff (0.15.21)

[error] 1787-1788: try-except-continue detected, consider logging the exception

(S112)


[warning] 1787-1787: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/dataset_api_service.py` around lines 1785 - 1788, Update
the JSON parsing block for content_with_weight to catch the relevant JSON input
exception explicitly, log the row’s tid and malformed-payload context, then
continue skipping that row. Preserve the existing fallback for missing content
and the current graph-processing flow for valid payloads.

Sources: Coding guidelines, Linters/SAST tools

Comment on lines 503 to +506
try:
await cleanup_timeline_isolated_entities(
tenant_id,
kb_id,
doc_id,
compilation_template_id=template_id,
)
saved_template = CompilationTemplateService.get_saved(template_id, tenant_id)
if saved_template:
structure_kind = (saved_template.get("kind") or "").strip() or None

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether Peewee service calls are wrapped for async or called directly elsewhere.
rg -nP -C2 'CompilationTemplateService\.get_saved' --type=py
rg -nP -C2 'thread_pool_exec\([^)]*Service' --type=py | head -50

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file and inspect the surrounding code path.
wc -l rag/advanced_rag/knowlege_compile/runner.py
ast-grep outline rag/advanced_rag/knowlege_compile/runner.py --view expanded
sed -n '460,540p' rag/advanced_rag/knowlege_compile/runner.py

# Inspect the service implementation and nearby async call sites.
fd -a 'CompilationTemplateService*' .
rg -n -C 3 'class CompilationTemplateService|def get_saved|async def|thread_pool_exec|run_in_executor|to_thread' rag -g '*.py'

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the exact runner flow around the call site.
sed -n '480,520p' rag/advanced_rag/knowlege_compile/runner.py

# Locate the service implementation and its call style.
fd -a 'CompilationTemplateService*.py' .
rg -n -C 4 'class CompilationTemplateService|def get_saved|get_saved\(' rag common -g '*.py'

# Look for nearby async patterns around this service in the same area.
rg -n -C 3 'CompilationTemplateService|thread_pool_exec|to_thread|run_in_executor' rag/advanced_rag/knowlege_compile -g '*.py'

Repository: infiniflow/ragflow

Length of output: 45861


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the service implementation to see whether it is a plain Peewee lookup.
sed -n '1,220p' api/db/services/compilation_template_service.py

# Check whether the service exposes any async wrapper or helper elsewhere.
rg -n -C 3 'CompilationTemplateService|get_saved|thread_pool_exec|to_thread|run_in_executor' api/db/services -g '*.py'

Repository: infiniflow/ragflow

Length of output: 19417


Wrap CompilationTemplateService.get_saved in thread_pool_exec here. This is still synchronous Peewee work on the async worker’s event loop; offloading it avoids blocking co-scheduled coroutines.

🤖 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/runner.py` around lines 503 - 506, Update
the template-loading path around CompilationTemplateService.get_saved to execute
the synchronous database call through thread_pool_exec, while preserving the
existing template_id and tenant_id arguments and saved_template handling. Keep
the surrounding async flow and structure_kind derivation unchanged.

Comment thread rag/nlp/search.py
src.append(f"q_{len(q_vec)}_vec")

fusionExpr = FusionExpr("weighted_sum", topk, {"weights": "0.05,0.95"})
fusionExpr = FusionExpr("weighted_sum", topk, {"weights": "0.001,1"})

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not set the text boost to zero.

rag/utils/es_conn.py uses only the second weight as vector_similarity_weight, then sets the text boost to 1.0 - vector_similarity_weight. Therefore "0.001,1" makes dense retrieval weight 1.0 and lexical relevance 0.0, so strong text matches can be dropped from the candidate window before downstream reranking. The first value is ignored by that parser; if the intended blend is 0.001 text / 0.999 vector, use "0.001,0.999" instead.

🤖 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/nlp/search.py` at line 210, Update the FusionExpr configuration in the
search flow to use weights "0.001,0.999" instead of "0.001,1", ensuring lexical
relevance retains a 0.001 boost while vector similarity receives 0.999.

@KevinHuSh
KevinHuSh force-pushed the feat/agentic_search4 branch from d00c495 to be3c7b8 Compare July 22, 2026 04:40

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rag/advanced_rag/knowlege_compile/structure.py (2)

1599-1638: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Hardcoded 10000-row limit no longer safe once alias rewrite is KB-wide.

Under dataset scope, doc_id is intentionally dropped from the relation-reference search condition In doc scope a renamed entity only affects relations inside the same document; in dataset scope the canonical entity is shared, so every relation in the KB that references an alias must be rewritten. but the search below still caps results at 10000 — the same limit that was previously bounded by a single document's relation count. In dataset scope this cap now bounds the entire KB's relations for a (compile_kwd, template) pair; any KB exceeding it will silently miss alias rewrites for the truncated tail, leaving stale from_entity_kwd/to_entity_kwd references pointing at renamed (no-longer-canonical) entity names.

🤖 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/structure.py` around lines 1599 - 1638, The
relation-reference search in the merge scope flow must not truncate dataset-wide
results at 10,000 rows. Update the search and subsequent processing around
scopes, condition, and thread_pool_exec so every matching relation is retrieved
and rewritten when dataset_scope is enabled, while preserving the existing
bounded behavior for document scope if appropriate.

2634-2657: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Dataset merge lock: fail-open on acquire failure defeats its purpose, and it's nested inside the local sequencing gate.

Two related concerns:

  1. On lock-acquire failure, merge_lock is set to None and the code falls through to run the unprotected KNN dedup/merge anyway: logging.exception("merge_compiled_structures: dataset merge lock acquire failed for kb=%s", kb_id) This silently reintroduces the exact race (concurrent KNN-miss + duplicate canonical insert) this lock was added to prevent, under precisely the condition (Redis unavailable/contended) when protection matters most.
  2. The lock is acquired/released inside the pre-existing local doc_storage_waiter/doc_storage_releaser critical section (which serializes all doc-storage flushes within this process). A slow or contended cross-process Redis lock now head-of-line-blocks every subsequent flush in this process — including unrelated doc-scope flushes for other templates/documents — until it is acquired and released.
🤖 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/structure.py` around lines 2634 - 2657,
Update the merge-lock handling around _struct_doc_storage_dedup_batch so
acquisition failure does not fall through to an unprotected merge: propagate the
failure or otherwise abort the operation, preserving cleanup of any acquired
lock. Move dataset-scope RedisDistributedLock acquisition and release outside
the doc_storage_waiter/doc_storage_releaser local sequencing critical section,
while keeping the lock held across the complete read-modify-write KNN merge and
retaining the existing doc_storage_waiter ordering needed to avoid deadlocks.
🧹 Nitpick comments (4)
rag/advanced_rag/knowlege_compile/wiki.py (1)

1519-1520: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Move _wiki_all_map_doc_ids(...) below the cache-hit early return.

reduce_source_doc_ids is computed up front, but on a cache hit (Lines 1521-1531) the function returns cached without ever using it — so this full paginated scan of every artifact_map_extract row runs for nothing on the exact path the incremental gate is meant to make cheap. Compute it lazily only when you're about to persist.

Also applies to: 2311 (plan_source_doc_ids in wiki_plan_from_reduction, wasted on the PLAN cache hit at Lines 2312-2322).

🤖 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.py` around lines 1519 - 1520, Move the
_wiki_all_map_doc_ids(tenant_id, kb_id) call in the reduction flow below the
cache-hit early return, computing reduce_source_doc_ids only immediately before
persistence requires it. Apply the same lazy-loading change in
wiki_plan_from_reduction for plan_source_doc_ids, preserving both cache-hit
return paths without performing the paginated scan.
rag/svr/task_executor_refactor/dataset_wiki_generator.py (1)

277-364: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Ref-counted derived-row cleanup here duplicates DocumentService.remove_artifact_products.

The read-partition-into-drop/shrink logic is reimplemented almost verbatim in api/db/services/document_service.py (Lines 604-665). The comment frames this as a self-healing backstop for the eager path, so keeping both is defensible, but the two copies will drift (e.g. the async version shrinks per-row via explicit remaining, the sync one uses store-side {"remove": ...}). Consider extracting the shared partition step (owners → sole-owner ids vs shrink set) into one helper both call.

🤖 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 277 -
364, The derived-row owner partitioning in the cleanup block duplicates
DocumentService.remove_artifact_products and risks behavioral drift. Extract the
shared owners-to-delete-or-surviving-owners partition logic into a reusable
helper, then update both this async cleanup flow and
DocumentService.remove_artifact_products to use it while preserving their
existing async and store-side update mechanisms.
api/db/services/document_service.py (1)

570-666: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a summary log for this new cleanup flow.

remove_artifact_products performs deletes/detaches across derived rows but emits no log on the success path — the caller only logs failures. A one-line summary (rows dropped vs. detached, like _wiki_delete_deleted_doc_state does) makes delete-time cleanup diagnosable. Logic itself looks correct: the up-front read guards against blindly dropping rows with no source_doc_ids, and re-checking owners protects against fulltext over-matching.

As per coding guidelines: "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/db/services/document_service.py` around lines 570 - 666, Add a success
summary log in remove_artifact_products after the derived-row cleanup completes,
reporting the counts of rows deleted and detached, consistent with
_wiki_delete_deleted_doc_state. Preserve the existing cleanup logic and ensure
the log is emitted only after all applicable operations succeed.

Source: Coding guidelines

rag/advanced_rag/knowlege_compile/structure.py (1)

552-566: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale "ES doc" wording after the doc-storage rename.

Build one ES doc for an extracted entity or relation. is now generic (the function is _struct_to_doc_storage_doc, part of the ES→doc-storage rename per this PR). The rebuild helper's docstring has the same leftover phrasing: Rebuild an ES doc from a merged payload using _struct_to_doc_storage_doc, then overlay identity fields (id, from_entity_kwd, to_entity_kwd) from base_doc. Update both to reflect the generic doc-storage terminology.

Also applies to: 1009-1011

🤖 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/structure.py` around lines 552 - 566,
Update the docstrings for _struct_to_doc_storage_doc and the rebuild helper
around the referenced lines to replace stale “ES doc” wording with generic
“doc-storage document” terminology, including the rebuild description. Keep the
documented behavior and field descriptions unchanged.

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 `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 1650-1656: Update the relation-alias rewrite loop around
_struct_embed to match the sibling embedding calls’ explicit exception handling
and fallback behavior, ensuring failures do not escape the dataset-scope-locked
critical section. Validate that the returned vector count matches batch before
rebuilding documents, and replace the non-strict zip(batch, vectors) with strict
pairing or equivalent handling that logs and safely handles mismatches without
silently dropping relations.

---

Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 1599-1638: The relation-reference search in the merge scope flow
must not truncate dataset-wide results at 10,000 rows. Update the search and
subsequent processing around scopes, condition, and thread_pool_exec so every
matching relation is retrieved and rewritten when dataset_scope is enabled,
while preserving the existing bounded behavior for document scope if
appropriate.
- Around line 2634-2657: Update the merge-lock handling around
_struct_doc_storage_dedup_batch so acquisition failure does not fall through to
an unprotected merge: propagate the failure or otherwise abort the operation,
preserving cleanup of any acquired lock. Move dataset-scope RedisDistributedLock
acquisition and release outside the doc_storage_waiter/doc_storage_releaser
local sequencing critical section, while keeping the lock held across the
complete read-modify-write KNN merge and retaining the existing
doc_storage_waiter ordering needed to avoid deadlocks.

---

Nitpick comments:
In `@api/db/services/document_service.py`:
- Around line 570-666: Add a success summary log in remove_artifact_products
after the derived-row cleanup completes, reporting the counts of rows deleted
and detached, consistent with _wiki_delete_deleted_doc_state. Preserve the
existing cleanup logic and ensure the log is emitted only after all applicable
operations succeed.

In `@rag/advanced_rag/knowlege_compile/structure.py`:
- Around line 552-566: Update the docstrings for _struct_to_doc_storage_doc and
the rebuild helper around the referenced lines to replace stale “ES doc” wording
with generic “doc-storage document” terminology, including the rebuild
description. Keep the documented behavior and field descriptions unchanged.

In `@rag/advanced_rag/knowlege_compile/wiki.py`:
- Around line 1519-1520: Move the _wiki_all_map_doc_ids(tenant_id, kb_id) call
in the reduction flow below the cache-hit early return, computing
reduce_source_doc_ids only immediately before persistence requires it. Apply the
same lazy-loading change in wiki_plan_from_reduction for plan_source_doc_ids,
preserving both cache-hit return paths without performing the paginated scan.

In `@rag/svr/task_executor_refactor/dataset_wiki_generator.py`:
- Around line 277-364: The derived-row owner partitioning in the cleanup block
duplicates DocumentService.remove_artifact_products and risks behavioral drift.
Extract the shared owners-to-delete-or-surviving-owners partition logic into a
reusable helper, then update both this async cleanup flow and
DocumentService.remove_artifact_products to use it while preserving their
existing async and store-side update mechanisms.
🪄 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

Run ID: 14d93625-6fd8-4d87-8e4b-704a2d11283c

📥 Commits

Reviewing files that changed from the base of the PR and between be3c7b8 and 3ab6415.

📒 Files selected for processing (7)
  • api/db/services/document_service.py
  • rag/advanced_rag/knowlege_compile/_common.py
  • rag/advanced_rag/knowlege_compile/runner.py
  • rag/advanced_rag/knowlege_compile/structure.py
  • rag/advanced_rag/knowlege_compile/wiki.py
  • rag/svr/task_executor_refactor/dataset_wiki_generator.py
  • rag/utils/infinity_conn.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/advanced_rag/knowlege_compile/runner.py

Comment on lines 1650 to 1656
for start in range(0, len(rewrite_batch), _ES_DEDUP_EMBED_BATCH_SIZE):
batch = rewrite_batch[start : start + _ES_DEDUP_EMBED_BATCH_SIZE]
vectors = await _struct_embed(embd_mdl, [_struct_payload_description(payload) for _, payload in batch])
rewritten = [_struct_rebuild_es_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors)]
rewritten = [_struct_rebuild_doc_storage_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors)]
if rewritten:
await thread_pool_exec(settings.docStoreConn.insert, rewritten, index, kb_id)
existing_relation_updates += len(rewritten)

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 | 🟡 Minor | ⚡ Quick win

Missing failure handling around embedding for relation-alias rewrite; zip() risks silent truncation.

Unlike the sibling embed calls at lines 668-672 and 1546-1549 (both wrapped in try/except with an explicit fallback), the _struct_embed call here has no exception handling, and the Ruff-flagged zip(batch, vectors) has no length check or strict=True. If the embedding call raises or returns fewer vectors than requested, an unhandled exception propagates out of this dataset-scope-locked/sequenced critical section, or the mismatch is silently truncated and some alias-carrying relations are dropped from the rewrite batch without any log signal.

🛠️ Proposed fix
-                vectors = await _struct_embed(embd_mdl, [_struct_payload_description(payload) for _, payload in batch])
-                rewritten = [_struct_rebuild_doc_storage_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors)]
+                try:
+                    vectors = await _struct_embed(embd_mdl, [_struct_payload_description(payload) for _, payload in batch])
+                except Exception:
+                    logging.exception("merge_compiled_structures: relation alias re-embedding failed for %d docs", len(batch))
+                    continue
+                if len(vectors) != len(batch):
+                    logging.error("merge_compiled_structures: embedding count mismatch for relation alias rewrite (%d vs %d)", len(vectors), len(batch))
+                    continue
+                rewritten = [_struct_rebuild_doc_storage_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors, strict=True)]
📝 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
for start in range(0, len(rewrite_batch), _ES_DEDUP_EMBED_BATCH_SIZE):
batch = rewrite_batch[start : start + _ES_DEDUP_EMBED_BATCH_SIZE]
vectors = await _struct_embed(embd_mdl, [_struct_payload_description(payload) for _, payload in batch])
rewritten = [_struct_rebuild_es_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors)]
rewritten = [_struct_rebuild_doc_storage_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors)]
if rewritten:
await thread_pool_exec(settings.docStoreConn.insert, rewritten, index, kb_id)
existing_relation_updates += len(rewritten)
for start in range(0, len(rewrite_batch), _ES_DEDUP_EMBED_BATCH_SIZE):
batch = rewrite_batch[start : start + _ES_DEDUP_EMBED_BATCH_SIZE]
try:
vectors = await _struct_embed(embd_mdl, [_struct_payload_description(payload) for _, payload in batch])
except Exception:
logging.exception("merge_compiled_structures: relation alias re-embedding failed for %d docs", len(batch))
continue
if len(vectors) != len(batch):
logging.error("merge_compiled_structures: embedding count mismatch for relation alias rewrite (%d vs %d)", len(vectors), len(batch))
continue
rewritten = [_struct_rebuild_doc_storage_doc(payload, base, vector, base.get("source_chunk_ids") or [], preserve_id=True) for (base, payload), vector in zip(batch, vectors, strict=True)]
if rewritten:
await thread_pool_exec(settings.docStoreConn.insert, rewritten, index, kb_id)
existing_relation_updates += len(rewritten)
🧰 Tools
🪛 Ruff (0.15.21)

[warning] 1653-1653: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)

🤖 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/structure.py` around lines 1650 - 1656,
Update the relation-alias rewrite loop around _struct_embed to match the sibling
embedding calls’ explicit exception handling and fallback behavior, ensuring
failures do not escape the dataset-scope-locked critical section. Validate that
the returned vector count matches batch before rebuilding documents, and replace
the non-strict zip(batch, vectors) with strict pairing or equivalent handling
that logs and safely handles mismatches without silently dropping relations.

Source: Linters/SAST tools

@yingfeng yingfeng added the ci Continue Integration label Jul 23, 2026
@yingfeng
yingfeng merged commit 3e4c6df into infiniflow:main Jul 23, 2026
5 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants