Skip to content

Collapse small RAPTOR layers in one step instead of one node per layer - #16633

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
afrozenpeach:fix/raptor-small-layer-collapse
Jul 6, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
afrozenpeach:fix/raptor-small-layer-collapse

Conversation

@afrozenpeach

Copy link
Copy Markdown
Contributor

Problem

Above the first layer, self.clustering() runs on a small set of
well-separated summary nodes. BIC there almost always returns n-1, so the
tree descends one node per layer — N -> N-1 -> N-2 -> ... -> 1 — and
each 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 ConvergenceWarning flood
from 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 -> N case). It doesn't catch the staircase, because each
N -> N-1 step does technically reduce the count by one — so the guard
never 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_collapse nodes (default 8), there's no meaningful
sub-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_collapse constructor argument.

Result

N -> N-1 -> ... -> 1 staircases become a single
N -> 1 (small-N collapse) step. Verified in logs (5 -> 1 (small-N collapse)). Upper-layer build time drops from minutes to seconds; the
resulting tree's leaves are unchanged.

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).
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jul 4, 2026
@coderabbitai

coderabbitai Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: aa1dc2dd-5b89-4582-8c7a-0bde0d3c95ba

📥 Commits

Reviewing files that changed from the base of the PR and between 6478b57 and d8d1ef1.

📒 Files selected for processing (1)
  • rag/advanced_rag/knowlege_compile/raptor.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/advanced_rag/knowlege_compile/raptor.py

📝 Walkthrough

Walkthrough

Adds a small_layer_collapse constructor parameter (default 8) to RecursiveAbstractiveProcessing4TreeOrganizedRetrieval, and a corresponding branch in the layer-materialization loop that bypasses clustering for small layers, summarizing them directly into a single parent cluster.

Changes

RAPTOR Small Layer Collapse

Layer / File(s) Summary
Small layer collapse configuration and control flow
rag/advanced_rag/knowlege_compile/raptor.py
Adds small_layer_collapse parameter (default 8) stored as self._small_layer_collapse, and a branch in __call__ that, when a layer size is at or below this threshold, skips clustering, summarizes the whole layer as one cluster, appends the layer boundary, logs/callback, and breaks the loop.

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
Loading

Poem

A tiny layer, small and neat,
No need to cluster, that's a treat!
One summary, quick and light,
Eight or fewer, done just right 🐇
Hoppy trees grow clean and tight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: collapsing small RAPTOR layers in one step.
Description check ✅ Passed The description explains the problem, fix, and result, but it does not use the template's explicit Summary section heading.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
rag/advanced_rag/knowlege_compile/raptor.py (3)

849-863: 🎯 Functional Correctness | 🔵 Trivial

Missing 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 exercises small_layer_collapse in the classic (non-Psi) __call__ path added here. Given the behavioral change flagged above (collapse triggering on layer 0), a regression test asserting expected layers boundaries 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 win

Add 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 no logging.info/logging.debug call, unlike other new-flow branches in this file (e.g. the n_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) == 2 branch is now effectively unreachable.

With the new small_layer_collapse check (default 8) placed first, any layer with end - start <= 8 — which always includes end - start == 2 — is handled by that branch and the loop breaks. This special case only remains reachable if a caller explicitly sets small_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

📥 Commits

Reviewing files that changed from the base of the PR and between 0fcfb38 and 6478b57.

📒 Files selected for processing (1)
  • rag/advanced_rag/knowlege_compile/raptor.py

@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3a247db) to head (2d6b5d9).
⚠️ Report is 9 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit 0c2fb62 into infiniflow:main Jul 6, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants