Skip to content

perf(filtered-read): consolidate take-shaped masked reads off the consumer - #7783

Merged
LuQQiu merged 5 commits into
lance-format:mainfrom
LuQQiu:lu/take-mask
Jul 14, 2026
Merged

LuQQiu merged 5 commits into
lance-format:mainfrom
LuQQiu:lu/take-mask

Conversation

@LuQQiu

@LuQQiu LuQQiu commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A masked (row-set) read whose plan touches many fragments with only a few rows each — the shape a take-style workload produces — emits one tiny batch per fragment (a batch never spans fragments). The per-batch pipeline driving executes inline in whichever task polls the node's output, so concurrent small reads serialize on their consumers. A flamegraph of 64 concurrent take-100 masked reads shows the polling thread saturated by the task_stream unfold/buffer machinery while workers sit idle.

Fix

For take-shaped plans only — a row-set input, at least 8 fragments planned non-empty, and fewer than 1024 planned rows per fragment on average — pump the read on a spawned task and hand the consumer consolidated batches (merge-only: order preserved, any batch already at the target passes through whole).

Everything else is byte-for-byte unchanged: plain scans, single-fragment reads, dense masked reads (including filtered scans, whose planned rows are a pre-refine upper bound) and the byte-based rechunk path keep their batch boundaries, first-batch latency and backpressure.

Benchmarks

Single node, 100M rows / 100 fragments (NVMe, warm), fixed-seed scattered row sets, identical physical I/O between arms:

cell before after
masked take-100, concurrency 64 291 QPS 634 QPS (TakeExec: 485)
masked take-100K, concurrency 32 5.4 QPS 12.1 QPS
masked take-100 / take-10K / take-100K, concurrency 1 339 / 12.9 / 11.4 341 / 13.9 / 10.3 (within noise)
scan 2M rows, concurrency 1 / 8 287 / 175 256 / 158 (untouched code path, run-to-run variance)

Testing

  • New test_take_shaped_mask_consolidation covers the consolidated shape (single output batch, fragment order preserved), the few-fragment counterexample and the dense counterexample (per-fragment boundaries kept). It also pins the gate to count only fragments planned non-empty.
  • Existing filtered_read and scanner suites pass (the intermittent suite-mode failures reproduce on main without this change).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance Improvements
    • Improved masked read execution by consolidating many small per-fragment results into fewer larger batches when appropriate.
    • Reduced batch count for “take-shaped” masked reads to speed up downstream processing.
    • Preserved existing behavior for dense masked reads and for configurations that rely on byte-based rechunking or do not meet consolidation conditions.
  • Tests
    • Added a new test to validate batch consolidation for take-shaped masked reads and to confirm batch boundaries are maintained for dense/too-few-fragment scenarios.

…sumer

A masked read whose plan touches many fragments with only a few rows
each (the take shape) emits one tiny batch per fragment, and the
per-batch pipeline driving executes inline in whichever task polls the
output; concurrent small reads then serialize on their consumers
(flamegraph: the polling thread spends its time in the task_stream
unfold/buffer machinery while workers sit idle).

For such plans only — a row-set input, at least 8 fragments, and fewer
than 1024 planned rows per fragment on average — pump the read on a
spawned task and hand the consumer consolidated batches (merge-only:
order preserved, any batch already at the target passes through whole).
Plain scans, single-fragment reads, dense masked reads and the
byte-based rechunk path keep the inline path byte-for-byte: batch
boundaries, first-batch latency and backpressure are unchanged.

Single-node A/B on a 100M-row dataset (100 fragments, take-100 masked,
concurrency 64): 296 -> 557 QPS with identical physical I/O; scan and
low-concurrency cells unchanged within noise.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Filtered reads now detect sparse take-shaped plans, compute a target batch size, and optionally consolidate scalar-index masked batches. Byte rechunking and passthrough behavior remain unchanged, with tests covering sparse, dense, and small-fragment cases.

Changes

Take-shaped masked read consolidation

Layer / File(s) Summary
Batch coalescing pipeline
rust/lance/src/io/exec/filtered_read.rs
Adds asynchronous batch consolidation that merges batches toward a target row count while preserving order and existing target-sized batches.
Filtered read planning and integration
rust/lance/src/io/exec/filtered_read.rs
Computes sparse-plan metadata, selects consolidation for eligible scalar-index reads, preserves byte rechunking or passthrough paths, and tests sparse, dense, and few-fragment behavior.

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

Suggested reviewers: westonpace, xuanwo, bubblecal

Sequence Diagram(s)

