Skip to content

refa: improve tree clustering - #17285

Merged
wangq8 merged 7 commits into
infiniflow:mainfrom
buua436:b120
Jul 23, 2026
Merged

wangq8 merged 7 commits into
infiniflow:mainfrom
buua436:b120

Conversation

@buua436

@buua436 buua436 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Improve knowledge compilation tree clustering and graph generation.

This change:

  • Switches tree compilation from GMM to average-linkage AHC with cosine distance.
  • Clusters directly on raw embeddings instead of reducing them with UMAP first.
  • Adds cosine-based centroid adjustment and close-cluster merging.
  • Enforces the configured maximum cluster count and records clustering statistics.
  • Collapses tree nodes that only contain a single child.
  • Prevents self-loop relations when parent and child nodes have the same generated title.
  • Enables AHC for both compiler and task-executor tree compilation paths.

Type of change

  • Refactor (no breaking API change)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

RAPTOR now forms contiguous clusters from adjacent cosine similarities using a configurable percentile threshold. Tree-template callers select AHC, graph projection collapses unary nodes and rewrites duplicate titles, and frontend tree rendering guards against self-references and empty branches.

Changes

RAPTOR clustering and tree pipeline

Layer / File(s) Summary
Percentile-based adjacent cosine AHC
rag/advanced_rag/knowlege_compile/raptor.py, test/unit_test/rag/test_raptor_psi_tree_builder.py
Adds cluster_percentile thresholding for adjacent normalized-embedding similarities, removes Ward-linkage refinement, passes gen_conf directly, and updates the clustering test stub.
Tree-template AHC wiring
rag/flow/compiler/compiler.py, rag/svr/task_executor_refactor/chunk_post_processor.py
Changes compiled and runtime RAPTOR tree-template clustering from GMM to AHC.
Unary projection and duplicate-title cleanup
rag/svr/task_executor_refactor/chunk_post_processor.py
Collapses unary wrapper chains, combines descriptions and source chunk IDs, rewrites conflicting duplicate titles, enforces title uniqueness, and prevents self-loop child relations.
Frontend tree rendering guards
web/src/pages/chunk/representation/utils/adapters.ts, web/src/components/ui/tree-view.tsx
Skips self-referencing relations and renders empty child arrays as leaves.

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

Sequence Diagram(s)

sequenceDiagram
  participant TreeTemplates
  participant RAPTOR
  participant AHC
  participant GraphProjection
  participant TreeRenderer
  TreeTemplates->>RAPTOR: build tree with clustering_method="ahc"
  RAPTOR->>AHC: cluster normalized embeddings
  AHC-->>RAPTOR: contiguous cluster labels
  RAPTOR-->>GraphProjection: tree structure
  GraphProjection->>GraphProjection: rewrite duplicate titles and collapse unary nodes
  GraphProjection-->>TreeRenderer: graph entities and relations
  TreeRenderer->>TreeRenderer: skip self-references and render empty branches as leaves
Loading

Possibly related PRs

  • infiniflow/ragflow#17270: Changes the same _chat LLM call path by adding the generation-configuration wrapper that this PR removes.

Suggested labels: 💞 feature, size:XXL

Suggested reviewers: kevinhush

Poem

I hop through clusters in a row,
Where cosine currents ebb and flow.
Unary branches softly bend,
Self-loop tangles meet their end.
Leaves now know when children hide—
A tidy tree from side to side!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: improved tree clustering.
Description check ✅ Passed It clearly explains the PR’s purpose and context, though it doesn’t use the template’s exact 'Summary' heading.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

❤️ Share

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

@yingfeng yingfeng added the ci Continue Integration label Jul 23, 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/svr/task_executor_refactor/chunk_post_processor.py (1)

512-533: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Give RAPTOR tree_node entities a stable unique id separate from their display title.

_struct_merge_graph_entities() deduplicates graph rows by (name, type), and the tree projection uses the generated label as both name and relation endpoint. Siblings or unrelated nodes that receive the same LLM-generated title will be merged into one entity/row and their source_chunk_ids can be coalesced incorrectly, while a title collision in parents can still create an invalid child edge when that parent title exists elsewhere in the tree. Assign a stable node id and keep title/name purely as display attributes in this projection.

