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/06/18 17:18:42 UTC

[PR] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   ## Which issue does this PR close?
   
   - N/A — opening as a draft to share the shape with reviewers and gather
     feedback before filing the tracking issue. Related context: #22356
     (PARTITION BY parallelization), #22395 (`Partitioning::Range`
     groundwork by @gabotechs / Datadog).
   
   ## Rationale for this change
   
   Bounded RANGE-frame window functions with `ORDER BY` but no
   `PARTITION BY` currently collapse to a single execution partition.
   `BoundedWindowAggExec::required_input_distribution()` returns
   `Distribution::SinglePartition` in that case, which causes
   `EnsureRequirements` to insert a `SortPreservingMergeExec` and serialize
   a step that is otherwise embarrassingly parallel along the sort key.
   
   The natural unit of parallelism here is a *range bucket* on the order
   key. If the sort key range can be split into `N` disjoint buckets, the
   window operator can run `N` ways in parallel — almost. RANGE frames
   need to see a small window of "halo" rows from the neighbouring bucket
   to compute frame values at boundary seams, but those halo rows must
   not flow through into the final output or be visible to slide
   accumulator math after the boundary row.
   
   ## What changes are included in this PR?
   
   Four pieces, intentionally small and decoupled:
   
   1. **`PartitionExtremes` + `ExecutionPlan::runtime_partition_extremes`**
      (`physical-plan/src/execution_plan.rs:97-127, 540-560`). A new trait
      method that returns per-partition lex-min / lex-max tuples of the
      declared output ordering, populated at runtime rather than from
      plan-time `Statistics`. Default `Ok(None)`.
   
      The type doc calls out a *dual interpretation* the implementer can
      choose: *observed* (the default, what `SortExec` does) or *intended*
      (what `RangeRepartitionExec` does — its bucket's primary range,
      which is narrower than the data it actually carries). The
      distinction matters because `HaloDropExec` consumes the "intended"
      interpretation to strip halo rows without a side-channel.
   
   2. **`SortExec` runtime observer** (`physical-plan/src/sorts/sort.rs`).
      Folds first/last rows of each `sort_batch_chunked` invocation into
      a per-partition `Mutex<Option<PartitionExtremes>>` slot. Cheap, no
      per-row cost — uses the already-sorted chunks the operator
      produces. The slot is the consumer's contract: drive the upstream
      to first batch, then read.
   
   3. **`RangeRepartitionExec`** (`physical-plan/src/range_repartition.rs`).
      K-way fan-in / fan-out coordinator. On first `execute()` it opens
      every input partition, drives each to its first batch (which makes
      the pipeline-breaking sort below populate its extremes slot),
      lex-reduces per-input extremes into a global, derives N equal-width
      Int64 boundaries, and routes every subsequent batch into per-bucket
      mpsc channels. Halo rows land in *two* buckets (their primary and
      the neighbour that needs them for frame context). Also implements
      `runtime_partition_extremes` returning each output partition's
      *intended* primary range — the "useful lie" mentioned above.
   
   4. **`HaloDropExec`** (`physical-plan/src/halo_drop.rs`). Per-partition
      filter that reads its input's `runtime_partition_extremes(partition)`
      on the first batch and drops rows whose leading sort key falls
      outside that range. Sits above `BoundedWindowAggExec`, below the
      final `SortPreservingMergeExec`. The lazy first-batch read works
      because the upstream `RangeRepartitionExec` has populated the
      primary ranges by the time any batch reaches us.
   
   5. **`ParallelWindow` optimizer rule**
      (`physical-optimizer/src/parallel_window.rs`). Runs *before*
      `EnsureRequirements` so it owns the distribution decision instead
      of fighting an inserted SPM. For an eligible window
      (RANGE frame, no PARTITION BY, single Column sort key, Int64
      halo distances) the rule rebuilds the operator as
      `HaloDropExec(BWAG_parallel_aware(RangeRepartitionExec(input)))`.
      `BoundedWindowAggExec` grew a `parallel_aware: bool` flag that
      flips its `required_input_distribution()` to
      `UnspecifiedDistribution`.
   
   Target physical plan shape (from the included SLT):
   
   ```
   SortPreservingMergeExec  (N → 1)
     HaloDropExec  (N partitions; per-partition primary filter)
       BoundedWindowAggExec  (N partitions, parallel_aware)
         RangeRepartitionExec  (N, halo duplicates intended)
           SortExec  (preserve_partitioning, N)
             DataSource
   ```
   
   ## Are these changes tested?
   
   `sqllogictest/test_files/parallel_window.slt` is the fixture:
   - 4 parquet files with overlapping `seq` ranges (so routing actually
     has to move rows around),
   - EXPLAIN assertion on the new plan shape,
   - value assertion on a 5-row truncation,
   - row-count assertion that catches halo leakage
     (`count(rolling_sum) = 100`, not 115).
   
   I have *not* yet added a feature flag + equality SLT comparing parallel
   vs. serial outputs row-for-row. That's the next baby step and is what
   will catch slide-accumulator boundary bugs that the current count
   assertion can't see. Posting now to drive the design conversation
   before investing in that loop.
   
   ## Are there any user-facing changes?
   
   - New nodes in plan trees: `RangeRepartitionExec`, `HaloDropExec`.
   - New trait method `ExecutionPlan::runtime_partition_extremes` with a
     default `Ok(None)` — existing implementations are unaffected.
   - New `PartitionExtremes` re-export from `physical-plan`.
   - No SQL surface changes.
   
   ## Known scope cuts (PoC)
   
   - **Int64-only** leading sort key with Int64-bounded RANGE distances.
     The `runtime_partition_extremes` *type* is generic
     (`Vec<ScalarValue>`); the coordinator's bucketing arithmetic is
     what's Int64-only. `DataType`-dispatch is the permanent architecture
     here, not sample-based bucketing.
   - **Single sort key** (`LexOrdering` len 1). Multi-key extremes are
     in the type from day one; coordinator + halo math are not.
   - **No feature flag** yet. The rule fires unconditionally on eligible
     windows. A session config `optimizer.enable_parallel_window` (default
     off) is the next commit.
   - **No equality SLT** comparing parallel-on vs. parallel-off outputs.
     Next commit after the flag.
   - **No Ballista distribution** yet. The coordinator is the AQE
     reducer; lifting it scheduler-side is a follow-up (~300-500 LoC).
   - **No benchmark numbers** yet. Coming after the equality SLT lands.
   
   ## Coexistence with #22395
   
   `Partitioning::Range` + `RangePartitioning { ordering, split_points }`
   have already merged from @gabotechs. The execution slot in
   `RepartitionExec` for `Partitioning::Range` is still
   `not_impl_err!`. This PR keeps `RangeRepartitionExec` as a separate
   operator for now because it does something `RepartitionExec` is
   unlikely to absorb (halo duplication). Once the design is settled here
   I expect to thread the existing `RangePartitioning` shape through
   where the boundaries live, rather than carry a parallel
   `Vec<ScalarValue>` representation forever.
   
   ## Draft status
   
   This is up for *architecture review*, not approval. CI will be red —
   clippy / fmt / unrelated tests are not yet tended. I will not push
   forward to "green" until reviewers agree the shape is roughly right.


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   In terms of evaluating window functions with more memory efficiency, there is this paper which is the new hotness
   - https://www.vldb.org/pvldb/vol8/p1058-leis.pdf


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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


##########
datafusion/physical-plan/src/range_repartition.rs:
##########
@@ -0,0 +1,636 @@
+// 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.
+
+//! Range-partition an input stream on a single Int64 order-key into N
+//! output partitions, with halo overlap for bounded RANGE-frame window
+//! functions sitting above it.
+//!
+//! `execute()`'s first call spawns a coordinator that:
+//!  1. opens `child.execute(k)` for every input partition `k`,
+//!  2. drives each stream to its first batch (which makes the pipeline-
+//!     breaking sort child populate its `PartitionExtremes` slot),
+//!  3. reads `child.runtime_partition_extremes(k)` per input,
+//!  4. lex-reduces those into a single global [`PartitionExtremes`], derives
+//!     `N` equal-width Int64 bucket boundaries from `[global.min,
+//!     global.max]`, and computes per-bucket expanded ranges by
+//!     extending each primary [b_i, b_{i+1}) outward by
+//!     `halo_preceding` / `halo_following`,
+//!  5. then for every batch flowing out of every input stream, splits
+//!     the batch into per-bucket pieces (rows whose order key lies in
+//!     bucket `b`'s expanded range), and sends each piece into bucket
+//!     `b`'s output channel.
+//!
+//! Halo rows therefore appear in *two* output partitions (their primary
+//! bucket and the neighbor whose expanded range reaches them). That's
+//! correct for letting the per-bucket window operator compute frame
+//! values at the seams — but it also means rows are duplicated in the
+//! merged output until a future `HaloDropExec` strips halo rows after
+//! the window.
+
+use std::sync::{Arc, Mutex};
+
+use arrow::array::{Array, Int64Array, RecordBatch, UInt32Array};
+use arrow::compute::take_arrays;
+use arrow::datatypes::SchemaRef;
+use datafusion_common::{DataFusionError, Result, internal_datafusion_err};
+use datafusion_execution::TaskContext;
+use datafusion_physical_expr::LexOrdering;
+use datafusion_physical_expr_common::sort_expr::OrderingRequirements;
+use futures::StreamExt;
+use log::info;
+use tokio::sync::{mpsc, oneshot};
+
+use datafusion_common::ScalarValue;
+
+use crate::sorts::sort::lex_compare;
+use crate::stream::RecordBatchStreamAdapter;
+use crate::{
+    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties,
+    PartitionExtremes, PlanProperties, SendableRecordBatchStream,
+};
+
+#[derive(Debug)]
+pub struct RangeRepartitionExec {
+    input: Arc<dyn ExecutionPlan>,
+    cache: Arc<PlanProperties>,
+    /// Required input ordering — passed down from the consumer (window
+    /// operator) so EnsureRequirements inserts the pipeline-breaking sort
+    /// *below* us, not above. Same key feeds the routing decision.
+    ordering: LexOrdering,
+    /// Halo distance preceding each bucket's primary range, in
+    /// leading-sort-key units. Carried over from the window frame at plan
+    /// time so the coordinator can derive per-bucket expanded ranges.
+    halo_preceding: i64,
+    /// Halo distance following each bucket's primary range.
+    halo_following: i64,
+    state: Arc<Mutex<State>>,
+    /// Per-output-partition primary `[lo, hi_exclusive)` ranges, filled
+    /// by the coordinator before any batch is routed. Surfaced through
+    /// `runtime_partition_extremes(partition)` so downstream operators
+    /// (e.g. HaloDropExec) can read each bucket's intended primary
+    /// range without needing the global extremes.
+    bucket_primary_ranges: Arc<Mutex<Option<Vec<(i64, i64)>>>>,
+}
+
+struct State {
+    initialized: bool,
+    /// One `oneshot::Receiver` per output partition, populated when the
+    /// coordinator hands off this partition's data. `take()`n by the
+    /// corresponding `execute(partition)` call.
+    handoffs: Vec<Option<oneshot::Receiver<Result<PartitionData>>>>,
+}
+
+/// Per-output-partition payload the coordinator hands to its stream.
+/// Once the coordinator has computed boundaries it starts router tasks
+/// that funnel routed batches into bucket-keyed mpsc channels. Each
+/// output partition's stream drains its receiver.
+struct PartitionData {
+    rx: mpsc::Receiver<Result<RecordBatch>>,
+}
+
+impl std::fmt::Debug for State {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("State")
+            .field("initialized", &self.initialized)
+            .field("handoffs", &self.handoffs.len())
+            .finish()
+    }
+}
+
+impl RangeRepartitionExec {
+    pub fn new(
+        input: Arc<dyn ExecutionPlan>,
+        ordering: LexOrdering,
+        halo_preceding: i64,
+        halo_following: i64,
+    ) -> Self {
+        let n = input.output_partitioning().partition_count();
+        let cache = Arc::clone(input.properties());
+        Self {
+            input,
+            cache,
+            ordering,
+            halo_preceding,
+            halo_following,
+            state: Arc::new(Mutex::new(State {
+                initialized: false,
+                handoffs: (0..n).map(|_| None).collect(),
+            })),
+            bucket_primary_ranges: Arc::new(Mutex::new(None)),
+        }
+    }
+
+    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
+        &self.input
+    }
+}
+
+impl DisplayAs for RangeRepartitionExec {
+    fn fmt_as(
+        &self,
+        _t: DisplayFormatType,
+        f: &mut std::fmt::Formatter,
+    ) -> std::fmt::Result {
+        write!(f, "RangeRepartitionExec")
+    }
+}
+
+impl ExecutionPlan for RangeRepartitionExec {
+    fn name(&self) -> &'static str {
+        "RangeRepartitionExec"
+    }
+
+    fn properties(&self) -> &Arc<PlanProperties> {
+        &self.cache
+    }
+
+    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
+        vec![&self.input]
+    }
+
+    fn with_new_children(
+        self: Arc<Self>,
+        mut children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        Ok(Arc::new(Self::new(
+            children.swap_remove(0),
+            self.ordering.clone(),
+            self.halo_preceding,
+            self.halo_following,
+        )))
+    }
+
+    fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
+        vec![Some(OrderingRequirements::from(self.ordering.clone()))]
+    }
+
+    fn maintains_input_order(&self) -> Vec<bool> {
+        vec![true]
+    }
+
+    /// Returns each output partition's *intended primary range* as
+    /// inclusive `[min, max]` — not the actual range of routed data
+    /// (which is wider, by `halo_preceding`/`halo_following`). This is a
+    /// "useful lie" the downstream `HaloDropExec` consumes to filter
+    /// halo rows back out.
+    ///
+    /// Returns `Ok(None)` if the coordinator hasn't computed boundaries
+    /// yet — callers must drive the input stream to first batch before
+    /// reading, per the trait contract on `runtime_partition_extremes`.
+    fn runtime_partition_extremes(
+        &self,
+        partition: usize,
+    ) -> Result<Option<PartitionExtremes>> {
+        let guard = self.bucket_primary_ranges.lock().map_err(|_| {
+            internal_datafusion_err!(
+                "RangeRepartitionExec bucket_primary_ranges mutex poisoned"
+            )
+        })?;
+        let Some(ranges) = guard.as_ref() else {
+            return Ok(None);
+        };
+        let &(lo, hi_excl) = &ranges[partition];
+        // Convert [lo, hi_exclusive) → inclusive [min, max].
+        let max = hi_excl.saturating_sub(1);
+        Ok(Some(PartitionExtremes {
+            min: vec![ScalarValue::Int64(Some(lo))],
+            max: vec![ScalarValue::Int64(Some(max))],
+            row_count: 0, // not tracked; consumers shouldn't rely on it
+        }))
+    }
+
+    fn execute(
+        &self,
+        partition: usize,
+        context: Arc<TaskContext>,
+    ) -> Result<SendableRecordBatchStream> {
+        let mut state = self.state.lock().map_err(|_| {
+            internal_datafusion_err!("RangeRepartitionExec mutex poisoned")
+        })?;
+        if !state.initialized {
+            state.initialized = true;
+            let n = state.handoffs.len();
+            let mut senders = Vec::with_capacity(n);
+            for slot in state.handoffs.iter_mut() {
+                let (tx, rx) = oneshot::channel();
+                senders.push(tx);
+                *slot = Some(rx);
+            }
+            let child = Arc::clone(&self.input);
+            let ctx = Arc::clone(&context);
+            let halo_preceding = self.halo_preceding;
+            let halo_following = self.halo_following;
+            let primaries = Arc::clone(&self.bucket_primary_ranges);
+            tokio::spawn(coordinator(
+                child,
+                ctx,
+                senders,
+                halo_preceding,
+                halo_following,
+                primaries,
+            ));
+        }
+        let rx = state
+            .handoffs
+            .get_mut(partition)
+            .and_then(Option::take)
+            .ok_or_else(|| {
+                internal_datafusion_err!("partition {partition} already taken")
+            })?;
+        drop(state);
+
+        let schema = self.schema();
+        Ok(Box::pin(RecordBatchStreamAdapter::new(
+            Arc::clone(&schema),
+            partition_stream(schema, rx),
+        )))
+    }
+}
+
+/// Stream that awaits the coordinator's handoff for one output partition,
+/// then drains the bucket-keyed mpsc receiver router tasks are pushing
+/// into. If the coordinator drops the sender (e.g. setup failed) the
+/// stream surfaces an error.
+fn partition_stream(
+    _schema: SchemaRef,
+    rx: oneshot::Receiver<Result<PartitionData>>,
+) -> impl futures::Stream<Item = Result<RecordBatch>> + Send {
+    use futures::stream::{TryStreamExt, once};
+    once(async move {
+        let data = rx
+            .await
+            .map_err(|_| internal_datafusion_err!("coordinator dropped"))??;
+        let mut bucket_rx = data.rx;
+        let inner = futures::stream::poll_fn(move |cx| bucket_rx.poll_recv(cx));
+        Ok::<_, DataFusionError>(inner)
+    })
+    .try_flatten()
+}
+
+/// Coordinator task: drive every input partition to first batch, gather
+/// runtime extremes, log the lex-reduced global, then hand off per-input
+/// payloads to their corresponding output partition.
+async fn coordinator(
+    child: Arc<dyn ExecutionPlan>,
+    ctx: Arc<TaskContext>,
+    mut senders: Vec<oneshot::Sender<Result<PartitionData>>>,
+    halo_preceding: i64,
+    halo_following: i64,
+    bucket_primary_ranges: Arc<Mutex<Option<Vec<(i64, i64)>>>>,
+) {
+    let n = senders.len();
+
+    // Phase 1: open every input stream and pull the first batch from each.
+    let mut firsts: Vec<(Option<RecordBatch>, SendableRecordBatchStream)> =
+        Vec::with_capacity(n);
+    for k in 0..n {
+        let mut stream = match child.execute(k, Arc::clone(&ctx)) {
+            Ok(s) => s,
+            Err(e) => {
+                let msg = format!("input {k} open failed: {e}");
+                for tx in senders.drain(..) {
+                    let _ = tx.send(Err(internal_datafusion_err!("{msg}")));
+                }
+                return;
+            }
+        };
+        let first = match stream.next().await {
+            Some(Ok(batch)) => Some(batch),
+            Some(Err(e)) => {
+                let msg = format!("first batch from input {k} failed: {e}");
+                for tx in senders.drain(..) {
+                    let _ = tx.send(Err(internal_datafusion_err!("{msg}")));
+                }
+                return;
+            }
+            None => None,
+        };
+        firsts.push((first, stream));
+    }
+
+    // Phase 2: collect per-input runtime extremes.
+    let per_input: Vec<Option<PartitionExtremes>> = (0..n)
+        .map(|k| child.runtime_partition_extremes(k).ok().flatten())
+        .collect();
+
+    // Phase 3: lex-reduce per-input → global, using the input's declared
+    // output ordering so direction and null ordering are honored.
+    let ordering: Option<LexOrdering> = child.output_ordering().cloned();
+    let global = ordering
+        .as_ref()
+        .and_then(|o| reduce_global_extremes(&per_input, o));
+
+    info!(
+        "RangeRepartitionExec: coordinator gathered {} input partitions; \
+         global extremes = {:?}",
+        n, global
+    );
+
+    // Phase 4: derive bucket boundaries from the global extremes. v1 is

Review Comment:
   Repartition dynamically without a true AQE boundry



-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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


##########
datafusion/sqllogictest/test_files/parallel_window.slt:
##########
@@ -0,0 +1,141 @@
+# 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.
+
+# Goal: parallelize window functions that have ORDER BY but no PARTITION BY,
+# over a bounded RANGE frame. Today this collapses to a single partition via
+# BoundedWindowAggExec::required_input_distribution -> Distribution::SinglePartition
+# (datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:333-340).
+
+statement ok
+set datafusion.execution.target_partitions = 4;
+
+statement ok
+set datafusion.explain.show_statistics = true;
+
+# Build four parquet files with OVERLAPPING seq ranges so range-repartitioning
+# actually has to move rows around. Each file has seq congruent to its index
+# mod 4 in [0, 100); a deterministic scramble (seq * 37 mod 100) defeats the
+# natural generate_series ordering so DataFusion does not claim output_ordering
+# on seq. Per-file min/max still come back Exact from the parquet footer.
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(0, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/0.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(1, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/1.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(2, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/2.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(3, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/3.parquet'
+STORED AS PARQUET;
+----
+25
+
+statement ok
+CREATE EXTERNAL TABLE events
+STORED AS PARQUET
+LOCATION 'test_files/scratch/parallel_window/events';
+
+# Bounded RANGE frame, ORDER BY only (no PARTITION BY). Canonical shape.
+# Each input partition should report Exact min/max on seq from its parquet footer.
+query TT
+EXPLAIN SELECT
+    seq,
+    SUM(amount) OVER (
+        ORDER BY seq
+        RANGE BETWEEN 5 PRECEDING AND CURRENT ROW
+    ) AS rolling_sum
+FROM events
+ORDER BY seq
+LIMIT 5;
+----
+logical_plan
+01)Sort: events.seq ASC NULLS LAST, fetch=5
+02)--Projection: events.seq, sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW AS rolling_sum
+03)----WindowAggr: windowExpr=[[sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW]]
+04)------TableScan: events projection=[seq, amount]
+physical_plan
+01)SortPreservingMergeExec: [seq@0 ASC NULLS LAST], fetch=5, statistics=[Rows=Absent, Bytes=Absent, [(Col[0]:),(Col[1]:)]]