sequenceDiagram
  participant FilteredReadStream
  participant FilteredReadExec
  participant consolidated_stream
  participant coalesce_batches
  FilteredReadStream->>FilteredReadExec: provide sparse-plan metadata and target rows
  FilteredReadExec->>consolidated_stream: wrap eligible scalar-index stream
  consolidated_stream->>coalesce_batches: merge batches to target row count
  coalesce_batches-->>FilteredReadExec: return consolidated batches
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: consolidating take-shaped masked reads off the consumer for performance.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@LuQQiu

LuQQiu commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

@bench-bot please run benchmark

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 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 `@rust/lance/src/io/exec/filtered_read.rs`:
- Around line 337-341: Rename the sparse_plan boolean field to is_sparse_plan in
its declaration and every use site, preserving its existing behavior and value
flow.
- Around line 2594-2597: Move the preceding “Round-trip every interval…”
documentation from test_take_shaped_mask_consolidation to
test_index_expr_result_serialize_roundtrip, leaving only the
consolidation-specific documentation attached to
test_take_shaped_mask_consolidation. Ensure each test’s doc comment accurately
describes its own semantics.
- Around line 2598-2641: The test currently uses inline imports and manually
encodes row addresses. Move OneShotExec, RowAddrMask, and RowAddrTreeMap imports
to the test module’s import section, then update the addr helper to construct
typed RowAddress values instead of using `(frag << 32) | offset`, preserving the
existing fragment and offset semantics.
- Around line 400-407: Update the emit method to remove the bare unwrap when
handling a single buffered batch. Safely extract the batch and return a
DataFusionError describing the violated buffer invariant if extraction
unexpectedly fails, while preserving the existing concatenation and successful
single-batch behavior.
- Around line 2631-2638: Update the test’s run closure to configure
FilteredReadOptions with an explicit batch size of 2,000 via
with_batch_size(2000) before constructing FilteredReadExec, preserving the
existing execution and collection flow so the eight-batch assertion is
independent of LANCE_DEFAULT_BATCH_SIZE.
- Around line 566-569: After resolving the final batch target in the
filtered-read setup, validate that batch_target_rows is nonzero before
constructing the coalescer; reject zero whether it came from options.batch_size
or get_default_batch_size(), while preserving the existing fallback resolution
for positive values.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6bedb152-25dd-43db-b0d7-a7a086177c07

📥 Commits

Reviewing files that changed from the base of the PR and between fff336c and 222cf60.

📒 Files selected for processing (1)
  • rust/lance/src/io/exec/filtered_read.rs

Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
@LuQQiu
LuQQiu requested a review from westonpace July 14, 2026 17:01

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rust/lance/src/io/exec/filtered_read.rs (2)

2675-2678: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the redundant inline import.

use lance_select::{RowAddrMask, RowAddrTreeMap}; at Line 2677 duplicates the module-level import already added at Line 2373 during the import-consolidation fix for the consolidation test — this instance in test_index_expr_result_serialize_roundtrip was missed. As per coding guidelines, "Place use imports at the top of the file, not inline within function bodies."