🤖 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/chunk_post_processor.py` around lines 512 -
533, Update the tree-building logic in _walk so each RAPTOR tree_node receives a
stable unique identifier independent of the LLM-generated title, using that
identifier for entity identity and child relation endpoints. Preserve the title
as the display name/attribute, and ensure source_chunk_ids remain attached to
the correct node without deduplication across title collisions; remove the
title-based self-loop check in favor of identifier-based parent-child linking.
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/chunk_post_processor.py (1)

472-511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No logging for the new unary-collapse flow.

_collapse_unary silently rewrites tree structure (merging descriptions/source_chunk_ids across potentially many levels) with no visibility into how often/how deep collapsing occurs. As per coding guidelines, "Add logging for new flows" applies 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 `@rag/svr/task_executor_refactor/chunk_post_processor.py` around lines 472 -
511, Add logging within _collapse_unary to record each unary-node collapse,
including the collapse depth or level and relevant node context such as titles.
Use the module’s existing logging mechanism and keep the current description,
source_chunk_ids, and children merge behavior unchanged.

Source: Coding guidelines

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

183-188: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

ahc_distance_threshold isn't exposed through the per-template ext config.

psi_exact_max_leaves/psi_bucket_size are read from raptor_cfg.get("ext") at the call sites (raptor_service.py::build_doc_tree), but the new ahc_distance_threshold always falls back to its hardcoded default (0.3) since it isn't threaded through the same ext mechanism. Given this directly controls how aggressively the new AHC path clusters, consider exposing it the same way for per-template tuning.

Also applies to: 346-405

🤖 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/raptor.py` around lines 183 - 188, Expose
ahc_distance_threshold through the per-template ext configuration and thread it
from raptor_service.py::build_doc_tree into the RAPTOR configuration instead of
always using the default 0.3. Follow the existing psi_exact_max_leaves and
psi_bucket_size ext lookup pattern, while retaining 0.3 only when the setting is
absent.
🤖 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/raptor.py`:
- Line 355: Update the RAPTOR clustering log statement in the surrounding method
to use a format specifier compatible with both the embedding dimension and the
`"?"` fallback, while preserving the existing dimension calculation and message
content.

---

Outside diff comments:
In `@rag/svr/task_executor_refactor/chunk_post_processor.py`:
- Around line 512-533: Update the tree-building logic in _walk so each RAPTOR
tree_node receives a stable unique identifier independent of the LLM-generated
title, using that identifier for entity identity and child relation endpoints.
Preserve the title as the display name/attribute, and ensure source_chunk_ids
remain attached to the correct node without deduplication across title
collisions; remove the title-based self-loop check in favor of identifier-based
parent-child linking.

---

Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Around line 183-188: Expose ahc_distance_threshold through the per-template
ext configuration and thread it from raptor_service.py::build_doc_tree into the
RAPTOR configuration instead of always using the default 0.3. Follow the
existing psi_exact_max_leaves and psi_bucket_size ext lookup pattern, while
retaining 0.3 only when the setting is absent.

In `@rag/svr/task_executor_refactor/chunk_post_processor.py`:
- Around line 472-511: Add logging within _collapse_unary to record each
unary-node collapse, including the collapse depth or level and relevant node
context such as titles. Use the module’s existing logging mechanism and keep the
current description, source_chunk_ids, and children merge behavior 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 Plus

Run ID: 2de0e12c-1eef-4e68-8677-b02b33cd580a

📥 Commits

Reviewing files that changed from the base of the PR and between e3e2d0a and b96253e.

📒 Files selected for processing (3)
  • rag/advanced_rag/knowlege_compile/raptor.py
  • rag/flow/compiler/compiler.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py

@buua436
buua436 requested a review from wangq8 July 23, 2026 07:56

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this PR — the switch from GMM+UMAP to average-linkage AHC with cosine distance is a solid direction. I left some detailed feedback below.

Overall

The refactor direction makes sense: AHC with cosine distance on raw embeddings avoids the information loss from UMAP and the instability of GMM on arbitrary-dimension reduced data. The _collapse_unary helper and self-loop guard are good defensive additions.

Suggestion: make ahc_distance_threshold configurable

The new ahc_distance_threshold=0.3 parameter on RecursiveAbstractiveProcessing4TreeOrganizedRetrieval.__init__ is hardcoded with no path to override it from build_doc_tree or any config. If 0.3 turns out to be too aggressive or too conservative for certain embedding models or datasets, users have no way to tune it. Consider threading it through build_doc_tree and the RaptorConfig / ext dict, similar to how clustering_method is already handled in raptor_utils.py.

Missing type annotations

The new parameter ahc_distance_threshold and the new methods _merge_close_clusters, _collapse_unary are missing type hints. The rest of the file uses type annotations (np.ndarray, int, etc.) — worth matching the existing style.

Dead code in GMM path

In clustering(), the top already returns early on len(embeddings) == 0, but the GMM branch repeats the same check:

if len(embeddings) == 0:
    return 0, []

This is now unreachable and can be removed.

Potential issue: _adjust_tree_nodes with zero-norm embeddings

The new _adjust_tree_nodes uses np.divide(..., out=np.zeros_like(...), where=norms > 0). If an embedding is a true zero-vector, its normalized form becomes the zero vector and it will have cosine similarity 0 with every centroid — meaning it gets randomly assigned to the first cluster (argmax breaks ties to the first index). In practice zero embeddings are unlikely, but it is worth being aware of. The same applies to _merge_close_clusters.

Question: _collapse_unary description growth

When collapsing a chain of single-child nodes, descriptions are concatenated with "\n\n". In a degenerate deeply-nested tree this could produce a very long description string that exceeds LLM context when passed for downstream summarisation. Is there a realistic maximum tree depth that keeps this safe? If depth can be unbounded, a truncation guard would be prudent.

Tests

The existing test_ahc_clustering_method_is_supported_in_original_tree_builder test exercises _get_clusters_ahc but only checks len(labels) == 4. No tests cover the new _merge_close_clusters, the refactored _adjust_tree_nodes (cosine path), _collapse_unary, or the self-loop guard. Adding coverage — even a few simple cases — would help catch regressions.

Minor: import style

The import umap was moved inside the GMM branch, which is fine (avoids importing a heavy dependency when using AHC). The downside is that an ImportError would only surface at runtime inside clustering rather than at import time. Not a blocker, just noting it.

@buua436
buua436 marked this pull request as draft July 23, 2026 08:18
@buua436
buua436 marked this pull request as ready for review July 23, 2026 08:18
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jul 23, 2026
@buua436
buua436 marked this pull request as draft July 23, 2026 08:21
@buua436
buua436 marked this pull request as ready for review July 23, 2026 08:21
@6ba3i 6ba3i added ci Continue Integration and removed ci Continue Integration labels Jul 23, 2026
@yingfeng yingfeng closed this Jul 23, 2026
@yingfeng yingfeng reopened this Jul 23, 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

🤖 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/raptor.py`:
- Around line 184-195: Update the constructor docstring for cluster_percentile
near _max_cluster, _small_layer_collapse, and _cluster_percentile to describe
the adjacent-pair cosine similarity threshold used by _get_clusters_ahc. State
that a lower percentile produces a lower threshold and therefore fewer, coarser
clusters, matching the existing _get_clusters_ahc documentation; remove the
stale Ward/distance wording.