Review Comment:
   > Why is the SortPreservingMergeExec needed? 
   
   It is not. I just inherited the plan that way.
   
   > use e.g. a partition preserving coalescepartitions here
   
   It 100% should



-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > In terms of evaluating window functions with more memory efficiency, there is this paper which is the new hotness that describes segment trees
   > 
   > * https://www.vldb.org/pvldb/vol8/p1058-leis.pdf
   
   I had a look at segment trees but I think they might not be _that_ great if for performance optimization of existing functionality:
   
   * Segment Tree is actually slower algorithmically and in practice than _removable cumulative_ (which DataFusion uses/supports, i.e. `retract_batch`)  on some functions (e.g. SUM), see Table 1 and Figure 10:
   
   <img width="962" height="176" alt="image" src="https://github.com/user-attachments/assets/3888d868-28de-41de-8f1e-729cb1c5decc" />
   
   <img width="514" height="364" alt="image" src="https://github.com/user-attachments/assets/7cf6b5ba-f345-453a-9328-c63b4499adc3" />
   
   * The paper also agrees segment trees has overhead and other approaches should be taken in other cases
   
   * They are mainly better for _variable frame bounds_ (e.g. `between column_1 and column_2 preceding` ), which is something DataFusion does not support yet (although arguably adding it might require segment trees or something similar to add that).
   
   
   


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   Benchmarks appear to be a popular way to show the merits of a PR, so I added one. As per tradition, I stacked it in this PR's favor:
   
   <img width="1560" height="600" alt="image" src="https://github.com/user-attachments/assets/aa9cc60a-8b8f-4ec6-8c47-b756b6730cb5" />
   


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > FWIW I don't think "halo rows" is a standard database term -- it means "overlapping partitions with replicated boundary rows"
   
   I had to look up where the terminology comes from (as Claude _really_ likes the term) - it comes from HPC / parallel scientific computing literature (halo or ghost cells) where it is often called this way.
   
   But I agree overlap or boundary rows or something makes more sense.


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > In terms of evaluating window functions with more memory efficiency, there is this paper which is the new hotness that describes segment trees
   > 
   > * https://www.vldb.org/pvldb/vol8/p1058-leis.pdf
   
   I must admit our true motivation is Ballista, and halo rows make it easy to distribute. The optimal solution would probably be segment trees within node and hallow rows between nodes.


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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


##########
datafusion/sqllogictest/test_files/parallel_window.slt:
##########
@@ -0,0 +1,141 @@
+# 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.
+
+# Goal: parallelize window functions that have ORDER BY but no PARTITION BY,
+# over a bounded RANGE frame. Today this collapses to a single partition via
+# BoundedWindowAggExec::required_input_distribution -> Distribution::SinglePartition
+# (datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:333-340).
+
+statement ok
+set datafusion.execution.target_partitions = 4;
+
+statement ok
+set datafusion.explain.show_statistics = true;
+
+# Build four parquet files with OVERLAPPING seq ranges so range-repartitioning
+# actually has to move rows around. Each file has seq congruent to its index
+# mod 4 in [0, 100); a deterministic scramble (seq * 37 mod 100) defeats the
+# natural generate_series ordering so DataFusion does not claim output_ordering
+# on seq. Per-file min/max still come back Exact from the parquet footer.
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(0, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/0.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(1, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/1.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(2, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/2.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(3, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/3.parquet'
+STORED AS PARQUET;
+----
+25
+
+statement ok
+CREATE EXTERNAL TABLE events
+STORED AS PARQUET
+LOCATION 'test_files/scratch/parallel_window/events';
+
+# Bounded RANGE frame, ORDER BY only (no PARTITION BY). Canonical shape.
+# Each input partition should report Exact min/max on seq from its parquet footer.
+query TT
+EXPLAIN SELECT
+    seq,
+    SUM(amount) OVER (
+        ORDER BY seq
+        RANGE BETWEEN 5 PRECEDING AND CURRENT ROW
+    ) AS rolling_sum
+FROM events
+ORDER BY seq
+LIMIT 5;
+----
+logical_plan
+01)Sort: events.seq ASC NULLS LAST, fetch=5
+02)--Projection: events.seq, sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW AS rolling_sum
+03)----WindowAggr: windowExpr=[[sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW]]
+04)------TableScan: events projection=[seq, amount]
+physical_plan
+01)SortPreservingMergeExec: [seq@0 ASC NULLS LAST], fetch=5, statistics=[Rows=Absent, Bytes=Absent, [(Col[0]:),(Col[1]:)]]