♻️ Proposed fix
     fn test_index_expr_result_serialize_roundtrip() {
-        use lance_select::{RowAddrMask, RowAddrTreeMap};
-
         let mk = |rows: &[u64]| RowAddrMask::from_allowed(RowAddrTreeMap::from_iter(rows));
🤖 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 `@rust/lance/src/io/exec/filtered_read.rs` around lines 2675 - 2678, Remove the
redundant inline lance_select import from
test_index_expr_result_serialize_roundtrip, relying on the existing module-level
RowAddrMask and RowAddrTreeMap import instead.

Source: Coding guidelines


352-447: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Extract the coalescing pipeline into a submodule.

consolidated_stream/coalesce_batches (~90 lines of new batch-merging logic, plus the private Coalescer state machine) are inlined directly into filtered_read.rs, which is already a very large file. As per coding guidelines, "Extract substantial new logic such as bin packing or scheduling into dedicated submodules instead of inlining it into large files."

🤖 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 `@rust/lance/src/io/exec/filtered_read.rs` around lines 352 - 447, Extract
consolidated_stream, coalesce_batches, and the private Coalescer state machine
into a dedicated submodule, then update filtered_read.rs to import and call the
extracted consolidated_stream API. Preserve the existing batching, ordering,
cancellation, and error behavior while keeping the implementation details
private to the new module.

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 `@rust/lance/src/io/exec/filtered_read.rs`:
- Around line 2675-2678: Remove the redundant inline lance_select import from
test_index_expr_result_serialize_roundtrip, relying on the existing module-level
RowAddrMask and RowAddrTreeMap import instead.
- Around line 352-447: Extract consolidated_stream, coalesce_batches, and the
private Coalescer state machine into a dedicated submodule, then update
filtered_read.rs to import and call the extracted consolidated_stream API.
Preserve the existing batching, ordering, cancellation, and error behavior while
keeping the implementation details private to the new module.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e6568dec-4da1-494f-9f90-0eb88c68470c

📥 Commits

Reviewing files that changed from the base of the PR and between 222cf60 and cc8f040.

📒 Files selected for processing (1)
  • rust/lance/src/io/exec/filtered_read.rs

@LuQQiu

LuQQiu commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

@westonpace in benchmarking I found that for random-access (take-like) masked reads, each touched fragment only contributes a few rows, and since a batch never spans fragments, the node emits one tiny batch (1-2 rows) per fragment , a take-100 scattered over 63 fragments emits ~63 batches. The consumer has to poll each of these tiny batches through the DataFusion pipeline, and each poll also drives the read pipeline machinery inline on the consumer's thread (flamegraph shows the polling thread saturated in the task_stream unfold/buffer code while workers sit idle). Under concurrency the queries serialize on their consumers: 64 concurrent take-100s plateau at ~296 QPS, vs ~634 after consolidating

Could you help trigger @bench-bot, looks like i cannot trigger them #7783 (comment)

@westonpace westonpace left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just one request but otherwise this seems like a very sensible addition!

Comment thread rust/lance/src/io/exec/filtered_read.rs Outdated
Comment on lines +569 to +570
.map(|batch_size| batch_size as usize)
.unwrap_or_else(|| get_default_batch_size().unwrap_or(BATCH_SIZE_FALLBACK));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Instead of unwrapping to BATCH_SIZE_FALLBACK can we use the batch size from the TaskContext? This means we need to resolve the batch size at execute time (not construction time) but I think that would be ok.

LuQQiu and others added 2 commits July 14, 2026 14:29
…time

Per review: prefer the DataFusion session batch size over the hard
BATCH_SIZE_FALLBACK when neither the option nor the lance env default
is set. The stream now records planned-shape counts and the gate
resolves at execute time where the TaskContext is available.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rust/lance/src/io/exec/filtered_read.rs (2)

337-446: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Extract the coalescing pipeline into a dedicated submodule.

consolidated_stream, coalesce_batches, and the private Coalescer state machine add substantial batching logic to this already large file. Move them behind a small private submodule API, preserving the existing ordering, cancellation, and error behavior. As per coding guidelines, “Extract substantial new logic such as bin packing or scheduling into dedicated submodules instead of inlining it into large files.”

🤖 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 `@rust/lance/src/io/exec/filtered_read.rs` around lines 337 - 446, Extract
consolidated_stream, coalesce_batches, and the private Coalescer state machine
into a small private submodule, exposing only the stream-consolidation entry
point needed by the parent module. Update the parent call sites to use that API
while preserving batching order, cancellation when the receiver drops, and
existing error propagation behavior.

Source: Coding guidelines


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

Use named column access in the test.

column(0) couples this assertion to projection order; use batches[0]["value"] instead. As per coding guidelines, “use batch["column_name"] in tests.”

Proposed fix
-        assert_eq!(batches[0].column(0).as_ref(), &expected);
+        assert_eq!(batches[0]["value"].as_ref(), &expected);
🤖 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 `@rust/lance/src/io/exec/filtered_read.rs` at line 2658, Update the test
assertion around batches[0] to access the expected column by its named "value"
field using the batch name-based indexing convention, replacing the positional
column(0) access while preserving the existing comparison.

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 `@rust/lance/src/io/exec/filtered_read.rs`:
- Around line 337-446: Extract consolidated_stream, coalesce_batches, and the
private Coalescer state machine into a small private submodule, exposing only
the stream-consolidation entry point needed by the parent module. Update the
parent call sites to use that API while preserving batching order, cancellation
when the receiver drops, and existing error propagation behavior.
- Line 2658: Update the test assertion around batches[0] to access the expected
column by its named "value" field using the batch name-based indexing
convention, replacing the positional column(0) access while preserving the
existing comparison.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 58b59c99-691e-461f-815c-b64e0e498400

📥 Commits

Reviewing files that changed from the base of the PR and between cc8f040 and 26c1821.

📒 Files selected for processing (1)
  • rust/lance/src/io/exec/filtered_read.rs

@LuQQiu
LuQQiu merged commit 45bc880 into lance-format:main Jul 14, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants