Skip to main content

datafusion_physical_expr/
partitioning.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`Partitioning`] and [`Distribution`] for `ExecutionPlans`
6
7use crate::expressions::{Literal, UnKnownColumn};
8use crate::simplifier::const_evaluator::create_dummy_batch;
9use crate::{
10    EquivalenceProperties, PhysicalExpr, ScalarFunctionExpr,
11    equivalence::ProjectionMapping, physical_exprs_contains, physical_exprs_equal,
12};
13use arrow::datatypes::Schema;
14pub use datafusion_common::SplitPoint;
15use datafusion_common::tree_node::{Transformed, TreeNode};
16use datafusion_common::{Result, ScalarValue, plan_err, validate_range_split_points};
17use datafusion_expr::ColumnarValue;
18use datafusion_physical_expr_common::physical_expr::format_physical_expr_list;
19use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
20#[cfg(feature = "proto")]
21use datafusion_physical_expr_common::sort_expr::{
22    sort_exprs_try_from_proto, sort_exprs_try_to_proto,
23};
24use std::fmt;
25use std::fmt::Display;
26use std::sync::Arc;
27
28/// Output partitioning supported by [`ExecutionPlan`]s.
29///
30/// Calling [`ExecutionPlan::execute`] produce one or more independent streams of
31/// [`RecordBatch`]es in parallel, referred to as partitions. The streams are Rust
32/// `async` [`Stream`]s (a special kind of future). The number of output
33/// partitions varies based on the input and the operation performed.
34///
35/// For example, an `ExecutionPlan` that has output partitioning of 3 will
36/// produce 3 distinct output streams as the result of calling
37/// `ExecutionPlan::execute(0)`, `ExecutionPlan::execute(1)`, and
38/// `ExecutionPlan::execute(2)`, as shown below:
39///
40/// ```text
41///                                                   ...         ...        ...
42///               ...                                  ▲           ▲           ▲
43///                                                    │           │           │
44///                ▲                                   │           │           │
45///                │                                   │           │           │
46///                │                               ┌───┴────┐  ┌───┴────┐  ┌───┴────┐
47///     ┌────────────────────┐                     │ Stream │  │ Stream │  │ Stream │
48///     │   ExecutionPlan    │                     │  (0)   │  │  (1)   │  │  (2)   │
49///     └────────────────────┘                     └────────┘  └────────┘  └────────┘
50///                ▲                                   ▲           ▲           ▲
51///                │                                   │           │           │
52///     ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─                          │           │           │
53///             Input        │                         │           │           │
54///     └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─                          │           │           │
55///                ▲                               ┌ ─ ─ ─ ─   ┌ ─ ─ ─ ─   ┌ ─ ─ ─ ─
56///                │                                 Input  │    Input  │    Input  │
57///                │                               │ Stream    │ Stream    │ Stream
58///                                                   (0)   │     (1)   │     (2)   │
59///               ...                              └ ─ ▲ ─ ─   └ ─ ▲ ─ ─   └ ─ ▲ ─ ─
60///                                                    │           │           │
61///                                                    │           │           │
62///                                                    │           │           │
63///
64/// ExecutionPlan with 1 input                      3 (async) streams, one for each
65/// that has 3 partitions, which itself             output partition
66/// has 3 output partitions
67/// ```
68///
69/// It is common (but not required) that an `ExecutionPlan` has the same number
70/// of input partitions as output partitions. However, some plans have different
71/// numbers such as the `RepartitionExec` that redistributes batches from some
72/// number of inputs to some number of outputs
73///
74/// ```text
75///               ...                                     ...         ...        ...
76///
77///                                                        ▲           ▲           ▲
78///                ▲                                       │           │           │
79///                │                                       │           │           │
80///       ┌────────┴───────────┐                           │           │           │
81///       │  RepartitionExec   │                      ┌────┴───┐  ┌────┴───┐  ┌────┴───┐
82///       └────────────────────┘                      │ Stream │  │ Stream │  │ Stream │
83///                ▲                                  │  (0)   │  │  (1)   │  │  (2)   │
84///                │                                  └────────┘  └────────┘  └────────┘
85///                │                                       ▲           ▲           ▲
86///                ...                                     │           │           │
87///                                                        └──────────┐│┌──────────┘
88///                                                                   │││
89///                                                                   │││
90/// RepartitionExec with 1 input
91/// partition and 3 output partitions                 3 (async) streams, that internally
92///                                                    pull from the same input stream
93///                                                                  ...
94/// ```
95///
96/// # Additional Examples
97///
98/// A simple `FileScanExec` might produce one output stream (partition) for each
99/// file (note the actual DataFusion file scanners can read individual files in
100/// parallel, potentially producing multiple partitions per file)
101///
102/// Plans such as `SortPreservingMerge` produce a single output stream
103/// (1 output partition) by combining some number of input streams (input partitions)
104///
105/// Plans such as `FilterExec` produce the same number of output streams
106/// (partitions) as input streams (partitions).
107///
108/// [`RecordBatch`]: arrow::record_batch::RecordBatch
109/// [`ExecutionPlan::execute`]: https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.ExecutionPlan.html#tymethod.execute
110/// [`ExecutionPlan`]: https://docs.rs/datafusion/latest/datafusion/physical_plan/trait.ExecutionPlan.html
111/// [`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html
112#[derive(Debug, Clone)]
113pub enum Partitioning {
114    /// Allocate batches using a round-robin algorithm and the specified number of partitions
115    RoundRobinBatch(usize),
116    /// Allocate rows based on a hash of one of more expressions and the specified number of
117    /// partitions
118    Hash(Vec<Arc<dyn PhysicalExpr>>, usize),
119    /// Partition rows by source-declared ranges
120    Range(RangePartitioning),
121    /// Unknown partitioning scheme with a known number of partitions
122    UnknownPartitioning(usize),
123}
124
125impl Display for Partitioning {
126    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127        match self {
128            Partitioning::RoundRobinBatch(size) => write!(f, "RoundRobinBatch({size})"),
129            Partitioning::Hash(phy_exprs, size) => {
130                let phy_exprs_str = phy_exprs
131                    .iter()
132                    .map(|e| format!("{e}"))
133                    .collect::<Vec<String>>()
134                    .join(", ");
135                write!(f, "Hash([{phy_exprs_str}], {size})")
136            }
137            Partitioning::Range(range) => write!(f, "{range}"),
138            Partitioning::UnknownPartitioning(size) => {
139                write!(f, "UnknownPartitioning({size})")
140            }
141        }
142    }
143}
144
145/// Physical range partitioning.
146///
147/// [`RangePartitioning`] describes an ordered key space with sampled split points.
148///
149/// - `ordering` defines the partitioning key and ordering.
150/// - `samples` are the maximum-resolution split points supplied by the caller.
151/// - The effective `split_points` are derived from those samples for the selected
152///   partition count; the count itself is `split_points.len() + 1` and is not
153///   stored separately.
154///
155/// Comparisons use the lexicographic order defined by `ordering`, including
156/// `ASC`/`DESC` and null ordering. Samples must be strictly ordered according
157/// to that ordering, and each sample must have one value per ordering
158/// expression. See [`SplitPoint`] for the shared boundary convention.
159///
160/// When `partition_count` is smaller than [`Self::max_partition_count`], the
161/// samples are evenly down-sampled to derive the effective split points. This
162/// allows planners to reduce or later restore the number of partitions without
163/// losing the original distribution sample.
164///
165/// Like other user-specified data properties such as sortedness, if a source
166/// declares range partitioning, it is responsible for placing each row in the
167/// partition described by the split points. DataFusion will not validate this is
168/// upheld.
169///
170/// For a single range key:
171///
172/// ```text
173/// ordering = [date ASC NULLS LAST]
174/// split_points = [
175///   (2022-01-01),
176///   (2023-01-01),
177/// ]
178///
179/// partition 0: date before 2022-01-01
180/// partition 1: date between 2022-01-01 (inclusive) and 2023-01-01 (exclusive)
181/// partition 2: date at/after 2023-01-01
182/// ```
183///
184/// The same model extends to compound keys.
185/// For `ordering = [time ASC, city ASC]`, split points are ordered
186/// lexicographically by `(time, city)`:
187///
188/// ```text
189/// ordering = [time ASC NULLS LAST, city ASC NULLS LAST]
190/// split_points = [
191///   (2022, Allston),
192///   (2023, Allston),
193/// ]
194///
195/// partition 0: keys before  (2022, Allston)
196/// partition 1: keys between (2022, Allston) and (2023, Allston)
197/// partition 2: keys at/after (2023, Allston)
198/// ```
199///
200/// Equality includes retained samples, since they determine which future scales
201/// are possible. Use [`Self::has_same_layout`] to compare only the current layout.
202#[derive(Debug, Clone, PartialEq)]
203pub struct RangePartitioning {
204    /// Ordered partitioning key.
205    ordering: LexOrdering,
206    /// Caller-supplied maximum-resolution split points used to derive the
207    /// effective boundaries.
208    samples: Arc<[SplitPoint]>,
209    /// Effective boundaries for the current partition count.
210    split_points: Arc<[SplitPoint]>,
211}
212
213impl RangePartitioning {
214    /// Creates range partitioning metadata without validating split points.
215    ///
216    /// Use [`Self::try_new`] to validate exact boundaries, or
217    /// [`Self::try_new_with_samples`] to retain additional samples for scaling up.
218    #[deprecated(
219        since = "56.0.0",
220        note = "Use RangePartitioning::try_new or try_new_with_samples instead"
221    )]
222    pub fn new(ordering: LexOrdering, split_points: Vec<SplitPoint>) -> Self {
223        let split_points: Arc<[SplitPoint]> = Arc::from(split_points);
224        Self {
225            ordering,
226            samples: Arc::clone(&split_points),
227            split_points,
228        }
229    }
230
231    /// Creates range partitioning metadata and validates split point shape and
232    /// ordering.
233    ///
234    /// The exact boundaries are also the retained samples. This allows scaling
235    /// down and back up to the original count, but not beyond it. Prefer
236    /// [`Self::try_new_with_samples`] when additional sample points are available.
237    pub fn try_new(ordering: LexOrdering, split_points: Vec<SplitPoint>) -> Result<Self> {
238        let partition_count = split_points.len() + 1;
239        Self::try_new_with_samples(ordering, split_points, partition_count)
240    }
241
242    /// Creates sample-backed range partitioning and validates the sample shape,
243    /// ordering, and target partition count.
244    ///
245    /// `partition_count` must be at least one and no larger than
246    /// `samples.len() + 1`. When it is smaller than that maximum, the samples
247    /// are evenly down-sampled to derive the effective split points.
248    ///
249    /// For a single range key:
250    ///
251    /// ```text
252    /// ordering = [key ASC NULLS LAST]
253    /// samples = [(10), (20), (30), (40), (50)]
254    /// partition_count = 3
255    /// split_points = [(20), (40)]
256    ///
257    /// partition 0: key before 20
258    /// partition 1: key between 20 (inclusive) and 40 (exclusive)
259    /// partition 2: key at/after 40
260    ///
261    /// scale(5): split_points = [(20), (30), (40), (50)]
262    /// scale(7): None (at most 6 partitions)
263    /// ```
264    ///
265    /// Retain at least `maximum_expected_partitions - 1` distinct samples to
266    /// support that many partitions later. Small inputs may not have enough
267    /// distinct values to do so.
268    pub fn try_new_with_samples(
269        ordering: LexOrdering,
270        samples: Vec<SplitPoint>,
271        partition_count: usize,
272    ) -> Result<Self> {
273        validate_range_split_points(
274            &samples,
275            &ordering
276                .iter()
277                .map(|sort_expr| sort_expr.options)
278                .collect::<Vec<_>>(),
279        )?;
280        validate_range_partition_count(partition_count, samples.len() + 1)?;
281        let samples: Arc<[SplitPoint]> = Arc::from(samples);
282        let split_points = downsample_split_points(&samples, partition_count);
283        Ok(Self {
284            ordering,
285            samples,
286            split_points,
287        })
288    }
289
290    /// Returns the ordering that defines the range key.
291    pub fn ordering(&self) -> &LexOrdering {
292        &self.ordering
293    }
294
295    /// Returns the maximum-resolution sample points.
296    pub fn samples(&self) -> &[SplitPoint] {
297        &self.samples
298    }
299
300    /// Returns the effective split points between partitions.
301    pub fn split_points(&self) -> &[SplitPoint] {
302        &self.split_points
303    }
304
305    /// Returns the number of partitions.
306    pub fn partition_count(&self) -> usize {
307        self.split_points.len() + 1
308    }
309
310    /// Returns the largest partition count supported by the stored samples.
311    pub fn max_partition_count(&self) -> usize {
312        self.samples.len() + 1
313    }
314
315    /// Whether two range partitionings have the same current key ordering and
316    /// effective boundaries, irrespective of their retained samples.
317    ///
318    /// This does not imply equal scaling capacity. In particular, a plan that
319    /// combines inputs must not use this comparison to inherit one input's samples
320    /// for all inputs. Structural equality is required for that use case.
321    pub fn has_same_layout(&self, other: &Self) -> bool {
322        self.ordering == other.ordering && self.split_points == other.split_points
323    }
324
325    /// Returns this range partitioning scaled to `target_partitions`.
326    ///
327    /// Scaling retains the original samples, so a range partitioning that was
328    /// scaled down can later be scaled back up to [`Self::max_partition_count`].
329    /// Returns `None` when `target_partitions` is zero or the retained samples do
330    /// not support that many partitions. Insufficient samples are an expected
331    /// condition; callers should retain the layout or choose another partitioning.
332    /// This method changes metadata only; the caller must ensure that the actual
333    /// row distribution matches the resulting boundaries.
334    pub fn scale(&self, target_partitions: usize) -> Option<Self> {
335        if target_partitions == 0 || target_partitions > self.max_partition_count() {
336            return None;
337        }
338        if target_partitions == self.partition_count() {
339            return Some(self.clone());
340        }
341        Some(Self {
342            ordering: self.ordering.clone(),
343            samples: Arc::clone(&self.samples),
344            split_points: downsample_split_points(&self.samples, target_partitions),
345        })
346    }
347
348    /// Calculates the range partitioning after applying the given projection.
349    ///
350    /// Returns `None` if any range key cannot be projected or if projection
351    /// collapses distinct range keys into duplicate output expressions.
352    fn project(
353        &self,
354        mapping: &ProjectionMapping,
355        input_eq_properties: &EquivalenceProperties,
356    ) -> Option<Self> {
357        let exprs = self
358            .ordering
359            .iter()
360            .map(|sort_expr| Arc::clone(&sort_expr.expr))
361            .collect::<Vec<_>>();
362        let projected_exprs = input_eq_properties
363            .project_expressions(&exprs, mapping)
364            .collect::<Option<Vec<_>>>()?;
365        let sort_exprs = self
366            .ordering
367            .iter()
368            .zip(projected_exprs)
369            .map(|(sort_expr, expr)| PhysicalSortExpr::new(expr, sort_expr.options))
370            .collect::<Vec<_>>();
371        let ordering = LexOrdering::new(sort_exprs)?;
372        if ordering.len() != self.ordering.len() {
373            return None;
374        }
375
376        Some(Self {
377            ordering,
378            samples: Arc::clone(&self.samples),
379            split_points: Arc::clone(&self.split_points),
380        })
381    }
382
383    /// Checks whether the types of the given expressions match the data types of the split points in this range partitioning.
384    pub fn is_compatible_with_expressions(
385        &self,
386        exprs: &[Arc<dyn PhysicalExpr>],
387        schema: &Schema,
388    ) -> bool {
389        if self.ordering.len() != exprs.len() {
390            return false;
391        }
392        if let Some(first_split) = self.samples.first() {
393            exprs.iter().zip(first_split.values()).all(|(expr, val)| {
394                expr.data_type(schema)
395                    .map(|dt| dt == val.data_type())
396                    .unwrap_or(false)
397            })
398        } else {
399            true
400        }
401    }
402
403    /// Adapts this range partitioning to the given expressions, preserving split points and sort options.
404    /// Returns `None` if `exprs` count doesn't match ordering length or expression types don't match split points.
405    pub fn adapt(
406        &self,
407        exprs: &[Arc<dyn PhysicalExpr>],
408        schema: &Schema,
409    ) -> Option<Self> {
410        if !self.is_compatible_with_expressions(exprs, schema) {
411            return None;
412        }
413        let new_ordering = LexOrdering::new(
414            exprs
415                .iter()
416                .zip(&self.ordering)
417                .map(|(expr, sort_expr)| PhysicalSortExpr {
418                    expr: Arc::clone(expr),
419                    options: sort_expr.options,
420                })
421                .collect::<Vec<_>>(),
422        )?;
423        if new_ordering.len() != self.ordering.len() {
424            return None;
425        }
426        Some(Self {
427            ordering: new_ordering,
428            samples: Arc::clone(&self.samples),
429            split_points: Arc::clone(&self.split_points),
430        })
431    }
432}
433
434impl Display for RangePartitioning {
435    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
436        let split_points = format_range_split_points(&self.split_points);
437        write!(
438            f,
439            "Range([{}], [{}], {}",
440            self.ordering,
441            split_points,
442            self.partition_count()
443        )?;
444        if self.max_partition_count() != self.partition_count() {
445            write!(f, ", max {}", self.max_partition_count())?;
446        }
447        write!(f, ")")
448    }
449}
450
451fn downsample_split_points(
452    samples: &Arc<[SplitPoint]>,
453    partition_count: usize,
454) -> Arc<[SplitPoint]> {
455    if partition_count == samples.len() + 1 {
456        return Arc::clone(samples);
457    }
458
459    let sample_count = samples.len();
460    (1..partition_count)
461        .map(|partition| {
462            // Use a wider intermediate so valid slice lengths cannot overflow
463            // when calculating the evenly spaced sample index.
464            let sample_index = ((partition as u128 * sample_count as u128)
465                / partition_count as u128) as usize;
466            samples[sample_index].clone()
467        })
468        .collect::<Vec<_>>()
469        .into()
470}
471
472fn validate_range_partition_count(
473    partition_count: usize,
474    max_partition_count: usize,
475) -> Result<()> {
476    if partition_count == 0 {
477        return plan_err!("Range partitioning partition count must be at least 1");
478    }
479    if partition_count > max_partition_count {
480        return plan_err!(
481            "Range partitioning partition count {partition_count} exceeds maximum {max_partition_count}"
482        );
483    }
484    Ok(())
485}
486
487fn format_range_split_points(split_points: &[SplitPoint]) -> String {
488    split_points
489        .iter()
490        .map(ToString::to_string)
491        .collect::<Vec<_>>()
492        .join(", ")
493}
494
495fn equivalent_exprs(
496    left: &[Arc<dyn PhysicalExpr>],
497    right: &[Arc<dyn PhysicalExpr>],
498    eq_properties: &EquivalenceProperties,
499) -> bool {
500    if physical_exprs_equal(left, right) {
501        return true;
502    }
503
504    let eq_groups = eq_properties.eq_group();
505    if eq_groups.is_empty() {
506        return false;
507    }
508
509    let normalized_left = normalize_exprs(left, eq_properties);
510    let normalized_right = normalize_exprs(right, eq_properties);
511
512    physical_exprs_equal(&normalized_left, &normalized_right)
513}
514
515fn normalize_exprs(
516    exprs: &[Arc<dyn PhysicalExpr>],
517    eq_properties: &EquivalenceProperties,
518) -> Vec<Arc<dyn PhysicalExpr>> {
519    let eq_groups = eq_properties.eq_group();
520    exprs
521        .iter()
522        .map(|expr| eq_groups.normalize_expr(Arc::clone(expr)))
523        .collect()
524}
525
526fn evaluate_with_range_value(
527    expr: &Arc<dyn PhysicalExpr>,
528    range_key: &Arc<dyn PhysicalExpr>,
529    value: &ScalarValue,
530) -> Option<ScalarValue> {
531    let literal: Arc<dyn PhysicalExpr> = Arc::new(Literal::new(value.clone()));
532    let rewritten = Arc::clone(expr)
533        .transform(|node| {
534            if node.eq(range_key) {
535                Ok(Transformed::yes(Arc::clone(&literal)))
536            } else {
537                Ok(Transformed::no(node))
538            }
539        })
540        .ok()?;
541    if !rewritten.transformed {
542        return None;
543    }
544
545    match rewritten.data.evaluate(create_dummy_batch().ok()?).ok()? {
546        ColumnarValue::Scalar(value) => Some(value),
547        ColumnarValue::Array(array) => ScalarValue::try_from_array(&array, 0).ok(),
548    }
549}
550
551fn checked_adjacent_timestamp(
552    value: &ScalarValue,
553    is_successor: bool,
554) -> Option<ScalarValue> {
555    let offset = if is_successor { 1 } else { -1 };
556    match value {
557        ScalarValue::TimestampSecond(Some(value), None) => value
558            .checked_add(offset)
559            .map(|value| ScalarValue::TimestampSecond(Some(value), None)),
560        ScalarValue::TimestampMillisecond(Some(value), None) => value
561            .checked_add(offset)
562            .map(|value| ScalarValue::TimestampMillisecond(Some(value), None)),
563        ScalarValue::TimestampMicrosecond(Some(value), None) => value
564            .checked_add(offset)
565            .map(|value| ScalarValue::TimestampMicrosecond(Some(value), None)),
566        ScalarValue::TimestampNanosecond(Some(value), None) => value
567            .checked_add(offset)
568            .map(|value| ScalarValue::TimestampNanosecond(Some(value), None)),
569        _ => None,
570    }
571}
572
573/// Determines whether a nondecreasing transform keeps equal output keys local.
574///
575/// For one ascending range key, split points `x₁, ..., xₙ` define:
576///
577/// ```text
578/// P₀ = (-∞, x₁)
579/// Pᵢ = [xᵢ, xᵢ₊₁) for 1 ≤ i < n
580/// Pₙ = [xₙ, +∞)
581/// ```
582///
583/// Aggregation can reuse these partitions after applying `f` only if no output
584/// key occurs in two partitions. In other words, the partition images must be
585/// disjoint: `f(Pᵢ) ∩ f(Pⱼ) = ∅` for `i ≠ j`.
586///
587/// Monotonicity alone is insufficient. Ordered metadata gives only
588///
589/// ```text
590/// f(predecessor(xᵢ)) ≤ f(xᵢ)
591/// ```
592///
593/// but locality requires strict separation at every split:
594///
595/// ```text
596/// f(predecessor(xᵢ)) < f(xᵢ)
597/// ```
598///
599/// Since ordering already supplies the non-strict inequality, the analysis
600/// proves strictness by explicitly checking that the two outputs are not equal.
601/// Otherwise, the same transformed key could occur in both adjacent partitions,
602/// so the transform would not preserve key locality. For example, an hourly
603/// truncation maps timestamps immediately before and at a `01:30` split to the
604/// same `01:00` bucket. A split at `01:00` is safe because its predecessor maps
605/// to `00:00`, while the split itself maps to `01:00`.
606///
607/// `predecessor(xᵢ)` is the greatest representable timestamp below the split.
608/// Therefore, for every `x < xᵢ` and `y ≥ xᵢ`, ordering and the strict boundary
609/// check give
610///
611/// ```text
612/// f(x) ≤ f(predecessor(xᵢ)) < f(xᵢ) ≤ f(y)
613/// ```
614///
615/// Thus no transformed key can occur on both sides of the split. The successor of
616/// an ascending split is already in the same partition as `xᵢ`, so checking it
617/// would not say anything about groups crossing that split.
618///
619/// The argument is the same for descending ranges, but `successor(xᵢ)` must be
620/// used instead. Null preservation is also required so the transform cannot
621/// introduce a null group outside the source partition selected by null order.
622fn range_splits_separate_transformed_keys(
623    function: &Arc<dyn PhysicalExpr>,
624    range_key: &Arc<dyn PhysicalExpr>,
625    range: &RangePartitioning,
626    schema: &Schema,
627) -> bool {
628    let Ok(range_type) = range_key.data_type(schema) else {
629        return false;
630    };
631    let sort_options = range.ordering().first().options;
632    if validate_range_split_points(range.split_points(), &[sort_options]).is_err() {
633        return false;
634    }
635    range.split_points().iter().all(|split_point| {
636        let Some(split_value) = split_point.values().first() else {
637            return false;
638        };
639        if split_value.data_type() != range_type {
640            return false;
641        }
642        let Some(adjacent) =
643            checked_adjacent_timestamp(split_value, sort_options.descending)
644        else {
645            return false;
646        };
647        let Some(at_split) = evaluate_with_range_value(function, range_key, split_value)
648        else {
649            return false;
650        };
651        let Some(across_split) =
652            evaluate_with_range_value(function, range_key, &adjacent)
653        else {
654            return false;
655        };
656
657        !at_split.is_null()
658            && !across_split.is_null()
659            && at_split.data_type() == across_split.data_type()
660            && at_split != across_split
661    })
662}
663
664fn range_transform_proves_key_locality(
665    candidate: &Arc<dyn PhysicalExpr>,
666    range_key: &Arc<dyn PhysicalExpr>,
667    range: &RangePartitioning,
668    eq_properties: &EquivalenceProperties,
669) -> bool {
670    let Some(function) = candidate.downcast_ref::<ScalarFunctionExpr>() else {
671        return false;
672    };
673    let schema = eq_properties.schema();
674    if datafusion_physical_expr_common::physical_expr::is_volatile(candidate)
675        || !function
676            .supports_range_key_locality_analysis(schema)
677            .unwrap_or(false)
678        || !eq_properties.is_same_direction_ordered_transform(candidate, range_key)
679    {
680        return false;
681    }
682
683    let mut range_argument_count = 0;
684    for argument in function.args() {
685        if eq_properties.eq_group().exprs_equal(argument, range_key) {
686            range_argument_count += 1;
687        } else if !argument.is::<Literal>() {
688            return false;
689        }
690    }
691
692    range_argument_count == 1
693        && range_splits_separate_transformed_keys(candidate, range_key, range, schema)
694}
695
696fn range_partitioning_keeps_keys_local(
697    range: &RangePartitioning,
698    required_exprs: &[Arc<dyn PhysicalExpr>],
699    eq_properties: &EquivalenceProperties,
700    allow_subset: bool,
701) -> bool {
702    // Currently, transform locality analysis only supports single-key ranges.
703    // Extending the proof to compound range keys is tracked in #24644.
704    if range.ordering().len() != 1 || required_exprs.is_empty() {
705        return false;
706    }
707
708    let range_key = &range.ordering()[0].expr;
709    let has_key_locality_proof = required_exprs.iter().any(|required| {
710        range_transform_proves_key_locality(required, range_key, range, eq_properties)
711    });
712
713    has_key_locality_proof && (required_exprs.len() == 1 || allow_subset)
714}
715
716/// Represents how a [`Partitioning`] satisfies a [`Distribution`] requirement.
717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub enum PartitioningSatisfaction {
719    /// The partitioning does not satisfy the distribution requirement
720    NotSatisfied,
721    /// The partitioning exactly matches the distribution requirement
722    Exact,
723    /// The partitioning satisfies the distribution requirement via subset logic
724    Subset,
725}
726
727impl PartitioningSatisfaction {
728    pub fn is_satisfied(&self) -> bool {
729        matches!(self, Self::Exact | Self::Subset)
730    }
731
732    pub fn is_subset(&self) -> bool {
733        *self == Self::Subset
734    }
735}
736
737impl Partitioning {
738    /// Returns the number of partitions in this partitioning scheme
739    pub fn partition_count(&self) -> usize {
740        use Partitioning::*;
741        match self {
742            RoundRobinBatch(n) | Hash(_, n) | UnknownPartitioning(n) => *n,
743            Range(range) => range.partition_count(),
744        }
745    }
746
747    /// Returns true if `subset_exprs` is a subset of `exprs`.
748    /// For example: Hash(a, b) is subset of Hash(a) since a partition with all occurrences of
749    /// a distinct (a) must also contain all occurrences of a distinct (a, b) with the same (a).
750    fn is_subset_partitioning(
751        subset_exprs: &[Arc<dyn PhysicalExpr>],
752        superset_exprs: &[Arc<dyn PhysicalExpr>],
753    ) -> bool {
754        // Require strict subset: fewer expressions, not equal
755        if subset_exprs.is_empty() || subset_exprs.len() >= superset_exprs.len() {
756            return false;
757        }
758
759        subset_exprs
760            .iter()
761            .all(|subset_expr| physical_exprs_contains(superset_exprs, subset_expr))
762    }
763
764    #[deprecated(since = "52.0.0", note = "Use satisfaction instead")]
765    pub fn satisfy(
766        &self,
767        required: &Distribution,
768        eq_properties: &EquivalenceProperties,
769    ) -> bool {
770        self.satisfaction(required, eq_properties, false)
771            == PartitioningSatisfaction::Exact
772    }
773
774    /// Returns how this [`Partitioning`] satisfies the partitioning scheme mandated
775    /// by the `required` [`Distribution`].
776    #[expect(
777        deprecated,
778        reason = "HashPartitioned is accepted during the KeyPartitioned migration"
779    )]
780    pub fn satisfaction(
781        &self,
782        required: &Distribution,
783        eq_properties: &EquivalenceProperties,
784        allow_subset: bool,
785    ) -> PartitioningSatisfaction {
786        match required {
787            Distribution::UnspecifiedDistribution => PartitioningSatisfaction::Exact,
788            Distribution::SinglePartition if self.partition_count() == 1 => {
789                PartitioningSatisfaction::Exact
790            }
791            // When partition count is 1, key partitioning is satisfied.
792            Distribution::HashPartitioned(_) | Distribution::KeyPartitioned(_)
793                if self.partition_count() == 1 =>
794            {
795                PartitioningSatisfaction::Exact
796            }
797            Distribution::HashPartitioned(required_exprs)
798            | Distribution::KeyPartitioned(required_exprs) => match self {
799                // Here we do not check the partition count for hash partitioning and assumes the partition count
800                // and hash functions in the system are the same. In future if we plan to support storage partition-wise joins,
801                // then we need to have the partition count and hash functions validation.
802                Partitioning::Hash(partition_exprs, _) => Self::key_satisfaction(
803                    partition_exprs,
804                    required_exprs,
805                    eq_properties,
806                    allow_subset,
807                ),
808                Partitioning::Range(range) => {
809                    let partition_exprs = range
810                        .ordering()
811                        .iter()
812                        .map(|sort_expr| Arc::clone(&sort_expr.expr))
813                        .collect::<Vec<_>>();
814                    Self::key_satisfaction(
815                        &partition_exprs,
816                        required_exprs,
817                        eq_properties,
818                        allow_subset,
819                    )
820                }
821                Partitioning::RoundRobinBatch(_)
822                | Partitioning::UnknownPartitioning(_) => {
823                    PartitioningSatisfaction::NotSatisfied
824                }
825            },
826            Distribution::SinglePartition => PartitioningSatisfaction::NotSatisfied,
827        }
828    }
829
830    /// Returns true when it can prove that equal tuples of `required_exprs`
831    /// cannot occur in different partitions.
832    ///
833    /// Unlike [`Self::satisfaction`], this does not claim a concrete partition
834    /// layout. This weaker guarantee is sufficient for independent keyed
835    /// operations such as aggregation, but not for co-partitioning multiple
836    /// inputs. Transform analysis is currently limited to single-key range
837    /// partitioning.
838    pub fn keeps_keys_local(
839        &self,
840        required_exprs: &[Arc<dyn PhysicalExpr>],
841        eq_properties: &EquivalenceProperties,
842        allow_subset: bool,
843    ) -> bool {
844        let required = Distribution::KeyPartitioned(required_exprs.to_vec());
845        if self
846            .satisfaction(&required, eq_properties, allow_subset)
847            .is_satisfied()
848        {
849            return true;
850        }
851
852        match self {
853            Self::Range(range) => range_partitioning_keeps_keys_local(
854                range,
855                required_exprs,
856                eq_properties,
857                allow_subset,
858            ),
859            Self::RoundRobinBatch(_)
860            | Self::Hash(_, _)
861            | Self::UnknownPartitioning(_) => false,
862        }
863    }
864
865    fn key_satisfaction(
866        partition_exprs: &[Arc<dyn PhysicalExpr>],
867        required_exprs: &[Arc<dyn PhysicalExpr>],
868        eq_properties: &EquivalenceProperties,
869        allow_subset: bool,
870    ) -> PartitioningSatisfaction {
871        if partition_exprs.is_empty() || required_exprs.is_empty() {
872            return PartitioningSatisfaction::NotSatisfied;
873        }
874
875        if equivalent_exprs(required_exprs, partition_exprs, eq_properties) {
876            return PartitioningSatisfaction::Exact;
877        }
878
879        let eq_groups = eq_properties.eq_group();
880        if !eq_groups.is_empty() {
881            if allow_subset {
882                let normalized_partition_exprs =
883                    normalize_exprs(partition_exprs, eq_properties);
884                let normalized_required_exprs =
885                    normalize_exprs(required_exprs, eq_properties);
886                if Self::is_subset_partitioning(
887                    &normalized_partition_exprs,
888                    &normalized_required_exprs,
889                ) {
890                    return PartitioningSatisfaction::Subset;
891                }
892            }
893        } else if allow_subset
894            && Self::is_subset_partitioning(partition_exprs, required_exprs)
895        {
896            return PartitioningSatisfaction::Subset;
897        }
898
899        PartitioningSatisfaction::NotSatisfied
900    }
901
902    /// Calculate the output partitioning after applying the given projection.
903    pub fn project(
904        &self,
905        mapping: &ProjectionMapping,
906        input_eq_properties: &EquivalenceProperties,
907    ) -> Self {
908        match self {
909            Partitioning::Hash(exprs, part) => {
910                let normalized_exprs = input_eq_properties
911                    .project_expressions(exprs, mapping)
912                    .zip(exprs)
913                    .map(|(proj_expr, expr)| {
914                        proj_expr.unwrap_or_else(|| {
915                            Arc::new(UnKnownColumn::new(&expr.to_string()))
916                        })
917                    })
918                    .collect();
919                Partitioning::Hash(normalized_exprs, *part)
920            }
921            Partitioning::Range(range) => {
922                if let Some(projected) = range.project(mapping, input_eq_properties) {
923                    Partitioning::Range(projected)
924                } else {
925                    Partitioning::UnknownPartitioning(range.partition_count())
926                }
927            }
928            Partitioning::RoundRobinBatch(_) | Partitioning::UnknownPartitioning(_) => {
929                self.clone()
930            }
931        }
932    }
933
934    /// Adapts this partitioning scheme to satisfy a required [`Distribution`] on the given schema.
935    ///
936    /// - For `Partitioning::Hash`: creates `Partitioning::Hash(exprs, partition_count)`.
937    /// - For `Partitioning::Range`: adapts the range partitioning to the requirement's expressions using [`RangePartitioning::adapt`].
938    /// - For other partitioning schemes: returns `None`.
939    #[expect(
940        deprecated,
941        reason = "HashPartitioned is accepted during the KeyPartitioned migration"
942    )]
943    pub fn adapt(
944        &self,
945        child_requirement: &Distribution,
946        child_schema: &Schema,
947    ) -> Option<Self> {
948        let (Distribution::HashPartitioned(exprs) | Distribution::KeyPartitioned(exprs)) =
949            child_requirement
950        else {
951            return None;
952        };
953
954        match self {
955            Partitioning::Range(ref_range) => ref_range
956                .adapt(exprs, child_schema)
957                .map(Partitioning::Range),
958            Partitioning::Hash(_, ref_count) => {
959                Some(Partitioning::Hash(exprs.to_vec(), *ref_count))
960            }
961            _ => None,
962        }
963    }
964}
965
966/// Protobuf conversions for [`Partitioning`].
967///
968/// Child expressions (hash keys, range orderings) and `ScalarValue` split
969/// points are (de)serialized through the expression-level context, so this is
970/// the single copy of the partitioning wire format: `RepartitionExec` and
971/// `datafusion-proto`'s central serializer route through it, and the remaining
972/// per-plan migrations (`FileScanConfig` and friends) are meant to do the same
973/// rather than grow another copy.
974///
975/// [`protobuf::Partitioning`]: datafusion_proto_models::protobuf::Partitioning
976#[cfg(feature = "proto")]
977impl Partitioning {
978    /// Serialize this partitioning into its protobuf representation.
979    pub fn try_to_proto(
980        &self,
981        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
982    ) -> Result<datafusion_proto_models::protobuf::Partitioning> {
983        use datafusion_common::utils::usize_to_wire;
984        use datafusion_proto_models::protobuf;
985
986        let partition_count =
987            |count: usize| usize_to_wire::<u64>(count, "Partitioning", "partition_count");
988        let partition_method = match self {
989            Partitioning::RoundRobinBatch(n) => {
990                protobuf::partitioning::PartitionMethod::RoundRobin(partition_count(*n)?)
991            }
992            Partitioning::Hash(exprs, n) => {
993                protobuf::partitioning::PartitionMethod::Hash(
994                    protobuf::PhysicalHashRepartition {
995                        hash_expr: ctx.encode_children_expressions(exprs)?,
996                        partition_count: partition_count(*n)?,
997                    },
998                )
999            }
1000            Partitioning::Range(range) => {
1001                let sort_expr = sort_exprs_try_to_proto(range.ordering().iter(), ctx)?;
1002                let encode_split_points = |split_points: &[SplitPoint]| {
1003                    split_points
1004                        .iter()
1005                        .map(|split_point| {
1006                            let value = split_point
1007                                .values()
1008                                .iter()
1009                                .map(|value| value.try_into().map_err(Into::into))
1010                                .collect::<Result<Vec<_>>>()?;
1011                            Ok(protobuf::PhysicalRangeSplitPoint { value })
1012                        })
1013                        .collect::<Result<Vec<_>>>()
1014                };
1015                let split_point = encode_split_points(range.split_points())?;
1016                let sample_point = encode_split_points(range.samples())?;
1017                protobuf::partitioning::PartitionMethod::Range(
1018                    protobuf::PhysicalRangePartitioning {
1019                        sort_expr,
1020                        split_point,
1021                        sample_point,
1022                        partition_count: partition_count(range.partition_count())?,
1023                    },
1024                )
1025            }
1026            Partitioning::UnknownPartitioning(n) => {
1027                protobuf::partitioning::PartitionMethod::Unknown(partition_count(*n)?)
1028            }
1029        };
1030        Ok(protobuf::Partitioning {
1031            partition_method: Some(partition_method),
1032        })
1033    }
1034
1035    /// Reconstruct a [`Partitioning`] from its protobuf representation.
1036    ///
1037    /// Returns `Ok(None)` when the message carries no `partition_method`, which
1038    /// the wire format uses to mean "no output partitioning declared"; callers
1039    /// for which it is required should turn that into their own error.
1040    pub fn try_from_proto(
1041        node: &datafusion_proto_models::protobuf::Partitioning,
1042        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
1043    ) -> Result<Option<Self>> {
1044        use datafusion_common::utils::usize_from_wire;
1045        use datafusion_common::{ScalarValue, internal_datafusion_err, internal_err};
1046        use datafusion_proto_models::protobuf;
1047
1048        let partition_count =
1049            |count: u64| usize_from_wire(count, "Partitioning", "partition_count");
1050        let protobuf::Partitioning { partition_method } = node;
1051        let Some(partition_method) = partition_method.as_ref() else {
1052            return Ok(None);
1053        };
1054        let partitioning = match partition_method {
1055            protobuf::partitioning::PartitionMethod::RoundRobin(n) => {
1056                Partitioning::RoundRobinBatch(partition_count(*n)?)
1057            }
1058            protobuf::partitioning::PartitionMethod::Hash(hash) => {
1059                let protobuf::PhysicalHashRepartition {
1060                    hash_expr,
1061                    partition_count: hash_partition_count,
1062                } = hash;
1063                let exprs = hash_expr
1064                    .iter()
1065                    .map(|expr| ctx.decode(expr))
1066                    .collect::<Result<Vec<_>>>()?;
1067                Partitioning::Hash(exprs, partition_count(*hash_partition_count)?)
1068            }
1069            protobuf::partitioning::PartitionMethod::Unknown(n) => {
1070                Partitioning::UnknownPartitioning(partition_count(*n)?)
1071            }
1072            protobuf::partitioning::PartitionMethod::Range(range) => {
1073                let sort_exprs = sort_exprs_try_from_proto(&range.sort_expr, ctx)?;
1074                let sort_expr_count = sort_exprs.len();
1075                let ordering = LexOrdering::new(sort_exprs).ok_or_else(|| {
1076                    internal_datafusion_err!(
1077                        "Range partitioning requires non-empty ordering"
1078                    )
1079                })?;
1080                if ordering.len() != sort_expr_count {
1081                    return internal_err!(
1082                        "Range partitioning ordering must not contain duplicate expressions"
1083                    );
1084                }
1085                let decode_split_points =
1086                    |split_points: &[protobuf::PhysicalRangeSplitPoint]| {
1087                        split_points
1088                            .iter()
1089                            .map(|split_point| {
1090                                let values = split_point
1091                                    .value
1092                                    .iter()
1093                                    .map(|value| {
1094                                        ScalarValue::try_from(value).map_err(Into::into)
1095                                    })
1096                                    .collect::<Result<Vec<_>>>()?;
1097                                Ok(SplitPoint::new(values))
1098                            })
1099                            .collect::<Result<Vec<_>>>()
1100                    };
1101                let split_points = decode_split_points(&range.split_point)?;
1102                if range.partition_count == 0 {
1103                    // Older payloads derive their partition count from the exact
1104                    // split points and do not carry this field.
1105                    Partitioning::Range(RangePartitioning::try_new(
1106                        ordering,
1107                        split_points,
1108                    )?)
1109                } else {
1110                    let samples = decode_split_points(&range.sample_point)?;
1111                    let range_partitioning = RangePartitioning::try_new_with_samples(
1112                        ordering,
1113                        samples,
1114                        partition_count(range.partition_count)?,
1115                    )?;
1116                    if range_partitioning.split_points() != split_points {
1117                        return internal_err!(
1118                            "Range partitioning effective split points do not match its samples and partition count"
1119                        );
1120                    }
1121                    Partitioning::Range(range_partitioning)
1122                }
1123            }
1124        };
1125        Ok(Some(partitioning))
1126    }
1127}
1128
1129impl PartialEq for Partitioning {
1130    fn eq(&self, other: &Partitioning) -> bool {
1131        match (self, other) {
1132            (
1133                Partitioning::RoundRobinBatch(count1),
1134                Partitioning::RoundRobinBatch(count2),
1135            ) if count1 == count2 => true,
1136            (Partitioning::Hash(exprs1, count1), Partitioning::Hash(exprs2, count2))
1137                if physical_exprs_equal(exprs1, exprs2) && (count1 == count2) =>
1138            {
1139                true
1140            }
1141            (Partitioning::Range(left), Partitioning::Range(right)) => left == right,
1142            _ => false,
1143        }
1144    }
1145}
1146
1147/// How data is distributed amongst partitions. See [`Partitioning`] for more
1148/// details.
1149#[derive(Debug, Clone)]
1150pub enum Distribution {
1151    /// Unspecified distribution
1152    UnspecifiedDistribution,
1153    /// A single partition is required
1154    SinglePartition,
1155    /// Deprecated historical name for [`Distribution::KeyPartitioned`].
1156    /// See <https://github.com/apache/datafusion/issues/23236> for details.
1157    #[deprecated(since = "55.0.0", note = "Use Distribution::KeyPartitioned")]
1158    HashPartitioned(Vec<Arc<dyn PhysicalExpr>>),
1159    /// Requires children to be distributed in such a way that the same
1160    /// values of the keys end up in the same partition
1161    KeyPartitioned(Vec<Arc<dyn PhysicalExpr>>),
1162}
1163
1164#[expect(
1165    deprecated,
1166    reason = "HashPartitioned is accepted during the KeyPartitioned migration"
1167)]
1168impl Distribution {
1169    /// Creates a `Partitioning` that satisfies this `Distribution`
1170    pub fn create_partitioning(self, partition_count: usize) -> Partitioning {
1171        match self {
1172            Distribution::UnspecifiedDistribution => {
1173                Partitioning::UnknownPartitioning(partition_count)
1174            }
1175            Distribution::SinglePartition => Partitioning::UnknownPartitioning(1),
1176            Distribution::HashPartitioned(expr) | Distribution::KeyPartitioned(expr) => {
1177                Partitioning::Hash(expr, partition_count)
1178            }
1179        }
1180    }
1181}
1182
1183#[expect(
1184    deprecated,
1185    reason = "HashPartitioned display is preserved during the KeyPartitioned migration"
1186)]
1187impl Display for Distribution {
1188    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1189        match self {
1190            Distribution::UnspecifiedDistribution => write!(f, "Unspecified"),
1191            Distribution::SinglePartition => write!(f, "SinglePartition"),
1192            Distribution::HashPartitioned(exprs) => {
1193                write!(f, "HashPartitioned[{}])", format_physical_expr_list(exprs))
1194            }
1195            Distribution::KeyPartitioned(exprs) => {
1196                write!(f, "KeyPartitioned[{}])", format_physical_expr_list(exprs))
1197            }
1198        }
1199    }
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204
1205    use super::*;
1206    use crate::expressions::Column;
1207    use crate::projection::ProjectionTargets;
1208
1209    use arrow::compute::SortOptions;
1210    use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit};
1211    use datafusion_common::config::ConfigOptions;
1212    use datafusion_common::{Result, ScalarValue};
1213
1214    struct PartitioningTestFixture {
1215        schema: SchemaRef,
1216        cols: Vec<Arc<dyn PhysicalExpr>>,
1217        eq_properties: EquivalenceProperties,
1218    }
1219
1220    impl PartitioningTestFixture {
1221        fn new(fields: Vec<(&str, DataType)>) -> Result<Self> {
1222            let schema = Arc::new(Schema::new(
1223                fields
1224                    .iter()
1225                    .map(|(name, data_type)| Field::new(*name, data_type.clone(), false))
1226                    .collect::<Vec<_>>(),
1227            ));
1228            let cols = fields
1229                .iter()
1230                .map(|(name, _)| {
1231                    Ok(Arc::new(Column::new_with_schema(name, &schema)?)
1232                        as Arc<dyn PhysicalExpr>)
1233                })
1234                .collect::<Result<_>>()?;
1235            let eq_properties = EquivalenceProperties::new(Arc::clone(&schema));
1236
1237            Ok(Self {
1238                schema,
1239                cols,
1240                eq_properties,
1241            })
1242        }
1243
1244        fn int64(names: &[&str]) -> Result<Self> {
1245            Self::new(names.iter().map(|name| (*name, DataType::Int64)).collect())
1246        }
1247
1248        fn col(&self, index: usize) -> Arc<dyn PhysicalExpr> {
1249            Arc::clone(&self.cols[index])
1250        }
1251
1252        fn cols(
1253            &self,
1254            indices: impl IntoIterator<Item = usize>,
1255        ) -> Vec<Arc<dyn PhysicalExpr>> {
1256            indices.into_iter().map(|index| self.col(index)).collect()
1257        }
1258
1259        fn hash_partitioning(
1260            &self,
1261            indices: impl IntoIterator<Item = usize>,
1262            partition_count: usize,
1263        ) -> Partitioning {
1264            Partitioning::Hash(self.cols(indices), partition_count)
1265        }
1266
1267        fn key_distribution(
1268            &self,
1269            indices: impl IntoIterator<Item = usize>,
1270        ) -> Distribution {
1271            Distribution::KeyPartitioned(self.cols(indices))
1272        }
1273
1274        fn range_sort_expr(
1275            &self,
1276            index: usize,
1277            options: SortOptions,
1278        ) -> PhysicalSortExpr {
1279            PhysicalSortExpr::new(self.col(index), options)
1280        }
1281
1282        fn range_ordering(
1283            &self,
1284            indices: impl IntoIterator<Item = usize>,
1285        ) -> LexOrdering {
1286            LexOrdering::new(
1287                indices
1288                    .into_iter()
1289                    .map(|index| PhysicalSortExpr::new_default(self.col(index))),
1290            )
1291            .expect("ordering must not be empty")
1292        }
1293
1294        fn range(
1295            &self,
1296            indices: impl IntoIterator<Item = usize>,
1297            split_points: Vec<SplitPoint>,
1298        ) -> RangePartitioning {
1299            RangePartitioning::try_new(self.range_ordering(indices), split_points)
1300                .expect("test range partitioning should be valid")
1301        }
1302
1303        fn range_partitioning(
1304            &self,
1305            indices: impl IntoIterator<Item = usize>,
1306            split_points: Vec<SplitPoint>,
1307        ) -> Partitioning {
1308            Partitioning::Range(self.range(indices, split_points))
1309        }
1310
1311        fn range_partitioning_with_ordering(
1312            &self,
1313            ordering: LexOrdering,
1314            split_points: Vec<SplitPoint>,
1315        ) -> Partitioning {
1316            Partitioning::Range(
1317                RangePartitioning::try_new(ordering, split_points)
1318                    .expect("test range partitioning should be valid"),
1319            )
1320        }
1321    }
1322
1323    fn assert_satisfaction(
1324        desc: &str,
1325        partitioning: &Partitioning,
1326        required: &Distribution,
1327        eq_properties: &EquivalenceProperties,
1328        expected_with_subset: PartitioningSatisfaction,
1329        expected_without_subset: PartitioningSatisfaction,
1330    ) {
1331        assert_eq!(
1332            partitioning.satisfaction(required, eq_properties, true),
1333            expected_with_subset,
1334            "Failed for {desc} with subset enabled"
1335        );
1336        assert_eq!(
1337            partitioning.satisfaction(required, eq_properties, false),
1338            expected_without_subset,
1339            "Failed for {desc} with subset disabled"
1340        );
1341    }
1342
1343    fn assert_key_locality(
1344        desc: &str,
1345        partitioning: &Partitioning,
1346        required_exprs: &[Arc<dyn PhysicalExpr>],
1347        eq_properties: &EquivalenceProperties,
1348        expected_with_subset: bool,
1349        expected_without_subset: bool,
1350    ) {
1351        assert_eq!(
1352            partitioning.keeps_keys_local(required_exprs, eq_properties, true),
1353            expected_with_subset,
1354            "Failed for {desc} with subset enabled"
1355        );
1356        assert_eq!(
1357            partitioning.keeps_keys_local(required_exprs, eq_properties, false),
1358            expected_without_subset,
1359            "Failed for {desc} with subset disabled"
1360        );
1361    }
1362
1363    fn date_trunc_of(
1364        timestamp: Arc<dyn PhysicalExpr>,
1365        precision: &str,
1366        timezone: Option<&str>,
1367    ) -> Arc<dyn PhysicalExpr> {
1368        let timezone = timezone.map(Into::into);
1369        Arc::new(ScalarFunctionExpr::new(
1370            "date_trunc",
1371            datafusion_functions::datetime::date_trunc(),
1372            vec![
1373                Arc::new(Literal::new(ScalarValue::Utf8(Some(precision.into())))),
1374                timestamp,
1375            ],
1376            Field::new(
1377                "date_trunc",
1378                DataType::Timestamp(TimeUnit::Nanosecond, timezone),
1379                true,
1380            )
1381            .into(),
1382            Arc::new(ConfigOptions::default()),
1383        ))
1384    }
1385
1386    /// Builds `date_bin(stride, timestamp)` with a nanosecond-only literal stride
1387    /// and the default epoch origin. This constructs the expression without evaluating it.
1388    fn date_bin_of(
1389        timestamp: Arc<dyn PhysicalExpr>,
1390        stride_nanos: i64,
1391    ) -> Arc<dyn PhysicalExpr> {
1392        Arc::new(ScalarFunctionExpr::new(
1393            "date_bin",
1394            datafusion_functions::datetime::date_bin(),
1395            vec![
1396                Arc::new(Literal::new(ScalarValue::new_interval_mdn(
1397                    0,
1398                    0,
1399                    stride_nanos,
1400                ))),
1401                timestamp,
1402            ],
1403            Field::new(
1404                "date_bin",
1405                DataType::Timestamp(TimeUnit::Nanosecond, None),
1406                true,
1407            )
1408            .into(),
1409            Arc::new(ConfigOptions::default()),
1410        ))
1411    }
1412
1413    #[test]
1414    fn date_bin_requires_disjoint_bins_at_every_split() -> Result<()> {
1415        let fixture = PartitioningTestFixture::new(vec![(
1416            "ts",
1417            DataType::Timestamp(TimeUnit::Nanosecond, None),
1418        )])?;
1419        let hour = 3_600_000_000_000;
1420        let function = date_bin_of(fixture.col(0), hour);
1421        // Ascending compares split - 1 ns with split. Descending compares split
1422        // with split + 1 ns, so aligned descending splits end a bin rather than start it.
1423        let cases = [
1424            ("ascending aligned", false, vec![-hour, 0, hour], true),
1425            ("ascending crossing", false, vec![-hour, 1, hour], false),
1426            (
1427                "descending aligned",
1428                true,
1429                vec![hour - 1, -1, -hour - 1],
1430                true,
1431            ),
1432            ("descending crossing", true, vec![hour, 0, -hour], false),
1433        ];
1434        for (description, descending, splits, expected) in cases {
1435            for nulls_first in [false, true] {
1436                let range = fixture.range_partitioning_with_ordering(
1437                    [fixture
1438                        .range_sort_expr(0, SortOptions::new(descending, nulls_first))]
1439                    .into(),
1440                    splits
1441                        .iter()
1442                        .map(|value| timestamp_split(Some(*value), None))
1443                        .collect(),
1444                );
1445                assert_eq!(
1446                    range.keeps_keys_local(
1447                        &[Arc::clone(&function)],
1448                        &fixture.eq_properties,
1449                        false,
1450                    ),
1451                    expected,
1452                    "{description}, nulls_first={nulls_first}",
1453                );
1454            }
1455        }
1456        Ok(())
1457    }
1458
1459    #[test]
1460    fn date_bin_rejects_adjacent_timestamp_binning_errors() -> Result<()> {
1461        let fixture = PartitioningTestFixture::new(vec![(
1462            "ts",
1463            DataType::Timestamp(TimeUnit::Nanosecond, None),
1464        )])?;
1465        let hour = 3_600_000_000_000;
1466        // The hour containing i64::MIN starts outside the timestamp range.
1467        let nanos_to_next_hour = hour - i64::MIN.rem_euclid(hour);
1468        let first_representable_hour = i64::MIN + nanos_to_next_hour;
1469        let at_split =
1470            ScalarValue::TimestampNanosecond(Some(first_representable_hour), None);
1471        let before_split =
1472            ScalarValue::TimestampNanosecond(Some(first_representable_hour - 1), None);
1473        let timestamp = fixture.col(0);
1474        let function = date_bin_of(Arc::clone(&timestamp), hour);
1475
1476        let bin_at_split = evaluate_with_range_value(&function, &timestamp, &at_split);
1477        assert_eq!(bin_at_split, Some(at_split));
1478
1479        let bin_before_split =
1480            evaluate_with_range_value(&function, &timestamp, &before_split);
1481        assert!(
1482            bin_before_split.is_none(),
1483            "binning 1 ns before the split must fail"
1484        );
1485
1486        let range = fixture.range_partitioning(
1487            [0],
1488            vec![timestamp_split(Some(first_representable_hour), None)],
1489        );
1490        assert!(
1491            !range.keeps_keys_local(&[function], &fixture.eq_properties, false),
1492            "a boundary evaluation error must reject the optimization",
1493        );
1494        Ok(())
1495    }
1496
1497    fn timestamp_split(value: Option<i64>, timezone: Option<&str>) -> SplitPoint {
1498        SplitPoint::new(vec![ScalarValue::TimestampNanosecond(
1499            value,
1500            timezone.map(Into::into),
1501        )])
1502    }
1503
1504    /// Assigns sample rows to source ranges and evaluates whole arrays,
1505    /// independently of the optimizer's boundary-adjacency proof.
1506    fn date_trunc_partition_images_are_disjoint<
1507        T: arrow::array::types::ArrowTimestampType,
1508    >(
1509        function: &Arc<dyn PhysicalExpr>,
1510        splits: &[i64],
1511        options: SortOptions,
1512        schema: &SchemaRef,
1513    ) -> Result<bool> {
1514        use arrow::array::{PrimitiveArray, RecordBatch};
1515        use datafusion_common::HashSet;
1516
1517        let mut partitions = vec![vec![]; splits.len() + 1];
1518        let rows = splits
1519            .iter()
1520            .flat_map(|split| [Some(split - 1), Some(*split), Some(split + 1)])
1521            .chain([None, None]);
1522        for value in rows {
1523            let index = match value {
1524                None if options.nulls_first => 0,
1525                None => splits.len(),
1526                Some(value) => splits
1527                    .iter()
1528                    .filter(|split| {
1529                        if options.descending {
1530                            value <= **split
1531                        } else {
1532                            value >= **split
1533                        }
1534                    })
1535                    .count(),
1536            };
1537            partitions[index].push(value);
1538        }
1539        let images = partitions
1540            .into_iter()
1541            .map(|values| {
1542                let input = Arc::new(PrimitiveArray::<T>::from_iter(values));
1543                let batch = RecordBatch::try_new(Arc::clone(schema), vec![input])?;
1544                let output = function.evaluate(&batch)?.into_array(batch.num_rows())?;
1545                (0..output.len())
1546                    .map(|i| ScalarValue::try_from_array(&output, i))
1547                    .collect::<Result<HashSet<_>>>()
1548            })
1549            .collect::<Result<Vec<_>>>()?;
1550
1551        Ok(images.iter().enumerate().all(|(i, left)| {
1552            images
1553                .iter()
1554                .skip(i + 1)
1555                .all(|right| left.is_disjoint(right))
1556        }))
1557    }
1558
1559    fn assert_date_trunc_partition_images<T: arrow::array::types::ArrowTimestampType>()
1560    -> Result<()> {
1561        let ticks_per_second = match T::UNIT {
1562            TimeUnit::Second => 1,
1563            TimeUnit::Millisecond => 1_000,
1564            TimeUnit::Microsecond => 1_000_000,
1565            TimeUnit::Nanosecond => 1_000_000_000,
1566        };
1567        let hour = 3600 * ticks_per_second;
1568        let data_type = DataType::Timestamp(T::UNIT, None);
1569        let schema =
1570            Arc::new(Schema::new(vec![Field::new("ts", data_type.clone(), true)]));
1571        let timestamp: Arc<dyn PhysicalExpr> = Arc::new(Column::new("ts", 0));
1572        let properties = EquivalenceProperties::new(Arc::clone(&schema));
1573
1574        let mut cases = vec![
1575            (
1576                "aligned ascending hours",
1577                "hour",
1578                false,
1579                vec![-hour, 0, hour],
1580                true,
1581            ),
1582            (
1583                "unaligned ascending hours",
1584                "hour",
1585                false,
1586                vec![-hour + 1, 1, hour + 1],
1587                false,
1588            ),
1589            (
1590                "days cross hourly splits",
1591                "day",
1592                false,
1593                vec![-hour, 0, hour],
1594                false,
1595            ),
1596            (
1597                "descending splits inside hour buckets",
1598                "hour",
1599                true,
1600                vec![-hour, 0, hour],
1601                false,
1602            ),
1603            (
1604                "descending splits between hour buckets",
1605                "hour",
1606                true,
1607                vec![-hour - 1, -1, hour - 1],
1608                true,
1609            ),
1610        ];
1611        for (precision, divisor) in [("millisecond", 1_000), ("microsecond", 1_000_000)] {
1612            let width = (ticks_per_second / divisor).max(1);
1613            cases.extend([
1614                (
1615                    "aligned ascending subsecond splits",
1616                    precision,
1617                    false,
1618                    vec![-width, 0, width],
1619                    true,
1620                ),
1621                // In particular, microsecond input with millisecond precision
1622                // must reject split -999: both adjacent array values map to -1000.
1623                (
1624                    "offset ascending subsecond split",
1625                    precision,
1626                    false,
1627                    vec![-width + 1],
1628                    width == 1,
1629                ),
1630                (
1631                    "descending splits at subsecond bucket starts",
1632                    precision,
1633                    true,
1634                    vec![-width, 0, width],
1635                    width == 1,
1636                ),
1637                (
1638                    "descending splits at subsecond bucket ends",
1639                    precision,
1640                    true,
1641                    vec![-width - 1, -1, width - 1],
1642                    true,
1643                ),
1644            ]);
1645        }
1646        for (description, precision, descending, source_splits, expect_disjoint) in cases
1647        {
1648            for nulls_first in [false, true] {
1649                let options = SortOptions::new(descending, nulls_first);
1650                let mut splits = source_splits.clone();
1651                if descending {
1652                    splits.reverse();
1653                }
1654                let range = Partitioning::Range(RangePartitioning::try_new(
1655                    [PhysicalSortExpr::new(Arc::clone(&timestamp), options)].into(),
1656                    splits
1657                        .iter()
1658                        .map(|value| {
1659                            SplitPoint::new(vec![ScalarValue::new_timestamp::<T>(
1660                                Some(*value),
1661                                None,
1662                            )])
1663                        })
1664                        .collect(),
1665                )?);
1666                let function: Arc<dyn PhysicalExpr> = Arc::new(ScalarFunctionExpr::new(
1667                    "date_trunc",
1668                    datafusion_functions::datetime::date_trunc(),
1669                    vec![
1670                        Arc::new(Literal::new(ScalarValue::from(precision))),
1671                        Arc::clone(&timestamp),
1672                    ],
1673                    Field::new("bucket", data_type.clone(), true).into(),
1674                    Arc::new(ConfigOptions::default()),
1675                ));
1676                assert_eq!(
1677                    range.keeps_keys_local(&[Arc::clone(&function)], &properties, false),
1678                    expect_disjoint,
1679                    "optimizer: {description}, {precision}, {:?}, {options:?}, splits={splits:?}",
1680                    T::UNIT
1681                );
1682                assert_eq!(
1683                    date_trunc_partition_images_are_disjoint::<T>(
1684                        &function, &splits, options, &schema,
1685                    )?,
1686                    expect_disjoint,
1687                    "array evaluation: {description}, {precision}, {:?}, {options:?}, splits={splits:?}",
1688                    T::UNIT
1689                );
1690            }
1691        }
1692        Ok(())
1693    }
1694
1695    #[test]
1696    fn date_trunc_partition_images_are_disjoint_only_for_safe_splits() -> Result<()> {
1697        use arrow::array::types::{
1698            TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
1699            TimestampSecondType,
1700        };
1701        assert_date_trunc_partition_images::<TimestampSecondType>()?;
1702        assert_date_trunc_partition_images::<TimestampMillisecondType>()?;
1703        assert_date_trunc_partition_images::<TimestampMicrosecondType>()?;
1704        assert_date_trunc_partition_images::<TimestampNanosecondType>()
1705    }
1706
1707    #[test]
1708    fn range_transform_requires_literal_parameters() -> Result<()> {
1709        use crate::expressions::CastExpr;
1710        let fixture = PartitioningTestFixture::new(vec![(
1711            "ts",
1712            DataType::Timestamp(TimeUnit::Nanosecond, None),
1713        )])?;
1714        let function = date_trunc_of(fixture.col(0), "hour", None);
1715        let scalar_but_not_literal: Arc<dyn PhysicalExpr> = Arc::new(CastExpr::new(
1716            Arc::new(Literal::new(ScalarValue::from("hour"))),
1717            DataType::Utf8View,
1718            None,
1719        ));
1720        let function =
1721            function.with_new_children(vec![scalar_but_not_literal, fixture.col(0)])?;
1722        let range = fixture.range_partitioning([0], vec![timestamp_split(Some(0), None)]);
1723        assert!(!range.keeps_keys_local(&[function], &fixture.eq_properties, false));
1724        Ok(())
1725    }
1726
1727    #[test]
1728    fn range_transform_establishes_key_locality_only() -> Result<()> {
1729        let fixture = PartitioningTestFixture::new(vec![
1730            ("timestamp", DataType::Timestamp(TimeUnit::Nanosecond, None)),
1731            ("tag", DataType::Utf8),
1732        ])?;
1733        let hour = 1_704_070_800_000_000_000;
1734        let aligned =
1735            fixture.range_partitioning([0], vec![timestamp_split(Some(hour), None)]);
1736        let trunc_hour = date_trunc_of(fixture.col(0), "hour", None);
1737
1738        let exact_key_exprs = vec![Arc::clone(&trunc_hour)];
1739        assert_eq!(
1740            aligned.satisfaction(
1741                &Distribution::KeyPartitioned(exact_key_exprs.clone()),
1742                &fixture.eq_properties,
1743                false,
1744            ),
1745            PartitioningSatisfaction::NotSatisfied
1746        );
1747        assert_key_locality(
1748            "aligned transformed key",
1749            &aligned,
1750            &exact_key_exprs,
1751            &fixture.eq_properties,
1752            true,
1753            true,
1754        );
1755
1756        assert_key_locality(
1757            "additional grouping keys require subset permission",
1758            &aligned,
1759            &[trunc_hour, fixture.col(1)],
1760            &fixture.eq_properties,
1761            true,
1762            false,
1763        );
1764
1765        let trunc_day = date_trunc_of(fixture.col(0), "day", None);
1766        assert_key_locality(
1767            "an hour split straddles a day bucket",
1768            &aligned,
1769            &[trunc_day],
1770            &fixture.eq_properties,
1771            false,
1772            false,
1773        );
1774
1775        let two_aligned = fixture.range_partitioning(
1776            [0],
1777            vec![
1778                timestamp_split(Some(hour), None),
1779                timestamp_split(Some(hour + 3_600_000_000_000), None),
1780            ],
1781        );
1782        assert_key_locality(
1783            "every split must be aligned",
1784            &two_aligned,
1785            &exact_key_exprs,
1786            &fixture.eq_properties,
1787            true,
1788            true,
1789        );
1790
1791        let unaligned =
1792            fixture.range_partitioning([0], vec![timestamp_split(Some(hour + 1), None)]);
1793        assert_key_locality(
1794            "an unaligned split straddles an hour bucket",
1795            &unaligned,
1796            &exact_key_exprs,
1797            &fixture.eq_properties,
1798            false,
1799            false,
1800        );
1801        Ok(())
1802    }
1803
1804    #[test]
1805    fn range_transform_rejects_compound_range_keys() -> Result<()> {
1806        let fixture = PartitioningTestFixture::new(vec![
1807            ("key", DataType::Utf8),
1808            ("timestamp", DataType::Timestamp(TimeUnit::Nanosecond, None)),
1809        ])?;
1810        let split = SplitPoint::new(vec![
1811            ScalarValue::Utf8(Some("m".into())),
1812            ScalarValue::TimestampNanosecond(Some(1_704_070_800_000_000_000), None),
1813        ]);
1814        let range = fixture.range_partitioning([0, 1], vec![split]);
1815
1816        // Start with single-key ranges; compound transforms can follow once
1817        // tuple-boundary safety is established.
1818        assert!(!range.keeps_keys_local(
1819            &[fixture.col(0), date_trunc_of(fixture.col(1), "hour", None),],
1820            &fixture.eq_properties,
1821            false,
1822        ));
1823        Ok(())
1824    }
1825
1826    #[test]
1827    #[expect(
1828        deprecated,
1829        reason = "test intentionally constructs malformed range splits"
1830    )]
1831    fn range_transform_rejects_malformed_split_points() -> Result<()> {
1832        let fixture = PartitioningTestFixture::new(vec![(
1833            "timestamp",
1834            DataType::Timestamp(TimeUnit::Nanosecond, None),
1835        )])?;
1836        let required = vec![date_trunc_of(fixture.col(0), "hour", None)];
1837        let hour = 3_600_000_000_000;
1838        let timestamp = |value| ScalarValue::TimestampNanosecond(Some(value), None);
1839
1840        for (description, descending, splits) in [
1841            (
1842                "reversed ascending splits",
1843                false,
1844                vec![vec![timestamp(2 * hour)], vec![timestamp(hour)]],
1845            ),
1846            (
1847                "reversed descending splits",
1848                true,
1849                vec![vec![timestamp(hour - 1)], vec![timestamp(2 * hour - 1)]],
1850            ),
1851            (
1852                "duplicate ascending splits",
1853                false,
1854                vec![vec![timestamp(hour)], vec![timestamp(hour)]],
1855            ),
1856            (
1857                "duplicate descending splits",
1858                true,
1859                vec![vec![timestamp(hour - 1)], vec![timestamp(hour - 1)]],
1860            ),
1861            (
1862                "overwide split tuple",
1863                false,
1864                vec![vec![timestamp(hour), ScalarValue::Int64(Some(0))]],
1865            ),
1866            ("empty split tuple", false, vec![vec![]]),
1867        ] {
1868            let range = Partitioning::Range(RangePartitioning::new(
1869                [PhysicalSortExpr::new(
1870                    fixture.col(0),
1871                    SortOptions::new(descending, false),
1872                )]
1873                .into(),
1874                splits.into_iter().map(SplitPoint::new).collect(),
1875            ));
1876            assert_key_locality(
1877                description,
1878                &range,
1879                &required,
1880                &fixture.eq_properties,
1881                false,
1882                false,
1883            );
1884        }
1885        Ok(())
1886    }
1887
1888    #[test]
1889    fn range_transform_rejects_null_or_minimum_timestamp_splits() -> Result<()> {
1890        let fixture = PartitioningTestFixture::new(vec![(
1891            "timestamp",
1892            DataType::Timestamp(TimeUnit::Nanosecond, None),
1893        )])?;
1894        let required = vec![date_trunc_of(fixture.col(0), "hour", None)];
1895
1896        for (description, split) in [
1897            ("null", timestamp_split(None, None)),
1898            (
1899                "minimum has no predecessor",
1900                timestamp_split(Some(i64::MIN), None),
1901            ),
1902        ] {
1903            assert_key_locality(
1904                description,
1905                &fixture.range_partitioning([0], vec![split]),
1906                &required,
1907                &fixture.eq_properties,
1908                false,
1909                false,
1910            );
1911        }
1912        Ok(())
1913    }
1914
1915    #[test]
1916    #[expect(
1917        deprecated,
1918        reason = "test intentionally constructs a malformed range split"
1919    )]
1920    fn range_transform_rejects_split_type_mismatch() -> Result<()> {
1921        let fixture = PartitioningTestFixture::new(vec![(
1922            "timestamp",
1923            DataType::Timestamp(TimeUnit::Nanosecond, None),
1924        )])?;
1925        let required = vec![date_trunc_of(fixture.col(0), "hour", None)];
1926        let mismatched_split = Partitioning::Range(RangePartitioning::new(
1927            fixture.range_ordering([0]),
1928            vec![SplitPoint::new(vec![ScalarValue::Int64(Some(10))])],
1929        ));
1930        assert_key_locality(
1931            "split scalar type must match the range key",
1932            &mismatched_split,
1933            &required,
1934            &fixture.eq_properties,
1935            false,
1936            false,
1937        );
1938        Ok(())
1939    }
1940
1941    #[test]
1942    fn range_transform_rejects_boundary_evaluation_errors() -> Result<()> {
1943        let fixture = PartitioningTestFixture::new(vec![(
1944            "timestamp",
1945            DataType::Timestamp(TimeUnit::Nanosecond, None),
1946        )])?;
1947        let invalid_precision =
1948            vec![date_trunc_of(fixture.col(0), "not-a-precision", None)];
1949        let aligned = fixture.range_partitioning(
1950            [0],
1951            vec![timestamp_split(Some(1_704_070_800_000_000_000), None)],
1952        );
1953        assert_key_locality(
1954            "split evaluation errors fail closed",
1955            &aligned,
1956            &invalid_precision,
1957            &fixture.eq_properties,
1958            false,
1959            false,
1960        );
1961        Ok(())
1962    }
1963
1964    #[test]
1965    fn range_transform_rejects_adjacent_timestamp_evaluation_errors() -> Result<()> {
1966        let fixture = PartitioningTestFixture::new(vec![(
1967            "timestamp",
1968            DataType::Timestamp(TimeUnit::Nanosecond, None),
1969        )])?;
1970        let nanoseconds_per_hour = 3_600_000_000_000;
1971        let first_representable_hour =
1972            i64::MIN / nanoseconds_per_hour * nanoseconds_per_hour;
1973        let split =
1974            ScalarValue::TimestampNanosecond(Some(first_representable_hour), None);
1975        let predecessor =
1976            ScalarValue::TimestampNanosecond(Some(first_representable_hour - 1), None);
1977        let timestamp = fixture.col(0);
1978        let trunc_hour = date_trunc_of(Arc::clone(&timestamp), "hour", None);
1979
1980        assert_eq!(
1981            evaluate_with_range_value(&trunc_hour, &timestamp, &split),
1982            Some(split.clone()),
1983        );
1984        assert_eq!(
1985            evaluate_with_range_value(&trunc_hour, &timestamp, &predecessor),
1986            None,
1987        );
1988
1989        let range = fixture.range_partitioning([0], vec![SplitPoint::new(vec![split])]);
1990        assert_key_locality(
1991            "predecessor truncation underflows even though split truncation succeeds",
1992            &range,
1993            &[trunc_hour],
1994            &fixture.eq_properties,
1995            false,
1996            false,
1997        );
1998        Ok(())
1999    }
2000
2001    #[test]
2002    fn range_transform_rejects_timezone_annotated_timestamps() -> Result<()> {
2003        let fixture = PartitioningTestFixture::new(vec![(
2004            "timestamp",
2005            DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
2006        )])?;
2007        let trunc_hour = date_trunc_of(fixture.col(0), "hour", Some("UTC"));
2008        let range = fixture.range_partitioning(
2009            [0],
2010            vec![timestamp_split(
2011                Some(1_704_070_800_000_000_000),
2012                Some("UTC"),
2013            )],
2014        );
2015        assert_key_locality(
2016            "timezone-aware date_trunc is not audited",
2017            &range,
2018            &[trunc_hour],
2019            &fixture.eq_properties,
2020            false,
2021            false,
2022        );
2023        Ok(())
2024    }
2025
2026    #[test]
2027    fn descending_range_uses_the_open_side_successor() -> Result<()> {
2028        let fixture = PartitioningTestFixture::new(vec![(
2029            "timestamp",
2030            DataType::Timestamp(TimeUnit::Nanosecond, None),
2031        )])?;
2032        let hour = 1_704_070_800_000_000_000;
2033        let ordering: LexOrdering =
2034            [fixture.range_sort_expr(0, SortOptions::new(true, false))].into();
2035        let required = vec![date_trunc_of(fixture.col(0), "hour", None)];
2036
2037        assert_key_locality(
2038            "the successor of an hour boundary is in the same bucket",
2039            &fixture.range_partitioning_with_ordering(
2040                ordering.clone(),
2041                vec![timestamp_split(Some(hour), None)],
2042            ),
2043            &required,
2044            &fixture.eq_properties,
2045            false,
2046            false,
2047        );
2048        assert_key_locality(
2049            "the successor of the final nanosecond starts a new bucket",
2050            &fixture.range_partitioning_with_ordering(
2051                ordering.clone(),
2052                vec![timestamp_split(Some(hour + 3_600_000_000_000 - 1), None)],
2053            ),
2054            &required,
2055            &fixture.eq_properties,
2056            true,
2057            true,
2058        );
2059        assert_key_locality(
2060            "the maximum timestamp has no successor",
2061            &fixture.range_partitioning_with_ordering(
2062                ordering,
2063                vec![timestamp_split(Some(i64::MAX), None)],
2064            ),
2065            &required,
2066            &fixture.eq_properties,
2067            false,
2068            false,
2069        );
2070        Ok(())
2071    }
2072
2073    #[test]
2074    #[expect(
2075        deprecated,
2076        reason = "test intentionally covers deprecated HashPartitioned compatibility"
2077    )]
2078    fn partitioning_satisfy_distribution() -> Result<()> {
2079        let fixture = PartitioningTestFixture::new(vec![
2080            ("column_1", DataType::Int64),
2081            ("column_2", DataType::Utf8),
2082        ])?;
2083
2084        let distribution_types = vec![
2085            Distribution::UnspecifiedDistribution,
2086            Distribution::SinglePartition,
2087            Distribution::HashPartitioned(fixture.cols([0, 1])),
2088            fixture.key_distribution([0, 1]),
2089        ];
2090
2091        let single_partition = Partitioning::UnknownPartitioning(1);
2092        let unspecified_partition = Partitioning::UnknownPartitioning(10);
2093        let round_robin_partition = Partitioning::RoundRobinBatch(10);
2094        let hash_partition1 = fixture.hash_partitioning([0, 1], 10);
2095        let hash_partition2 = fixture.hash_partitioning([1, 0], 10);
2096
2097        for distribution in distribution_types {
2098            let result = (
2099                single_partition
2100                    .satisfaction(&distribution, &fixture.eq_properties, true)
2101                    .is_satisfied(),
2102                unspecified_partition
2103                    .satisfaction(&distribution, &fixture.eq_properties, true)
2104                    .is_satisfied(),
2105                round_robin_partition
2106                    .satisfaction(&distribution, &fixture.eq_properties, true)
2107                    .is_satisfied(),
2108                hash_partition1
2109                    .satisfaction(&distribution, &fixture.eq_properties, true)
2110                    .is_satisfied(),
2111                hash_partition2
2112                    .satisfaction(&distribution, &fixture.eq_properties, true)
2113                    .is_satisfied(),
2114            );
2115
2116            match distribution {
2117                Distribution::UnspecifiedDistribution => {
2118                    assert_eq!(result, (true, true, true, true, true))
2119                }
2120                Distribution::SinglePartition => {
2121                    assert_eq!(result, (true, false, false, false, false))
2122                }
2123                Distribution::HashPartitioned(_) | Distribution::KeyPartitioned(_) => {
2124                    assert_eq!(result, (true, false, false, true, false))
2125                }
2126            }
2127        }
2128
2129        Ok(())
2130    }
2131
2132    #[test]
2133    #[expect(
2134        deprecated,
2135        reason = "test intentionally covers deprecated HashPartitioned compatibility"
2136    )]
2137    fn deprecated_hash_partitioned_matches_key_partitioned() -> Result<()> {
2138        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2139        let partitioning = fixture.hash_partitioning([0, 1], 4);
2140        let hash_distribution = Distribution::HashPartitioned(fixture.cols([0, 1]));
2141        let key_distribution = fixture.key_distribution([0, 1]);
2142
2143        assert_eq!(
2144            partitioning.satisfaction(&hash_distribution, &fixture.eq_properties, false),
2145            partitioning.satisfaction(&key_distribution, &fixture.eq_properties, false)
2146        );
2147        assert_eq!(
2148            hash_distribution.create_partitioning(4),
2149            key_distribution.create_partitioning(4)
2150        );
2151
2152        Ok(())
2153    }
2154
2155    #[test]
2156    fn hash_partitioning_key_distribution_satisfaction() -> Result<()> {
2157        let fixture = PartitioningTestFixture::int64(&["a", "b", "c"])?;
2158        let unknown: Arc<dyn PhysicalExpr> = Arc::new(UnKnownColumn::new("dropped"));
2159
2160        let test_cases = vec![
2161            (
2162                "exact: KeyPartitioned([a, b]) satisfied by Hash([a, b])",
2163                fixture.hash_partitioning([0, 1], 4),
2164                fixture.key_distribution([0, 1]),
2165                PartitioningSatisfaction::Exact,
2166                PartitioningSatisfaction::Exact,
2167            ),
2168            (
2169                "subset: KeyPartitioned([a, b]) satisfied by Hash([a])",
2170                fixture.hash_partitioning([0], 4),
2171                fixture.key_distribution([0, 1]),
2172                PartitioningSatisfaction::Subset,
2173                PartitioningSatisfaction::NotSatisfied,
2174            ),
2175            (
2176                "subset: KeyPartitioned([a, b, c]) satisfied by Hash([b])",
2177                fixture.hash_partitioning([1], 4),
2178                fixture.key_distribution([0, 1, 2]),
2179                PartitioningSatisfaction::Subset,
2180                PartitioningSatisfaction::NotSatisfied,
2181            ),
2182            (
2183                "subset reordered: KeyPartitioned([a, b, c]) satisfied by Hash([b, a])",
2184                fixture.hash_partitioning([1, 0], 4),
2185                fixture.key_distribution([0, 1, 2]),
2186                PartitioningSatisfaction::Subset,
2187                PartitioningSatisfaction::NotSatisfied,
2188            ),
2189            (
2190                "superset: KeyPartitioned([a]) not satisfied by Hash([a, b])",
2191                fixture.hash_partitioning([0, 1], 4),
2192                fixture.key_distribution([0]),
2193                PartitioningSatisfaction::NotSatisfied,
2194                PartitioningSatisfaction::NotSatisfied,
2195            ),
2196            (
2197                "superset: KeyPartitioned([a, b]) not satisfied by Hash([a, b, c])",
2198                fixture.hash_partitioning([0, 1, 2], 4),
2199                fixture.key_distribution([0, 1]),
2200                PartitioningSatisfaction::NotSatisfied,
2201                PartitioningSatisfaction::NotSatisfied,
2202            ),
2203            (
2204                "partial overlap: KeyPartitioned([a, b]) not satisfied by Hash([a, c])",
2205                fixture.hash_partitioning([0, 2], 4),
2206                fixture.key_distribution([0, 1]),
2207                PartitioningSatisfaction::NotSatisfied,
2208                PartitioningSatisfaction::NotSatisfied,
2209            ),
2210            (
2211                "no overlap: KeyPartitioned([b, c]) not satisfied by Hash([a])",
2212                fixture.hash_partitioning([0], 4),
2213                fixture.key_distribution([1, 2]),
2214                PartitioningSatisfaction::NotSatisfied,
2215                PartitioningSatisfaction::NotSatisfied,
2216            ),
2217            (
2218                "unknown partition expr",
2219                Partitioning::Hash(vec![Arc::clone(&unknown)], 4),
2220                fixture.key_distribution([0, 1]),
2221                PartitioningSatisfaction::NotSatisfied,
2222                PartitioningSatisfaction::NotSatisfied,
2223            ),
2224            (
2225                "unknown required expr",
2226                fixture.hash_partitioning([0, 1], 4),
2227                Distribution::KeyPartitioned(vec![Arc::clone(&unknown)]),
2228                PartitioningSatisfaction::NotSatisfied,
2229                PartitioningSatisfaction::NotSatisfied,
2230            ),
2231            (
2232                "same unknown expr",
2233                Partitioning::Hash(vec![Arc::clone(&unknown)], 4),
2234                Distribution::KeyPartitioned(vec![Arc::clone(&unknown)]),
2235                PartitioningSatisfaction::NotSatisfied,
2236                PartitioningSatisfaction::NotSatisfied,
2237            ),
2238            (
2239                "unknown partition expr is not a valid subset",
2240                Partitioning::Hash(vec![Arc::clone(&unknown)], 4),
2241                Distribution::KeyPartitioned(vec![Arc::clone(&unknown), fixture.col(0)]),
2242                PartitioningSatisfaction::NotSatisfied,
2243                PartitioningSatisfaction::NotSatisfied,
2244            ),
2245            (
2246                "empty hash partitioning",
2247                Partitioning::Hash(vec![], 4),
2248                fixture.key_distribution([0]),
2249                PartitioningSatisfaction::NotSatisfied,
2250                PartitioningSatisfaction::NotSatisfied,
2251            ),
2252            (
2253                "empty key distribution",
2254                fixture.hash_partitioning([0], 4),
2255                Distribution::KeyPartitioned(vec![]),
2256                PartitioningSatisfaction::NotSatisfied,
2257                PartitioningSatisfaction::NotSatisfied,
2258            ),
2259        ];
2260
2261        for (desc, partition, required, expected_with_subset, expected_without_subset) in
2262            test_cases
2263        {
2264            assert_satisfaction(
2265                desc,
2266                &partition,
2267                &required,
2268                &fixture.eq_properties,
2269                expected_with_subset,
2270                expected_without_subset,
2271            );
2272        }
2273
2274        Ok(())
2275    }
2276
2277    fn int_split_point(values: impl IntoIterator<Item = i64>) -> SplitPoint {
2278        SplitPoint::new(
2279            values
2280                .into_iter()
2281                .map(|value| ScalarValue::Int64(Some(value)))
2282                .collect(),
2283        )
2284    }
2285
2286    fn assert_range_try_new_error(
2287        ordering: LexOrdering,
2288        split_points: Vec<SplitPoint>,
2289        expected: &str,
2290    ) {
2291        let error = RangePartitioning::try_new(ordering, split_points)
2292            .unwrap_err()
2293            .to_string();
2294        assert!(error.contains(expected), "{error}");
2295    }
2296
2297    #[test]
2298    fn test_range_partitioning_metadata() -> Result<()> {
2299        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2300
2301        let range_partitioning =
2302            fixture.range([0], vec![int_split_point([10]), int_split_point([20])]);
2303        assert_eq!(range_partitioning.ordering()[0].to_string(), "a@0 ASC");
2304        assert_eq!(
2305            range_partitioning.split_points(),
2306            &[int_split_point([10]), int_split_point([20])]
2307        );
2308        let partitioning = Partitioning::Range(range_partitioning);
2309
2310        assert_eq!(partitioning.partition_count(), 3);
2311        assert_eq!(
2312            partitioning.to_string(),
2313            "Range([a@0 ASC], [(10), (20)], 3)"
2314        );
2315
2316        Ok(())
2317    }
2318
2319    #[test]
2320    fn test_range_partitioning_scales_from_samples() -> Result<()> {
2321        let fixture = PartitioningTestFixture::int64(&["a"])?;
2322        let samples = (10..=90)
2323            .step_by(10)
2324            .map(|value| int_split_point([value]))
2325            .collect::<Vec<_>>();
2326        let range = RangePartitioning::try_new_with_samples(
2327            fixture.range_ordering([0]),
2328            samples.clone(),
2329            4,
2330        )?;
2331
2332        assert_eq!(range.partition_count(), 4);
2333        assert_eq!(range.max_partition_count(), 10);
2334        assert_eq!(range.samples(), samples);
2335        assert_eq!(
2336            range.split_points(),
2337            vec![
2338                int_split_point([30]),
2339                int_split_point([50]),
2340                int_split_point([70]),
2341            ]
2342        );
2343        assert_eq!(
2344            range.to_string(),
2345            "Range([a@0 ASC], [(30), (50), (70)], 4, max 10)"
2346        );
2347
2348        let single = range.scale(1).expect("one partition is supported");
2349        assert_eq!(single.partition_count(), 1);
2350        assert!(single.split_points().is_empty());
2351        assert_eq!(single.max_partition_count(), 10);
2352        assert_eq!(single.to_string(), "Range([a@0 ASC], [], 1, max 10)");
2353
2354        let restored = single
2355            .scale(single.max_partition_count())
2356            .expect("retained samples support restoration");
2357        assert_eq!(restored.split_points(), samples);
2358        assert_eq!(restored.samples(), samples);
2359
2360        Ok(())
2361    }
2362
2363    #[test]
2364    fn test_range_partitioning_rejects_invalid_partition_count() -> Result<()> {
2365        let fixture = PartitioningTestFixture::int64(&["a"])?;
2366        let ordering = fixture.range_ordering([0]);
2367        let samples = vec![int_split_point([10]), int_split_point([20])];
2368
2369        let error =
2370            RangePartitioning::try_new_with_samples(ordering.clone(), samples.clone(), 0)
2371                .unwrap_err()
2372                .to_string();
2373        assert!(error.contains("must be at least 1"), "{error}");
2374
2375        let error =
2376            RangePartitioning::try_new_with_samples(ordering.clone(), samples.clone(), 4)
2377                .unwrap_err()
2378                .to_string();
2379        assert!(error.contains("exceeds maximum 3"), "{error}");
2380
2381        let range = RangePartitioning::try_new(ordering, samples)?;
2382        assert!(range.scale(4).is_none());
2383
2384        Ok(())
2385    }
2386
2387    #[test]
2388    fn test_range_partitioning_equality_includes_scaling_capacity() -> Result<()> {
2389        let fixture = PartitioningTestFixture::int64(&["a"])?;
2390        let ordering = fixture.range_ordering([0]);
2391        let sampled = RangePartitioning::try_new_with_samples(
2392            ordering.clone(),
2393            (10..=90)
2394                .step_by(10)
2395                .map(|value| int_split_point([value]))
2396                .collect(),
2397            4,
2398        )?;
2399        let exact = RangePartitioning::try_new(
2400            ordering,
2401            vec![
2402                int_split_point([30]),
2403                int_split_point([50]),
2404                int_split_point([70]),
2405            ],
2406        )?;
2407
2408        assert_eq!(sampled.split_points(), exact.split_points());
2409        assert!(sampled.has_same_layout(&exact));
2410        assert!(exact.has_same_layout(&sampled));
2411        assert!(sampled.scale(10).is_some());
2412        assert!(exact.scale(10).is_none());
2413        assert_ne!(sampled, exact);
2414        assert_ne!(Partitioning::Range(sampled), Partitioning::Range(exact));
2415
2416        Ok(())
2417    }
2418
2419    #[test]
2420    fn test_range_partitioning_layout_requires_keys_options_and_boundaries() -> Result<()>
2421    {
2422        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2423        let range = RangePartitioning::try_new_with_samples(
2424            fixture.range_ordering([0]),
2425            vec![int_split_point([10])],
2426            2,
2427        )?;
2428        assert!(range.has_same_layout(&range.clone()));
2429        let different_boundary = RangePartitioning::try_new_with_samples(
2430            fixture.range_ordering([0]),
2431            vec![int_split_point([20])],
2432            2,
2433        )?;
2434        assert!(!range.has_same_layout(&different_boundary));
2435        assert!(!range.has_same_layout(&range.scale(1).unwrap()));
2436        let singleton = range.scale(1).unwrap();
2437        for ordering in [
2438            fixture.range_ordering([1]),
2439            [fixture.range_sort_expr(0, SortOptions::new(true, false))].into(),
2440            [fixture.range_sort_expr(0, SortOptions::new(false, false))].into(),
2441        ] {
2442            let other = RangePartitioning::try_new_with_samples(ordering, vec![], 1)?;
2443            assert!(!singleton.has_same_layout(&other));
2444        }
2445        Ok(())
2446    }
2447
2448    #[test]
2449    fn test_range_partitioning_scaling_limits() -> Result<()> {
2450        let fixture = PartitioningTestFixture::int64(&["a"])?;
2451        let range = RangePartitioning::try_new_with_samples(
2452            fixture.range_ordering([0]),
2453            vec![int_split_point([10])],
2454            1,
2455        )?;
2456        assert_eq!(range.scale(0), None);
2457        for target_partitions in [3, usize::MAX] {
2458            assert_eq!(range.scale(target_partitions), None);
2459        }
2460        assert_eq!(range.scale(1).unwrap(), range);
2461        assert_eq!(range.scale(2).unwrap().scale(1).unwrap(), range);
2462        assert_eq!(range.scale(2).unwrap().partition_count(), 2);
2463        let empty = RangePartitioning::try_new_with_samples(
2464            fixture.range_ordering([0]),
2465            vec![],
2466            1,
2467        )?;
2468        assert_eq!(empty.scale(1).unwrap(), empty);
2469        assert_eq!(empty.scale(2), None);
2470        Ok(())
2471    }
2472
2473    #[test]
2474    fn test_range_partitioning_try_new_validates_split_points() -> Result<()> {
2475        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2476        let asc_a = fixture.range_ordering([0]);
2477        let ordering_ab = fixture.range_ordering([0, 1]);
2478
2479        assert_range_try_new_error(
2480            ordering_ab.clone(),
2481            vec![int_split_point([10])],
2482            "split point 0 has width 1, but ordering has width 2",
2483        );
2484
2485        RangePartitioning::try_new(
2486            [fixture.range_sort_expr(0, SortOptions::new(true, false))].into(),
2487            vec![int_split_point([20]), int_split_point([10])],
2488        )?;
2489
2490        assert_range_try_new_error(
2491            asc_a,
2492            vec![int_split_point([20]), int_split_point([10])],
2493            "split points must be strictly ordered",
2494        );
2495
2496        assert_range_try_new_error(
2497            [fixture.range_sort_expr(0, SortOptions::new(false, false))].into(),
2498            vec![
2499                SplitPoint::new(vec![ScalarValue::Int64(None)]),
2500                int_split_point([10]),
2501            ],
2502            "split points must be strictly ordered",
2503        );
2504
2505        RangePartitioning::try_new(
2506            ordering_ab.clone(),
2507            vec![int_split_point([10, 20]), int_split_point([10, 30])],
2508        )?;
2509
2510        assert_range_try_new_error(
2511            ordering_ab,
2512            vec![int_split_point([10, 30]), int_split_point([10, 20])],
2513            "split points must be strictly ordered",
2514        );
2515
2516        Ok(())
2517    }
2518
2519    #[test]
2520    fn test_range_partitioning_project_preserves_or_degrades() -> Result<()> {
2521        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2522        let range_partitioning =
2523            Partitioning::Range(RangePartitioning::try_new_with_samples(
2524                [fixture.range_sort_expr(1, SortOptions::new(true, false))].into(),
2525                vec![
2526                    int_split_point([30]),
2527                    int_split_point([20]),
2528                    int_split_point([10]),
2529                ],
2530                2,
2531            )?);
2532
2533        let keep_b_mapping = ProjectionMapping::from_indices(&[1], &fixture.schema)?;
2534        let projected =
2535            range_partitioning.project(&keep_b_mapping, &fixture.eq_properties);
2536        assert_eq!(
2537            projected.to_string(),
2538            "Range([b@0 DESC NULLS LAST], [(20)], 2, max 4)"
2539        );
2540        let Partitioning::Range(projected_range) = &projected else {
2541            panic!("expected range partitioning, got {projected:?}");
2542        };
2543        assert_eq!(projected_range.max_partition_count(), 4);
2544        assert_eq!(projected_range.scale(4).unwrap().split_points().len(), 3);
2545
2546        let drop_b_mapping = ProjectionMapping::from_indices(&[0], &fixture.schema)?;
2547        let projected =
2548            range_partitioning.project(&drop_b_mapping, &fixture.eq_properties);
2549        let Partitioning::UnknownPartitioning(partition_count) = projected else {
2550            panic!("expected UnknownPartitioning, got {projected:?}");
2551        };
2552        assert_eq!(partition_count, 2);
2553
2554        Ok(())
2555    }
2556
2557    #[test]
2558    fn test_range_partitioning_project_degrades_if_ordering_collapses() -> Result<()> {
2559        let fixture = PartitioningTestFixture::int64(&["a", "b"])?;
2560        let target: Arc<dyn PhysicalExpr> = Arc::new(Column::new("x", 0));
2561        let range_partitioning =
2562            fixture.range_partitioning([0, 1], vec![int_split_point([10, 100])]);
2563        let mapping = ProjectionMapping::from_iter([
2564            (
2565                fixture.col(0),
2566                ProjectionTargets::from(vec![(Arc::clone(&target), 0)]),
2567            ),
2568            (
2569                fixture.col(1),
2570                ProjectionTargets::from(vec![(Arc::clone(&target), 0)]),
2571            ),
2572        ]);
2573
2574        let projected = range_partitioning.project(&mapping, &fixture.eq_properties);
2575        let Partitioning::UnknownPartitioning(partition_count) = projected else {
2576            panic!("expected UnknownPartitioning, got {projected:?}");
2577        };
2578        assert_eq!(partition_count, 2);
2579
2580        Ok(())
2581    }
2582
2583    #[test]
2584    fn range_partitioning_key_distribution_satisfaction() -> Result<()> {
2585        let fixture = PartitioningTestFixture::int64(&["a", "b", "c"])?;
2586        let range_a = fixture.range_partitioning([0], vec![int_split_point([10])]);
2587        let range_ab =
2588            fixture.range_partitioning([0, 1], vec![int_split_point([10, 100])]);
2589
2590        assert_satisfaction(
2591            "exact single key",
2592            &range_a,
2593            &fixture.key_distribution([0]),
2594            &fixture.eq_properties,
2595            PartitioningSatisfaction::Exact,
2596            PartitioningSatisfaction::Exact,
2597        );
2598        assert_satisfaction(
2599            "exact compound key",
2600            &range_ab,
2601            &fixture.key_distribution([0, 1]),
2602            &fixture.eq_properties,
2603            PartitioningSatisfaction::Exact,
2604            PartitioningSatisfaction::Exact,
2605        );
2606        assert_satisfaction(
2607            "subset key",
2608            &range_a,
2609            &fixture.key_distribution([0, 1]),
2610            &fixture.eq_properties,
2611            PartitioningSatisfaction::Subset,
2612            PartitioningSatisfaction::NotSatisfied,
2613        );
2614        assert_satisfaction(
2615            "incompatible key",
2616            &range_a,
2617            &fixture.key_distribution([1]),
2618            &fixture.eq_properties,
2619            PartitioningSatisfaction::NotSatisfied,
2620            PartitioningSatisfaction::NotSatisfied,
2621        );
2622
2623        let mut eq_properties = fixture.eq_properties.clone();
2624        eq_properties.add_equal_conditions(fixture.col(0), fixture.col(2))?;
2625        assert_satisfaction(
2626            "equivalent subset key",
2627            &range_a,
2628            &fixture.key_distribution([1, 2]),
2629            &eq_properties,
2630            PartitioningSatisfaction::Subset,
2631            PartitioningSatisfaction::NotSatisfied,
2632        );
2633
2634        let mut eq_properties = fixture.eq_properties.clone();
2635        eq_properties.add_equal_conditions(fixture.col(0), fixture.col(1))?;
2636        assert_satisfaction(
2637            "equivalent exact key",
2638            &range_a,
2639            &fixture.key_distribution([1]),
2640            &eq_properties,
2641            PartitioningSatisfaction::Exact,
2642            PartitioningSatisfaction::Exact,
2643        );
2644
2645        Ok(())
2646    }
2647
2648    #[test]
2649    fn test_range_partitioning_adapt() -> Result<()> {
2650        let fixture = PartitioningTestFixture::new(vec![
2651            ("a", DataType::Int32),
2652            ("b", DataType::Int64),
2653            ("c", DataType::Int32),
2654        ])?;
2655
2656        let range = RangePartitioning::try_new_with_samples(
2657            fixture.range_ordering([0]),
2658            vec![
2659                SplitPoint::new(vec![ScalarValue::Int32(Some(10))]),
2660                SplitPoint::new(vec![ScalarValue::Int32(Some(15))]),
2661                SplitPoint::new(vec![ScalarValue::Int32(Some(20))]),
2662                SplitPoint::new(vec![ScalarValue::Int32(Some(25))]),
2663            ],
2664            3,
2665        )?;
2666
2667        // Adapting to col_c (same type Int32) succeeds
2668        let adapted = range.adapt(&[fixture.col(2)], &fixture.schema).unwrap();
2669        assert_eq!(adapted.ordering().len(), 1);
2670        assert!(adapted.ordering()[0].expr.eq(&fixture.col(2)));
2671        assert_eq!(adapted.partition_count(), 3);
2672        assert_eq!(adapted.max_partition_count(), 5);
2673        assert_eq!(adapted.scale(5).unwrap().partition_count(), 5);
2674
2675        // Adapting to col_b (different type Int64) fails
2676        assert!(range.adapt(&[fixture.col(1)], &fixture.schema).is_none());
2677        // Scaling to one partition removes effective boundaries, not sample types.
2678        let singleton = range.scale(1).unwrap();
2679        assert!(
2680            singleton
2681                .adapt(&[fixture.col(1)], &fixture.schema)
2682                .is_none()
2683        );
2684        let adapted_singleton =
2685            singleton.adapt(&[fixture.col(2)], &fixture.schema).unwrap();
2686        assert_eq!(
2687            adapted_singleton.scale(5).unwrap().samples(),
2688            range.samples()
2689        );
2690
2691        // Adapting to empty or mismatch count fails
2692        assert!(range.adapt(&[], &fixture.schema).is_none());
2693        assert!(
2694            range
2695                .adapt(&fixture.cols([0, 2]), &fixture.schema)
2696                .is_none()
2697        );
2698
2699        // Partitioning::adapt works with Distribution::KeyPartitioned
2700        let part = Partitioning::Range(range);
2701        assert!(
2702            part.adapt(&fixture.key_distribution([1]), &fixture.schema)
2703                .is_none()
2704        );
2705
2706        let adapted_part = part
2707            .adapt(&fixture.key_distribution([2]), &fixture.schema)
2708            .unwrap();
2709        match adapted_part {
2710            Partitioning::Range(r) => assert!(r.ordering()[0].expr.eq(&fixture.col(2))),
2711            _ => panic!("expected Range partitioning"),
2712        }
2713
2714        // Partitioning::Hash adaptation
2715        let hash_part = fixture.hash_partitioning([1], 4);
2716        let adapted_hash = hash_part
2717            .adapt(&fixture.key_distribution([2]), &fixture.schema)
2718            .unwrap();
2719        match adapted_hash {
2720            Partitioning::Hash(exprs, count) => {
2721                assert_eq!(count, 4);
2722                assert_eq!(exprs.len(), 1);
2723                assert!(exprs[0].eq(&fixture.col(2)));
2724            }
2725            _ => panic!("expected Hash partitioning"),
2726        }
2727
2728        Ok(())
2729    }
2730
2731    #[test]
2732    fn test_range_partitioning_adapt_rejects_duplicate_keys() -> Result<()> {
2733        let fixture = PartitioningTestFixture::new(vec![
2734            ("a", DataType::Int32),
2735            ("b", DataType::Int32),
2736            ("c", DataType::Int32),
2737        ])?;
2738        let range = RangePartitioning::try_new_with_samples(
2739            fixture.range_ordering([0, 1]),
2740            vec![SplitPoint::new(vec![
2741                ScalarValue::Int32(Some(10)),
2742                ScalarValue::Int32(Some(20)),
2743            ])],
2744            1,
2745        )?;
2746        for count in [1, 2] {
2747            assert!(
2748                range
2749                    .scale(count)
2750                    .unwrap()
2751                    .adapt(&fixture.cols([2, 2]), &fixture.schema)
2752                    .is_none()
2753            );
2754        }
2755        Ok(())
2756    }
2757
2758    #[test]
2759    fn test_range_partitioning_adapt_multi_key() -> Result<()> {
2760        let fixture = PartitioningTestFixture::new(vec![
2761            ("k1", DataType::Int32),
2762            ("k2", DataType::Utf8),
2763            ("t1", DataType::Int32),
2764            ("t2", DataType::Utf8),
2765        ])?;
2766
2767        let opt_k1 = SortOptions {
2768            descending: true,
2769            nulls_first: false,
2770        };
2771        let opt_k2 = SortOptions {
2772            descending: false,
2773            nulls_first: true,
2774        };
2775
2776        let ordering = LexOrdering::new(vec![
2777            fixture.range_sort_expr(0, opt_k1),
2778            fixture.range_sort_expr(1, opt_k2),
2779        ])
2780        .unwrap();
2781
2782        let split_points = vec![
2783            SplitPoint::new(vec![ScalarValue::Int32(Some(20)), ScalarValue::Utf8(None)]),
2784            SplitPoint::new(vec![
2785                ScalarValue::Int32(Some(10)),
2786                ScalarValue::Utf8(Some("foo".to_string())),
2787            ]),
2788        ];
2789
2790        let range = RangePartitioning::try_new(ordering, split_points.clone())?;
2791        let adapted = range.adapt(&fixture.cols([2, 3]), &fixture.schema).unwrap();
2792
2793        assert_eq!(adapted.ordering().len(), 2);
2794        assert!(adapted.ordering()[0].expr.eq(&fixture.col(2)));
2795        assert_eq!(adapted.ordering()[0].options, opt_k1);
2796        assert!(adapted.ordering()[1].expr.eq(&fixture.col(3)));
2797        assert_eq!(adapted.ordering()[1].options, opt_k2);
2798        assert_eq!(adapted.split_points(), &split_points);
2799        assert_eq!(adapted.partition_count(), 3);
2800
2801        Ok(())
2802    }
2803}
2804
2805#[cfg(all(test, feature = "proto"))]
2806mod ordering_proto_tests {
2807    use std::sync::Arc;
2808
2809    use arrow::compute::SortOptions;
2810    use arrow::datatypes::{DataType, Field, Schema};
2811    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
2812    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
2813    use datafusion_physical_expr_common::sort_expr::{
2814        LexRequirement, PhysicalSortExpr, PhysicalSortRequirement,
2815        sort_exprs_try_from_proto, sort_exprs_try_to_proto,
2816    };
2817
2818    use crate::expressions::Column;
2819    use crate::proto_test_util::{StubDecoder, StubEncoder};
2820
2821    fn schema() -> Schema {
2822        Schema::new(vec![Field::new("a", DataType::Int32, false)])
2823    }
2824
2825    fn sort_expr(descending: bool, nulls_first: bool) -> PhysicalSortExpr {
2826        PhysicalSortExpr::new(
2827            Arc::new(Column::new("a", 0)),
2828            SortOptions {
2829                descending,
2830                nulls_first,
2831            },
2832        )
2833    }
2834
2835    #[test]
2836    fn sort_exprs_round_trip_preserves_options_and_order() {
2837        let encoder = StubEncoder::ok();
2838        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2839        let exprs = vec![sort_expr(true, false), sort_expr(false, true)];
2840
2841        let nodes = sort_exprs_try_to_proto(&exprs, &encode_ctx).unwrap();
2842        // `asc` is the inverse of `descending` on the wire.
2843        assert_eq!(
2844            nodes
2845                .iter()
2846                .map(|node| (node.asc, node.nulls_first))
2847                .collect::<Vec<_>>(),
2848            vec![(false, false), (true, true)]
2849        );
2850
2851        let schema = schema();
2852        let decoder = StubDecoder::ok();
2853        let decode_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2854        let decoded = sort_exprs_try_from_proto(&nodes, &decode_ctx).unwrap();
2855        assert_eq!(
2856            decoded.iter().map(|expr| expr.options).collect::<Vec<_>>(),
2857            exprs.iter().map(|expr| expr.options).collect::<Vec<_>>()
2858        );
2859    }
2860
2861    #[test]
2862    fn sort_exprs_accepts_owned_requirements() {
2863        let encoder = StubEncoder::ok();
2864        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2865        let requirement = LexRequirement::from([PhysicalSortRequirement::new(
2866            Arc::new(Column::new("a", 0)),
2867            Some(SortOptions {
2868                descending: true,
2869                nulls_first: true,
2870            }),
2871        )]);
2872
2873        let nodes = sort_exprs_try_to_proto(
2874            requirement
2875                .iter()
2876                .map(|req| PhysicalSortExpr::from(req.clone())),
2877            &encode_ctx,
2878        )
2879        .unwrap();
2880
2881        assert_eq!(nodes.len(), 1);
2882        assert!(!nodes[0].asc);
2883        assert!(nodes[0].nulls_first);
2884    }
2885
2886    #[test]
2887    fn sort_exprs_propagate_encode_errors() {
2888        let encoder = StubEncoder::failing_on(2);
2889        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2890        let exprs = vec![sort_expr(false, false), sort_expr(true, true)];
2891
2892        let err = sort_exprs_try_to_proto(&exprs, &encode_ctx).unwrap_err();
2893        assert!(err.to_string().contains("stub encode failure on call 2"));
2894    }
2895
2896    #[test]
2897    fn sort_exprs_reject_missing_inner_expr() {
2898        let encoder = StubEncoder::ok();
2899        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2900        let mut nodes =
2901            sort_exprs_try_to_proto(&[sort_expr(false, false)], &encode_ctx).unwrap();
2902        nodes[0].expr = None;
2903
2904        let schema = schema();
2905        let decoder = StubDecoder::ok();
2906        let decode_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2907        let err = sort_exprs_try_from_proto(&nodes, &decode_ctx).unwrap_err();
2908        assert!(
2909            err.to_string()
2910                .contains("PhysicalSortExpr is missing required field 'expr'")
2911        );
2912    }
2913}
2914
2915#[cfg(all(test, feature = "proto"))]
2916mod range_partitioning_proto_tests {
2917    use std::sync::Arc;
2918
2919    use arrow::datatypes::{DataType, Field, Schema};
2920    use datafusion_common::{Result, ScalarValue, SplitPoint};
2921    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
2922    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
2923    use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
2924    use datafusion_proto_models::protobuf;
2925
2926    use super::{Partitioning, RangePartitioning};
2927    use crate::expressions::Column;
2928    use crate::proto_test_util::{StubDecoder, StubEncoder};
2929
2930    fn sampled_partitioning() -> Result<Partitioning> {
2931        let ordering = LexOrdering::new([PhysicalSortExpr::new_default(Arc::new(
2932            Column::new("a", 0),
2933        ))])
2934        .expect("non-empty ordering");
2935        let samples = [10, 20, 30, 40, 50]
2936            .into_iter()
2937            .map(|value| SplitPoint::new(vec![ScalarValue::Int32(Some(value))]))
2938            .collect();
2939        Ok(Partitioning::Range(
2940            RangePartitioning::try_new_with_samples(ordering, samples, 3)?,
2941        ))
2942    }
2943
2944    fn decode(partitioning: &protobuf::Partitioning) -> Result<Partitioning> {
2945        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2946        let decoder = StubDecoder::ok();
2947        let decode_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2948        Ok(Partitioning::try_from_proto(partitioning, &decode_ctx)?
2949            .expect("partitioning method is present"))
2950    }
2951
2952    #[test]
2953    fn sampled_range_partitioning_round_trip_preserves_resolution() -> Result<()> {
2954        let partitioning = sampled_partitioning()?;
2955        let encoder = StubEncoder::ok();
2956        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2957        let encoded = partitioning.try_to_proto(&encode_ctx)?;
2958        let Some(protobuf::partitioning::PartitionMethod::Range(encoded_range)) =
2959            encoded.partition_method.as_ref()
2960        else {
2961            panic!("expected range partitioning");
2962        };
2963
2964        // Field 2 remains the effective boundary list for older readers.
2965        assert_eq!(encoded_range.split_point.len(), 2);
2966        assert_eq!(encoded_range.sample_point.len(), 5);
2967        assert_eq!(encoded_range.partition_count, 3);
2968
2969        let decoded = decode(&encoded)?;
2970        let Partitioning::Range(decoded) = decoded else {
2971            panic!("expected range partitioning");
2972        };
2973        let Partitioning::Range(original) = partitioning else {
2974            panic!("expected range partitioning");
2975        };
2976        assert_eq!(decoded.partition_count(), original.partition_count());
2977        assert_eq!(decoded.split_points(), original.split_points());
2978        assert_eq!(
2979            decoded.ordering()[0].options,
2980            original.ordering()[0].options
2981        );
2982        assert_eq!(decoded.samples(), original.samples());
2983        assert_eq!(decoded.max_partition_count(), 6);
2984
2985        Ok(())
2986    }
2987
2988    #[test]
2989    fn legacy_range_partitioning_payload_remains_exact() -> Result<()> {
2990        let partitioning = sampled_partitioning()?;
2991        let encoder = StubEncoder::ok();
2992        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
2993        let mut encoded = partitioning.try_to_proto(&encode_ctx)?;
2994        let Some(protobuf::partitioning::PartitionMethod::Range(encoded_range)) =
2995            encoded.partition_method.as_mut()
2996        else {
2997            panic!("expected range partitioning");
2998        };
2999        encoded_range.sample_point.clear();
3000        encoded_range.partition_count = 0;
3001
3002        let decoded = decode(&encoded)?;
3003        let Partitioning::Range(decoded) = decoded else {
3004            panic!("expected range partitioning");
3005        };
3006        assert_eq!(decoded.partition_count(), 3);
3007        assert_eq!(decoded.max_partition_count(), 3);
3008        assert_eq!(decoded.split_points().len(), 2);
3009
3010        Ok(())
3011    }
3012
3013    #[test]
3014    fn sampled_range_partitioning_rejects_inconsistent_effective_points() -> Result<()> {
3015        let partitioning = sampled_partitioning()?;
3016        let encoder = StubEncoder::ok();
3017        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
3018        let mut encoded = partitioning.try_to_proto(&encode_ctx)?;
3019        let Some(protobuf::partitioning::PartitionMethod::Range(encoded_range)) =
3020            encoded.partition_method.as_mut()
3021        else {
3022            panic!("expected range partitioning");
3023        };
3024        encoded_range.split_point.pop();
3025
3026        let error = decode(&encoded).unwrap_err().to_string();
3027        assert!(
3028            error.contains("effective split points do not match"),
3029            "{error}"
3030        );
3031
3032        Ok(())
3033    }
3034}
3035
3036/// Partition counts are `usize` in memory and `u64` on the wire, so every
3037/// counted [`Partitioning`] variant crosses a width boundary in both
3038/// directions. These pin that neither crossing wraps or panics.
3039#[cfg(all(test, feature = "proto"))]
3040mod partition_count_proto_tests {
3041    use std::sync::Arc;
3042
3043    use arrow::compute::SortOptions;
3044    use arrow::datatypes::{DataType, Field, Schema};
3045    use datafusion_common::{ScalarValue, SplitPoint};
3046    use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
3047    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
3048    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
3049    use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
3050    use datafusion_proto_models::protobuf;
3051
3052    use super::{Partitioning, RangePartitioning};
3053    use crate::expressions::Column;
3054    use crate::proto_test_util::{StubDecoder, StubEncoder, column_node};
3055
3056    fn partitioning_node(
3057        method: protobuf::partitioning::PartitionMethod,
3058    ) -> protobuf::Partitioning {
3059        protobuf::Partitioning {
3060            partition_method: Some(method),
3061        }
3062    }
3063
3064    /// The counted variants, each carrying `count`. `Range` is excluded: it
3065    /// derives its partition count from its split points rather than reading
3066    /// one off the wire.
3067    fn counted_methods(count: u64) -> Vec<protobuf::partitioning::PartitionMethod> {
3068        use protobuf::partitioning::PartitionMethod;
3069
3070        vec![
3071            PartitionMethod::RoundRobin(count),
3072            PartitionMethod::Unknown(count),
3073            PartitionMethod::Hash(protobuf::PhysicalHashRepartition {
3074                hash_expr: vec![column_node("a")],
3075                partition_count: count,
3076            }),
3077        ]
3078    }
3079
3080    #[test]
3081    fn try_from_proto_narrows_every_counted_variant() {
3082        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3083        let decoder = StubDecoder::ok();
3084        let decode_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3085
3086        for method in counted_methods(u64::MAX) {
3087            let decoded =
3088                Partitioning::try_from_proto(&partitioning_node(method), &decode_ctx);
3089
3090            #[cfg(target_pointer_width = "64")]
3091            assert_eq!(decoded.unwrap().unwrap().partition_count(), usize::MAX);
3092
3093            #[cfg(not(target_pointer_width = "64"))]
3094            assert!(
3095                decoded
3096                    .unwrap_err()
3097                    .to_string()
3098                    .contains("is out of range for usize")
3099            );
3100        }
3101    }
3102
3103    #[test]
3104    fn try_to_proto_widens_every_counted_variant() {
3105        use protobuf::partitioning::PartitionMethod;
3106
3107        let encoder = StubEncoder::ok();
3108        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
3109        let hash_key: Arc<dyn PhysicalExpr> = Arc::new(Column::new("a", 0));
3110
3111        let encoded = [
3112            Partitioning::RoundRobinBatch(usize::MAX),
3113            Partitioning::UnknownPartitioning(usize::MAX),
3114            Partitioning::Hash(vec![hash_key], usize::MAX),
3115        ]
3116        .iter()
3117        .map(|partitioning| {
3118            match partitioning
3119                .try_to_proto(&encode_ctx)
3120                .unwrap()
3121                .partition_method
3122            {
3123                Some(PartitionMethod::RoundRobin(n) | PartitionMethod::Unknown(n)) => n,
3124                Some(PartitionMethod::Hash(hash)) => hash.partition_count,
3125                other => panic!("expected a counted partition method, got {other:?}"),
3126            }
3127        })
3128        .collect::<Vec<_>>();
3129
3130        // Every variant widens to the same wire value, with no truncation.
3131        assert_eq!(encoded, vec![u64::try_from(usize::MAX).unwrap(); 3]);
3132    }
3133
3134    #[test]
3135    fn range_partitioning_round_trip_preserves_split_points_and_options() {
3136        // Single-column ordering so the stub encoder (which emits an identical
3137        // placeholder for every expression) cannot produce duplicates that the
3138        // decoder's deduplication step would collapse.
3139        let sort_options = SortOptions {
3140            descending: false,
3141            nulls_first: true,
3142        };
3143        let ordering = LexOrdering::from([PhysicalSortExpr::new(
3144            Arc::new(Column::new("a", 0)),
3145            sort_options,
3146        )]);
3147        let split_points = vec![
3148            SplitPoint::new(vec![ScalarValue::Int32(Some(10))]),
3149            SplitPoint::new(vec![ScalarValue::Int32(Some(30))]),
3150        ];
3151        let range =
3152            RangePartitioning::try_new(ordering.clone(), split_points.clone()).unwrap();
3153
3154        let encoder = StubEncoder::ok();
3155        let encode_ctx = PhysicalExprEncodeCtx::new(&encoder);
3156        let node = Partitioning::Range(range)
3157            .try_to_proto(&encode_ctx)
3158            .unwrap();
3159
3160        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3161        let decoder = StubDecoder::ok();
3162        let decode_ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
3163        let decoded = Partitioning::try_from_proto(&node, &decode_ctx)
3164            .unwrap()
3165            .unwrap();
3166
3167        let Partitioning::Range(decoded_range) = decoded else {
3168            panic!("expected Range partitioning, got {decoded:?}");
3169        };
3170        assert_eq!(
3171            decoded_range
3172                .ordering()
3173                .iter()
3174                .map(|e| e.options)
3175                .collect::<Vec<_>>(),
3176            [sort_options],
3177        );
3178        assert_eq!(decoded_range.split_points(), split_points);
3179    }
3180}