You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "stuhood (via GitHub)" <gi...@apache.org> on 2026/08/23 22:10:27 UTC
[PR] Range partition on primitives. [datafusion]
stuhood opened a new pull request, #24598:
URL: https://github.com/apache/datafusion/pull/24598
## Which issue does this PR close?
- Closes #24597.
- Related to [EPIC: Implement Range Partitioning #22395](https://github.com/apache/datafusion/issues/22395).
## Rationale for this change
In query plans that use range re-partitioning (such as matching the range partitioning of underlying base data, or evaluating dynamic range filters in hash joins), range re-partitioning can represent a significant fraction of total query execution time.
As detailed in the issue, the existing implementation in [`RepartitionExec`](https://github.com/apache/datafusion/blob/6fe001d4baf5c6089d24b5634a23b1345797fb14/datafusion/physical-plan/src/repartition/mod.rs#L100-L150) / [`BatchPartitioner`](https://github.com/apache/datafusion/blob/6fe001d4baf5c6089d24b5634a23b1345797fb14/datafusion/physical-plan/src/repartition/mod.rs#L623-L640) and [`RangeExpr`](https://github.com/apache/datafusion/blob/6fe001d4baf5c6089d24b5634a23b1345797fb14/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs#L180-L240) assigns rows to partitions on a row-by-row basis using [`extract_row_at_idx_to_buf`](https://github.com/apache/datafusion/blob/6fe001d4baf5c6089d24b5634a23b1345797fb14/datafusion-common/src/utils/mod.rs) and dynamic [`ScalarValue`](https://github.com/apache/datafusion/blob/6fe001d4baf5c6089d24b5634a23b1345797fb14/datafusion-common/src/scalar/mod.rs) comparisons. This creates allocates per row, and has dynamic dispatch overhead, makin
g range re-partitioning 15x–30x slower than hash re-partitioning on standard integer keys.
This PR adds a vectorized, zero-allocation implementation, bringing range re-partitioning to near-parity with hash repartitioning (10x–22x speedup on primitive numeric keys and 2x–3x speedup on string and composite keys).
## What changes are included in this PR?
- Adds an internal `RangeRouter` with specialized routing paths:
- A zero-allocation path for single primitive numeric, temporal, and float columns that binary searches directly over Arrow buffer slices.
- A vectorized path using Arrow's `RowConverter` for strings, decimals, dictionary arrays, and composite keys.
- Updates `BatchPartitioner` and `RangeExpr` to delegate partition routing to `RangeRouter`.
- Adds a Criterion suite.
### Benchmark Comparison (8,192 Rows)
| Workload | Partitions | `main` | `branch` | Speedup |
| :--- | :--- | :--- | :--- | :--- |
| `range_expr_routing_i64` (Isolated Primitive Routing) | 8 | 237.3 µs | 13.8 µs | 17.2x |
| | 16 | 286.7 µs | 15.8 µs | 18.1x |
| | 64 | 415.2 µs | 23.5 µs | 17.7x |
| | 512 | 854.6 µs | 38.9 µs | 22.0x |
| `range_repartition_i64_uniform` (End-to-End `BatchPartitioner`) | 8 | 264.8 µs | 24.5 µs | 10.8x |
| | 16 | 313.5 µs | 27.0 µs | 11.6x |
| | 64 | 462.1 µs | 40.3 µs | 11.5x |
| | 512 | 872.0 µs | 69.8 µs | 12.5x |
| `range_repartition_utf8_uniform` (String Keys via `RowConverter`) | 8 | 464.7 µs | 207.1 µs | 2.2x |
| | 64 | 958.4 µs | 340.5 µs | 2.8x |
| `range_repartition_composite_i64` (Composite `(i64, i64)` Keys) | 8 | 344.2 µs | 143.5 µs | 2.4x |
| | 64 | 545.9 µs | 288.3 µs | 1.9x |
## Are these changes tested?
Yes:
- New tests in `datafusion/physical-plan/src/repartition/range.rs` covering ASC/DESC sort options, `nulls_first` / `nulls_last`, floats (with total order comparison), strings, and composite keys.
- Criterion suite in `datafusion/physical-plan/benches/range_repartition.rs`.
## Are there any user-facing changes?
No.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5556578219
I believe so, yes: the last change I pushed was to avoid changing method signatures. Note that there are two deprecations added that the bot is complaining about, but I'd be surprised if that violated the deprecation policy...?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3847411841
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
Review Comment:
I simplified this a bit, but because of the deduping of the `RowConverter` construction, it will now only run once per plan.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3880807598
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
Review Comment:
here we infer the data type of the spilt pionts and this gets passed to try_new()
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
Review Comment:
another point: that if there is only one split point, then we aren't really validating anything. So I think `RowConverter` should check the expected types and schemas and compare it with the inptu arraya before calling arrow
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
Review Comment:
this is importatnt to note, maybe for me or a follow up.
`pull_from_input` is called once for each partition and make a new `BatchPartitioner` which for range also makes a `RangeRouter`. With this if we have a lot of input / output partitions, for each of these ew are encoding a lot of split points repetitively. If this becomes visible we should have an `Arc<RangeRouter>`
I think this is follow up but maybe document this comehwere?
##########
datafusion/physical-plan/benches/range_repartition.rs:
##########
@@ -0,0 +1,373 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::hint::black_box;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, Int64Array, RecordBatch, StringArray};
+use arrow::compute::SortOptions;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
+use datafusion_common::ScalarValue;
+use datafusion_physical_expr::expressions::col;
+use datafusion_physical_expr::{
+ LexOrdering, PhysicalExpr, PhysicalSortExpr, RangePartitioning, SplitPoint,
+};
+use datafusion_physical_plan::metrics::Time;
+use datafusion_physical_plan::repartition::{BatchPartitioner, RangeExpr};
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+
+const BATCH_SIZE: usize = 8192;
+const PARTITION_COUNTS: [usize; 7] = [8, 16, 32, 64, 128, 256, 512];
+const SEED: u64 = 42;
+
+fn create_i64_uniform_batch(schema: &SchemaRef, max_val: i64) -> RecordBatch {
+ let mut rng = StdRng::seed_from_u64(SEED);
+ let key_values: Vec<i64> = (0..BATCH_SIZE)
+ .map(|_| rng.random_range(0..max_val))
+ .collect();
+ let payload_values: Vec<i64> = (0..BATCH_SIZE).map(|i| i as i64).collect();
+
+ RecordBatch::try_new(
+ Arc::clone(schema),
+ vec![
+ Arc::new(Int64Array::from(key_values)) as ArrayRef,
+ Arc::new(Int64Array::from(payload_values)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+fn create_i64_sequential_batch(schema: &SchemaRef, max_val: i64) -> RecordBatch {
+ let key_values: Vec<i64> = (0..BATCH_SIZE)
+ .map(|i| ((i as i64) * max_val) / (BATCH_SIZE as i64))
+ .collect();
+ let payload_values: Vec<i64> = (0..BATCH_SIZE).map(|i| i as i64).collect();
+
+ RecordBatch::try_new(
+ Arc::clone(schema),
+ vec![
+ Arc::new(Int64Array::from(key_values)) as ArrayRef,
+ Arc::new(Int64Array::from(payload_values)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+fn create_utf8_uniform_batch(schema: &SchemaRef, max_val: usize) -> RecordBatch {
+ let mut rng = StdRng::seed_from_u64(SEED);
+ let key_strings: Vec<String> = (0..BATCH_SIZE)
+ .map(|_| format!("key_{:010}", rng.random_range(0..max_val)))
+ .collect();
+ let payload_values: Vec<i64> = (0..BATCH_SIZE).map(|i| i as i64).collect();
+
+ RecordBatch::try_new(
+ Arc::clone(schema),
+ vec![
+ Arc::new(StringArray::from_iter_values(
+ key_strings.iter().map(String::as_str),
+ )) as ArrayRef,
+ Arc::new(Int64Array::from(payload_values)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+fn create_composite_i64_batch(schema: &SchemaRef, max_val: i64) -> RecordBatch {
+ let mut rng = StdRng::seed_from_u64(SEED);
+ let key1_values: Vec<i64> = (0..BATCH_SIZE)
+ .map(|_| rng.random_range(0..max_val))
+ .collect();
+ let key2_values: Vec<i64> = (0..BATCH_SIZE)
+ .map(|_| rng.random_range(0..max_val))
+ .collect();
+ let payload_values: Vec<i64> = (0..BATCH_SIZE).map(|i| i as i64).collect();
+
+ RecordBatch::try_new(
+ Arc::clone(schema),
+ vec![
+ Arc::new(Int64Array::from(key1_values)) as ArrayRef,
+ Arc::new(Int64Array::from(key2_values)) as ArrayRef,
+ Arc::new(Int64Array::from(payload_values)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+fn bench_range_repartition_i64_uniform(c: &mut Criterion) {
+ let mut group = c.benchmark_group("range_repartition_i64_uniform");
+ group.throughput(Throughput::Elements(BATCH_SIZE as u64));
+
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("key", DataType::Int64, false),
+ Field::new("payload", DataType::Int64, false),
+ ]));
+
+ let max_val = 1_000_000i64;
+ let batch = create_i64_uniform_batch(&schema, max_val);
+
+ for &num_partitions in &PARTITION_COUNTS {
+ let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
+ col("key", &schema).unwrap(),
+ SortOptions::default(),
+ )])
+ .unwrap();
+
+ let split_points: Vec<SplitPoint> = (1..num_partitions)
+ .map(|i| {
+ let val = (i as i64 * max_val) / (num_partitions as i64);
+ SplitPoint::new(vec![ScalarValue::Int64(Some(val))])
+ })
+ .collect();
+
+ let range_part = RangePartitioning::try_new(ordering, split_points).unwrap();
+
+ group.bench_with_input(
+ BenchmarkId::new("partitions", num_partitions),
+ &num_partitions,
+ |b, _| {
+ let mut partitioner = BatchPartitioner::try_new_range_partitioner(
+ &range_part,
+ Time::default(),
+ )
+ .unwrap();
+ b.iter(|| {
+ partitioner
+ .partition(batch.clone(), |p, b| {
+ black_box((p, b));
+ Ok(())
+ })
+ .unwrap();
+ });
+ },
+ );
+ }
+ group.finish();
+}
+
+fn bench_range_repartition_i64_sequential(c: &mut Criterion) {
+ let mut group = c.benchmark_group("range_repartition_i64_sequential");
+ group.throughput(Throughput::Elements(BATCH_SIZE as u64));
+
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("key", DataType::Int64, false),
+ Field::new("payload", DataType::Int64, false),
+ ]));
+
+ let max_val = 1_000_000i64;
+ let batch = create_i64_sequential_batch(&schema, max_val);
+
+ for &num_partitions in &PARTITION_COUNTS {
+ let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
+ col("key", &schema).unwrap(),
+ SortOptions::default(),
+ )])
+ .unwrap();
+
+ let split_points: Vec<SplitPoint> = (1..num_partitions)
+ .map(|i| {
+ let val = (i as i64 * max_val) / (num_partitions as i64);
+ SplitPoint::new(vec![ScalarValue::Int64(Some(val))])
+ })
+ .collect();
+
+ let range_part = RangePartitioning::try_new(ordering, split_points).unwrap();
+
+ group.bench_with_input(
+ BenchmarkId::new("partitions", num_partitions),
+ &num_partitions,
+ |b, _| {
+ let mut partitioner = BatchPartitioner::try_new_range_partitioner(
Review Comment:
I think we woudl want to add the try_new_range_partitioner in the bench to ensure we are constructing efficiently with clones and what not 👍
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
Review Comment:
I think this might be worth to do in this PR
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -47,18 +46,20 @@ use crate::{
PlanProperties, ReplaceChildrenOptions, Statistics, validate_child_count,
};
-use arrow::array::{Array, PrimitiveArray, RecordBatch, RecordBatchOptions, UInt64Array};
+#[cfg(test)]
Review Comment:
probably shouldnt have
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && !sort_options.is_empty()
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter path
+ let row_router =
+ RowConverterRangeRouter::try_new(&data_types, sort_options, split_points)?;
+ Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Row(row_router),
+ })
+ }
+
+ /// Split points configured in this router.
+ pub(crate) fn split_points(&self) -> &[SplitPoint] {
+ &self.split_points
+ }
+
+ /// Sort options configured in this router.
+ pub(crate) fn sort_options(&self) -> &[SortOptions] {
+ &self.sort_options
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ /// Generic routing entry point that calls `emit(row_idx, partition)` for every row.
+ pub(crate) fn route_with<E>(&self, arrays: &[ArrayRef], mut emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ if self.split_points.is_empty() {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ for row_idx in 0..num_rows {
+ emit(row_idx, 0);
+ }
+ return Ok(());
+ }
+
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_with(first_col.as_ref(), emit)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_with(arrays, emit),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ self.route_with(arrays, |row_idx, partition| {
+ indices[partition].push(row_idx as u32);
+ })
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ partition_ids
+ .try_reserve(num_rows)
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ self.route_with(arrays, |_row_idx, partition| {
+ partition_ids.push(partition as u64);
+ })
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn route_with<E>(&self, array: &dyn Array, emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn route_with<A: ArrowPrimitiveType<Native = T>, E: FnMut(usize, usize)>(
+ &self,
+ array: &PrimitiveArray<A>,
+ mut emit: E,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_with<E: FnMut(usize, usize)>(&self, array: &$arr, mut emit: E) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ converter: Arc<RowConverter>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return not_impl_err!(
+ "Range partitioning is not supported for data types: {:?}",
+ data_types
+ );
+ }
+
+ let row_converter = RowConverter::new(sort_fields)?;
+ let num_cols = data_types.len();
+
+ let split_point_rows = if split_points.is_empty() {
+ vec![]
+ } else {
+ let split_point_arrays = (0..num_cols)
+ .map(|col_idx| {
+ let col_scalars =
+ split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ ScalarValue::iter_to_array(col_scalars)
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ row_converter
+ .convert_columns(&split_point_arrays)?
+ .iter()
+ .map(|r| r.owned())
+ .collect()
+ };
+
+ Ok(Self {
+ converter: Arc::new(row_converter),
+ split_point_rows,
+ })
+ }
+
+ fn route_with<E: FnMut(usize, usize)>(
+ &self,
+ arrays: &[ArrayRef],
+ mut emit: E,
+ ) -> Result<()> {
+ let rows = self.converter.convert_columns(arrays)?;
Review Comment:
another note here is we could use a scartch pad in the `BatchPartitioner` to keep appending to and clearing rather thn allocating each batch
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && !sort_options.is_empty()
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter path
+ let row_router =
+ RowConverterRangeRouter::try_new(&data_types, sort_options, split_points)?;
+ Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Row(row_router),
+ })
+ }
+
+ /// Split points configured in this router.
+ pub(crate) fn split_points(&self) -> &[SplitPoint] {
+ &self.split_points
+ }
+
+ /// Sort options configured in this router.
+ pub(crate) fn sort_options(&self) -> &[SortOptions] {
+ &self.sort_options
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ /// Generic routing entry point that calls `emit(row_idx, partition)` for every row.
+ pub(crate) fn route_with<E>(&self, arrays: &[ArrayRef], mut emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ if self.split_points.is_empty() {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ for row_idx in 0..num_rows {
+ emit(row_idx, 0);
+ }
+ return Ok(());
+ }
+
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_with(first_col.as_ref(), emit)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_with(arrays, emit),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ self.route_with(arrays, |row_idx, partition| {
+ indices[partition].push(row_idx as u32);
+ })
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ partition_ids
+ .try_reserve(num_rows)
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ self.route_with(arrays, |_row_idx, partition| {
+ partition_ids.push(partition as u64);
+ })
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn route_with<E>(&self, array: &dyn Array, emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn route_with<A: ArrowPrimitiveType<Native = T>, E: FnMut(usize, usize)>(
+ &self,
+ array: &PrimitiveArray<A>,
+ mut emit: E,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_with<E: FnMut(usize, usize)>(&self, array: &$arr, mut emit: E) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ converter: Arc<RowConverter>,
+ split_point_rows: Vec<OwnedRow>,
Review Comment:
another point is that this may not be the ebst shape for rows.
Since we call `convert_columns()` we get Arrow rows which store all the rows in a buffer like this:
```text
offsets: [0, 12 , 24, 39, 52]
^ ^ ^ ^
| | | |
buffer: [row0 row1 row2 row3]
its one contiguous allocation
```
then we immediately call `owned()` on every split point right here:
```rust
row_converter
.convert_columns(&split_point_arrays)?
.iter()
.map(|r| r.owned())
.collect()
```
So this changes the internal representation to be a vec or owner rows which you can think of as a pointer to a `Box<[row bytes]>` for each row. This will have more overhead. We could just keep the `Rows` that convert_columns` gives use then use those in binary search. I think this would help at high partition counts but can also be marked as follow up. I am mostly documenting for me to have notes. 😄
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && !sort_options.is_empty()
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter path
+ let row_router =
+ RowConverterRangeRouter::try_new(&data_types, sort_options, split_points)?;
+ Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Row(row_router),
+ })
+ }
+
+ /// Split points configured in this router.
+ pub(crate) fn split_points(&self) -> &[SplitPoint] {
+ &self.split_points
+ }
+
+ /// Sort options configured in this router.
+ pub(crate) fn sort_options(&self) -> &[SortOptions] {
+ &self.sort_options
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ /// Generic routing entry point that calls `emit(row_idx, partition)` for every row.
+ pub(crate) fn route_with<E>(&self, arrays: &[ArrayRef], mut emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ if self.split_points.is_empty() {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ for row_idx in 0..num_rows {
+ emit(row_idx, 0);
+ }
+ return Ok(());
+ }
+
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_with(first_col.as_ref(), emit)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_with(arrays, emit),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ self.route_with(arrays, |row_idx, partition| {
+ indices[partition].push(row_idx as u32);
+ })
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ partition_ids
+ .try_reserve(num_rows)
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ self.route_with(arrays, |_row_idx, partition| {
+ partition_ids.push(partition as u64);
+ })
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn route_with<E>(&self, array: &dyn Array, emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn route_with<A: ArrowPrimitiveType<Native = T>, E: FnMut(usize, usize)>(
+ &self,
+ array: &PrimitiveArray<A>,
+ mut emit: E,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_with<E: FnMut(usize, usize)>(&self, array: &$arr, mut emit: E) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ converter: Arc<RowConverter>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return not_impl_err!(
+ "Range partitioning is not supported for data types: {:?}",
+ data_types
+ );
+ }
+
+ let row_converter = RowConverter::new(sort_fields)?;
+ let num_cols = data_types.len();
+
+ let split_point_rows = if split_points.is_empty() {
+ vec![]
+ } else {
+ let split_point_arrays = (0..num_cols)
+ .map(|col_idx| {
+ let col_scalars =
+ split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ ScalarValue::iter_to_array(col_scalars)
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ row_converter
+ .convert_columns(&split_point_arrays)?
+ .iter()
+ .map(|r| r.owned())
+ .collect()
+ };
+
+ Ok(Self {
+ converter: Arc::new(row_converter),
+ split_point_rows,
+ })
+ }
+
+ fn route_with<E: FnMut(usize, usize)>(
+ &self,
+ arrays: &[ArrayRef],
+ mut emit: E,
+ ) -> Result<()> {
+ let rows = self.converter.convert_columns(arrays)?;
Review Comment:
then later on we will evaluate the arrays and use this `convert_columns()` from arrow: https://arrow.apache.org/rust/arrow_row/struct.RowConverter.html#method.convert_columns
This documents that it will panic if the schemas dont match what was ever put in `RowConverter::new`
we do not check this in this path and could panic if these dont match. These should be checked up front then if they are not use the scalar comparartor if the `ScalarValues` can be compared or error if not
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && !sort_options.is_empty()
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter path
+ let row_router =
+ RowConverterRangeRouter::try_new(&data_types, sort_options, split_points)?;
+ Ok(Self {
+ split_points: split_points.to_vec(),
+ sort_options: sort_options.to_vec(),
+ inner: RangeRouterInner::Row(row_router),
+ })
+ }
+
+ /// Split points configured in this router.
+ pub(crate) fn split_points(&self) -> &[SplitPoint] {
+ &self.split_points
+ }
+
+ /// Sort options configured in this router.
+ pub(crate) fn sort_options(&self) -> &[SortOptions] {
+ &self.sort_options
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ /// Generic routing entry point that calls `emit(row_idx, partition)` for every row.
+ pub(crate) fn route_with<E>(&self, arrays: &[ArrayRef], mut emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ if self.split_points.is_empty() {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ for row_idx in 0..num_rows {
+ emit(row_idx, 0);
+ }
+ return Ok(());
+ }
+
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_with(first_col.as_ref(), emit)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_with(arrays, emit),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ self.route_with(arrays, |row_idx, partition| {
+ indices[partition].push(row_idx as u32);
+ })
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ partition_ids
+ .try_reserve(num_rows)
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ self.route_with(arrays, |_row_idx, partition| {
+ partition_ids.push(partition as u64);
+ })
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn route_with<E>(&self, array: &dyn Array, emit: E) -> Result<()>
+ where
+ E: FnMut(usize, usize),
+ {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_with(arr, emit);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn route_with<A: ArrowPrimitiveType<Native = T>, E: FnMut(usize, usize)>(
+ &self,
+ array: &PrimitiveArray<A>,
+ mut emit: E,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_with<E: FnMut(usize, usize)>(&self, array: &$arr, mut emit: E) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ emit(idx, p);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ emit(idx, p);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ emit(idx, null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ emit(idx, p);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ converter: Arc<RowConverter>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return not_impl_err!(
+ "Range partitioning is not supported for data types: {:?}",
+ data_types
+ );
+ }
+
+ let row_converter = RowConverter::new(sort_fields)?;
Review Comment:
then the `RowConverter` is configured with the sort fields that used those data types
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5485191960
> A type method is now #[deprecated]. Downstream crates will get a compiler warning when using this method.
Hm... is this not allowed for commits landing on `main`? Or is this not a blocking comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5400136182
here are my samplys:
- No Linear Scan and no cache `RowConverter`: https://profiler.firefox.com/from-url/https%3A%2F%2Fgist.githubusercontent.com%2Fgene-bordegaray%2F87a66e96650dd9ec88dc5dac66c549db%2Fraw%2Fprofile_base_baked.json/
- Linear Scan and cache RowConverter in Arc: https://profiler.firefox.com/from-url/https%3A%2F%2Fgist.githubusercontent.com%2Fgene-bordegaray%2Fdccf6a47d4cc100fe5d22197c7513643%2Fraw%2Fprofile_opt_baked.json/
You will see the cachine `RowConverter` gets rid of the `drop_glue::RowConverter` then the `partition_grouped_take` takes over as dominant
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846883702
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Ya I would like to dig into this a it further before addin to this PR but would like to tag an issue or track this somewhere 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846977653
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Mm... yea. I think that this suggests that doing followup that explores all the algorithmic options might be better than adding that type of threshold here. This PR could stay focused on removing allocation and dynamic dispatch.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3841628102
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
Review Comment:
This seems like it could optimized further?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846742779
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Interesting! I think that I would have assumed that Rust's own binary search would already have those thresholds built in. Apparently not, heh.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3841630600
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
+ let rows = row_converter.convert_columns(arrays)?;
+ let num_rows = rows.num_rows();
+ let sp_rows = &self.split_point_rows;
+
+ for row_idx in 0..num_rows {
+ let row = rows.row(row_idx);
+ let partition = sp_rows.partition_point(|sp| sp.as_ref() <= row.as_ref());
+ indices[partition].push(row_idx as u32);
+ }
+ Ok(())
+ }
+
+ fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
+ let rows = row_converter.convert_columns(arrays)?;
+ let num_rows = rows.num_rows();
+ let sp_rows = &self.split_point_rows;
+
+ for row_idx in 0..num_rows {
+ let row = rows.row(row_idx);
+ let partition = sp_rows.partition_point(|sp| sp.as_ref() <= row.as_ref());
+ partition_ids.push(partition as u64);
Review Comment:
`extend`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846977653
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Mm... yea. I think that this suggests that doing followup that explores all the algorithmic options might be better. This PR could stay focused on removing allocation and dynamic dispatch.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3872391420
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -999,25 +1009,31 @@ impl BatchPartitioner {
/// # Parameters
/// - `range_partitioning`: `RangePartitioning` struct used for ordering, split points, and number of partitions
/// - `timer`: Metric used to record time spent during repartitioning.
- pub fn new_range_partitioner(
+ pub fn try_new_range_partitioner(
range_partitioning: &RangePartitioning,
timer: metrics::Time,
- ) -> Self {
+ ) -> Result<Self> {
let ordering = range_partitioning.ordering().clone();
- let split_points = range_partitioning.split_points().to_vec();
+ let split_points = range_partitioning.split_points();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..ordering.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
Review Comment:
```rs
/// Split points are not required to carry the key's exact type: `compare_rows`,
/// the routing function the range router replaced, compares `Decimal128` on
/// scale alone and ignores precision. Routing must not depend on the split
/// point's precision matching the column's.
#[tokio::test]
async fn range_repartition_routes_decimal_with_wider_column_precision() -> Result<()>
{
let schema = Arc::new(Schema::new(vec![Field::new(
"k",
DataType::Decimal128(20, 2),
true,
)]));
let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
col("k", &schema)?,
SortOptions::default(),
)])
.unwrap();
// Split point is Decimal128(10, 2); the column is Decimal128(20, 2).
let partitioning = Partitioning::Range(RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![ScalarValue::Decimal128(
Some(1000),
10,
2,
)])],
)?);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(
Decimal128Array::from(vec![Some(500i128), Some(2000i128)])
.with_precision_and_scale(20, 2)?,
)],
)?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(2, output_partitions.len());
assert_eq!(1, partition_row_count(&output_partitions[0]));
assert_eq!(1, partition_row_count(&output_partitions[1]));
Ok(())
}
/// Same contract for timestamps: `compare_rows` ignores the timezone, since
/// the underlying values are UTC either way. A tz-less split point must
/// still route a `Timestamp(ns, "UTC")` column — including when the key is
/// compound, where the single-column fast path does not apply.
#[tokio::test]
async fn range_repartition_routes_compound_timestamp_key_ignoring_timezone()
-> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new(
"t",
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
true,
),
Field::new("i", DataType::Int64, true),
]));
let ordering = LexOrdering::new(vec![
PhysicalSortExpr::new(col("t", &schema)?, SortOptions::default()),
PhysicalSortExpr::new(col("i", &schema)?, SortOptions::default()),
])
.unwrap();
// Split point timestamp carries no timezone; the column carries "UTC".
let partitioning = Partitioning::Range(RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![
ScalarValue::TimestampNanosecond(Some(100), None),
ScalarValue::Int64(Some(0)),
])],
)?);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(
TimestampNanosecondArray::from(vec![Some(50i64), Some(200)])
.with_timezone("UTC"),
),
Arc::new(Int64Array::from(vec![Some(1i64), Some(2)])),
],
)?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(2, output_partitions.len());
assert_eq!(1, partition_row_count(&output_partitions[0]));
assert_eq!(1, partition_row_count(&output_partitions[1]));
Ok(())
}
```
Here are the edge cases
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3841622948
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
Review Comment:
Similar here
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5484013249
<!-- semver-check-comment -->
Thank you for opening this pull request!
Reviewer note: [cargo-semver-checks](https://github.com/obi1kenobi/cargo-semver-checks) reported the current version number is not SemVer-compatible with the changes in this pull request (compared against the base branch).
<details>
<summary>Details</summary>
```
Cloning apache/main
Building datafusion-physical-plan v55.0.0 (current)
Built [ 41.251s] (current)
Parsing datafusion-physical-plan v55.0.0 (current)
Parsed [ 0.130s] (current)
Building datafusion-physical-plan v55.0.0 (baseline)
Built [ 33.886s] (baseline)
Parsing datafusion-physical-plan v55.0.0 (baseline)
Parsed [ 0.127s] (baseline)
Checking datafusion-physical-plan v55.0.0 -> v55.0.0 (no change; assume patch)
Checked [ 0.879s] 223 checks: 222 pass, 1 fail, 0 warn, 31 skip
--- failure type_method_marked_deprecated: type method #[deprecated] added ---
Description:
A type method is now #[deprecated]. Downstream crates will get a compiler warning when using this method.
ref: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-deprecated-attribute
impl: https://github.com/obi1kenobi/cargo-semver-checks/tree/v0.50.0/src/lints/type_method_marked_deprecated.ron
Failed in:
method datafusion_physical_plan::repartition::BatchPartitioner::new_range_partitioner in /home/runner/work/datafusion/datafusion/datafusion/physical-plan/src/repartition/mod.rs:1013
Summary semver requires new minor version: 0 major and 1 minor checks failed
Finished [ 77.791s] datafusion-physical-plan
```
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5401295761
<!-- semver-check-comment -->
Thank you for opening this pull request!
Reviewer note: [cargo-semver-checks](https://github.com/obi1kenobi/cargo-semver-checks) reported the current version number is not SemVer-compatible with the changes in this pull request (compared against the base branch).
<details>
<summary>Details</summary>
```
Cloning apache/main
Building datafusion-physical-plan v55.0.0 (current)
Built [ 36.491s] (current)
Parsing datafusion-physical-plan v55.0.0 (current)
Parsed [ 0.122s] (current)
Building datafusion-physical-plan v55.0.0 (baseline)
Built [ 30.711s] (baseline)
Parsing datafusion-physical-plan v55.0.0 (baseline)
Parsed [ 0.121s] (baseline)
Checking datafusion-physical-plan v55.0.0 -> v55.0.0 (no change; assume patch)
Checked [ 0.876s] 223 checks: 222 pass, 1 fail, 0 warn, 31 skip
--- failure inherent_method_missing: pub method removed or renamed ---
Description:
A publicly-visible method or associated fn is no longer available under its prior name. It may have been renamed or removed entirely.
ref: https://doc.rust-lang.org/cargo/reference/semver.html#item-remove
impl: https://github.com/obi1kenobi/cargo-semver-checks/tree/v0.50.0/src/lints/inherent_method_missing.ron
Failed in:
BatchPartitioner::new_range_partitioner, previously in file /home/runner/work/datafusion/datafusion/target/semver-checks/git-apache_main/7f66ea7cb840e6752ccdedef94ed84cf1cacaa5b/datafusion/physical-plan/src/repartition/mod.rs:1002
Summary semver requires new major version: 1 major and 0 minor checks failed
Finished [ 70.094s] datafusion-physical-plan
```
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846942182
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Yeah it doesn't implement this.
One can also make linear search or binary search faster for small N by specializing it for fixed N (generating more efficient code than a branchy for loop).
@geoffreyclaude worked on something similar in DataFusion for IN LIST (different strategy for each size):
https://github.com/apache/datafusion/pull/23014
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846883702
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Ya I would like to dig into this a it further before addin to this PR but would like to add if you producesame resutls 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5560296291
did another pass on this this morning, thanks for pushing this through @jayzhan211 and @stuhood ❤️
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3858596383
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -999,25 +1009,31 @@ impl BatchPartitioner {
/// # Parameters
/// - `range_partitioning`: `RangePartitioning` struct used for ordering, split points, and number of partitions
/// - `timer`: Metric used to record time spent during repartitioning.
- pub fn new_range_partitioner(
+ pub fn try_new_range_partitioner(
range_partitioning: &RangePartitioning,
timer: metrics::Time,
- ) -> Self {
+ ) -> Result<Self> {
let ordering = range_partitioning.ordering().clone();
- let split_points = range_partitioning.split_points().to_vec();
+ let split_points = range_partitioning.split_points();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..ordering.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
Review Comment:
could we call validate_range_split_points before indexing here?
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
Review Comment:
I am looking at the overall design here and I think a good amount of things are getting spread around / responsibilities kinda jumbled up and making this hard to follow.
What I imaging is the `RangeRouter` owning the range metadata with the enum to either use the `Primitive` or the `Rows` routes.
Botht he `RangeExpr` and the `BatchPartitioner` are doing all the `RangeRouter` construction separtely. I think this should just be consilidated into `RangeRouter::try_new`. Thus `RangeRouter` becomes the single place we ensure that split point invariants, guarantees, type matching, etc.
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,830 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{DataFusionError, Result, ScalarValue, not_impl_err};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && !sort_options.is_empty()
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter path
+ let row_router =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?;
+ Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ })
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
route_indices and route_partition_ids duplicate a lot
Could we have one generic routing loop that emits (row_idx, partition) like:
```rust
fn route_with<E>(&self, arrays: &[ArrayRef], emit: E) -> Result<()>
where
E: FnMut(usize, usize);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3863207293
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -999,25 +1009,31 @@ impl BatchPartitioner {
/// # Parameters
/// - `range_partitioning`: `RangePartitioning` struct used for ordering, split points, and number of partitions
/// - `timer`: Metric used to record time spent during repartitioning.
- pub fn new_range_partitioner(
+ pub fn try_new_range_partitioner(
range_partitioning: &RangePartitioning,
timer: metrics::Time,
- ) -> Self {
+ ) -> Result<Self> {
let ordering = range_partitioning.ordering().clone();
- let split_points = range_partitioning.split_points().to_vec();
+ let split_points = range_partitioning.split_points();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..ordering.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
Review Comment:
Should the key types come from the ordering exprs rather than split_points[0]? RowConverter needs an exact type match where compare_rows tolerated decimal precision / timestamp tz differences.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3904106399
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,907 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{Row, RowConverter, Rows, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, exec_err, not_impl_err, plan_err,
+ validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ data_types: Vec<DataType>,
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points,
+ /// inferring key data types from the split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ let data_types: Option<Vec<DataType>> = if !split_points.is_empty() {
+ Some(
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect(),
+ )
+ } else {
+ None
+ };
+ Self::try_new_with_optional_data_types(
+ sort_options,
+ split_points,
+ data_types.as_deref(),
+ )
Review Comment:
```suggestion
Self::try_new_with_optional_data_types(sort_options, split_points, None)
```
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -667,34 +703,26 @@ impl RangeExpr {
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
Review Comment:
```suggestion
range_partitioning: &RangePartitioning,
schema: &Schema,
```
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -667,34 +703,26 @@ impl RangeExpr {
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
) -> Result<Self> {
- let sort_options = range_partitioning
+ let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
- Self::try_new_parts(
- on_columns,
- range_partitioning.split_points().to_vec(),
- sort_options,
- )
+ Self::try_new_parts(on_columns, range_partitioning.split_points(), &sort_options)
Review Comment:
```suggestion
Self::try_new_parts(
on_columns,
range_partitioning.split_points(),
&sort_options,
schema,
)
```
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,907 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{Row, RowConverter, Rows, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, exec_err, not_impl_err, plan_err,
+ validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ data_types: Vec<DataType>,
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points,
+ /// inferring key data types from the split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ let data_types: Option<Vec<DataType>> = if !split_points.is_empty() {
+ Some(
+ (0..sort_options.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect(),
+ )
+ } else {
+ None
+ };
+ Self::try_new_with_optional_data_types(
+ sort_options,
+ split_points,
+ data_types.as_deref(),
+ )
Review Comment:
**Split-point width mismatch panics instead of returning a plan error**
`RangeRouter::try_new` indexes into `values()` before `validate_range_split_points` gets a chance to run (validation happens inside `try_new_with_optional_data_types`):
```rust
// range.rs:60
.map(|col_idx| split_points[0].values()[col_idx].data_type())
// thread panicked: index out of bounds: the len is 1 but the index is 1
```
A width-1 split point with a width-2 ordering panics. Before this PR, RangeExpr::try_new_parts called validate_range_split_points first and returned plan_err!("Range partitioning split point 0 has width 1, but ordering has width 2"). This is reachable from RangeExpr::try_from_proto, so a malformed serialized plan panics the process rather than erroring.
The pre-computation is redundant anyway — try_new_with_optional_data_types infers the identical types after validating
That also makes the else if !split_points.is_empty() arm in try_new_with_optional_data_types live again (it's currently unreachable, since try_new always passes Some for non-empty split points). Worth a test asserting the plan error for a mismatched width.
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -667,34 +703,26 @@ impl RangeExpr {
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
) -> Result<Self> {
- let sort_options = range_partitioning
+ let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
- Self::try_new_parts(
- on_columns,
- range_partitioning.split_points().to_vec(),
- sort_options,
- )
+ Self::try_new_parts(on_columns, range_partitioning.split_points(), &sort_options)
}
fn try_new_parts(
on_columns: Vec<PhysicalExprRef>,
- split_points: Vec<SplitPoint>,
- sort_options: Vec<SortOptions>,
+ split_points: &[SplitPoint],
+ sort_options: &[SortOptions],
Review Comment:
```suggestion
fn try_new_parts(
on_columns: Vec<PhysicalExprRef>,
split_points: &[SplitPoint],
sort_options: &[SortOptions],
schema: &Schema,
```
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -667,34 +703,26 @@ impl RangeExpr {
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
) -> Result<Self> {
- let sort_options = range_partitioning
+ let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
- Self::try_new_parts(
- on_columns,
- range_partitioning.split_points().to_vec(),
- sort_options,
- )
+ Self::try_new_parts(on_columns, range_partitioning.split_points(), &sort_options)
}
fn try_new_parts(
on_columns: Vec<PhysicalExprRef>,
- split_points: Vec<SplitPoint>,
- sort_options: Vec<SortOptions>,
+ split_points: &[SplitPoint],
+ sort_options: &[SortOptions],
) -> Result<Self> {
assert_or_internal_err!(!on_columns.is_empty(), "RangeExpr requires a key");
assert_or_internal_err!(
on_columns.len() == sort_options.len(),
"RangeExpr key count must match sort options"
);
- validate_range_split_points(&split_points, &sort_options)?;
- Ok(Self {
- on_columns,
- split_points,
- sort_options,
- })
+ let router = RangeRouter::try_new(sort_options, split_points)?;
Review Comment:
**`RangeExpr` now rejects key types that `compare_rows` accepted**
`try_new_parts` builds the router with `RangeRouter::try_new`, which infers `data_types` from the split-point scalars, and `RangeRouter::route_with` then hard-rejects any array whose `DataType` isn't exactly equal. `RepartitionExecState` sidesteps this by calling `try_new_with_data_types` with the schema types, but the `RangeExpr` path (`shared_bounds.rs:764`) does no coercion — so the dynamic filter fails on exactly the mismatches your own new repartition tests assert must work:
```rust
// split point Decimal128(10, 2), probe column Decimal128(20, 2)
let expr = RangeExpr::try_new(vec![col("k", &schema)?], &range_part)?;
expr.evaluate(&batch)
// Err(Execution("Range partitioning expected column 0 to be of type Decimal128(10, 2), but got Decimal128(20, 2)"))
```
Before this PR compare_rows routed that fine (per the comment on range_repartition_routes_decimal_with_wider_column_precision). A range-partitioned probe side whose split points come from stats/metadata — tz-less timestamps, narrower decimals — goes from working to a hard query failure. BatchPartitioner::try_new_range_partitioner has the same gap for external callers.
A schema is available at every construction site, so resolve the key types there
Callers: shared_bounds.rs:764 has self.probe_schema; try_from_proto has ctx.schema(). with_new_children can keep the router as-is (Self { on_columns: children, router: self.router.clone() }), which also drops a rebuild+revalidate.
Please add a regression test through RangeExpr::evaluate mirroring the two repartition tests you added — the current ones only cover the RepartitionExec path, which is the one that already coerces
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -667,34 +703,26 @@ impl RangeExpr {
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
) -> Result<Self> {
- let sort_options = range_partitioning
+ let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
- Self::try_new_parts(
- on_columns,
- range_partitioning.split_points().to_vec(),
- sort_options,
- )
+ Self::try_new_parts(on_columns, range_partitioning.split_points(), &sort_options)
}
fn try_new_parts(
on_columns: Vec<PhysicalExprRef>,
- split_points: Vec<SplitPoint>,
- sort_options: Vec<SortOptions>,
+ split_points: &[SplitPoint],
+ sort_options: &[SortOptions],
) -> Result<Self> {
assert_or_internal_err!(!on_columns.is_empty(), "RangeExpr requires a key");
assert_or_internal_err!(
on_columns.len() == sort_options.len(),
"RangeExpr key count must match sort options"
);
- validate_range_split_points(&split_points, &sort_options)?;
- Ok(Self {
- on_columns,
- split_points,
- sort_options,
- })
+ let router = RangeRouter::try_new(sort_options, split_points)?;
Review Comment:
```suggestion
// Route on the key's actual types, not the split points' types: split
// points are not required to carry the key's exact type (`Decimal128`
// precision, timestamp timezone), and `RangeRouter` rejects any array
// whose type differs from the one it was built for.
let data_types = on_columns
.iter()
.map(|expr| expr.data_type(schema))
.collect::<Result<Vec<_>>>()?;
let router = RangeRouter::try_new_with_data_types(
sort_options,
split_points,
&data_types,
)?;
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5392365502
Nice results!
I think two easy further optimizations could be using `extend` and perhaps further optimizing the rowconverter path.
Ok to postpone it to a follow-up PR however you like!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3843778660
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
Review Comment:
Is it better to return not yet implemented or internal error for unknown type
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3843489335
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
Review Comment:
What kinds of types fall back to this path? I thought RowConverter supports most types. If not, are these types simply not supported yet, or are they fundamentally unsupported? Ideally, we wouldn’t need the Fallback enum at all.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3880804979
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
Review Comment:
here we infer the data type of the spilt pionts and this gets passed to `try_new()`
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,720 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+use std::sync::Arc;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::{
+ DataFusionError, Result, ScalarValue, not_impl_err, validate_range_split_points,
+};
+use datafusion_physical_expr::SplitPoint;
+
+/// A router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given sort options and split points.
+ pub(crate) fn try_new(
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ validate_range_split_points(split_points, sort_options)?;
+
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
Review Comment:
here we infer the data type of the spilt pionts and this gets passed to `try_new()`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5484005763
Split out the benchmarks into the bottom commit, and applied review feedback in the top commit.
The initial benchmark results were a bit optimistic (they never regressed during review feedback: they were just a bit off when they were initially posted). Now updated.
Thanks for the feedback!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846942182
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Yeah it doesn't implement this.
One can also make linear search faster for small N by specializing it for fixed N (generating more efficient code than a branchy for loop).
@geoffreyclaude worked on something similar in DataFusion for IN LIST (different strategy for each size):
https://github.com/apache/datafusion/pull/23014
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3847014685
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
^ I agree with this, can be a follow up. This can be part of the upcmong epic for range optimizations I am planning on making
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3844974416
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -751,16 +782,9 @@ impl PhysicalExpr for RangeExpr {
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
let arrays = evaluate_expressions_to_arrays(self.on_columns.iter(), batch)?;
Review Comment:
should we add a fast path for split_points == 0
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
+ let rows = row_converter.convert_columns(arrays)?;
+ let num_rows = rows.num_rows();
+ let sp_rows = &self.split_point_rows;
+
+ for row_idx in 0..num_rows {
+ let row = rows.row(row_idx);
+ let partition = sp_rows.partition_point(|sp| sp.as_ref() <= row.as_ref());
+ indices[partition].push(row_idx as u32);
+ }
+ Ok(())
+ }
+
+ fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
Review Comment:
could this be stored an Arc<RowConverter> do that this cline isnt per batch?
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
Review Comment:
ditto to other comment on storing arc
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
+ let rows = row_converter.convert_columns(arrays)?;
+ let num_rows = rows.num_rows();
+ let sp_rows = &self.split_point_rows;
+
+ for row_idx in 0..num_rows {
+ let row = rows.row(row_idx);
+ let partition = sp_rows.partition_point(|sp| sp.as_ref() <= row.as_ref());
+ indices[partition].push(row_idx as u32);
+ }
+ Ok(())
+ }
+
+ fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let row_converter = RowConverter::new(self.sort_fields.clone())?;
+ let rows = row_converter.convert_columns(arrays)?;
+ let num_rows = rows.num_rows();
+ let sp_rows = &self.split_point_rows;
+
+ for row_idx in 0..num_rows {
+ let row = rows.row(row_idx);
+ let partition = sp_rows.partition_point(|sp| sp.as_ref() <= row.as_ref());
+ partition_ids.push(partition as u64);
+ }
+ Ok(())
+ }
+}
+
+/// Fallback router using dynamic row-by-row comparisons.
+#[derive(Debug, Clone)]
+struct FallbackRangeRouter {
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+}
+
+impl FallbackRangeRouter {
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ let mut row_key_buffer = Vec::with_capacity(arrays.len());
+ for row_idx in 0..num_rows {
+ extract_row_at_idx_to_buf(arrays, row_idx, &mut row_key_buffer)?;
+ let partition = range_partition_id_fallback(
+ &row_key_buffer,
+ &self.split_points,
+ &self.sort_options,
+ )?;
+ indices[partition].push(row_idx as u32);
+ }
+ Ok(())
+ }
+
+ fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ let num_rows = arrays.first().map(|a| a.len()).unwrap_or(0);
+ let mut row_key_buffer = Vec::with_capacity(arrays.len());
+ for row_idx in 0..num_rows {
+ extract_row_at_idx_to_buf(arrays, row_idx, &mut row_key_buffer)?;
+ let partition = range_partition_id_fallback(
+ &row_key_buffer,
+ &self.split_points,
+ &self.sort_options,
+ )?;
+ partition_ids.push(partition as u64);
+ }
+ Ok(())
+ }
+}
+
+fn range_partition_id_fallback(
+ row_key: &[ScalarValue],
+ split_points: &[SplitPoint],
+ sort_options: &[SortOptions],
+) -> Result<usize> {
+ let mut low = 0;
+ let mut high = split_points.len();
+ while low < high {
+ let mid = low + (high - low) / 2;
+ match compare_rows(row_key, split_points[mid].values(), sort_options)? {
+ Ordering::Less => high = mid,
+ Ordering::Equal | Ordering::Greater => low = mid + 1,
+ }
+ }
+ Ok(low)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Arc;
+
+ #[test]
+ fn test_primitive_router_i64_asc() -> Result<()> {
Review Comment:
nit: could we extract some boilderplate
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
Review Comment:
I second this, I think if there isnt a type that actually falls back to this now we could represent this with something
```rust
enum RangeRouterInner { Primitive, Row}
```
then throw internal error if we encounter something that isnt supported.
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
I tested this locally and profiled and saw small sppedups up to about 16 partition threshold. Dont think its needed for this PR but just interesting to think about
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
This is non blocking but something I would be curious in exploring: a linear scan path for smaller partition counts that is a bit less "branchy". In the binary search we can have somewhat random access patterns across what split points we are going to be indexing. If we did a linear scan we would only have a single branch where we find the split point that is grater than the row, thus due to the less randomness the CPU may be able to predict a bit better and reduce cycles.
I may experiment with something like this and profile if this is really the case as I am less experiencd with SIMD-able algorithms.
This said I think this is just applicable to the `RowConverter` path since in the primitive path the comparison is on i64's but may help here
cc: @Dandandan I know you are very involved in this kind of optimization work would love thoughts
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3851470924
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ partition_ids: &mut Vec<u64>,
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+}
+
+/// Generic router for floating point values using total ordering.
+#[derive(Debug, Clone)]
+struct FloatValuesRouter<T: Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: Copy + Send + Sync + 'static> FloatValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+}
+
+macro_rules! impl_float_values_router {
+ ($t:ty, $arr:ty) => {
+ impl FloatValuesRouter<$t> {
+ fn route_indices(&self, array: &$arr, indices: &mut [Vec<u32>]) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ indices[p].push(idx as u32);
+ }
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &$arr, partition_ids: &mut Vec<u64>) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ });
+ partition_ids.push(p as u64);
+ }
+ } else {
+ for &val in values {
+ let p = split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ });
+ partition_ids.push(p as u64);
+ }
+ }
+ } else {
+ let null_partition =
+ (if nulls_first { 0 } else { split_points.len() }) as u64;
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ partition_ids.push(null_partition);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Greater
+ })
+ } else {
+ split_points.partition_point(|&sp| {
+ sp.total_cmp(&val) != Ordering::Less
+ })
+ };
+ partition_ids.push(p as u64);
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+impl_float_values_router!(f32, Float32Array);
+impl_float_values_router!(f64, Float64Array);
+
+/// Router backed by Arrow's RowConverter.
+#[derive(Debug, Clone)]
+struct RowConverterRangeRouter {
+ sort_fields: Vec<SortField>,
+ split_point_rows: Vec<OwnedRow>,
+}
+
+impl RowConverterRangeRouter {
+ fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Option<Self>> {
+ let sort_fields = data_types
+ .iter()
+ .zip(sort_options)
+ .map(|(dt, opt)| SortField::new_with_options(dt.clone(), *opt))
+ .collect::<Vec<_>>();
+
+ if !RowConverter::supports_fields(&sort_fields) {
+ return Ok(None);
+ }
+
+ let row_converter = RowConverter::new(sort_fields.clone())?;
+ let num_cols = data_types.len();
+
+ let mut split_point_arrays = Vec::with_capacity(num_cols);
+ for col_idx in 0..num_cols {
+ let col_scalars = split_points.iter().map(|sp| sp.values()[col_idx].clone());
+ let col_array = ScalarValue::iter_to_array(col_scalars)?;
+ split_point_arrays.push(col_array);
+ }
+
+ let rows = row_converter.convert_columns(&split_point_arrays)?;
+ let split_point_rows = (0..rows.num_rows())
+ .map(|i| rows.row(i).owned())
+ .collect::<Vec<_>>();
+
+ Ok(Some(Self {
+ sort_fields,
+ split_point_rows,
+ }))
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_point_rows.len()
+ }
+
+ fn route_indices(&self, arrays: &[ArrayRef], indices: &mut [Vec<u32>]) -> Result<()> {
Review Comment:
Replying to the ping: I agree it's clearer to separate complex performance optimizations from purely functional improvements. And it will allow doing it in a systematic, benchmarked manner as I'm doing for IN LIST, where each optim in turn can be discussed and validated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5555501931
Is this PR ready to merge? 🚀
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 merged PR #24598:
URL: https://github.com/apache/datafusion/pull/24598
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5544441985
Sorry for the delay! Applied.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "stuhood (via GitHub)" <gi...@apache.org>.
stuhood commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3865966550
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -999,25 +1009,31 @@ impl BatchPartitioner {
/// # Parameters
/// - `range_partitioning`: `RangePartitioning` struct used for ordering, split points, and number of partitions
/// - `timer`: Metric used to record time spent during repartitioning.
- pub fn new_range_partitioner(
+ pub fn try_new_range_partitioner(
range_partitioning: &RangePartitioning,
timer: metrics::Time,
- ) -> Self {
+ ) -> Result<Self> {
let ordering = range_partitioning.ordering().clone();
- let split_points = range_partitioning.split_points().to_vec();
+ let split_points = range_partitioning.split_points();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
+ let data_types: Vec<DataType> = if !split_points.is_empty() {
+ (0..ordering.len())
+ .map(|col_idx| split_points[0].values()[col_idx].data_type())
+ .collect()
+ } else {
+ vec![]
+ };
Review Comment:
AFAIK, we don't have the schema here. But after planning, `split_points` should already be aligned with the expected schema, so that should be fine...?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#issuecomment-5388848207
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/24598?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `62.50000%` with `216 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.35%. Comparing base ([`7e4188e`](https://app.codecov.io/gh/apache/datafusion/commit/7e4188ed44ca67e08e5a58b87807697e5afe3c43?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`5579f93`](https://app.codecov.io/gh/apache/datafusion/commit/5579f93709d7afb0691cd2845e3868ab5a07398a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/24598?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [datafusion/physical-plan/src/repartition/range.rs](https://app.codecov.io/gh/apache/datafusion/pull/24598?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Frepartition%2Frange.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9yZXBhcnRpdGlvbi9yYW5nZS5ycw==) | 62.61% | [175 Missing and 28 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24598?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [datafusion/physical-plan/src/repartition/mod.rs](https://app.codecov.io/gh/apache/datafusion/pull/24598?src=pr&el=tree&filepath=datafusion%2Fphysical-plan%2Fsrc%2Frepartition%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1wbGFuL3NyYy9yZXBhcnRpdGlvbi9tb2QucnM=) | 60.60% | [9 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24598?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #24598 +/- ##
==========================================
- Coverage 81.38% 81.35% -0.04%
==========================================
Files 1116 1117 +1
Lines 397973 398497 +524
Branches 397973 398497 +524
==========================================
+ Hits 323893 324193 +300
- Misses 55118 55310 +192
- Partials 18962 18994 +32
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/24598?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3841622001
##########
datafusion/physical-plan/src/repartition/range.rs:
##########
@@ -0,0 +1,903 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Routers for range partitioning.
+
+use std::cmp::Ordering;
+
+use arrow::array::*;
+use arrow::compute::SortOptions;
+use arrow::datatypes::*;
+use arrow::row::{OwnedRow, RowConverter, SortField};
+use datafusion_common::utils::{compare_rows, extract_row_at_idx_to_buf};
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_physical_expr::SplitPoint;
+
+/// An router for assigning rows to range partitions.
+#[derive(Debug, Clone)]
+pub(crate) struct RangeRouter {
+ inner: RangeRouterInner,
+}
+
+#[derive(Debug, Clone)]
+enum RangeRouterInner {
+ /// Specialized fast path for a single primitive column with non-null split points.
+ Primitive(PrimitiveRangeRouter),
+ /// Universal fast path using Arrow's RowConverter for arbitrary types and composite keys.
+ Row(RowConverterRangeRouter),
+ /// Fallback for rare types not supported by RowConverter.
+ Fallback(FallbackRangeRouter),
+}
+
+impl RangeRouter {
+ /// Constructs the best router for the given key types, split points, and sort options.
+ pub(crate) fn try_new(
+ data_types: &[DataType],
+ sort_options: &[SortOptions],
+ split_points: &[SplitPoint],
+ ) -> Result<Self> {
+ if split_points.is_empty() {
+ return Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ));
+ }
+
+ // Try single-column primitive fast path
+ if data_types.len() == 1
+ && let Some(primitive_router) =
+ PrimitiveRangeRouter::try_new(split_points, sort_options[0])
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Primitive(primitive_router),
+ });
+ }
+
+ // Try RowConverter fast path
+ if let Some(row_router) =
+ RowConverterRangeRouter::try_new(data_types, sort_options, split_points)?
+ {
+ return Ok(Self {
+ inner: RangeRouterInner::Row(row_router),
+ });
+ }
+
+ // Fallback
+ Ok(Self::new_fallback(
+ split_points.to_vec(),
+ sort_options.to_vec(),
+ ))
+ }
+
+ /// Constructs a fallback router using dynamic row-by-row comparisons.
+ pub(crate) fn new_fallback(
+ split_points: Vec<SplitPoint>,
+ sort_options: Vec<SortOptions>,
+ ) -> Self {
+ Self {
+ inner: RangeRouterInner::Fallback(FallbackRangeRouter {
+ split_points,
+ sort_options,
+ }),
+ }
+ }
+
+ /// Number of split points configured in this router.
+ pub(crate) fn num_split_points(&self) -> usize {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => r.num_split_points(),
+ RangeRouterInner::Row(r) => r.num_split_points(),
+ RangeRouterInner::Fallback(r) => r.num_split_points(),
+ }
+ }
+
+ /// Groups row indices from `arrays` into partition index buckets.
+ pub(crate) fn route_indices(
+ &self,
+ arrays: &[ArrayRef],
+ indices: &mut [Vec<u32>],
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_indices(first_col.as_ref(), indices)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_indices(arrays, indices),
+ RangeRouterInner::Fallback(r) => r.route_indices(arrays, indices),
+ }
+ }
+
+ /// Appends output partition IDs to `partition_ids`.
+ pub(crate) fn route_partition_ids(
+ &self,
+ arrays: &[ArrayRef],
+ partition_ids: &mut Vec<u64>,
+ ) -> Result<()> {
+ match &self.inner {
+ RangeRouterInner::Primitive(r) => {
+ if let Some(first_col) = arrays.first() {
+ r.route_partition_ids(first_col.as_ref(), partition_ids)
+ } else {
+ Ok(())
+ }
+ }
+ RangeRouterInner::Row(r) => r.route_partition_ids(arrays, partition_ids),
+ RangeRouterInner::Fallback(r) => r.route_partition_ids(arrays, partition_ids),
+ }
+ }
+}
+
+macro_rules! define_primitive_router {
+ ($( ($variant:ident, $type:ty, $arrow_type:ty, $array:ident) ),* $(,)?) => {
+ /// Specialized router for primitive scalar types.
+ #[derive(Debug, Clone)]
+ enum PrimitiveRangeRouter {
+ $( $variant(PrimitiveValuesRouter<$type>), )*
+ Float32(FloatValuesRouter<f32>),
+ Float64(FloatValuesRouter<f64>),
+ }
+
+ impl PrimitiveRangeRouter {
+ fn try_new(split_points: &[SplitPoint], sort_options: SortOptions) -> Option<Self> {
+ if split_points.is_empty() {
+ return None;
+ }
+
+ let scalars = split_points.iter().map(|sp| sp.values()[0].clone());
+ let split_array = ScalarValue::iter_to_array(scalars).ok()?;
+ if split_array.null_count() > 0 {
+ return None;
+ }
+
+ macro_rules! make_primitive {
+ ($target_arrow_type:ty, $target_variant:ident) => {{
+ let arr = split_array
+ .as_any()
+ .downcast_ref::<PrimitiveArray<$target_arrow_type>>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::$target_variant(PrimitiveValuesRouter::new(vals, sort_options)))
+ }};
+ }
+
+ match split_array.data_type() {
+ DataType::Int8 => make_primitive!(Int8Type, Int8),
+ DataType::Int16 => make_primitive!(Int16Type, Int16),
+ DataType::Int32 => make_primitive!(Int32Type, Int32),
+ DataType::Int64 => make_primitive!(Int64Type, Int64),
+ DataType::UInt8 => make_primitive!(UInt8Type, UInt8),
+ DataType::UInt16 => make_primitive!(UInt16Type, UInt16),
+ DataType::UInt32 => make_primitive!(UInt32Type, UInt32),
+ DataType::UInt64 => make_primitive!(UInt64Type, UInt64),
+ DataType::Date32 => make_primitive!(Date32Type, Date32),
+ DataType::Date64 => make_primitive!(Date64Type, Date64),
+ DataType::Time32(TimeUnit::Second) => make_primitive!(Time32SecondType, Time32Second),
+ DataType::Time32(TimeUnit::Millisecond) => make_primitive!(Time32MillisecondType, Time32Millisecond),
+ DataType::Time64(TimeUnit::Microsecond) => make_primitive!(Time64MicrosecondType, Time64Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond) => make_primitive!(Time64NanosecondType, Time64Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, _) => make_primitive!(TimestampSecondType, TimestampSecond),
+ DataType::Timestamp(TimeUnit::Millisecond, _) => make_primitive!(TimestampMillisecondType, TimestampMillisecond),
+ DataType::Timestamp(TimeUnit::Microsecond, _) => make_primitive!(TimestampMicrosecondType, TimestampMicrosecond),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) => make_primitive!(TimestampNanosecondType, TimestampNanosecond),
+ DataType::Float32 => {
+ let arr = split_array.as_any().downcast_ref::<Float32Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float32(FloatValuesRouter::new(vals, sort_options)))
+ }
+ DataType::Float64 => {
+ let arr = split_array.as_any().downcast_ref::<Float64Array>()?;
+ let vals = arr.values().to_vec();
+ Some(Self::Float64(FloatValuesRouter::new(vals, sort_options)))
+ }
+ _ => None,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ match self {
+ $( Self::$variant(r) => r.num_split_points(), )*
+ Self::Float32(r) => r.num_split_points(),
+ Self::Float64(r) => r.num_split_points(),
+ }
+ }
+
+ fn route_indices(&self, array: &dyn Array, indices: &mut [Vec<u32>]) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_indices(arr, indices);
+ Ok(())
+ }
+ }
+ }
+
+ fn route_partition_ids(&self, array: &dyn Array, partition_ids: &mut Vec<u64>) -> Result<()> {
+ match self {
+ $(
+ Self::$variant(r) => {
+ let arr = array.as_any().downcast_ref::<$array>().ok_or_else(|| {
+ DataFusionError::Internal(format!("Expected {}", stringify!($array)))
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ )*
+ Self::Float32(r) => {
+ let arr = array.as_any().downcast_ref::<Float32Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float32Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ Self::Float64(r) => {
+ let arr = array.as_any().downcast_ref::<Float64Array>().ok_or_else(|| {
+ DataFusionError::Internal("Expected Float64Array".to_string())
+ })?;
+ r.route_partition_ids(arr, partition_ids);
+ Ok(())
+ }
+ }
+ }
+ }
+ };
+}
+
+define_primitive_router!(
+ (Int8, i8, Int8Type, Int8Array),
+ (Int16, i16, Int16Type, Int16Array),
+ (Int32, i32, Int32Type, Int32Array),
+ (Int64, i64, Int64Type, Int64Array),
+ (UInt8, u8, UInt8Type, UInt8Array),
+ (UInt16, u16, UInt16Type, UInt16Array),
+ (UInt32, u32, UInt32Type, UInt32Array),
+ (UInt64, u64, UInt64Type, UInt64Array),
+ (Date32, i32, Date32Type, Date32Array),
+ (Date64, i64, Date64Type, Date64Array),
+ (Time32Second, i32, Time32SecondType, Time32SecondArray),
+ (
+ Time32Millisecond,
+ i32,
+ Time32MillisecondType,
+ Time32MillisecondArray
+ ),
+ (
+ Time64Microsecond,
+ i64,
+ Time64MicrosecondType,
+ Time64MicrosecondArray
+ ),
+ (
+ Time64Nanosecond,
+ i64,
+ Time64NanosecondType,
+ Time64NanosecondArray
+ ),
+ (
+ TimestampSecond,
+ i64,
+ TimestampSecondType,
+ TimestampSecondArray
+ ),
+ (
+ TimestampMillisecond,
+ i64,
+ TimestampMillisecondType,
+ TimestampMillisecondArray
+ ),
+ (
+ TimestampMicrosecond,
+ i64,
+ TimestampMicrosecondType,
+ TimestampMicrosecondArray
+ ),
+ (
+ TimestampNanosecond,
+ i64,
+ TimestampNanosecondType,
+ TimestampNanosecondArray
+ ),
+);
+
+/// Generic router for primitive integer and temporal types.
+#[derive(Debug, Clone)]
+struct PrimitiveValuesRouter<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> {
+ split_points: Vec<T>,
+ sort_options: SortOptions,
+}
+
+impl<T: ArrowNativeTypeOp + Ord + Copy + Send + Sync + 'static> PrimitiveValuesRouter<T> {
+ fn new(split_points: Vec<T>, sort_options: SortOptions) -> Self {
+ Self {
+ split_points,
+ sort_options,
+ }
+ }
+
+ fn num_split_points(&self) -> usize {
+ self.split_points.len()
+ }
+
+ fn route_indices<A: ArrowPrimitiveType<Native = T>>(
+ &self,
+ array: &PrimitiveArray<A>,
+ indices: &mut [Vec<u32>],
+ ) {
+ let split_points = &self.split_points;
+ let descending = self.sort_options.descending;
+ let nulls_first = self.sort_options.nulls_first;
+
+ if array.null_count() == 0 {
+ let values = array.values().as_ref();
+ if !descending {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp <= val);
+ indices[p].push(idx as u32);
+ }
+ } else {
+ for (idx, &val) in values.iter().enumerate() {
+ let p = split_points.partition_point(|&sp| sp >= val);
+ indices[p].push(idx as u32);
+ }
+ }
+ } else {
+ let null_partition = if nulls_first { 0 } else { split_points.len() };
+ for idx in 0..array.len() {
+ if array.is_null(idx) {
+ indices[null_partition].push(idx as u32);
+ } else {
+ let val = array.value(idx);
+ let p = if !descending {
+ split_points.partition_point(|&sp| sp <= val)
+ } else {
+ split_points.partition_point(|&sp| sp >= val)
+ };
+ indices[p].push(idx as u32);
Review Comment:
The loop could use `extend` rather than `push` which generally generates better / branch free code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Range partition on primitives. [datafusion]
Posted by "gene-bordegaray (via GitHub)" <gi...@apache.org>.
gene-bordegaray commented on code in PR #24598:
URL: https://github.com/apache/datafusion/pull/24598#discussion_r3846639550
##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
Review Comment:
could we actually fast path this on a single partition? my samply is showing this takes about 41% of cpu time on skewwed data, so this would help if we didnt always call take_arrays if not needed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org