Repository navigation
refa: improve tree clustering - #17285
Conversation
📝 WalkthroughWalkthroughRAPTOR 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. ChangesRAPTOR clustering and tree pipeline
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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 liftGive RAPTOR
tree_nodeentities 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 bothnameand relation endpoint. Siblings or unrelated nodes that receive the same LLM-generated title will be merged into one entity/row and theirsource_chunk_idscan be coalesced incorrectly, while a title collision inparentscan still create an invalid child edge when that parent title exists elsewhere in the tree. Assign a stable node id and keeptitle/namepurely 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 winNo logging for the new unary-collapse flow.
_collapse_unarysilently 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_thresholdisn't exposed through the per-templateextconfig.
psi_exact_max_leaves/psi_bucket_sizeare read fromraptor_cfg.get("ext")at the call sites (raptor_service.py::build_doc_tree), but the newahc_distance_thresholdalways falls back to its hardcoded default (0.3) since it isn't threaded through the sameextmechanism. 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
📒 Files selected for processing (3)
rag/advanced_rag/knowlege_compile/raptor.pyrag/flow/compiler/compiler.pyrag/svr/task_executor_refactor/chunk_post_processor.py
wangq8
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
rag/advanced_rag/knowlege_compile/raptor.pyweb/src/components/ui/tree-view.tsxweb/src/pages/chunk/representation/utils/adapters.ts
| """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 |
There was a problem hiding this comment.
📐 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.
| """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 ? ( |
There was a problem hiding this comment.
📐 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 || trueRepository: 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' || trueRepository: 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
| // 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; |
There was a problem hiding this comment.
🎯 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/chunk_post_processor.py (2)
558-589: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSequential LLM calls per duplicate-title group.
The loop awaits
gen_jsonone group at a time. Documents with many duplicate-title groups will serialize N LLM round-trips (each with its own retry loop ingen_json), adding latency torun_tree_templatesproportional to duplicate count. Consider batching all groups into one call, or firing them concurrently (e.g.asyncio.gatherwith 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 winNo progress/outcome logging for this new flow.
rewrite_duplicate_tree_namesonly 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
📒 Files selected for processing (1)
rag/svr/task_executor_refactor/chunk_post_processor.py
| await rewrite_duplicate_tree_names(tree, chat_mdl_by_tid[template_id]) | ||
| graph = raptor_tree_to_graph(tree) |
There was a problem hiding this comment.
🩺 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.
| 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.
What problem does this PR solve?
Improve knowledge compilation tree clustering and graph generation.
This change:
Type of change