Repository navigation
refa: simplify RAPTOR tree clustering and configuration - #17614
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRAPTOR now uses adjacent-similarity watershed clustering with configurable ChangesRAPTOR watershed clustering
Backend integration and contracts
Frontend template configuration
Prompts and localization
API and SDK test coverage
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant TemplateForm
participant Backend
participant RAPTOR
TemplateForm->>Backend: submit clustering_threshold and clustering_ratio
Backend->>RAPTOR: construct with clustering parameters
RAPTOR->>RAPTOR: segment adjacent embeddings
RAPTOR->>Backend: return materialized tree
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx (1)
36-48: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winThe new clustering sliders use hardcoded English labels in both copies of
TreeTemplateFields. Both components already calluseTranslation, but the two added labels pass raw strings, so these controls stay untranslated in every locale.
web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx#L36-L48: replace'Clustering Threshold'and'Clustering Ratio'witht('setting.clusteringThreshold')andt('setting.clusteringRatio'), and add the new keys to the locale files.web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx#L36-L48: apply the same twot()calls so both forms share the identical keys.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx` around lines 36 - 48, Replace the hardcoded clustering slider labels in both TreeTemplateFields components with t('setting.clusteringThreshold') and t('setting.clusteringRatio') using their existing useTranslation hooks. Add these two keys to the locale files, updating the create-next component at web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx lines 36-48 and applying the same changes to the edit-next component at web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx lines 36-48.Source: Coding guidelines
🧹 Nitpick comments (4)
web/src/pages/user-setting/compilation-templates/create-next/utils.ts (1)
152-153: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the shared clustering defaults into named constants.
0.3and0.5now appear at four places in this file pair. The backend repeats the same defaults inrag/flow/compiler/compiler.py,rag/svr/task_executor.py, andrag/svr/task_executor_refactor/raptor_service.py. A drift between any two of them changes a template's behavior silently.Define the defaults once in this module and reuse them. The same change applies to
web/src/pages/user-setting/compilation-templates/edit-next/utils.tsat Lines 148-149 and 205-206.Use PascalCase for the constant names, as required by the coding guideline "Use PascalCase for components and top-level constants".
♻️ Proposed refactor
+export const DefaultClusteringThreshold = 0.3; +export const DefaultClusteringRatio = 0.5;- clustering_threshold: builtinRaptor.clustering_threshold ?? 0.3, - clustering_ratio: builtinRaptor.clustering_ratio ?? 0.5, + clustering_threshold: + builtinRaptor.clustering_threshold ?? DefaultClusteringThreshold, + clustering_ratio: + builtinRaptor.clustering_ratio ?? DefaultClusteringRatio,Also applies to: 209-210
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/user-setting/compilation-templates/create-next/utils.ts` around lines 152 - 153, Define named PascalCase top-level constants for the shared clustering threshold and ratio defaults in both create-next/utils.ts and edit-next/utils.ts, then replace every inline 0.3 and 0.5 fallback in these files with the corresponding constants, including all referenced locations.Source: Coding guidelines
test/unit_test/rag/utils/test_raptor_utils.py (1)
67-77: 📐 Maintainability & Code Quality | 🔵 TrivialAdd unit coverage for the new watershed clustering.
The removed tests correctly drop obsolete builder-selection behavior. No test in this cohort covers the replacement logic.
_get_clusters_ahcis pure and deterministic: it takes an embedding array and returns labels. The percentile threshold at Line 161 and the ratio cap at Lines 144 and 167-172 ofrag/advanced_rag/knowlege_compile/raptor.pyare the highest-risk branches.Do you want me to generate tests for the percentile threshold, the ratio cap, the zero-norm embedding path, and the
n <= 1early return?🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/rag/utils/test_raptor_utils.py` around lines 67 - 77, Add unit tests for the pure deterministic _get_clusters_ahc function covering the percentile threshold, ratio cap, zero-norm embeddings, and n <= 1 early-return paths. Use small controlled embedding arrays and assert the returned labels and expected behavior for each branch, replacing the obsolete builder-selection coverage.rag/advanced_rag/knowlege_compile/raptor.py (1)
118-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the stale AHC naming and the unused clustering inputs.
The method no longer performs agglomerative clustering, but it keeps the name
_get_clusters_ahc.clustering()still acceptsrandom_stateand never uses it.self._max_clusteris still stored in__init__and is no longer read by any clustering path. All three are leftovers from the removed strategy dispatch.Rename the method to match the watershed behavior, and drop the unused parameter and attribute. Update the four call sites that pass
random_state(rag/svr/task_executor.py,rag/svr/task_executor_refactor/raptor_service.py) if you drop it from the signature.Based on the coding guideline "Remove deprecated, legacy, or compatibility-only code; collapse duplicate implementations; drop stale comments and documentation".
#!/bin/bash # Verify remaining references to the renamed/unused clustering surface. rg -nP '_get_clusters_ahc|_max_cluster\b|clustering\(\s*$|random_state' --type=py -C2🤖 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 118 - 191, Rename _get_clusters_ahc to a watershed-specific name and update all references, including its invocation from clustering. Remove the unused random_state parameter from clustering and update the four callers in the task executor and RAPTOR service modules. Delete the obsolete self._max_cluster initialization and any remaining references, while preserving the current clustering behavior.Source: Coding guidelines
rag/svr/task_executor_refactor/raptor_service.py (1)
404-412: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDrop the stale PSI path and its legacy per-summary support.
RecursiveAbstractiveProcessing4TreeOrganizedRetrievalmaterializes only the classic tree path, so theNotImplementedErrorcatch is no longer reachable. Remove the fallback branches,_generate_raptor_legacy_rows, stale PSI wording in the related docstrings/comments, andraptor_kwd="raptor"legacy lookup/deletion references.🤖 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/raptor_service.py` around lines 404 - 412, Remove the unreachable NotImplementedError fallback around the Raptor generation flow and delete _generate_raptor_legacy_rows. Update related docstrings and comments to remove stale PSI/legacy per-summary terminology, and remove raptor_kwd="raptor" legacy lookup and deletion references while preserving the classic tree-path behavior.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/raptor.py`:
- Around line 48-66: Update the constructor docstring for clustering_threshold
in the RAPTOR configuration to describe its percentile-based behavior, matching
the implementation and the existing documentation at Lines 123-126, rather than
calling it an absolute cosine-similarity cutoff. Leave the clustering logic and
other parameter descriptions unchanged.
- Around line 143-172: Clamp the effective clustering ratio to a safe upper
bound before calculating max_clusters in the clustering method containing
_watershed, rather than using self._clustering_ratio directly. Ensure values
near 1.0 cannot permit an almost one-cluster-per-node result, while preserving
the existing lower bound and subsequent threshold-adjustment logic.
In `@rag/flow/compiler/compiler.py`:
- Around line 131-132: Update the RAPTOR configuration construction around
clustering_threshold and clustering_ratio to preserve explicitly configured zero
values by using default lookup semantics rather than truthiness fallback. Keep
the existing defaults of 0.3 and 0.5 when the keys are absent, matching the
behavior of other RAPTOR entry points.
In `@rag/svr/task_executor.py`:
- Around line 1058-1059: The fixed assignments currently precede function
docstrings, preventing Python from setting __doc__. In rag/svr/task_executor.py
lines 1058-1059, move tree_builder and clustering_method below the docstring and
assign tree_builder from RAPTOR_TREE_BUILDER; in
rag/svr/task_executor_refactor/raptor_service.py lines 153-154 and 212, move
tree_builder = "raptor" below each corresponding docstring, including
_run_dataset_level_raptor.
---
Outside diff comments:
In
`@web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx`:
- Around line 36-48: Replace the hardcoded clustering slider labels in both
TreeTemplateFields components with t('setting.clusteringThreshold') and
t('setting.clusteringRatio') using their existing useTranslation hooks. Add
these two keys to the locale files, updating the create-next component at
web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx
lines 36-48 and applying the same changes to the edit-next component at
web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx
lines 36-48.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Around line 118-191: Rename _get_clusters_ahc to a watershed-specific name and
update all references, including its invocation from clustering. Remove the
unused random_state parameter from clustering and update the four callers in the
task executor and RAPTOR service modules. Delete the obsolete self._max_cluster
initialization and any remaining references, while preserving the current
clustering behavior.
In `@rag/svr/task_executor_refactor/raptor_service.py`:
- Around line 404-412: Remove the unreachable NotImplementedError fallback
around the Raptor generation flow and delete _generate_raptor_legacy_rows.
Update related docstrings and comments to remove stale PSI/legacy per-summary
terminology, and remove raptor_kwd="raptor" legacy lookup and deletion
references while preserving the classic tree-path behavior.
In `@test/unit_test/rag/utils/test_raptor_utils.py`:
- Around line 67-77: Add unit tests for the pure deterministic _get_clusters_ahc
function covering the percentile threshold, ratio cap, zero-norm embeddings, and
n <= 1 early-return paths. Use small controlled embedding arrays and assert the
returned labels and expected behavior for each branch, replacing the obsolete
builder-selection coverage.
In `@web/src/pages/user-setting/compilation-templates/create-next/utils.ts`:
- Around line 152-153: Define named PascalCase top-level constants for the
shared clustering threshold and ratio defaults in both create-next/utils.ts and
edit-next/utils.ts, then replace every inline 0.3 and 0.5 fallback in these
files with the corresponding constants, including all referenced locations.
🪄 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: a12f683e-bb5a-4361-bc51-d05a1af6e09f
📒 Files selected for processing (14)
rag/advanced_rag/knowlege_compile/raptor.pyrag/flow/compiler/compiler.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/raptor_service.pyrag/utils/raptor_utils.pytest/unit_test/rag/test_raptor_psi_tree_builder.pytest/unit_test/rag/utils/test_raptor_utils.pyweb/src/interfaces/database/compilation-template.tsweb/src/interfaces/request/compilation-template.tsweb/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/edit-next/utils.ts
💤 Files with no reviewable changes (3)
- rag/svr/task_executor_refactor/chunk_post_processor.py
- test/unit_test/rag/test_raptor_psi_tree_builder.py
- rag/utils/raptor_utils.py
| clustering_threshold=0.3, | ||
| clustering_ratio=0.5, | ||
| ): | ||
| """Configure RAPTOR summarization, clustering, and Psi limits. | ||
| """Configure RAPTOR summarization and clustering. | ||
|
|
||
| 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. | ||
| clustering_threshold: Adjacent chunks with cosine similarity | ||
| below this value become cluster boundaries. Default 0.3. | ||
| clustering_ratio: Maximum number of clusters as a fraction of | ||
| chunk count (e.g. 0.5 means at most 50% of chunks become | ||
| cluster representatives). If the threshold-based watershed | ||
| produces more clusters than this cap, the threshold is | ||
| lowered using the distribution of recorded adjacent | ||
| similarities. | ||
| """ | ||
| self._max_cluster = max_cluster | ||
| self._small_layer_collapse = small_layer_collapse | ||
| self._cluster_percentile = cluster_percentile | ||
| self._clustering_threshold = clustering_threshold | ||
| self._clustering_ratio = clustering_ratio |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Align the clustering_threshold docstring with the percentile implementation.
The docstring states that clustering_threshold is an absolute cosine-similarity cutoff. The implementation at Line 161 converts it to a percentile of the adjacent-similarity distribution. The two descriptions produce very different behavior. A percentile threshold always splits a fixed fraction of adjacent pairs, even when all chunks are highly similar.
Pick one semantic and document it. The docstring text at Lines 123-126 already describes the percentile behavior, so the constructor docstring is the stale copy.
📝 Proposed docstring fix
Args:
- clustering_threshold: Adjacent chunks with cosine similarity
- below this value become cluster boundaries. Default 0.3.
+ clustering_threshold: Percentile (0-1) of the adjacent
+ cosine-similarity distribution used as the split
+ threshold. Adjacent chunks below the resulting value
+ become cluster boundaries. Default 0.3.
clustering_ratio: Maximum number of clusters as a fraction of📝 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.
| clustering_threshold=0.3, | |
| clustering_ratio=0.5, | |
| ): | |
| """Configure RAPTOR summarization, clustering, and Psi limits. | |
| """Configure RAPTOR summarization and clustering. | |
| 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. | |
| clustering_threshold: Adjacent chunks with cosine similarity | |
| below this value become cluster boundaries. Default 0.3. | |
| clustering_ratio: Maximum number of clusters as a fraction of | |
| chunk count (e.g. 0.5 means at most 50% of chunks become | |
| cluster representatives). If the threshold-based watershed | |
| produces more clusters than this cap, the threshold is | |
| lowered using the distribution of recorded adjacent | |
| similarities. | |
| """ | |
| self._max_cluster = max_cluster | |
| self._small_layer_collapse = small_layer_collapse | |
| self._cluster_percentile = cluster_percentile | |
| self._clustering_threshold = clustering_threshold | |
| self._clustering_ratio = clustering_ratio | |
| clustering_threshold=0.3, | |
| clustering_ratio=0.5, | |
| ): | |
| """Configure RAPTOR summarization and clustering. | |
| Args: | |
| clustering_threshold: Percentile (0-1) of the adjacent | |
| cosine-similarity distribution used as the split | |
| threshold. Adjacent chunks below the resulting value | |
| become cluster boundaries. Default 0.3. | |
| clustering_ratio: Maximum number of clusters as a fraction of | |
| chunk count (e.g. 0.5 means at most 50% of chunks become | |
| cluster representatives). If the threshold-based watershed | |
| produces more clusters than this cap, the threshold is | |
| lowered using the distribution of recorded adjacent | |
| similarities. | |
| """ | |
| self._max_cluster = max_cluster | |
| self._small_layer_collapse = small_layer_collapse | |
| self._clustering_threshold = clustering_threshold | |
| self._clustering_ratio = clustering_ratio |
🤖 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 48 - 66, Update the
constructor docstring for clustering_threshold in the RAPTOR configuration to
describe its percentile-based behavior, matching the implementation and the
existing documentation at Lines 123-126, rather than calling it an absolute
cosine-similarity cutoff. Leave the clustering logic and other parameter
descriptions unchanged.
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
rag/advanced_rag/knowlege_compile/raptor.py (3)
36-37: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRemove the obsolete PSI documentation.
The class docstring still says
"classic or Psi tree strategy". The__call__docstring also documentsPSI_TREE_BUILDERandNotImplementedErrorat Lines 275-279. The PSI implementation was removed. Update both docstrings to describe watershed clustering and the current tree contract.As per coding guidelines: “Remove dead tests, commented-out code, stale documentation, and ‘move later’ notes instead of preserving them.”
🤖 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 36 - 37, Update the class docstring for RecursiveAbstractiveProcessing4TreeOrganizedRetrieval and its __call__ docstring to remove all PSI_TREE_BUILDER and NotImplementedError references. Describe the supported watershed clustering strategy and the current tree-building contract instead, without retaining obsolete PSI documentation.Source: Coding guidelines
161-162: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winHonor the configured threshold endpoints.
api/utils/validation_utils.pyacceptsclustering_thresholdfrom0.0to1.0, but this code maps those values to percentiles1and99. A configured0.0does not select the minimum similarity, and1.0does not select the maximum similarity. Either support percentiles0-100or narrow the schema bounds and document the effective range.🤖 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 161 - 162, Update the percentile calculation in the clustering logic around _clustering_threshold so configured endpoints are honored: map 0.0 to percentile 0 and 1.0 to percentile 100, while retaining valid integer conversion and bounds for intermediate values. Keep the validation range in validation_utils.py consistent with this effective 0–100 percentile behavior.
262-280: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winAlign the documented RAPTOR return contract with the implementation.
The docstring says output tuples and input legacy tuples are 2/3-tuples, but
_normalizeandsummarizework with 4-tuples, includingsummary_ti. The tree branch also returns a 2-tuple ((tree, [])or(None, None)) instead of returning the tree directly. Update the__call__contract and the_materialize_treedocstring so the documented shape matches the code. If the legacy 2-tuple fallback is no longer needed by active callers, remove it.🤖 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 262 - 280, The RAPTOR return-contract documentation is inconsistent with the 4-tuple implementation and tree return values. Update __call__ and _materialize_tree docstrings to document the actual tuple shape, including summary_ti, and state that the tree branch returns (tree, []) or (None, None) rather than a tree directly; remove the documented legacy 2-tuple fallback if no active callers require it.Source: Coding guidelines
🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/raptor.py (2)
118-191: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd focused tests for the watershed boundaries.
Cover
n <= 1, zero vectors, threshold endpoints, ratio caps near1.0, and the flat/tree return shapes. These cases exercise the new boundary logic and prevent silent contract drift.🤖 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 118 - 191, Add focused tests for _get_clusters_ahc and clustering covering empty and single-item inputs, zero-vector normalization, threshold endpoints, clustering ratios near 1.0, and flat/tree output shapes. Assert both labels and returned cluster/count structures, preserving contiguous labels and the existing public return contract.
143-145: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winRemove or honor the obsolete RAPTOR clustering controls.
max_clusteris stored inRaptorbut never used by_get_clusters_ahc, and the watershed clusterer ignoresrandom_state.RaptorConfigstill exposesmax_clusterandrandom_seed, so acceptances for these settings are ineffective. Drop them from the public configuration and call chain, or make them affect clustering behavior where useful.🤖 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 143 - 145, Remove the obsolete max_cluster and random_seed controls from RaptorConfig, Raptor state, and the clustering call chain, including the max_clusters calculation near _get_clusters_ahc; remove related unused parameters and stored values while preserving the remaining clustering behavior.Source: Coding guidelines
web/src/locales/en.ts (1)
1905-1910: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the obsolete
setting.thresholdentry from both locale resources.The current compilation-template settings use
setting.clusteringThresholdandsetting.clusteringRatio, whilesetting.thresholdhas no current lookup sites. Keep only the active i18n keys.
web/src/locales/en.ts: remove thesetting.thresholdentry.web/src/locales/zh.ts: remove thesetting.thresholdentry.🤖 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/locales/en.ts` around lines 1905 - 1910, Remove the obsolete setting.threshold entry from web/src/locales/en.ts at lines 1905-1910 and web/src/locales/zh.ts at lines 1594-1599; retain the active setting.clusteringThreshold and setting.clusteringRatio translations in both locale resources.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/utils/validation_utils.py`:
- Around line 349-354: Update RaptorConfig/ParserConfig validation used by
get_parser_config and UpdateDocumentReq to migrate persisted legacy fields
before strict validation: rename threshold to clustering_threshold, map
clustering_method as required by the current schema, and remove the legacy keys
so extra-field rejection does not fail. Ensure task code no longer depends on
the old threshold and clustering_method names while preserving current
clustering configuration behavior.
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Line 70: Update RAPTOR initialization around _max_token and
LLMBundle.max_length so the configured max_tokens is validated against the
selected LLM context length before use. Reject or store a lower max_tokens bound
when it is below max_length, then derive _max_token from that validated boundary
so _summarize_texts receives a meaningful token budget instead of collapsing to
one character.
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 377-378: Normalize RAPTOR configuration in the task handler for
both use_raptor branches, ensuring the current prompt and max_token values are
always applied. Replace legacy threshold, clustering_method, and tree_builder
assignments with the canonical clustering_threshold and clustering_ratio keys,
remove deprecated compatibility fields and duplicate fallback behavior, and add
tests covering existing enabled datasets and newly enabled datasets.
In
`@web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx`:
- Around line 29-35: Update the create/reset defaults for
Raptor.config.max_token to 512, and modify the shared numeric input handler used
by SliderInputFormField to clamp or reject values below the configured min.
Ensure the field cannot retain or accept 0 when its minimum is 512, while
preserving existing behavior for valid values.
---
Outside diff comments:
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Around line 36-37: Update the class docstring for
RecursiveAbstractiveProcessing4TreeOrganizedRetrieval and its __call__ docstring
to remove all PSI_TREE_BUILDER and NotImplementedError references. Describe the
supported watershed clustering strategy and the current tree-building contract
instead, without retaining obsolete PSI documentation.
- Around line 161-162: Update the percentile calculation in the clustering logic
around _clustering_threshold so configured endpoints are honored: map 0.0 to
percentile 0 and 1.0 to percentile 100, while retaining valid integer conversion
and bounds for intermediate values. Keep the validation range in
validation_utils.py consistent with this effective 0–100 percentile behavior.
- Around line 262-280: The RAPTOR return-contract documentation is inconsistent
with the 4-tuple implementation and tree return values. Update __call__ and
_materialize_tree docstrings to document the actual tuple shape, including
summary_ti, and state that the tree branch returns (tree, []) or (None, None)
rather than a tree directly; remove the documented legacy 2-tuple fallback if no
active callers require it.
---
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Around line 118-191: Add focused tests for _get_clusters_ahc and clustering
covering empty and single-item inputs, zero-vector normalization, threshold
endpoints, clustering ratios near 1.0, and flat/tree output shapes. Assert both
labels and returned cluster/count structures, preserving contiguous labels and
the existing public return contract.
- Around line 143-145: Remove the obsolete max_cluster and random_seed controls
from RaptorConfig, Raptor state, and the clustering call chain, including the
max_clusters calculation near _get_clusters_ahc; remove related unused
parameters and stored values while preserving the remaining clustering behavior.
In `@web/src/locales/en.ts`:
- Around line 1905-1910: Remove the obsolete setting.threshold entry from
web/src/locales/en.ts at lines 1905-1910 and web/src/locales/zh.ts at lines
1594-1599; retain the active setting.clusteringThreshold and
setting.clusteringRatio translations in both locale resources.
🪄 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: d3cd2ac9-b861-4c14-9cfd-081706017c94
📒 Files selected for processing (13)
api/db/init_data/compilation_templates/tree.yamlapi/utils/api_utils.pyapi/utils/validation_utils.pyrag/advanced_rag/knowlege_compile/raptor.pyrag/flow/compiler/compiler.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/task_handler.pyweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/create-next/schema.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/edit-next/schema.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx
- rag/flow/compiler/compiler.py
- rag/svr/task_executor.py
| default="Summarize the paragraphs below without inventing facts or changing numbers.\nOutput exactly two parts in the same language as the source:\n1. First line: a concise title only.\n2. Following lines: a concise summary of the content.\nDo not output labels, Markdown headings, bullet points, or any other commentary.\n\nParagraphs:\n{cluster_content}" | ||
| ), | ||
| ] | ||
| max_token: Annotated[int, Field(default=256, ge=1, le=2048)] | ||
| threshold: Annotated[float, Field(default=0.1, ge=0.0, le=1.0)] | ||
| max_token: Annotated[int, Field(default=512, ge=512, le=2048)] | ||
| clustering_threshold: Annotated[float, Field(default=0.3, ge=0.0, le=1.0)] | ||
| clustering_ratio: Annotated[float, Field(default=0.5, ge=0.0, le=1.0)] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 4 '\b(threshold|clustering_method|tree_builder|ext)\b' \
api rag web --glob '*.py' --glob '*.yaml' --glob '*.json'
rg -n -C 5 'class Base\b|extra\s*=|ConfigDict' api rag --glob '*.py'Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== validation_utils Base and relevant class =="
rg -n -C 8 'class Base|class .*Raptor|threshold|clustering_threshold|clustering_ratio|max_token|tree_builder|clustering_method' api/utils/validation_utils.py
echo
echo "== api_utils deep_merge =="
fd -a 'api_utils.py' . | while read -r f; do
echo "--- $f"
rg -n -C 10 'def deep_merge|deep_merge|extra|ConfigDict' "$f"
done
echo
echo "== Pydantic import/usage and Base definition candidates =="
python3 - <<'PY'
import ast
from pathlib import Path
roots = [Path("api")]
for root in roots:
for p in root.rglob("*.py"):
text = p.read_text(errors="ignore")
if "class Base" in text or "extra" in text and "ConfigDict" in text:
print(f"\n--- {p}")
try:
tree = ast.parse(text)
except SyntaxError:
print("SYNTAX_ERROR")
continue
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name == "Base":
print("BASE_CLASS", node.lineno, ast.get_source_segment(text, node))
elif isinstance(node, ast.ClassDef):
for dec in node.decorator_list:
if isinstance(dec, ast.AnnAssign) and ast.unparse(dec.target) == "model_config" and isinstance(dec.value, ast.Dict):
extras = [(n, ast.unparse(v)) for n, v in zip(dec.value.keys, dec.value.values) if isinstance(n, ast.Constant) and n.value == "extra"]
if extras:
print("CLASS_EXTRA_MODEL_CONFIG", node.name, node.lineno, extras)
PY
echo
echo "== focused RAPTOR config usages =="
rg -n -C 4 'parser_config|ext|threshold|clustering_(threshold|ratio)|tree_builder|clustering_method' rag/svr/task_executor_refactor/raptor_service.py rag/svr/task_executor_refactor/task_handler.py rag/svr/task_executor_refactor/chunk_post_processor.py rag/utils -g '*.py' | head -n 220Repository: infiniflow/ragflow
Length of output: 7595
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate parser_config validation pipeline =="
rg -n -C 5 'RaptorConfig|RaptorParserConfig|UpdateDocumentReq|parse_obj|model_validate|Base.get\(|parser_config' api/apps/restful_apis/document_api.py api/utils/validation_utils.py rag -g '*.py' | head -n 260
echo
echo "== deep_merge function full tail =="
sed -n '603,645p' api/utils/api_utils.py
echo
echo "== migration references to threshold/clustering/tree_builder in migrations/move later/code =="
rg -n -C 3 'RaptorConfig|threshold|clustering_method|clustering_threshold|clustering_ratio|tree_builder|clustering_method' api migrations docker templates documentation web rag -g '*.py' -g '*.yaml' -g '*.yml' -g '*.json' -g '*.md' | head -n 320Repository: infiniflow/ragflow
Length of output: 48806
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== parser_config defaults context in api_utils.py =="
sed -n '300,375p' api/utils/api_utils.py
echo
echo "== ParserConfig outline/relevant lines =="
sed -n '380,430p' api/utils/validation_utils.py
echo
echo "== document update validation parser_config block =="
sed -n '663,705p' api/utils/validation_utils.py
echo
echo "== Pydantic base config for extra fields =="
python3 - <<'PY'
import ast
from pathlib import Path
src = Path("api/utils/validation_utils.py").read_text()
tree = ast.parse(src)
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name == "Base":
print("Base model_config:")
print(ast.get_source_segment(src, node))
break
PYRepository: infiniflow/ragflow
Length of output: 7509
Sanitize persisted RAPTOR configs before strict validation.
RaptorConfig forbids unknown fields, get_parser_config() preserves extra keys through deep_merge, and task code still reads old fields like threshold and clustering_method. Add a migration or ParserConfig validator that renames/drops threshold and clustering_method and maps them to clustering_threshold before UpdateDocumentReq validation fails.
🤖 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/utils/validation_utils.py` around lines 349 - 354, Update
RaptorConfig/ParserConfig validation used by get_parser_config and
UpdateDocumentReq to migrate persisted legacy fields before strict validation:
rename threshold to clustering_threshold, map clustering_method as required by
the current schema, and remove the legacy keys so extra-field rejection does not
fail. Ensure task code no longer depends on the old threshold and
clustering_method names while preserving current clustering configuration
behavior.
| "prompt": "Summarize the paragraphs below without inventing facts or changing numbers.\nOutput exactly two parts in the same language as the source:\n1. First line: a concise title only.\n2. Following lines: a concise summary of the content.\nDo not output labels, Markdown headings, bullet points, or any other commentary.\n\nParagraphs:\n{cluster_content}", | ||
| "max_token": 512, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Normalize the RAPTOR configuration before execution.
The new prompt and max_token values are assigned only when use_raptor is false. Existing datasets with raptor.use_raptor == true skip this block and retain the persisted legacy prompt and settings.
The fallback branch also writes threshold, clustering_method, and tree_builder, but it does not write clustering_threshold or clustering_ratio. The new RAPTOR implementation and template schema use the latter keys. This leaves two configuration contracts and can cause legacy-format summaries, unintended clustering defaults, or a downstream key error.
Normalize persisted RAPTOR configurations for both existing and newly enabled datasets. Remove the legacy fields. Add tests for both paths.
Proposed configuration change
- "threshold": 0.1,
+ "clustering_threshold": 0.3,
+ "clustering_ratio": 0.5,
...
- "clustering_method": "gmm",
- "tree_builder": "raptor",As per coding guidelines, during review remove deprecated, legacy, and compatibility-only code and collapse duplicate implementations.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@rag/svr/task_executor_refactor/task_handler.py` around lines 377 - 378,
Normalize RAPTOR configuration in the task handler for both use_raptor branches,
ensuring the current prompt and max_token values are always applied. Replace
legacy threshold, clustering_method, and tree_builder assignments with the
canonical clustering_threshold and clustering_ratio keys, remove deprecated
compatibility fields and duplicate fallback behavior, and add tests covering
existing enabled datasets and newly enabled datasets.
Source: Coding guidelines
| <SliderInputFormField | ||
| name={`templates.${index}.config.raptor.max_token`} | ||
| label={t('setting.maxToken')} | ||
| max={2048} | ||
| min={0} | ||
| min={512} | ||
| step={1} | ||
| /> |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 'TreeTemplateFields|defaultValues|reset\(|max_token' \
web/src/pages/user-setting/compilation-templatesRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- SliderInputFormField outline ---\n'
ast-grep outline web/src/components/slider-input-form-field.tsx || true
printf '\n--- SliderInputFormField relevant lines ---\n'
nl -ba web/src/components/slider-input-form-field.tsx | sed -n '1,220p'
printf '\n--- create-next schema outlines/relevant sections ---\n'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/schema.ts | sed -n '1,180p'
printf '\n--- create-next utils DefaultValues/relevant sections ---\n'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/utils.ts | sed -n '1,260p'
printf '\n--- create-next group form relevant section ---\n'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/hooks/use-compilation-template-group-form.ts | sed -n '1,140p'Repository: infiniflow/ragflow
Length of output: 247
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- SliderInputFormField outline ---'
ast-grep outline web/src/components/slider-input-form-field.tsx || true
echo
echo '--- SliderInputFormField relevant lines ---'
nl -ba web/src/components/slider-input-form-field.tsx | sed -n '1,220p'
echo
echo '--- create-next schema relevant sections ---'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/schema.ts | sed -n '1,180p'
echo
echo '--- create-next utils DefaultValues relevant sections ---'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/utils.ts | sed -n '1,260p'
echo
echo '--- create-next group form relevant section ---'
nl -ba web/src/pages/user-setting/compilation-templates/create-next/hooks/use-compilation-template-group-form.ts | sed -n '1,140p'Repository: infiniflow/ragflow
Length of output: 451
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- SliderInputFormField relevant lines ---'
sed -n '1,220p' web/src/components/slider-input-form-field.tsx
echo
echo '--- create-next schema relevant sections ---'
sed -n '1,180p' web/src/pages/user-setting/compilation-templates/create-next/schema.ts
echo
echo '--- create-next utils DefaultValues relevant sections ---'
sed -n '1,260p' web/src/pages/user-setting/compilation-templates/create-next/utils.ts
echo
echo '--- create-next group form relevant section ---'
sed -n '1,140p' web/src/pages/user-setting/compilation-templates/create-next/hooks/use-compilation-template-group-form.ts
echo
echo '--- DefaultValues symbol usages ---'
rg -n 'DefaultValues|useCompilationTemplateGroupForm|transform.*Form' web/src/pages/user-setting/compilation-templates/create-nextRepository: infiniflow/ragflow
Length of output: 17717
Keep max_token state within the new lower bound.
Raptor.config has no max_token default, so SliderInputFormField initializes an omitted value to 0. Its numeric input also accepts 0 before validation. Set the create/reset defaults to 512 and make the shared numeric handler enforce the field’s configured minimum.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx`
around lines 29 - 35, Update the create/reset defaults for
Raptor.config.max_token to 512, and modify the shared numeric input handler used
by SliderInputFormField to clamp or reject values below the configured min.
Ensure the field cannot retain or accept 0 when its minimum is 512, while
preserving existing behavior for valid values.
wangq8
left a comment
There was a problem hiding this comment.
Thanks for this simplification — the reduction from ~1200 lines to ~200 is a meaningful cleanup. I found a few issues that need attention:
🔴 Must-fix: task_handler.py incomplete update
rag/svr/task_executor_refactor/task_handler.py:_run_raptor was only partially updated. The fallback config dict still contains the removed fields (threshold: 0.1, clustering_method: "gmm", tree_builder: "raptor") and is missing the new fields (clustering_threshold, clustering_ratio). These removed fields will fail Pydantic validation since RaptorConfig no longer accepts them.
Please align this dict with the changes in api_utils.py, do_handle_task, and the compiler — add clustering_threshold: 0.3, clustering_ratio: 0.5, and remove threshold, clustering_method, and tree_builder.
🟡 Naming / docstring mismatch: clustering_threshold
The parameter is named like an absolute cosine-similarity threshold, and the constructor docstring says "Adjacent chunks with cosine similarity below this value become cluster boundaries." But in _get_clusters_ahc, the value is actually used as a percentile via int(round(self._clustering_threshold * 100)). A user setting 0.3 expects a similarity cutoff of 0.3, not the 30th percentile.
Consider either:
- Renaming to
clustering_percentileand updating the docstring, or - Using it as an absolute threshold (clamp to a percentile only in the ratio-cap fallback).
🟡 Method naming: _get_clusters_ahc
The method still carries ahc in its name but now implements 1D watershed segmentation over adjacent similarities, not agglomerative hierarchical clustering. Consider renaming to _get_clusters_watershed or _get_clusters_adjacent.
🟢 Minor: unused random_state parameter
clustering() still accepts random_state but no code path uses it anymore (GMM was the only consumer). Not a bug, but worth cleaning up in a follow-up.
✅ Good
- The watershed + ratio-cap approach is clean and O(N)
- Leaf-cluster materialization consolidation is correct
- Prompt restructuring to enforce title-first-line format is a nice improvement
max_tokenclamping to 512–2048 in the constructor adds a safety net- Test cleanup is thorough — no stale Psi references left
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17614 +/- ##
=======================================
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.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
rag/flow/compiler/compiler.py (2)
586-609: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winCollapse the duplicated
_normalize_upstream_chunkscalls.All three branches (
"chunks",{"markdown", "text", "html"},"json") call_normalize_upstream_chunkswith the identical argumentskwargs, split_json_text=should_rechunk, target_token_size=target_token_size. The"json"branch's early return duplicates the unconditionalif not chunksguard right after theif/elifchain.Since
_normalize_upstream_chunksalready dispatches internally onupstream.get("output_format"), one unconditional call covers all these cases.♻️ Proposed refactor
- if output_format == "chunks": - chunks = self._normalize_upstream_chunks( - kwargs, - split_json_text=should_rechunk, - target_token_size=target_token_size, - ) - elif output_format in {"markdown", "text", "html"}: - chunks = self._normalize_upstream_chunks( - kwargs, - split_json_text=should_rechunk, - target_token_size=target_token_size, - ) - elif output_format == "json": - chunks = self._normalize_upstream_chunks( - kwargs, - split_json_text=should_rechunk, - target_token_size=target_token_size, - ) - if not chunks: - self.set_output("chunks", chunks) - return - if not chunks: + chunks = self._normalize_upstream_chunks( + kwargs, + split_json_text=should_rechunk, + target_token_size=target_token_size, + ) + if not chunks: self.set_output("chunks", chunks) returnBased on coding guidelines: "During review, remove deprecated, legacy, and compatibility-only code; collapse duplicate implementations."
🤖 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 586 - 609, In the output-format handling flow, replace the duplicated `_normalize_upstream_chunks` calls across the `"chunks"`, markdown/text/html, and `"json"` branches with one unconditional call using the existing arguments. Remove the `"json"`-specific empty-chunks return and retain the single following `if not chunks` guard for all formats.Source: Coding guidelines
611-613: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winChunk id collisions for repeated verbatim text within a document.
ck["id"]is derived only fromck["text"]andck["doc_id"]. If the same text appears more than once in a document (boilerplate headers, footers, repeated table cells, TOC entries), two distinct chunks get the identical id.This matters because
_formalize_rechunked_chunks(Line 151) buildsoriginals = {str(chunk.get("id")): chunk for chunk in chunks if chunk.get("id")}. A colliding id causes the dict to keep only one of the chunks; the other is silently aliased to the wrong original when a rechunked group references it by id. The same id is also used later as a document/graph node reference in tree and structure compilation.Include a positional discriminator (index or original chunk id) in the hash input to keep ids unique per source position.
🐛 Proposed fix
- for ck in chunks: + for idx, ck in enumerate(chunks): ck["doc_id"] = doc_id - ck["id"] = xxhash.xxh64((ck["text"] + str(ck["doc_id"])).encode("utf-8")).hexdigest() + ck["id"] = xxhash.xxh64(f"{ck['text']}\x00{ck['doc_id']}\x00{idx}".encode("utf-8")).hexdigest()🤖 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 611 - 613, The chunk id computation at the xxhash.xxh64 call in the loop over chunks is missing a positional discriminator, causing identical ids when the same text appears multiple times within a document. This leads to silent data loss in _formalize_rechunked_chunks when the originals dictionary keyed by id keeps only one chunk per collision. Update the hash input to include a position-based discriminator such as the chunk's index or iteration count alongside the existing text and doc_id components, ensuring each chunk gets a unique id regardless of text repetition.
🧹 Nitpick comments (1)
rag/flow/compiler/compiler.py (1)
496-526: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winNon-"chunks" output formats normalize chunks twice.
For non-
"chunks"output formats,_normalize_upstream_chunks(kwargs)runs once at Line 506 (withoutsplit_json_text/target_token_size, only to check emptiness), then again with the correct arguments at Lines 592-603 after templates andshould_rechunkare resolved. This runs the full normalization pass, including recursive_slumber_candidatessplitting, twice for the same upstream payload on documents that reach the main processing path.Consider a lightweight emptiness check for the early guard (for example, checking the raw
upstream.get(output_format)string/list directly) instead of running full normalization twice.🤖 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 496 - 526, The non-"chunks" path invokes _normalize_upstream_chunks twice, causing duplicate normalization before main processing. Replace the early chunks assignment and emptiness guard near output_format handling with a lightweight check of the raw upstream value for the selected output format, while preserving the existing full normalization call after templates and should_rechunk are resolved; keep the "chunks" path behavior unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@rag/flow/compiler/compiler.py`:
- Around line 586-609: In the output-format handling flow, replace the
duplicated `_normalize_upstream_chunks` calls across the `"chunks"`,
markdown/text/html, and `"json"` branches with one unconditional call using the
existing arguments. Remove the `"json"`-specific empty-chunks return and retain
the single following `if not chunks` guard for all formats.
- Around line 611-613: The chunk id computation at the xxhash.xxh64 call in the
loop over chunks is missing a positional discriminator, causing identical ids
when the same text appears multiple times within a document. This leads to
silent data loss in _formalize_rechunked_chunks when the originals dictionary
keyed by id keeps only one chunk per collision. Update the hash input to include
a position-based discriminator such as the chunk's index or iteration count
alongside the existing text and doc_id components, ensuring each chunk gets a
unique id regardless of text repetition.
---
Nitpick comments:
In `@rag/flow/compiler/compiler.py`:
- Around line 496-526: The non-"chunks" path invokes _normalize_upstream_chunks
twice, causing duplicate normalization before main processing. Replace the early
chunks assignment and emptiness guard near output_format handling with a
lightweight check of the raw upstream value for the selected output format,
while preserving the existing full normalization call after templates and
should_rechunk are resolved; keep the "chunks" path behavior unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 896293f1-e08d-4a92-8d36-a5802a7c2ab4
📒 Files selected for processing (10)
api/utils/validation_utils.pyrag/flow/compiler/compiler.pyrag/svr/task_executor_refactor/chunk_post_processor.pytest/unit_test/rag/svr/task_executor_refactor/test_raptor_service.pyweb/src/interfaces/database/compilation-template.tsweb/src/interfaces/request/compilation-template.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/utils.ts
💤 Files with no reviewable changes (1)
- rag/svr/task_executor_refactor/chunk_post_processor.py
🚧 Files skipped from review as they are similar to previous changes (7)
- web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
- web/src/interfaces/request/compilation-template.ts
- web/src/interfaces/database/compilation-template.ts
- web/src/pages/user-setting/compilation-templates/create-next/utils.ts
- web/src/locales/zh.ts
- api/utils/validation_utils.py
- web/src/locales/en.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
rag/advanced_rag/knowlege_compile/raptor.py (2)
144-144: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant
int()casts.
round()with a single argument returns anint, soint(round(...))is redundant. Ruff reports RUF046 on both lines.♻️ Proposed cleanup
- max_clusters = max(1, int(round(n * self._clustering_ratio))) + max_clusters = max(1, round(n * self._clustering_ratio))- pct = max(1, min(99, int(round(self._clustering_threshold * 100)))) + pct = max(1, min(99, round(self._clustering_threshold * 100)))Also applies to: 161-161
🤖 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` at line 144, Remove the redundant int() wrappers around round() in the max_clusters calculations at both affected locations, preserving the existing max(1, ...) logic and behavior.Source: Linters/SAST tools
118-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename
_get_clusters_ahcand remove the unusedmax_clusterargument.
_get_clusters_ahc(...)only usesclustering_ratio;clustering_ratio *= 2now has no effect. Rename the helper to_watershed_labels(...)or remove redundant handling, and remove the stalemax_cluster/_max_clusterconstructor state unless it is required for the documented/configured API surface.🤖 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 118 - 119, Rename _get_clusters_ahc to _watershed_labels and update every call site; remove the unused max_cluster/_max_cluster constructor state and any related parameter or handling, including the ineffective clustering_ratio *= 2 logic, while preserving the existing watershed label behavior and configured API only if it is explicitly required.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.
Nitpick comments:
In `@rag/advanced_rag/knowlege_compile/raptor.py`:
- Line 144: Remove the redundant int() wrappers around round() in the
max_clusters calculations at both affected locations, preserving the existing
max(1, ...) logic and behavior.
- Around line 118-119: Rename _get_clusters_ahc to _watershed_labels and update
every call site; remove the unused max_cluster/_max_cluster constructor state
and any related parameter or handling, including the ineffective
clustering_ratio *= 2 logic, while preserving the existing watershed label
behavior and configured API only if it is explicitly required.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3ca919d8-6d38-4528-81f6-5694bb6244a6
📒 Files selected for processing (23)
api/db/init_data/compilation_templates/tree.yamlapi/utils/api_utils.pyapi/utils/validation_utils.pyrag/advanced_rag/knowlege_compile/raptor.pyrag/flow/compiler/compiler.pyrag/svr/task_executor.pyrag/svr/task_executor_refactor/chunk_post_processor.pyrag/svr/task_executor_refactor/raptor_service.pyrag/svr/task_executor_refactor/task_handler.pyrag/utils/raptor_utils.pytest/unit_test/rag/svr/task_executor_refactor/test_raptor_service.pytest/unit_test/rag/test_raptor_psi_tree_builder.pytest/unit_test/rag/utils/test_raptor_utils.pyweb/src/interfaces/database/compilation-template.tsweb/src/interfaces/request/compilation-template.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/create-next/schema.tsweb/src/pages/user-setting/compilation-templates/create-next/utils.tsweb/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsxweb/src/pages/user-setting/compilation-templates/edit-next/schema.tsweb/src/pages/user-setting/compilation-templates/edit-next/utils.ts
💤 Files with no reviewable changes (3)
- test/unit_test/rag/test_raptor_psi_tree_builder.py
- rag/utils/raptor_utils.py
- rag/svr/task_executor_refactor/chunk_post_processor.py
🚧 Files skipped from review as they are similar to previous changes (19)
- rag/svr/task_executor_refactor/task_handler.py
- web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx
- web/src/interfaces/database/compilation-template.ts
- web/src/pages/user-setting/compilation-templates/create-next/schema.ts
- api/utils/validation_utils.py
- rag/flow/compiler/compiler.py
- web/src/locales/en.ts
- api/utils/api_utils.py
- api/db/init_data/compilation_templates/tree.yaml
- web/src/pages/user-setting/compilation-templates/edit-next/schema.ts
- test/unit_test/rag/svr/task_executor_refactor/test_raptor_service.py
- rag/svr/task_executor_refactor/raptor_service.py
- web/src/interfaces/request/compilation-template.ts
- web/src/locales/zh.ts
- test/unit_test/rag/utils/test_raptor_utils.py
- rag/svr/task_executor.py
- web/src/pages/user-setting/compilation-templates/create-next/components/tree-template-fields.tsx
- web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
- web/src/pages/user-setting/compilation-templates/create-next/utils.ts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/testcases/test_http_api/test_dataset_management/test_create_dataset.py (1)
566-572: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winUpdate the stale RAPTOR
max_tokenerror expectations.The API now requires
max_token >= 512. These tests still expect the previous>= 1message, so both cases fail when validation returns the new message.
test/testcases/test_http_api/test_dataset_management/test_create_dataset.py#L566-L572: change the expected minimum-bound message toInput should be greater than or equal to 512.test/testcases/test_http_api/test_dataset_management/test_update_dataset.py#L696-L702: change the expected minimum-bound message toInput should be greater than or equal to 512.🤖 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 `@test/testcases/test_http_api/test_dataset_management/test_create_dataset.py` around lines 566 - 572, Update the expected minimum-bound error for RAPTOR max_token validation from “Input should be greater than or equal to 1” to “Input should be greater than or equal to 512” in test/testcases/test_http_api/test_dataset_management/test_create_dataset.py lines 566-572 and test/testcases/test_http_api/test_dataset_management/test_update_dataset.py lines 696-702; leave the other expectations unchanged.
🧹 Nitpick comments (1)
test/testcases/restful_api/test_datasets.py (1)
275-280: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd
clustering_ratiocontract cases.The migration adds
clustering_ratio, but these dataset create/update matrices only testclustering_threshold. Add valid boundary and invalid type and bound cases using the limits defined by backend validation.
test/testcases/restful_api/test_datasets.py#L275-L280: add REST create and update ratio cases.test/testcases/test_http_api/test_dataset_management/test_create_dataset.py#L442-L447: add HTTP create ratio cases.test/testcases/test_http_api/test_dataset_management/test_update_dataset.py#L576-L581: add HTTP update ratio cases.test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py#L399-L404: add SDK create ratio cases.test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py#L461-L466: add SDK update ratio cases.As per coding guidelines, preserve still-valid behavior with focused tests.
🤖 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 `@test/testcases/restful_api/test_datasets.py` around lines 275 - 280, Add clustering_ratio contract coverage using the backend validation limits: valid boundary cases plus invalid type and out-of-bound cases. Update the REST create/update matrices in test/testcases/restful_api/test_datasets.py:275-280, HTTP create cases in test/testcases/test_http_api/test_dataset_management/test_create_dataset.py:442-447, HTTP update cases in test/testcases/test_http_api/test_dataset_management/test_update_dataset.py:576-581, SDK create cases in test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py:399-404, and SDK update cases in test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py:461-466; preserve existing valid clustering_threshold coverage.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.
Outside diff comments:
In `@test/testcases/test_http_api/test_dataset_management/test_create_dataset.py`:
- Around line 566-572: Update the expected minimum-bound error for RAPTOR
max_token validation from “Input should be greater than or equal to 1” to “Input
should be greater than or equal to 512” in
test/testcases/test_http_api/test_dataset_management/test_create_dataset.py
lines 566-572 and
test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
lines 696-702; leave the other expectations unchanged.
---
Nitpick comments:
In `@test/testcases/restful_api/test_datasets.py`:
- Around line 275-280: Add clustering_ratio contract coverage using the backend
validation limits: valid boundary cases plus invalid type and out-of-bound
cases. Update the REST create/update matrices in
test/testcases/restful_api/test_datasets.py:275-280, HTTP create cases in
test/testcases/test_http_api/test_dataset_management/test_create_dataset.py:442-447,
HTTP update cases in
test/testcases/test_http_api/test_dataset_management/test_update_dataset.py:576-581,
SDK create cases in
test/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.py:399-404,
and SDK update cases in
test/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.py:461-466;
preserve existing valid clustering_threshold coverage.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4e265142-6d6a-4e4f-a44e-970514550de8
📒 Files selected for processing (9)
test/testcases/configs.pytest/testcases/restful_api/test_datasets.pytest/testcases/restful_api/test_documents.pytest/testcases/test_http_api/test_dataset_management/test_create_dataset.pytest/testcases/test_http_api/test_dataset_management/test_update_dataset.pytest/testcases/test_http_api/test_file_management_within_dataset/test_update_document.pytest/testcases/test_sdk_api/test_dataset_mangement/test_create_dataset.pytest/testcases/test_sdk_api/test_dataset_mangement/test_update_dataset.pytest/testcases/test_sdk_api/test_file_management_within_dataset/test_update_document.py
Summary
This PR simplifies RAPTOR tree construction and replaces the previous configurable GMM/Psi clustering paths with a deterministic adjacent-similarity clustering strategy.
Changes
clustering_thresholdandclustering_ratioconfiguration fields.max_tokento the supported range of 512–2048.thresholdclustering_methodtree_builderext