In `@web/src/components/ui/tree-view.tsx`:
- Line 145: Do not modify the shared TreeView component or its
children-rendering condition. Instead, obtain explicit approval before changing
TreeView; otherwise normalize empty children arrays in the calling tree-data
construction so the component receives the expected shape.

In `@web/src/pages/chunk/representation/utils/adapters.ts`:
- Around line 51-55: Apply the self-referencing relation guard in
buildUniqueTreeDataItems before its parent/child lookup, skipping relations
where relation.from equals relation.to. Preserve the existing tree-building
behavior for all non-self-loop relations.
🪄 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: 4f8b201c-43a0-4e2d-ba48-e4a9477fae49

📥 Commits

Reviewing files that changed from the base of the PR and between bee2b0d and 97b6df7.

📒 Files selected for processing (3)
  • rag/advanced_rag/knowlege_compile/raptor.py
  • web/src/components/ui/tree-view.tsx
  • web/src/pages/chunk/representation/utils/adapters.ts

Comment on lines +184 to +195
"""Configure RAPTOR summarization, clustering, and Psi limits.

Args:
cluster_percentile: AHC distance threshold is set to this
percentile of all pairwise cosine distances in each
layer. A lower value produces finer (more) clusters.
Default 30 means the threshold excludes the top 70%
most dissimilar pairs.
"""
self._max_cluster = max_cluster
self._small_layer_collapse = small_layer_collapse
self._cluster_percentile = cluster_percentile

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

cluster_percentile docstring describes the removed Ward/distance flow and inverts the tuning direction.

The implementation in _get_clusters_ahc (Lines 302-316) computes adjacent-pair cosine similarity and keeps chunks together when adj_sims[i-1] >= threshold. A lower cluster_percentile yields a lower similarity threshold, so more adjacent pairs stay merged → fewer/coarser clusters. The docstring here claims the opposite ("distance threshold … all pairwise cosine distances", "A lower value produces finer (more) clusters"), stale wording from the old pairwise Ward-linkage path. It also contradicts the correct docstring on _get_clusters_ahc (Lines 283-285). This will mislead anyone tuning the parameter.

📝 Proposed doc fix
         Args:
-            cluster_percentile: AHC distance threshold is set to this
-                percentile of all pairwise cosine distances in each
-                layer.  A lower value produces finer (more) clusters.
-                Default 30 means the threshold excludes the top 70%
-                most dissimilar pairs.
+            cluster_percentile: Adjacent-pair cosine-similarity cutoff,
+                set to this percentile of the current layer's adjacent
+                similarities. Adjacent chunks stay in the same cluster
+                when their similarity is >= the threshold. A *lower*
+                value lowers the threshold, merging more pairs and
+                producing coarser (fewer) clusters; a higher value
+                produces finer (more) clusters.

As per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes."

📝 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
"""Configure RAPTOR summarization, clustering, and Psi limits.
Args:
cluster_percentile: AHC distance threshold is set to this
percentile of all pairwise cosine distances in each
layer. A lower value produces finer (more) clusters.
Default 30 means the threshold excludes the top 70%
most dissimilar pairs.
"""
self._max_cluster = max_cluster
self._small_layer_collapse = small_layer_collapse
self._cluster_percentile = cluster_percentile
"""Configure RAPTOR summarization, clustering, and Psi limits.
Args:
cluster_percentile: Adjacent-pair cosine-similarity cutoff,
set to this percentile of the current layer's adjacent
similarities. Adjacent chunks stay in the same cluster
when their similarity is >= the threshold. A *lower*
value lowers the threshold, merging more pairs and
producing coarser (fewer) clusters; a higher value
produces finer (more) clusters.
"""
self._max_cluster = max_cluster
self._small_layer_collapse = small_layer_collapse
self._cluster_percentile = cluster_percentile
🤖 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/raptor.py` around lines 184 - 195, Update
the constructor docstring for cluster_percentile near _max_cluster,
_small_layer_collapse, and _cluster_percentile to describe the adjacent-pair
cosine similarity threshold used by _get_clusters_ahc. State that a lower
percentile produces a lower threshold and therefore fewer, coarser clusters,
matching the existing _get_clusters_ahc documentation; remove the stale
Ward/distance wording.

Source: Coding guidelines

{data.map((item) => (
<li key={item.id}>
{item.children ? (
{item.children && item.children.length > 0 ? (

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Tracked file presence:"
git ls-files | grep -F 'web/src/components/ui/tree-view.tsx' || true

echo
echo "UI directory contents sample:"
find web/src/components/ui -maxdepth 2 -type f 2>/dev/null | sed -n '1,80p' || true

echo
echo "Search for tree-view importers:"
rg -n "tree-view|TreeView|from ['\"].*\+tree-view|tree-view" web/src || true

echo
echo "Relevant file excerpt around line 145:"
if [ -f web/src/components/ui/tree-view.tsx ]; then
  nl -ba web/src/components/ui/tree-view.tsx | sed -n '120,165p'
fi

echo
echo "Changed files/stat:"
git diff --name-status || true
git diff --stat || true

Repository: infiniflow/ragflow

Length of output: 5465


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Relevant file excerpt around line 145:"
awk 'NR>=135 && NR<=155 { printf "%6d\t%s\n", NR, $0 }' web/src/components/ui/tree-view.tsx

echo
echo "Diff to tree-view.tsx, if any:"
git diff -- web/src/components/ui/tree-view.tsx | sed -n '1,220p' || true

Repository: infiniflow/ragflow

Length of output: 1057


Obtain approval before changing the shared TreeView component.

web/src/components/ui/tree-view.tsx is under the protected src/components/ui/ path, so this change needs explicit approval or should be addressed by normalizing empty-children arrays in the calling tree data 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 `@web/src/components/ui/tree-view.tsx` at line 145, Do not modify the shared
TreeView component or its children-rendering condition. Instead, obtain explicit
approval before changing TreeView; otherwise normalize empty children arrays in
the calling tree-data construction so the component receives the expected shape.

Source: Path instructions

Comment on lines +51 to +55
// Self-referencing relation (same entity as its own child) creates
// an infinite recursion in the tree renderer. This is a backend
// data integrity issue (duplicate entity names) but we defend
// against it in the frontend so the UI never hangs.
if (relation.from === relation.to) 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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Apply the self-loop guard to buildUniqueTreeDataItems too.

adaptMindMapToIndentedTree uses buildUniqueTreeDataItems, but that builder still processes from === to: it adds the entity to childIds and then removes it from the returned roots, causing the node to disappear. Add the same guard before the parent/child lookup in that builder.

🤖 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/chunk/representation/utils/adapters.ts` around lines 51 - 55,
Apply the self-referencing relation guard in buildUniqueTreeDataItems before its
parent/child lookup, skipping relations where relation.from equals relation.to.
Preserve the existing tree-building behavior for all non-self-loop relations.

@codecov

codecov Bot commented Jul 23, 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 (97b6df7).
⚠️ Report is 7 commits behind head on main.

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

🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/chunk_post_processor.py (2)

558-589: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Sequential LLM calls per duplicate-title group.

The loop awaits gen_json one group at a time. Documents with many duplicate-title groups will serialize N LLM round-trips (each with its own retry loop in gen_json), adding latency to run_tree_templates proportional to duplicate count. Consider batching all groups into one call, or firing them concurrently (e.g. asyncio.gather with a bounded semaphore to respect provider rate limits).

🤖 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/chunk_post_processor.py` around lines 558 -
589, Update the duplicate-title rewrite loop in run_tree_templates to avoid
awaiting gen_json sequentially for each group. Dispatch group rewrites
concurrently with asyncio.gather and a bounded semaphore to respect provider
rate limits, while preserving per-group exception handling, response parsing,
and node title updates.

539-609: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No progress/outcome logging for this new flow.

rewrite_duplicate_tree_names only logs on the exception path (line 580); there's no log line indicating how many duplicate-title groups were found/rewritten, making it hard to observe whether the rewrite step is doing anything useful in production. As per coding guidelines, "Add logging for new flows" applies to **/*.py.

📝 Suggested addition
     _walk(tree, (0,))
+    rewritten = 0
     for title, candidates in groups.items():
         descriptions = {description for _, _, description in candidates}
         if len(candidates) < 2 or len(descriptions) < 2:
             continue
@@
         for node, node_key, _ in candidates:
             new_title = rewrites.get(node_key)
             if new_title:
                 node["title"] = new_title
+                rewritten += 1
+
+    if rewritten:
+        logging.info("tree-template: rewrote %d duplicate node title(s)", rewritten)
🤖 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/chunk_post_processor.py` around lines 539 -
609, The new rewrite flow lacks progress logging for successful execution.
Update rewrite_duplicate_tree_names to track duplicate-title groups found and
titles rewritten, then emit a concise summary log after processing, while
preserving the existing exception logging and deterministic uniqueness
enforcement.

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/svr/task_executor_refactor/chunk_post_processor.py`:
- Around line 983-984: Wrap the rewrite_duplicate_tree_names call in the
per-template try/except pattern used by neighboring stages, logging the
exception and continuing or applying the established graceful fallback so
failures skip only title rewriting without aborting run_tree_templates. Keep the
subsequent raptor_tree_to_graph conversion and normal successful flow unchanged.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/chunk_post_processor.py`:
- Around line 558-589: Update the duplicate-title rewrite loop in
run_tree_templates to avoid awaiting gen_json sequentially for each group.
Dispatch group rewrites concurrently with asyncio.gather and a bounded semaphore
to respect provider rate limits, while preserving per-group exception handling,
response parsing, and node title updates.
- Around line 539-609: The new rewrite flow lacks progress logging for
successful execution. Update rewrite_duplicate_tree_names to track
duplicate-title groups found and titles rewritten, then emit a concise summary
log after processing, while preserving the existing exception logging and
deterministic uniqueness enforcement.
🪄 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: 2da7684e-0130-4f32-9e2a-64867ff00f3a

📥 Commits

Reviewing files that changed from the base of the PR and between 97b6df7 and 4452a3e.

📒 Files selected for processing (1)
  • rag/svr/task_executor_refactor/chunk_post_processor.py

Comment on lines +983 to 984
await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id])
graph = raptor_tree_to_graph(tree)

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 | 🟠 Major | ⚡ Quick win

Wrap rewrite_duplicate_tree_names in the same try/except pattern as its neighbors.

Every other stage in this loop (build_doc_tree, rechunk_doc_by_tree, _struct_upsert_graph_json) is wrapped in try/except with logging.exception + continue/graceful fallback, so a failure in one template doesn't abort the whole doc. The new await rewrite_duplicate_tree_names(...) call at line 983 has no such guard. Internally the function only catches exceptions around the gen_json call (line 572-581); an unexpected error elsewhere (e.g. malformed tree, dict shape assumptions in _walk/_ensure_unique) would propagate uncaught, breaking the per-template resilience pattern and aborting run_tree_templates for the remaining templates/doc instead of just skipping the title-rewrite step.

🛡️ Proposed fix
-        await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id])
+        try:
+            await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id])
+        except Exception:
+            logging.exception(
+                "tree-template %s: duplicate title rewrite failed for doc %s; persisting tree with original titles",
+                template_id,
+                doc_id,
+            )
         graph = raptor_tree_to_graph(tree)
📝 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
await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id])
graph = raptor_tree_to_graph(tree)
try:
await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id])
except Exception:
logging.exception(
"tree-template %s: duplicate title rewrite failed for doc %s; persisting tree with original titles",
template_id,
doc_id,
)
graph = raptor_tree_to_graph(tree)
🤖 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/chunk_post_processor.py` around lines 983 -
984, Wrap the rewrite_duplicate_tree_names call in the per-template try/except
pattern used by neighboring stages, logging the exception and continuing or
applying the established graceful fallback so failures skip only title rewriting
without aborting run_tree_templates. Keep the subsequent raptor_tree_to_graph
conversion and normal successful flow unchanged.

@6ba3i
6ba3i requested a review from wangq8 July 23, 2026 09:47
@wangq8
wangq8 merged commit d4a8c91 into infiniflow:main Jul 23, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 🌈 python Pull requests that update Python code ☯️ refactor Pull request that refactor/refine code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants