You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "avantgardnerio (via GitHub)" <gi...@apache.org> on 2026/07/24 15:05:33 UTC

[PR] feat(core): add OrderedRangeRepartitionExec — N sorted overlapping → K sorted disjoint [datafusion-ballista]

avantgardnerio opened a new pull request, #2169:
URL: https://github.com/apache/datafusion-ballista/pull/2169

   ## Summary
   
   Adds `OrderedRangeRepartitionExec` — the sorted sibling of `UnorderedRangeRepartitionExec` (#2123). Takes N locally-sorted input partitions whose value ranges may overlap; produces K range-disjoint output partitions where each output is *fully* sorted on the routing expression. Concatenating the K outputs in order yields a globally-sorted stream.
   
   Reuses `range_repartition_common.rs` verbatim (landed with #2123): same discovery mechanism — walk child subtree, find sibling `RuntimeStatsExec`, snapshot T-Digest, compute `K − 1` quantile cuts. Same fallback semantics: any discovery failure → single-bucket routing where every row lands in output 0.
   
   ## Why — Stage 2 → Stage 3 of the parallel-window path
   
   The parallel-window plan runs in three stages:
   
   1. **Stage 1** — sample. `RuntimeStatsExec` (#2094) accumulates a T-Digest as batches flow past. `BufferExec` (#2095) holds long enough for representative samples to arrive.
   2. **Stage 2** — sort each input partition locally. Cheap and embarrassingly parallel.
   3. **Stage 3** — one `BoundedWindowAggExec` per output partition, each fed a *globally-sorted* view of its value range.
   
   `UnorderedRangeRepartitionExec` covers the Stage-1→Stage-3 path for cases where sortedness is destroyed anyway (aggregate windows). This PR covers the Stage-2→Stage-3 path where downstream operators need the sort preserved.
   
   ## Execution model — N × K channels + K k-way merges
   
   - **N scatter tasks.** Each reads one sorted input, calls `split_batch_by_range` on every batch, forwards sub-batches to K per-input senders (one per output partition).
   - **K output-partition streams.** Each merges N sub-streams via DataFusion's `StreamingMergeBuilder` — the `SortPreservingMerge` internals, no custom heap machinery here.
   - **Backpressure.** Bounded `mpsc::channel(2)` per input × output, symmetric to the Unordered variant. Total buffered at rest ≤ N × K × 2 batches.
   
   Constructor requires `input.output_ordering()` to lead with the routing expression — otherwise the merger would produce garbled output. `PlanProperties::eq_properties` advertises each output partition as sorted on `order_by`, so downstream operators (BWAG, HaloDrop) can rely on that claim without inserting a redundant `SortExec`.
   
   ## Scope
   
   Just the operator + serde plumbing. Nothing inserts `OrderedRangeRepartitionExec` into a plan yet — no rewrite rule, no scheduler hook. Those land with the parallel-window detection rule alongside the Unordered sibling.
   
   Included:
   
   - `ordered_range_repartition.rs` — the operator + 8 unit tests.
   - Proto: `OrderedRangeRepartitionExecNode { repeated PhysicalSortExprNode order_by = 1; uint32 output_partitions = 2; }` on `BallistaPhysicalPlanNode.oneof` (tag 9; tag 8 is Unordered).
   - Codec encode/decode registration on `BallistaPhysicalExtensionCodec`.
   - One serde roundtrip test.
   - No new external deps.
   - No changes to `range_repartition_common.rs` — reused verbatim.
   
   ## Drift from source branch
   
   - `RuntimeStatsExec` now rejects nullable routing expressions at construction (T-Digest has no NULL slot; tightened during #2123's upstreaming). The original test suite declared `v2` as nullable and typed the batch builder as `Vec<Option<f64>>` but never actually populated a `None`. Tightened schema + helper types to non-nullable `f64`; will loosen again when we swap T-Digest for KLL and NULL becomes a first-class routing key.
   
   ## Tests (9 new)
   
   8 operator unit tests covering: constructor validation (empty order_by, unsorted input, mismatched sort key), end-to-end row conservation across two overlapping inputs, per-output sortedness, range-disjointness of outputs, no-stats fallback, and the double-execute guard.
   
   1 serde roundtrip test (single-key ORDER BY through the SortExec-wrap that satisfies the ordering claim).
   
   ## Test plan
   
   - [x] `cargo test -p ballista-core` — 175/175 pass (25 in the range-repartition modules).
   - [x] `cargo clippy --all-targets` clean across the workspace.
   - [x] `cargo fmt --all` clean.
   
   ## Next in the stack
   
   The rewrite rule (`ParallelWindowDetectRule`) that inserts either operator above `BoundedWindowAggExec` based on whether the wrapping plan needs ordering preserved.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(core): add OrderedRangeRepartitionExec — N sorted overlapping → K sorted disjoint [datafusion-ballista]

Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #2169:
URL: https://github.com/apache/datafusion-ballista/pull/2169#discussion_r3648768192


##########
ballista/core/src/execution_plans/ordered_range_repartition.rs:
##########
@@ -0,0 +1,931 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Value-range router over N locally-sorted overlapping input partitions.
+//! Redistributes them into K range-disjoint output partitions where each
+//! output is fully sorted on the routing expression. Concatenating the K
+//! outputs in order yields a globally-sorted stream.
+//!
+//! ```text
+//!    N sorted input                                              outputs (K = 4, each sorted)
+//!    partitions
+//!         ─┐                                                     ┌─▶ 0: sorted, key < c₁
+//!         ─┼──▶ RuntimeStatsExec ──▶ SortExec/preserve ──▶ OrderedRRE ─┼─▶ 1: sorted, c₁ ≤ key < c₂
+//!         ─┤    (T-Digest tap)      (per-partition sort)   (K = 4)    ├─▶ 2: sorted, c₂ ≤ key < c₃
+//!         ─┘                                                 │        └─▶ 3: sorted, c₃ ≤ key
+//!                     ▲                                      │
+//!                     └──────────── walker ◀─────────────────┘
+//!                                   (descends past sort-preserving
+//!                                    nodes, matches on routing expr,
+//!                                    reads K−1 quantile cuts)
+//!
+//!    Inside OrderedRRE: N × K channels + K k-way merges.
+//!    Each of N scatter tasks splits its sorted input by the K-1 cuts
+//!    (K sub-batches per batch) and forwards each sub-batch to its output's
+//!    sender. Each of K outputs runs a `StreamingMerge` across the N
+//!    sub-streams targeting it → the output stream is sorted.
+//! ```
+//!
+//! # Contrast with `UnorderedRangeRepartitionExec`
+//!
+//! The two operators share the same runtime discovery mechanism (walk child
+//! subtree → find matching `RuntimeStatsExec` → quantile cuts from T-Digest,
+//! see [`crate::execution_plans::range_repartition_common`]). They diverge
+//! on execution model:
+//!
+//! - **Unordered**: N scatter tasks → K channels → K raw receivers. Rows
+//!   from different sources arrive interleaved, order is lost.
+//! - **Ordered**: N scatter tasks → N × K channels → K [`StreamingMerge`]
+//!   streams. Each output p performs a heap-based k-way merge across N
+//!   sorted sub-streams (one per input source, pre-filtered to output p's
+//!   value range). Battle-tested merger via DataFusion's `SortPreservingMerge`
+//!   internals; no custom heap code here.
+//!
+//! # Discovery + fallback
+//!
+//! Identical to Unordered: walk `self.input`'s subtree through single-child
+//! chains and the distribution-preserving whitelist; snapshot the matching
+//! T-Digest on first batch; empty cut set = single-bucket fallback where all
+//! rows land in output 0.
+//!
+//! # Ordering claim
+//!
+//! Constructor requires `input.output_ordering()` to lead with the routing
+//! expression — otherwise the merger would produce garbled output.
+//! [`PlanProperties::eq_properties`] declares each output partition sorted
+//! on `order_by`, letting downstream operators (BWAG, HaloDrop) rely on the
+//! claim without inserting a redundant `SortExec`.
+//!
+//! [`StreamingMerge`]: datafusion::physical_plan::sorts::streaming_merge::StreamingMergeBuilder
+
+use std::fmt::{self, Debug, Formatter};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use datafusion::arrow::array::RecordBatch;
+use datafusion::arrow::datatypes::{DataType, SchemaRef};
+use datafusion::common::runtime::SpawnedTask;
+use datafusion::common::{Result, Statistics, internal_datafusion_err, internal_err};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::{
+    Distribution, EquivalenceProperties, LexOrdering, OrderingRequirements, Partitioning,
+    PhysicalExpr, PhysicalSortExpr,
+};
+use datafusion::physical_plan::execution_plan::{
+    CardinalityEffect, EvaluationType, SchedulingType,
+};
+use datafusion::physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet};
+use datafusion::physical_plan::sorts::streaming_merge::StreamingMergeBuilder;
+use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+use datafusion::physical_plan::{
+    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
+    SendableRecordBatchStream,
+};
+use futures::stream::StreamExt;
+use tokio::sync::mpsc;
+use tokio_stream::wrappers::ReceiverStream;
+
+use crate::execution_plans::range_repartition_common::{
+    discover_cuts, guarded_scatter, split_batch_by_range,
+};
+
+/// Per-output-partition channel capacity, per input source. Matches the
+/// unordered variant's default; see the discussion there. Total buffered
+/// batches at rest ≤ `N × K × CHANNEL_CAPACITY`.
+const CHANNEL_CAPACITY: usize = 2;
+
+/// Value-range router that preserves the input's sort order. See the
+/// module-level docs.
+pub struct OrderedRangeRepartitionExec {
+    input: Arc<dyn ExecutionPlan>,
+    /// Lexicographic ORDER BY. `try_new` guarantees the first entry evaluates
+    /// to `Float64` and matches the input's declared output ordering.
+    order_by: Vec<PhysicalSortExpr>,
+    /// K — number of output partitions.
+    output_partitions: usize,
+    /// Lazy channel + merge-stream setup guarded by `Mutex`. First
+    /// `execute()` call spawns the N input-reader tasks, wires N × K
+    /// channels, and constructs K `StreamingMerge` streams — one per
+    /// output partition. Subsequent `execute(p)` calls take
+    /// `merged_streams[p]`.
+    state: Arc<Mutex<DispatchState>>,
+    properties: Arc<PlanProperties>,
+    metrics: ExecutionPlanMetricsSet,
+}
+
+/// Per-exec-instance lazy state.
+struct DispatchState {
+    /// K slots. Each holds `Some(stream)` after setup, `None` once its
+    /// output partition has been consumed. Each stream is a k-way merge
+    /// (via `StreamingMerge`) across N sorted sub-streams — one per input
+    /// source, filtered to the output's value range on the scatter side.
+    merged_streams: Vec<Option<SendableRecordBatchStream>>,
+    /// N scatter tasks (one per input partition). Each runs its scatter
+    /// body inside `guarded_scatter`, which converts panic/error/clean-end
+    /// into an explicit signal on every output channel. `SpawnedTask`
+    /// aborts its inner tokio task on drop, so holding these here ties the
+    /// background work's lifetime to this exec's — dropping the exec
+    /// cancels all scatter work.
+    _drop_helper: Vec<SpawnedTask<()>>,

Review Comment:
   why the underscore? just curious



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(core): add OrderedRangeRepartitionExec — N sorted overlapping → K sorted disjoint [datafusion-ballista]

Posted by "avantgardnerio (via GitHub)" <gi...@apache.org>.
avantgardnerio commented on code in PR #2169:
URL: https://github.com/apache/datafusion-ballista/pull/2169#discussion_r3650181816


##########
ballista/core/src/execution_plans/ordered_range_repartition.rs:
##########
@@ -0,0 +1,931 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Value-range router over N locally-sorted overlapping input partitions.
+//! Redistributes them into K range-disjoint output partitions where each
+//! output is fully sorted on the routing expression. Concatenating the K
+//! outputs in order yields a globally-sorted stream.
+//!
+//! ```text
+//!    N sorted input                                              outputs (K = 4, each sorted)
+//!    partitions
+//!         ─┐                                                     ┌─▶ 0: sorted, key < c₁
+//!         ─┼──▶ RuntimeStatsExec ──▶ SortExec/preserve ──▶ OrderedRRE ─┼─▶ 1: sorted, c₁ ≤ key < c₂
+//!         ─┤    (T-Digest tap)      (per-partition sort)   (K = 4)    ├─▶ 2: sorted, c₂ ≤ key < c₃
+//!         ─┘                                                 │        └─▶ 3: sorted, c₃ ≤ key
+//!                     ▲                                      │
+//!                     └──────────── walker ◀─────────────────┘
+//!                                   (descends past sort-preserving
+//!                                    nodes, matches on routing expr,
+//!                                    reads K−1 quantile cuts)
+//!
+//!    Inside OrderedRRE: N × K channels + K k-way merges.
+//!    Each of N scatter tasks splits its sorted input by the K-1 cuts
+//!    (K sub-batches per batch) and forwards each sub-batch to its output's
+//!    sender. Each of K outputs runs a `StreamingMerge` across the N
+//!    sub-streams targeting it → the output stream is sorted.
+//! ```
+//!
+//! # Contrast with `UnorderedRangeRepartitionExec`
+//!
+//! The two operators share the same runtime discovery mechanism (walk child
+//! subtree → find matching `RuntimeStatsExec` → quantile cuts from T-Digest,
+//! see [`crate::execution_plans::range_repartition_common`]). They diverge
+//! on execution model:
+//!
+//! - **Unordered**: N scatter tasks → K channels → K raw receivers. Rows
+//!   from different sources arrive interleaved, order is lost.
+//! - **Ordered**: N scatter tasks → N × K channels → K [`StreamingMerge`]
+//!   streams. Each output p performs a heap-based k-way merge across N
+//!   sorted sub-streams (one per input source, pre-filtered to output p's
+//!   value range). Battle-tested merger via DataFusion's `SortPreservingMerge`
+//!   internals; no custom heap code here.
+//!
+//! # Discovery + fallback
+//!
+//! Identical to Unordered: walk `self.input`'s subtree through single-child
+//! chains and the distribution-preserving whitelist; snapshot the matching
+//! T-Digest on first batch; empty cut set = single-bucket fallback where all
+//! rows land in output 0.
+//!
+//! # Ordering claim
+//!
+//! Constructor requires `input.output_ordering()` to lead with the routing
+//! expression — otherwise the merger would produce garbled output.
+//! [`PlanProperties::eq_properties`] declares each output partition sorted
+//! on `order_by`, letting downstream operators (BWAG, HaloDrop) rely on the
+//! claim without inserting a redundant `SortExec`.
+//!
+//! [`StreamingMerge`]: datafusion::physical_plan::sorts::streaming_merge::StreamingMergeBuilder
+
+use std::fmt::{self, Debug, Formatter};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use datafusion::arrow::array::RecordBatch;
+use datafusion::arrow::datatypes::{DataType, SchemaRef};
+use datafusion::common::runtime::SpawnedTask;
+use datafusion::common::{Result, Statistics, internal_datafusion_err, internal_err};
+use datafusion::execution::TaskContext;
+use datafusion::physical_expr::{
+    Distribution, EquivalenceProperties, LexOrdering, OrderingRequirements, Partitioning,
+    PhysicalExpr, PhysicalSortExpr,
+};
+use datafusion::physical_plan::execution_plan::{
+    CardinalityEffect, EvaluationType, SchedulingType,
+};
+use datafusion::physical_plan::metrics::{BaselineMetrics, ExecutionPlanMetricsSet};
+use datafusion::physical_plan::sorts::streaming_merge::StreamingMergeBuilder;
+use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+use datafusion::physical_plan::{
+    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
+    SendableRecordBatchStream,
+};
+use futures::stream::StreamExt;
+use tokio::sync::mpsc;
+use tokio_stream::wrappers::ReceiverStream;
+
+use crate::execution_plans::range_repartition_common::{
+    discover_cuts, guarded_scatter, split_batch_by_range,
+};
+
+/// Per-output-partition channel capacity, per input source. Matches the
+/// unordered variant's default; see the discussion there. Total buffered
+/// batches at rest ≤ `N × K × CHANNEL_CAPACITY`.
+const CHANNEL_CAPACITY: usize = 2;
+
+/// Value-range router that preserves the input's sort order. See the
+/// module-level docs.
+pub struct OrderedRangeRepartitionExec {
+    input: Arc<dyn ExecutionPlan>,
+    /// Lexicographic ORDER BY. `try_new` guarantees the first entry evaluates
+    /// to `Float64` and matches the input's declared output ordering.
+    order_by: Vec<PhysicalSortExpr>,
+    /// K — number of output partitions.
+    output_partitions: usize,
+    /// Lazy channel + merge-stream setup guarded by `Mutex`. First
+    /// `execute()` call spawns the N input-reader tasks, wires N × K
+    /// channels, and constructs K `StreamingMerge` streams — one per
+    /// output partition. Subsequent `execute(p)` calls take
+    /// `merged_streams[p]`.
+    state: Arc<Mutex<DispatchState>>,
+    properties: Arc<PlanProperties>,
+    metrics: ExecutionPlanMetricsSet,
+}
+
+/// Per-exec-instance lazy state.
+struct DispatchState {
+    /// K slots. Each holds `Some(stream)` after setup, `None` once its
+    /// output partition has been consumed. Each stream is a k-way merge
+    /// (via `StreamingMerge`) across N sorted sub-streams — one per input
+    /// source, filtered to the output's value range on the scatter side.
+    merged_streams: Vec<Option<SendableRecordBatchStream>>,
+    /// N scatter tasks (one per input partition). Each runs its scatter
+    /// body inside `guarded_scatter`, which converts panic/error/clean-end
+    /// into an explicit signal on every output channel. `SpawnedTask`
+    /// aborts its inner tokio task on drop, so holding these here ties the
+    /// background work's lifetime to this exec's — dropping the exec
+    /// cancels all scatter work.
+    _drop_helper: Vec<SpawnedTask<()>>,

Review Comment:
   It's just to signify that no one reads this. It's just a struct member purely so it can get held until the struct is dropped.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(core): add OrderedRangeRepartitionExec — N sorted overlapping → K sorted disjoint [datafusion-ballista]

Posted by "avantgardnerio (via GitHub)" <gi...@apache.org>.
avantgardnerio commented on PR #2169:
URL: https://github.com/apache/datafusion-ballista/pull/2169#issuecomment-5071852108

   @phillipleblanc PTAL when you have a moment :raised_hands: 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] feat(core): add OrderedRangeRepartitionExec — N sorted overlapping → K sorted disjoint [datafusion-ballista]

Posted by "avantgardnerio (via GitHub)" <gi...@apache.org>.
avantgardnerio merged PR #2169:
URL: https://github.com/apache/datafusion-ballista/pull/2169


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org