Repository navigation
perf(filtered-read): consolidate take-shaped masked reads off the consumer - #7783
Conversation
…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]>
📝 WalkthroughWalkthroughFiltered 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. ChangesTake-shaped masked read consolidation
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested reviewers: 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
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
@bench-bot please run benchmark |
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
rust/lance/src/io/exec/filtered_read.rs
…ize in test, is_sparse_plan rename, zero-target guard Co-Authored-By: Claude Fable 5 <[email protected]>
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)
rust/lance/src/io/exec/filtered_read.rs (2)
2675-2678: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove 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 intest_index_expr_result_serialize_roundtripwas missed. As per coding guidelines, "Placeuseimports 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 liftExtract the coalescing pipeline into a submodule.
consolidated_stream/coalesce_batches(~90 lines of new batch-merging logic, plus the privateCoalescerstate machine) are inlined directly intofiltered_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
📒 Files selected for processing (1)
rust/lance/src/io/exec/filtered_read.rs
|
@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
left a comment
There was a problem hiding this comment.
Just one request but otherwise this seems like a very sensible addition!
| .map(|batch_size| batch_size as usize) | ||
| .unwrap_or_else(|| get_default_batch_size().unwrap_or(BATCH_SIZE_FALLBACK)); |
There was a problem hiding this comment.
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.
…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]>
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)
rust/lance/src/io/exec/filtered_read.rs (2)
337-446: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy liftExtract the coalescing pipeline into a dedicated submodule.
consolidated_stream,coalesce_batches, and the privateCoalescerstate 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 winUse named column access in the test.
column(0)couples this assertion to projection order; usebatches[0]["value"]instead. As per coding guidelines, “usebatch["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
📒 Files selected for processing (1)
rust/lance/src/io/exec/filtered_read.rs
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_streamunfold/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:
Testing
test_take_shaped_mask_consolidationcovers 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.filtered_readandscannersuites pass (the intermittent suite-mode failures reproduce on main without this change).🤖 Generated with Claude Code
Summary by CodeRabbit