Repository navigation
Collapse small RAPTOR layers in one step instead of one node per layer - #16633
Conversation
Above the first layer, self.clustering() on a small set of well-separated summary nodes typically returns n-1, so the tree descends one node per layer (N -> N-1 -> N-2 -> ... -> 1), each step a full clustering + summarize pass. This is distinct from the existing n_clusters >= len termination guard, which only fires on the degenerate N -> N case and still runs a clustering pass every layer. When a layer already has few enough nodes that there's no meaningful structure to find, skip clustering and summarize the whole layer into one parent. Threshold configurable via small_layer_collapse (default 8).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a ChangesRAPTOR Small Layer Collapse
Estimated code review effort: 2 (Simple) | ~10 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant RAPTOR as RecursiveAbstractiveProcessing4TreeOrganizedRetrieval
participant Summarizer
Caller->>RAPTOR: __call__(chunks)
RAPTOR->>RAPTOR: check end - start <= small_layer_collapse
alt layer is small
RAPTOR->>Summarizer: summarize entire layer as one cluster
Summarizer-->>RAPTOR: cluster summary
RAPTOR->>RAPTOR: append (end, len(chunks)) boundary
RAPTOR->>Caller: callback message, break loop
else layer is large
RAPTOR->>RAPTOR: proceed with clustering
end
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.
🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/raptor.py (3)
849-863: 🎯 Functional Correctness | 🔵 TrivialMissing test coverage for the classic-builder collapse branch.
The supplied test context only covers the PSI tree builder (
test_psi_tree_builder_materializes_rebalanced_summary_layers_without_umap); no test exercisessmall_layer_collapsein the classic (non-Psi)__call__path added here. Given the behavioral change flagged above (collapse triggering on layer 0), a regression test asserting expectedlayersboundaries for small documents (both above and below the threshold) would help lock in intended behavior.Want me to draft a unit test for this branch?
🤖 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 849 - 863, Add regression coverage for the classic RAPTOR builder path in raptor.py, specifically the small-layer collapse branch inside RAPTOR.__call__ (the summarize(list(range(start, end))) path). Create tests that exercise documents just below and just above self._small_layer_collapse and assert the resulting layers boundaries and callback/materialization behavior, so the collapse-on-layer-0 behavior is locked in for the non-Psi builder.
849-863: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a success-path log for the new collapse flow.
The failure branch (
produced == 0) logs a warning, but the success path — the primary new behavior this PR introduces — has nologging.info/logging.debugcall, unlike other new-flow branches in this file (e.g. then_clusters >= len(embeddings)collapse at Line 897 logs a warning, and the Psi layer materialization at Line 722 logs an info message per layer). Add an info-level log recording the collapse (e.g., node count collapsed and layer index) to aid diagnosing tree-shape regressions in production.As per coding guidelines, "Add logging for new flows".
📝 Proposed addition
if end - start <= self._small_layer_collapse: # Too few nodes for meaningful sub-clustering. Skip the # clustering pass entirely and summarize the whole layer # into one parent, so the upper tree doesn't descend one # node per layer (N -> N-1 -> N-2 -> ... each a full # clustering + summarize pass). + logging.info( + "RAPTOR: small layer (%d <= %d) collapsing directly into one summary", + end - start, + self._small_layer_collapse, + ) await summarize(list(range(start, end)))🤖 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 849 - 863, Add a success-path log for the small-N collapse flow in the RAPTOR layer materialization branch. In the `summarize(...)` path inside `raptor.py`, the `produced == 0` warning exists, but the normal collapse success path currently has no `logging.info` or `logging.debug` entry. Add an info-level log near the `layers.append(...)`/`callback(...)` logic that records the collapse details (such as the number of nodes collapsed and the layer index or range) so the new behavior can be traced alongside other flows in `materialize_layers`/the collapse branch.Source: Coding guidelines
864-875: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
len(embeddings) == 2branch is now effectively unreachable.With the new
small_layer_collapsecheck (default8) placed first, any layer withend - start <= 8— which always includesend - start == 2— is handled by that branch and the loopbreaks. This special case only remains reachable if a caller explicitly setssmall_layer_collapse < 2. Consider removing this now-redundant branch or merging its logic with the new collapse branch to avoid maintaining duplicate (and now dead-by-default) code paths.🤖 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 864 - 875, The `len(embeddings) == 2` path in `materialize` is now dead by default because the earlier `small_layer_collapse` check catches it and breaks first. Remove this redundant branch or fold its special handling into the `small_layer_collapse` branch so the `summarize`, `produced`, `callback`, `layers.append`, and `start/end` update logic isn’t duplicated across unreachable code paths.
🤖 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`:
- Around line 849-863: Add regression coverage for the classic RAPTOR builder
path in raptor.py, specifically the small-layer collapse branch inside
RAPTOR.__call__ (the summarize(list(range(start, end))) path). Create tests that
exercise documents just below and just above self._small_layer_collapse and
assert the resulting layers boundaries and callback/materialization behavior, so
the collapse-on-layer-0 behavior is locked in for the non-Psi builder.
- Around line 849-863: Add a success-path log for the small-N collapse flow in
the RAPTOR layer materialization branch. In the `summarize(...)` path inside
`raptor.py`, the `produced == 0` warning exists, but the normal collapse success
path currently has no `logging.info` or `logging.debug` entry. Add an info-level
log near the `layers.append(...)`/`callback(...)` logic that records the
collapse details (such as the number of nodes collapsed and the layer index or
range) so the new behavior can be traced alongside other flows in
`materialize_layers`/the collapse branch.
- Around line 864-875: The `len(embeddings) == 2` path in `materialize` is now
dead by default because the earlier `small_layer_collapse` check catches it and
breaks first. Remove this redundant branch or fold its special handling into the
`small_layer_collapse` branch so the `summarize`, `produced`, `callback`,
`layers.append`, and `start/end` update logic isn’t duplicated across
unreachable code paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 310f7960-79e3-4db5-84c0-9dfc61f49c6c
📒 Files selected for processing (1)
rag/advanced_rag/knowlege_compile/raptor.py
…; add collapse success log
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16633 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Problem
Above the first layer,
self.clustering()runs on a small set ofwell-separated summary nodes. BIC there almost always returns
n-1, so thetree descends one node per layer —
N -> N-1 -> N-2 -> ... -> 1— andeach of those steps is a full clustering + summarization pass. Observed across
several KBs as ~26–34 layers to collapse ~27–35 nodes, turning a sub-minute
build into minutes of upper-layer churn (plus a
ConvergenceWarningfloodfrom fitting many components to few points).
This is distinct from the existing
n_clusters >= len(embeddings)termination guard, and not a replacement for it. That guard is reactive:
it fires only after a clustering pass returns one-cluster-per-input (the
degenerate
N -> Ncase). It doesn't catch the staircase, because eachN -> N-1step does technically reduce the count by one — so the guardnever trips, and a clustering pass runs on every rung.
Fix
Proactively skip clustering for layers that are already small. When a layer
has
<= small_layer_collapsenodes (default 8), there's no meaningfulsub-cluster structure to discover, so summarize the whole layer into a single
parent in one step and finish. The threshold is configurable via a new
small_layer_collapseconstructor argument.Result
N -> N-1 -> ... -> 1staircases become a singleN -> 1 (small-N collapse)step. Verified in logs (5 -> 1 (small-N collapse)). Upper-layer build time drops from minutes to seconds; theresulting tree's leaves are unchanged.