Review Comment:
   > This is a draft PR as a PoC up for architecture feedback, not approval.
   
   If you approve, it would be great to do so on:
   
   1. https://github.com/apache/datafusion/pull/23090
   2. and https://github.com/apache/datafusion/pull/23094
   3. or https://github.com/apache/datafusion/issues/23194
   
   That would let us kick off the work for real. This is just a demo of a technique that I would merge for real if we allow the supporting infra to be merged. When that happens I would 100% go tackle the SPM.



-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #23026:
URL: https://github.com/apache/datafusion/pull/23026#discussion_r3501337552


##########
datafusion/sqllogictest/test_files/parallel_window.slt:
##########
@@ -0,0 +1,141 @@
+# 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.
+
+# Goal: parallelize window functions that have ORDER BY but no PARTITION BY,
+# over a bounded RANGE frame. Today this collapses to a single partition via
+# BoundedWindowAggExec::required_input_distribution -> Distribution::SinglePartition
+# (datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:333-340).
+
+statement ok
+set datafusion.execution.target_partitions = 4;
+
+statement ok
+set datafusion.explain.show_statistics = true;
+
+# Build four parquet files with OVERLAPPING seq ranges so range-repartitioning
+# actually has to move rows around. Each file has seq congruent to its index
+# mod 4 in [0, 100); a deterministic scramble (seq * 37 mod 100) defeats the
+# natural generate_series ordering so DataFusion does not claim output_ordering
+# on seq. Per-file min/max still come back Exact from the parquet footer.
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(0, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/0.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(1, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/1.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(2, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/2.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(3, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/3.parquet'
+STORED AS PARQUET;
+----
+25
+
+statement ok
+CREATE EXTERNAL TABLE events
+STORED AS PARQUET
+LOCATION 'test_files/scratch/parallel_window/events';
+
+# Bounded RANGE frame, ORDER BY only (no PARTITION BY). Canonical shape.
+# Each input partition should report Exact min/max on seq from its parquet footer.
+query TT
+EXPLAIN SELECT
+    seq,
+    SUM(amount) OVER (
+        ORDER BY seq
+        RANGE BETWEEN 5 PRECEDING AND CURRENT ROW
+    ) AS rolling_sum
+FROM events
+ORDER BY seq
+LIMIT 5;
+----
+logical_plan
+01)Sort: events.seq ASC NULLS LAST, fetch=5
+02)--Projection: events.seq, sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW AS rolling_sum
+03)----WindowAggr: windowExpr=[[sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW]]
+04)------TableScan: events projection=[seq, amount]
+physical_plan
+01)SortPreservingMergeExec: [seq@0 ASC NULLS LAST], fetch=5, statistics=[Rows=Absent, Bytes=Absent, [(Col[0]:),(Col[1]:)]]

Review Comment:
   (I think it's a bit wasteful it has to do a single threaded SPM when it did a RangeRepartition before)



-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   run benchmark h2o_medium_window


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "github-actions[bot] (via GitHub) via github" <gi...@datafusion.apache.org>.
github-actions[bot] closed pull request #23026: Parallel bounded RANGE-frame window functions without PARTITION BY (draft)
URL: https://github.com/apache/datafusion/pull/23026


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > I had a look at segment trees but I think they might not be that great if for performance optimization of existing functionality:
   
   
   Another downside is it without a lot of work the segment trees won't parallelize across many machines


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   run benchmark h2o_medium_window
   run benchmark h2o_big_window
   run benchmark h2o_medium_window h2o_big_window
   


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   Benchmark for [this request](https://github.com/apache/datafusion/pull/23026#issuecomment-5403049783) failed before finishing (Kubernetes reason: `BackoffLimitExceeded`).
   
   Benchmarks requested: `h2o_medium_window`
   
   <details><summary>Kubernetes message</summary>
   
   ```
   Job has reached the specified backoff limit
   ```
   
   </details>
   
   ---
   [File an issue](https://github.com/adriangb/datafusion-benchmarking/issues) against this benchmark runner


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   FWIW I don't think "halo rows" is a standard database term -- it means "overlapping partitions with replicated boundary rows"


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > I’ll write more about the intra-operator parallelism approach later and work on the implementation. For now, I’m trying to make the case that we should do intra-operator parallelism first, and I’m happy to help with this PR’s approach afterward. TL;DR: this order likely requires less total engineering effort.
   
   
   
   I think we need to think about how to do this carefully -- right now the execution model in DataFusion is basically single core --> single partition, and the cores share very little. If we start allowing more threads than cores (which could happen if we have operators launch tasks, for example) we may find that threading context switching, etc sucks down performance in a way we didn't expect 


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "Rich-T-kid (via GitHub)" <gi...@apache.org>.
Rich-T-kid commented on PR #23026:
URL: https://github.com/apache/datafusion/pull/23026#issuecomment-5403049783

   run benchmark h2o_medium_window


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   Hi @avantgardnerio, thanks for the request (https://github.com/apache/datafusion/pull/23026#issuecomment-4887387105). Only whitelisted users can trigger benchmarks. Allowed users: [Dandandan](https://github.com/Dandandan), [Fokko](https://github.com/Fokko), [Jefffrey](https://github.com/Jefffrey), [Omega359](https://github.com/Omega359), [Rachelint](https://github.com/Rachelint), [adriangb](https://github.com/adriangb), [alamb](https://github.com/alamb), [asubiotto](https://github.com/asubiotto), [brunal](https://github.com/brunal), [buraksenn](https://github.com/buraksenn), [cetra3](https://github.com/cetra3), [codephage2020](https://github.com/codephage2020), [coderfender](https://github.com/coderfender), [comphead](https://github.com/comphead), [erenavsarogullari](https://github.com/erenavsarogullari), [etseidl](https://github.com/etseidl), [friendlymatthew](https://github.com/friendlymatthew), [gabotechs](https://github.com/gabotechs), [geoffreyclaude](https://github.com/geoff
 reyclaude), [grtlr](https://github.com/grtlr), [haohuaijin](https://github.com/haohuaijin), [jonathanc-n](https://github.com/jonathanc-n), [kevinjqliu](https://github.com/kevinjqliu), [klion26](https://github.com/klion26), [kosiew](https://github.com/kosiew), [kumarUjjawal](https://github.com/kumarUjjawal), [kunalsinghdadhwal](https://github.com/kunalsinghdadhwal), [liamzwbao](https://github.com/liamzwbao), [mbutrovich](https://github.com/mbutrovich), [mkleen](https://github.com/mkleen), [mzabaluev](https://github.com/mzabaluev), [neilconway](https://github.com/neilconway), [rluvaton](https://github.com/rluvaton), [sdf-jkl](https://github.com/sdf-jkl), [timsaucer](https://github.com/timsaucer), [xudong963](https://github.com/xudong963), [zhuqi-lucas](https://github.com/zhuqi-lucas).
   
   ---
   [File an issue](https://github.com/adriangb/datafusion-benchmarking/issues) against this benchmark runner


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #23026:
URL: https://github.com/apache/datafusion/pull/23026#discussion_r3501270738


##########
datafusion/sqllogictest/test_files/parallel_window.slt:
##########
@@ -0,0 +1,141 @@
+# 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.
+
+# Goal: parallelize window functions that have ORDER BY but no PARTITION BY,
+# over a bounded RANGE frame. Today this collapses to a single partition via
+# BoundedWindowAggExec::required_input_distribution -> Distribution::SinglePartition
+# (datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:333-340).
+
+statement ok
+set datafusion.execution.target_partitions = 4;
+
+statement ok
+set datafusion.explain.show_statistics = true;
+
+# Build four parquet files with OVERLAPPING seq ranges so range-repartitioning
+# actually has to move rows around. Each file has seq congruent to its index
+# mod 4 in [0, 100); a deterministic scramble (seq * 37 mod 100) defeats the
+# natural generate_series ordering so DataFusion does not claim output_ordering
+# on seq. Per-file min/max still come back Exact from the parquet footer.
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(0, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/0.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(1, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/1.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(2, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/2.parquet'
+STORED AS PARQUET;
+----
+25
+
+query I
+COPY (SELECT seq, seq % 7 AS amount FROM (
+        SELECT value AS seq FROM generate_series(3, 99, 4)
+      ) ORDER BY (seq * 37) % 100)
+TO 'test_files/scratch/parallel_window/events/3.parquet'
+STORED AS PARQUET;
+----
+25
+
+statement ok
+CREATE EXTERNAL TABLE events
+STORED AS PARQUET
+LOCATION 'test_files/scratch/parallel_window/events';
+
+# Bounded RANGE frame, ORDER BY only (no PARTITION BY). Canonical shape.
+# Each input partition should report Exact min/max on seq from its parquet footer.
+query TT
+EXPLAIN SELECT
+    seq,
+    SUM(amount) OVER (
+        ORDER BY seq
+        RANGE BETWEEN 5 PRECEDING AND CURRENT ROW
+    ) AS rolling_sum
+FROM events
+ORDER BY seq
+LIMIT 5;
+----
+logical_plan
+01)Sort: events.seq ASC NULLS LAST, fetch=5
+02)--Projection: events.seq, sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW AS rolling_sum
+03)----WindowAggr: windowExpr=[[sum(events.amount) ORDER BY [events.seq ASC NULLS LAST] RANGE BETWEEN 5 PRECEDING AND CURRENT ROW]]
+04)------TableScan: events projection=[seq, amount]
+physical_plan
+01)SortPreservingMergeExec: [seq@0 ASC NULLS LAST], fetch=5, statistics=[Rows=Absent, Bytes=Absent, [(Col[0]:),(Col[1]:)]]

Review Comment:
   Why is the `SortPreservingMergeExec` needed? Couldn't it use e.g. a partition preserving coalescepartitions here as I think it is globally sorted?



-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   > I must admit our true motivation is Ballista, and halo rows make it easy to distribute. The optimal solution would probably be segment trees within node and hallow rows between nodes.
   
   I think one thing that Spark does is to effectively re-optimize the plan after certain stages (where the data was written to disk / shuffle files anyways). I vaguely remember Ballista / @milenkovicm was looking into something similar


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

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

   https://github.com/apache/datafusion-ballista/issues/1359
   
   Describing hugely underestimated effort still in progress 😀


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #23026:
URL: https://github.com/apache/datafusion/pull/23026#issuecomment-4774549328

   I think it would be easier to ship intra-operator parallelism first. It would support the segment-tree parallelism mentioned by @alamb in https://github.com/apache/datafusion/pull/23026#issuecomment-4770385196, and it can also support the workload targeted by this PR. We can then implement this PR’s repartition-based approach afterward.
   
   I’ll write more about the intra-operator parallelism approach later and work on the implementation. For now, I’m trying to make the case that we should do intra-operator parallelism first, and I’m happy to help with this PR’s approach afterward. TL;DR: this order likely requires less total engineering effort.
   
   I agree this PR’s approach is necessary for scaling out, especially for running certain window workloads in a distributed way. The tradeoff is that it is more complex, because it requires multiple `ExecutionPlan` nodes to cooperate to evaluate a single logical window node:
   
   - Temporary inconsistent intermediate states are introduced.
   - Optimizer rules become harder to implement. For example, we need to handle how filters are pushed down below the two newly introduced operators.
   
   By contrast, intra-operator parallelism is simpler and more broadly applicable. The same architecture can be extended to range-partitioned parallelism, segment-tree-based parallelism, and potentially other forms of parallelism.
   
   My suggestion is to implement this approach after we have architectural support for intra-node parallelism in the window operator. Alternatively, we could consider implementing this approach outside the core first to make maintenance easier.
   
   The main reason is the implementation order:
   
   - Intra-operator parallelism → repartition-based parallelism: the latter remains easy to add, since it mostly introduces new operators and does not require significant changes inside the existing window operator.
   - Repartition-based parallelism → intra-operator parallelism: this is more subtle, but I have thought about the intra-operator approach before. To support it properly, we will eventually need to refactor most window-function-related traits and structs because of some historical structural issues. If we land the repartition-based approach first, that refactor will likely become harder.
   
   It is also more common to scale up before scaling out, and to prioritize the more broadly applicable solution first.
   
   I’ll write more about the alternative intra-operator parallelism approach later. Here is an existing PoC:
   
   - https://github.com/apache/datafusion/pull/22356


-- 
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] Parallel bounded RANGE-frame window functions without PARTITION BY (draft) [datafusion]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #23026:
URL: https://github.com/apache/datafusion/pull/23026#issuecomment-6378320261

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


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