use std::fmt::{Debug, Display, Formatter};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use std::task::{Context, Poll};
use std::vec;
use super::common::SharedMemoryReservation;
use super::metrics::{self, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
use super::{
DisplayAs, ExecutionPlanProperties, RecordBatchStream, SendableRecordBatchStream,
};
use crate::coalesce::LimitedBatchCoalescer;
use crate::execution_plan::{CardinalityEffect, EvaluationType, SchedulingType};
use crate::hash_utils::create_hashes;
use crate::metrics::{BaselineMetrics, SpillMetrics};
use crate::projection::{ProjectionExec, all_columns, make_with_child, update_expr};
use crate::sorts::streaming_merge::StreamingMergeBuilder;
use crate::spill::spill_manager::SpillManager;
use crate::spill::spill_pool::{self, SpillPoolSink, SpillPoolWriter};
use crate::statistics::{ChildStats, StatisticsArgs};
use crate::stream::{EmptyRecordBatchStream, RecordBatchStreamAdapter};
use crate::{
ChildrenPropertiesMode, DisplayFormatType, ExecutionPlan, Partitioning,
PlanProperties, ReplaceChildrenOptions, Statistics, validate_child_count,
};
use arrow::array::{PrimitiveArray, RecordBatch, RecordBatchOptions, UInt64Array};
use arrow::compute::take_arrays;
use arrow::datatypes::{DataType, Schema, SchemaRef, UInt32Type};
use arrow_schema::SortOptions;
use datafusion_common::ScalarValue;
use datafusion_common::config::ConfigOptions;
use datafusion_common::stats::Precision;
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::utils::transpose;
use datafusion_common::{
ColumnStatistics, DataFusionError, HashMap, SplitPoint, assert_or_internal_err,
internal_datafusion_err, internal_err,
};
use datafusion_common::{Result, not_impl_err};
use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::MemoryConsumer;
use datafusion_expr::ColumnarValue;
use datafusion_physical_expr::{EquivalenceProperties, PhysicalExpr, RangePartitioning};
use datafusion_physical_expr_common::physical_expr::PhysicalExprRef;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
#[cfg(feature = "proto")]
use datafusion_physical_expr_common::sort_expr::{
sort_exprs_try_from_proto, sort_exprs_try_to_proto,
};
#[cfg(feature = "proto")]
use datafusion_proto_models::protobuf;
use crate::filter_pushdown::{
ChildPushdownResult, FilterDescription, FilterPushdownPhase,
FilterPushdownPropagation,
};
use crate::joins::SeededRandomState;
use crate::sort_pushdown::SortOrderPushdownResult;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::stream::Stream;
use futures::{FutureExt, StreamExt, TryStreamExt};
use log::trace;
use parking_lot::Mutex;
mod distributor_channels;
mod range;
use range::RangeRouter;
use std::hash::{Hash, Hasher};
use crate::repartition::distributor_channels::SendError;
use distributor_channels::{
DistributionReceiver, DistributionSender, channels, partition_aware_channels,
};
#[derive(Debug)]
enum RepartitionBatch {
Memory(RecordBatch),
Spilled,
}
type MaybeBatch = Option<Result<RepartitionBatch>>;
type InputPartitionsToCurrentPartitionSender = Vec<DistributionSender<MaybeBatch>>;
type InputPartitionsToCurrentPartitionReceiver = Vec<DistributionReceiver<MaybeBatch>>;
struct OutputChannel {
sender: DistributionSender<MaybeBatch>,
reservation: SharedMemoryReservation,
spill_writer: SpillPoolSink,
shared_coalescer: Option<SharedCoalescer>,
}
enum PartitionSpillWriters {
PerInput(Vec<Option<SpillPoolSink>>),
Shared(SpillPoolWriter),
}
impl PartitionSpillWriters {
fn take_for_input(&mut self, input: usize) -> Result<SpillPoolSink> {
match self {
PartitionSpillWriters::PerInput(writers) => {
writers[input].take().ok_or_else(|| {
internal_datafusion_err!(
"spill writer for input partition requested more than once"
)
})
}
PartitionSpillWriters::Shared(writer) => Ok(writer.new_sink()),
}
}
}
impl OutputChannel {
fn coalesce(&mut self, batch: RecordBatch, out: &mut Vec<RecordBatch>) -> Result<()> {
match &self.shared_coalescer {
Some(shared) => shared.push_and_drain(batch, out),
None => {
out.push(batch);
Ok(())
}
}
}
async fn send(&mut self, batch: RecordBatch) -> Result<(), SendError<MaybeBatch>> {
let size = batch.get_array_memory_size();
let (payload, is_memory_batch) = {
match self.reservation.try_grow(size) {
Ok(_) => (Ok(RepartitionBatch::Memory(batch)), true),
Err(_) => match self.spill_writer.push_batch(&batch) {
Ok(()) => (Ok(RepartitionBatch::Spilled), false),
Err(err) => (Err(err), false),
},
}
};
let result = self.sender.send(Some(payload)).await;
if result.is_err() && is_memory_batch {
self.reservation.shrink(size);
}
result
}
async fn finalize(mut self) -> Result<()> {
let Some(shared) = self.shared_coalescer.take() else {
return Ok(());
};
for batch in shared.finalize()? {
let _ = self.send(batch).await;
}
Ok(())
}
}
#[derive(Clone)]
struct SharedCoalescer {
inner: Arc<Mutex<LimitedBatchCoalescer>>,
active_senders: Arc<AtomicUsize>,
}
impl SharedCoalescer {
fn new(schema: SchemaRef, target_batch_size: usize, num_senders: usize) -> Self {
Self {
inner: Arc::new(Mutex::new(LimitedBatchCoalescer::new(
schema,
target_batch_size,
None,
))),
active_senders: Arc::new(AtomicUsize::new(num_senders)),
}
}
fn push_and_drain(
&self,
batch: RecordBatch,
out: &mut Vec<RecordBatch>,
) -> Result<()> {
let mut c = self.inner.lock();
c.push_batch(batch)?;
while let Some(b) = c.next_completed_batch() {
out.push(b);
}
Ok(())
}
fn finalize(&self) -> Result<Vec<RecordBatch>> {
let was_last = self.active_senders.fetch_sub(1, AtomicOrdering::AcqRel) == 1;
if !was_last {
return Ok(vec![]);
}
let mut acc = Vec::new();
let mut c = self.inner.lock();
c.finish()?;
while let Some(b) = c.next_completed_batch() {
acc.push(b);
}
Ok(acc)
}
}
struct PartitionChannels {
tx: InputPartitionsToCurrentPartitionSender,
rx: InputPartitionsToCurrentPartitionReceiver,
reservation: SharedMemoryReservation,
shared_coalescer: Option<SharedCoalescer>,
spill_writers: PartitionSpillWriters,
spill_readers: Vec<SendableRecordBatchStream>,
}
struct ConsumingInputStreamsState {
channels: HashMap<usize, PartitionChannels>,
abort_helper: Arc<Vec<SpawnedTask<()>>>,
}
impl Debug for ConsumingInputStreamsState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConsumingInputStreamsState")
.field("num_channels", &self.channels.len())
.field("abort_helper", &self.abort_helper)
.finish()
}
}
#[derive(Default)]
enum RepartitionExecState {
#[default]
NotInitialized,
InputStreamsInitialized(Vec<(SendableRecordBatchStream, RepartitionMetrics)>),
ConsumingInputStreams(ConsumingInputStreamsState),
}
impl Debug for RepartitionExecState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
RepartitionExecState::NotInitialized => write!(f, "NotInitialized"),
RepartitionExecState::InputStreamsInitialized(v) => {
write!(f, "InputStreamsInitialized({:?})", v.len())
}
RepartitionExecState::ConsumingInputStreams(v) => {
write!(f, "ConsumingInputStreams({v:?})")
}
}
}
}
impl RepartitionExecState {
fn ensure_input_streams_initialized(
&mut self,
input: &Arc<dyn ExecutionPlan>,
metrics: &ExecutionPlanMetricsSet,
output_partitions: usize,
ctx: &Arc<TaskContext>,
) -> Result<()> {
if !matches!(self, RepartitionExecState::NotInitialized) {
return Ok(());
}
let num_input_partitions = input.output_partitioning().partition_count();
let mut streams_and_metrics = Vec::with_capacity(num_input_partitions);
for i in 0..num_input_partitions {
let metrics = RepartitionMetrics::new(i, output_partitions, metrics);
let timer = metrics.fetch_time.timer();
let stream = input.execute(i, Arc::clone(ctx))?;
timer.done();
streams_and_metrics.push((stream, metrics));
}
*self = RepartitionExecState::InputStreamsInitialized(streams_and_metrics);
Ok(())
}
#[expect(clippy::too_many_arguments)]
fn consume_input_streams(
&mut self,
input: &Arc<dyn ExecutionPlan>,
metrics: &ExecutionPlanMetricsSet,
partitioning: &Partitioning,
preserve_order: bool,
name: &str,
context: &Arc<TaskContext>,
spill_manager: SpillManager,
coalescer_batch_size: usize,
) -> Result<&mut ConsumingInputStreamsState> {
let streams_and_metrics = match self {
RepartitionExecState::NotInitialized => {
self.ensure_input_streams_initialized(
input,
metrics,
partitioning.partition_count(),
context,
)?;
let RepartitionExecState::InputStreamsInitialized(value) = self else {
return internal_err!(
"Programming error: RepartitionExecState must be in the InputStreamsInitialized state after calling RepartitionExecState::ensure_input_streams_initialized"
);
};
value
}
RepartitionExecState::ConsumingInputStreams(value) => return Ok(value),
RepartitionExecState::InputStreamsInitialized(value) => value,
};
let num_input_partitions = streams_and_metrics.len();
let num_output_partitions = partitioning.partition_count();
let coalesce_batches = !preserve_order && !input.boundedness().is_unbounded();
let spill_manager = Arc::new(spill_manager);
let (txs, rxs) = if preserve_order {
let (txs_all, rxs_all) =
partition_aware_channels(num_input_partitions, num_output_partitions);
let txs = transpose(txs_all);
let rxs = transpose(rxs_all);
(txs, rxs)
} else {
let (txs, rxs) = channels(num_output_partitions);
let txs = txs
.into_iter()
.map(|item| vec![item; num_input_partitions])
.collect::<Vec<_>>();
let rxs = rxs.into_iter().map(|item| vec![item]).collect::<Vec<_>>();
(txs, rxs)
};
let mut channels = HashMap::with_capacity(txs.len());
for (partition, (tx, rx)) in txs.into_iter().zip(rxs).enumerate() {
let reservation = Arc::new(
MemoryConsumer::new(format!("{name}[{partition}]"))
.with_can_spill(true)
.register(context.memory_pool()),
);
let max_file_size = context
.session_config()
.options()
.execution
.max_spill_file_size_bytes
.get();
let (spill_writers, spill_readers) = if preserve_order {
let mut writers = Vec::with_capacity(num_input_partitions);
let mut readers = Vec::with_capacity(num_input_partitions);
for _ in 0..num_input_partitions {
let (writer, reader) = spill_pool::spsc_channel(
max_file_size,
Arc::clone(&spill_manager),
);
writers.push(Some(writer));
readers.push(reader);
}
(PartitionSpillWriters::PerInput(writers), readers)
} else {
let (writer, reader) =
spill_pool::mpsc_channel(max_file_size, Arc::clone(&spill_manager));
(PartitionSpillWriters::Shared(writer), vec![reader])
};
let shared_coalescer = coalesce_batches.then(|| {
SharedCoalescer::new(
input.schema(),
coalescer_batch_size,
num_input_partitions,
)
});
channels.insert(
partition,
PartitionChannels {
tx,
rx,
reservation,
shared_coalescer,
spill_writers,
spill_readers,
},
);
}
let range_router = if let Partitioning::Range(range_partitioning) = &partitioning
{
let ordering = range_partitioning.ordering();
let sort_options: Vec<SortOptions> =
ordering.iter().map(|e| e.options).collect();
let data_types = ordering
.iter()
.map(|e| e.expr.data_type(input.schema().as_ref()))
.collect::<Result<Vec<_>>>()?;
Some(Arc::new(RangeRouter::try_new_with_data_types(
&sort_options,
range_partitioning.split_points(),
&data_types,
)?))
} else {
None
};
let mut spawned_tasks = Vec::with_capacity(num_input_partitions);
for (i, (stream, metrics)) in
std::mem::take(streams_and_metrics).into_iter().enumerate()
{
let txs: HashMap<_, _> = channels
.iter_mut()
.map(|(partition, channels)| {
Ok((
*partition,
OutputChannel {
sender: channels.tx[i].clone(),
reservation: Arc::clone(&channels.reservation),
spill_writer: channels.spill_writers.take_for_input(i)?,
shared_coalescer: channels.shared_coalescer.clone(),
},
))
})
.collect::<Result<HashMap<_, _>>>()?;
let senders: HashMap<_, _> = txs
.iter()
.map(|(partition, channel)| (*partition, channel.sender.clone()))
.collect();
let input_task = SpawnedTask::spawn(RepartitionExec::pull_from_input(
stream,
txs,
partitioning.clone(),
range_router.clone(),
metrics,
if preserve_order { 0 } else { i },
num_input_partitions,
));
let wait_for_task =
SpawnedTask::spawn(RepartitionExec::wait_for_task(input_task, senders));
spawned_tasks.push(wait_for_task);
}
*self = Self::ConsumingInputStreams(ConsumingInputStreamsState {
channels,
abort_helper: Arc::new(spawned_tasks),
});
match self {
RepartitionExecState::ConsumingInputStreams(value) => Ok(value),
_ => unreachable!(),
}
}
}
pub struct BatchPartitioner {
state: BatchPartitionerState,
timer: metrics::Time,
}
enum BatchPartitionerState {
Hash {
exprs: Vec<Arc<dyn PhysicalExpr>>,
partition_reducer: StrengthReducedU64,
hash_buffer: Vec<u64>,
indices: Vec<Vec<u32>>,
},
RoundRobin {
num_partitions: usize,
next_idx: usize,
},
Range {
ordering: LexOrdering,
router: Arc<RangeRouter>,
indices: Vec<Vec<u32>>,
},
}
pub const REPARTITION_RANDOM_STATE: SeededRandomState = SeededRandomState::with_seed(0);
#[derive(Debug, Clone)]
pub struct RangeExpr {
on_columns: Vec<PhysicalExprRef>,
router: RangeRouter,
}
impl PartialEq for RangeExpr {
fn eq(&self, other: &Self) -> bool {
self.on_columns == other.on_columns
&& self.router.split_points() == other.router.split_points()
&& self.router.sort_options() == other.router.sort_options()
}
}
impl Eq for RangeExpr {}
impl Hash for RangeExpr {
fn hash<H: Hasher>(&self, state: &mut H) {
self.on_columns.hash(state);
self.router.split_points().hash(state);
self.router.sort_options().hash(state);
}
}
impl RangeExpr {
pub fn try_new_with_schema(
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
schema: &Schema,
) -> Result<Self> {
let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
Self::try_new_parts(
on_columns,
range_partitioning.split_points(),
&sort_options,
schema,
)
}
#[deprecated(since = "56.0.0", note = "Use RangeExpr::try_new_with_schema instead")]
pub fn try_new(
on_columns: Vec<PhysicalExprRef>,
range_partitioning: &RangePartitioning,
) -> Result<Self> {
let sort_options: Vec<SortOptions> = range_partitioning
.ordering()
.iter()
.map(|expr| expr.options)
.collect();
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"
);
let router =
RangeRouter::try_new(&sort_options, range_partitioning.split_points())?;
Ok(Self { on_columns, router })
}
fn try_new_parts(
on_columns: Vec<PhysicalExprRef>,
split_points: &[SplitPoint],
sort_options: &[SortOptions],
schema: &Schema,
) -> 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"
);
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,
)?;
Ok(Self { on_columns, router })
}
pub fn on_columns(&self) -> &[PhysicalExprRef] {
&self.on_columns
}
pub fn split_points(&self) -> &[SplitPoint] {
self.router.split_points()
}
pub fn sort_options(&self) -> &[SortOptions] {
self.router.sort_options()
}
pub(crate) fn route_partition_ids(
&self,
arrays: &[arrow::array::ArrayRef],
partition_ids: &mut Vec<u64>,
) -> Result<()> {
if self.router.split_points().is_empty() {
partition_ids.resize(partition_ids.len() + arrays[0].len(), 0);
return Ok(());
}
self.router.route_partition_ids(arrays, partition_ids)
}
}
impl Display for RangeExpr {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "range_partition")
}
}
impl PhysicalExpr for RangeExpr {
fn children(&self) -> Vec<&PhysicalExprRef> {
self.on_columns.iter().collect()
}
fn with_new_children(
self: Arc<Self>,
children: Vec<PhysicalExprRef>,
) -> Result<PhysicalExprRef> {
assert_or_internal_err!(
children.len() == self.on_columns.len(),
"RangeExpr expected {} children, got {}",
self.on_columns.len(),
children.len()
);
Ok(Arc::new(Self {
on_columns: children,
router: self.router.clone(),
}))
}
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(DataType::UInt64)
}
fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
Ok(false)
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
if self.router.split_points().is_empty() {
return Ok(ColumnarValue::Scalar(ScalarValue::UInt64(Some(0))));
}
let arrays = evaluate_expressions_to_arrays(self.on_columns.iter(), batch)?;
let mut partition_ids = Vec::with_capacity(batch.num_rows());
self.router
.route_partition_ids(&arrays, &mut partition_ids)?;
Ok(ColumnarValue::Array(Arc::new(UInt64Array::from(
partition_ids,
))))
}
fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "range_partition")
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
) -> Result<Option<protobuf::PhysicalExprNode>> {
let Self { on_columns, router } = self;
let sort_exprs = on_columns
.iter()
.zip(router.sort_options())
.map(|(expr, options)| PhysicalSortExpr::new(Arc::clone(expr), *options))
.collect::<Vec<_>>();
let sort_expr = sort_exprs_try_to_proto(&sort_exprs, ctx)?;
let split_point = router
.split_points()
.iter()
.map(|split_point| {
let value = split_point
.values()
.iter()
.map(|value| value.try_into().map_err(Into::into))
.collect::<Result<Vec<_>>>()?;
Ok(protobuf::PhysicalRangeSplitPoint { value })
})
.collect::<Result<Vec<_>>>()?;
Ok(Some(protobuf::PhysicalExprNode {
expr_id: None,
expr_type: Some(protobuf::physical_expr_node::ExprType::RangeExpr(
protobuf::PhysicalRangeExprNode {
sort_expr,
split_point,
},
)),
}))
}
}
#[cfg(feature = "proto")]
impl RangeExpr {
pub fn try_from_proto(
node: &protobuf::PhysicalExprNode,
ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
) -> Result<PhysicalExprRef> {
let protobuf::PhysicalExprNode {
expr_id: _,
expr_type,
} = node;
let Some(protobuf::physical_expr_node::ExprType::RangeExpr(range_expr)) =
expr_type
else {
return internal_err!("PhysicalExprNode is not a RangeExpr");
};
let protobuf::PhysicalRangeExprNode {
sort_expr,
split_point,
} = range_expr;
let sort_exprs = sort_exprs_try_from_proto(sort_expr, ctx)?;
let (on_columns, sort_options): (Vec<PhysicalExprRef>, Vec<SortOptions>) =
sort_exprs
.into_iter()
.map(|sort_expr| (sort_expr.expr, sort_expr.options))
.unzip();
let split_points = split_point
.iter()
.map(|split_point| {
let protobuf::PhysicalRangeSplitPoint { value } = split_point;
let values = value
.iter()
.map(|value| ScalarValue::try_from(value).map_err(Into::into))
.collect::<Result<Vec<_>>>()?;
Ok(SplitPoint::new(values))
})
.collect::<Result<Vec<_>>>()?;
Ok(Arc::new(Self::try_new_parts(
on_columns,
&split_points,
&sort_options,
ctx.schema(),
)?))
}
}
#[derive(Debug, Clone, Copy)]
enum StrengthReducedU64 {
PowerOfTwo { mask: u64 },
Reciprocal { divisor: u64, reciprocal: u128 },
}
impl StrengthReducedU64 {
fn new(divisor: u64) -> Self {
debug_assert!(divisor > 0);
if divisor.is_power_of_two() {
Self::PowerOfTwo { mask: divisor - 1 }
} else {
Self::Reciprocal {
divisor,
reciprocal: u128::MAX / u128::from(divisor) + 1,
}
}
}
fn partition_indices(self, hash_buffer: &[u64], indices: &mut [Vec<u32>]) {
match self {
Self::PowerOfTwo { mask } => {
for (index, hash) in hash_buffer.iter().enumerate() {
indices[(*hash & mask) as usize].push(index as u32);
}
}
Self::Reciprocal {
divisor,
reciprocal,
} => {
for (index, hash) in hash_buffer.iter().enumerate() {
let quotient = Self::quotient(*hash, reciprocal);
let partition = *hash - quotient * divisor;
indices[partition as usize].push(index as u32);
}
}
}
}
#[cfg(test)]
fn remainder(self, value: u64) -> u64 {
match self {
Self::PowerOfTwo { mask } => value & mask,
Self::Reciprocal {
divisor,
reciprocal,
} => value - Self::quotient(value, reciprocal) * divisor,
}
}
#[inline]
fn quotient(value: u64, reciprocal: u128) -> u64 {
let reciprocal_low = reciprocal as u64;
let reciprocal_high = (reciprocal >> 64) as u64;
let low_product = u128::from(value) * u128::from(reciprocal_low);
let high_product = u128::from(value) * u128::from(reciprocal_high);
let carry = ((high_product & u128::from(u64::MAX)) + (low_product >> 64)) >> 64;
((high_product >> 64) + carry) as u64
}
}
impl BatchPartitioner {
pub fn new_hash_partitioner(
exprs: Vec<Arc<dyn PhysicalExpr>>,
num_partitions: usize,
timer: metrics::Time,
) -> Result<Self> {
if num_partitions == 0 {
return internal_err!("Hash repartition requires at least one partition");
}
Ok(Self {
state: BatchPartitionerState::Hash {
exprs,
partition_reducer: StrengthReducedU64::new(num_partitions as u64),
hash_buffer: vec![],
indices: vec![vec![]; num_partitions],
},
timer,
})
}
pub fn new_round_robin_partitioner(
num_partitions: usize,
timer: metrics::Time,
input_partition: usize,
num_input_partitions: usize,
) -> Self {
Self {
state: BatchPartitionerState::RoundRobin {
num_partitions,
next_idx: (input_partition * num_partitions) / num_input_partitions,
},
timer,
}
}
pub fn try_new_range_partitioner(
range_partitioning: &RangePartitioning,
schema: &Schema,
timer: metrics::Time,
) -> Result<Self> {
let ordering = range_partitioning.ordering().clone();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
let data_types = ordering
.iter()
.map(|e| e.expr.data_type(schema))
.collect::<Result<Vec<_>>>()?;
let router = Arc::new(RangeRouter::try_new_with_data_types(
&sort_options,
range_partitioning.split_points(),
&data_types,
)?);
Ok(Self::new_range_partitioner_with_router(
ordering,
router,
num_partitions,
timer,
))
}
#[deprecated(
since = "56.0.0",
note = "Use try_new_range_partitioner with schema instead"
)]
pub fn new_range_partitioner(
range_partitioning: &RangePartitioning,
timer: metrics::Time,
) -> Self {
let ordering = range_partitioning.ordering().clone();
let num_partitions = range_partitioning.partition_count();
let sort_options: Vec<SortOptions> = ordering.iter().map(|e| e.options).collect();
let router = Arc::new(
RangeRouter::try_new(&sort_options, range_partitioning.split_points())
.expect("valid range partitioning"),
);
Self::new_range_partitioner_with_router(ordering, router, num_partitions, timer)
}
pub(crate) fn new_range_partitioner_with_router(
ordering: LexOrdering,
router: Arc<RangeRouter>,
num_partitions: usize,
timer: metrics::Time,
) -> Self {
Self {
state: BatchPartitionerState::Range {
ordering,
router,
indices: vec![vec![]; num_partitions],
},
timer,
}
}
pub fn try_new(
partitioning: Partitioning,
timer: metrics::Time,
input_partition: usize,
num_input_partitions: usize,
) -> Result<Self> {
match partitioning {
Partitioning::Hash(exprs, num_partitions) => {
Self::new_hash_partitioner(exprs, num_partitions, timer)
}
Partitioning::RoundRobinBatch(num_partitions) => {
Ok(Self::new_round_robin_partitioner(
num_partitions,
timer,
input_partition,
num_input_partitions,
))
}
Partitioning::Range(range_repartitioning) =>
{
#[expect(deprecated)]
Ok(Self::new_range_partitioner(&range_repartitioning, timer))
}
other => {
not_impl_err!("Unsupported repartitioning scheme {other:?}")
}
}
}
pub fn partition<F>(&mut self, batch: RecordBatch, mut f: F) -> Result<()>
where
F: FnMut(usize, RecordBatch) -> Result<()>,
{
self.partition_iter(batch)?.try_for_each(|res| match res {
Ok((partition, batch)) => f(partition, batch),
Err(e) => Err(e),
})
}
pub fn partition_iter(
&mut self,
batch: RecordBatch,
) -> Result<impl Iterator<Item = Result<(usize, RecordBatch)>> + Send + '_> {
let it: Box<dyn Iterator<Item = Result<(usize, RecordBatch)>> + Send> =
match &mut self.state {
BatchPartitionerState::RoundRobin {
num_partitions,
next_idx,
} => {
let idx = *next_idx;
*next_idx = (*next_idx + 1) % *num_partitions;
Box::new(std::iter::once(Ok((idx, batch))))
}
BatchPartitionerState::Hash {
exprs,
partition_reducer,
hash_buffer,
indices,
} => {
let timer = self.timer.timer();
let arrays =
evaluate_expressions_to_arrays(exprs.as_slice(), &batch)?;
hash_buffer.clear();
hash_buffer.resize(batch.num_rows(), 0);
create_hashes(
&arrays,
REPARTITION_RANDOM_STATE.random_state(),
hash_buffer,
)?;
for v in indices.iter_mut() {
v.clear();
}
partition_reducer.partition_indices(hash_buffer, indices);
timer.done();
let partitioned_batches =
Self::partition_grouped_take(&batch, indices, &self.timer)?;
Box::new(partitioned_batches.into_iter())
}
BatchPartitionerState::Range {
ordering,
router,
indices,
} => {
let timer = self.timer.timer();
if router.num_split_points() == 0 {
timer.done();
Box::new(std::iter::once(Ok((0, batch))))
} else {
let arrays = evaluate_expressions_to_arrays(
ordering.iter().map(|e| &e.expr),
&batch,
)?;
for v in indices.iter_mut() {
v.clear();
}
router.route_indices(&arrays, indices)?;
timer.done();
let partitioned_batches =
Self::partition_grouped_take(&batch, indices, &self.timer)?;
Box::new(partitioned_batches.into_iter())
}
}
};
Ok(it)
}
fn num_partitions(&self) -> usize {
match &self.state {
BatchPartitionerState::RoundRobin { num_partitions, .. } => *num_partitions,
BatchPartitionerState::Hash { indices, .. }
| BatchPartitionerState::Range { indices, .. } => indices.len(),
}
}
fn partition_grouped_take(
batch: &RecordBatch,
indices: &mut [Vec<u32>],
timer: &metrics::Time,
) -> Result<Vec<Result<(usize, RecordBatch)>>> {
let mut partition_ranges = Vec::with_capacity(indices.len());
let mut reordered_indices = Vec::with_capacity(batch.num_rows());
for (partition, p_indices) in indices.iter_mut().enumerate() {
if p_indices.is_empty() {
continue;
}
let start = reordered_indices.len();
reordered_indices.extend_from_slice(p_indices);
partition_ranges.push((partition, start, p_indices.len()));
p_indices.clear();
}
if reordered_indices.is_empty() {
return Ok(vec![]);
}
if partition_ranges.len() == 1 && partition_ranges[0].2 == batch.num_rows() {
let (partition, _, _) = partition_ranges[0];
return Ok(vec![Ok((partition, batch.clone()))]);
}
let batches = {
let _timer = timer.timer();
let indices_array: PrimitiveArray<UInt32Type> = reordered_indices.into();
let columns = take_arrays(batch.columns(), &indices_array, None)?;
let mut options = RecordBatchOptions::new();
options = options.with_row_count(Some(indices_array.len()));
let reordered_batch =
RecordBatch::try_new_with_options(batch.schema(), columns, &options)?;
partition_ranges
.into_iter()
.map(|(partition, start, len)| {
Ok((partition, reordered_batch.slice(start, len)))
})
.collect()
};
Ok(batches)
}
}
#[derive(Debug, Clone)]
pub struct RepartitionExec {
input: Arc<dyn ExecutionPlan>,
state: Arc<Mutex<RepartitionExecState>>,
metrics: ExecutionPlanMetricsSet,
preserve_order: bool,
cache: Arc<PlanProperties>,
batch_size: Option<usize>,
}
#[derive(Debug, Clone)]
struct RepartitionMetrics {
fetch_time: metrics::Time,
repartition_time: metrics::Time,
send_time: Vec<metrics::Time>,
}
impl RepartitionMetrics {
pub fn new(
input_partition: usize,
num_output_partitions: usize,
metrics: &ExecutionPlanMetricsSet,
) -> Self {
let fetch_time =
MetricBuilder::new(metrics).subset_time("fetch_time", input_partition);
let repartition_time =
MetricBuilder::new(metrics).subset_time("repartition_time", input_partition);
let send_time = (0..num_output_partitions)
.map(|output_partition| {
let label =
metrics::Label::new("outputPartition", output_partition.to_string());
MetricBuilder::new(metrics)
.with_label(label)
.subset_time("send_time", input_partition)
})
.collect();
Self {
fetch_time,
repartition_time,
send_time,
}
}
}
impl RepartitionExec {
pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
&self.input
}
pub fn partitioning(&self) -> &Partitioning {
&self.cache.partitioning
}
pub fn preserve_order(&self) -> bool {
self.preserve_order
}
pub fn name(&self) -> &str {
"RepartitionExec"
}
}
impl DisplayAs for RepartitionExec {
fn fmt_as(&self, t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result {
let input_partition_count = self.input.output_partitioning().partition_count();
match t {
DisplayFormatType::Default | DisplayFormatType::Verbose => {
write!(
f,
"{}: partitioning={}, input_partitions={}",
self.name(),
self.partitioning(),
input_partition_count,
)?;
if self.preserve_order {
write!(f, ", preserve_order=true")?;
} else if input_partition_count <= 1
&& self.input.output_ordering().is_some()
{
write!(f, ", maintains_sort_order=true")?;
}
if let Some(sort_exprs) = self.sort_exprs() {
write!(f, ", sort_exprs={}", sort_exprs.clone())?;
}
}
DisplayFormatType::TreeRender => {
writeln!(f, "partitioning_scheme={}", self.partitioning())?;
let output_partition_count = self.partitioning().partition_count();
let input_to_output_partition_str =
format!("{input_partition_count} -> {output_partition_count}");
writeln!(
f,
"partition_count(in->out)={input_to_output_partition_str}"
)?;
if self.preserve_order {
writeln!(f, "preserve_order={}", self.preserve_order)?;
}
}
}
Ok(())
}
}
impl ExecutionPlan for RepartitionExec {
fn name(&self) -> &'static str {
"RepartitionExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.input]
}
fn apply_expressions(
&self,
f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
match self.partitioning() {
Partitioning::Hash(exprs, _) => crate::apply_expression_roots(exprs, f),
Partitioning::Range(range) => crate::apply_expression_roots(
range.ordering().iter().map(|sort_expr| &sort_expr.expr),
f,
),
_ => Ok(TreeNodeRecursion::Continue),
}
}
fn replace_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
validate_child_count!(self, children);
match options.children_properties {
ChildrenPropertiesMode::Keep => Ok(Arc::new(Self {
input: children.swap_remove(0),
metrics: ExecutionPlanMetricsSet::new(),
state: Default::default(),
..Self::clone(&*self)
})),
ChildrenPropertiesMode::Recompute => {
let mut repartition = RepartitionExec::try_new(
children.swap_remove(0),
self.partitioning().clone(),
)?;
if self.preserve_order {
repartition = repartition.with_preserve_order();
}
Ok(Arc::new(repartition))
}
}
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn with_new_children_and_same_properties(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
)
}
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![matches!(self.partitioning(), Partitioning::Hash(_, _))]
}
fn maintains_input_order(&self) -> Vec<bool> {
Self::maintains_input_order_helper(self.input(), self.preserve_order)
}
fn execute(
&self,
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
trace!(
"Start {}::execute for partition: {}",
self.name(),
partition
);
let spill_metrics = SpillMetrics::new(&self.metrics, partition);
let input = Arc::clone(&self.input);
let partitioning = self.partitioning().clone();
let metrics = self.metrics.clone();
let preserve_order = self.sort_exprs().is_some();
let name = self.name().to_owned();
let schema = self.schema();
let schema_captured = Arc::clone(&schema);
let coalescer_batch_size = self
.batch_size
.unwrap_or_else(|| context.session_config().batch_size());
let spill_manager = SpillManager::new(
Arc::clone(&context.runtime_env()),
spill_metrics,
input.schema(),
)
.with_compression_type(context.session_config().spill_compression());
let sort_exprs = self.sort_exprs().cloned();
let state = Arc::clone(&self.state);
if let Some(mut state) = state.try_lock() {
state.ensure_input_streams_initialized(
&input,
&metrics,
partitioning.partition_count(),
&context,
)?;
}
let num_input_partitions = input.output_partitioning().partition_count();
let stream = futures::stream::once(async move {
let (rx, reservation, spill_readers, abort_helper) = {
let mut state = state.lock();
let state = state.consume_input_streams(
&input,
&metrics,
&partitioning,
preserve_order,
&name,
&context,
spill_manager.clone(),
coalescer_batch_size,
)?;
let PartitionChannels {
rx,
reservation,
spill_readers,
..
} = state
.channels
.remove(&partition)
.expect("partition not used yet");
(
rx,
reservation,
spill_readers,
Arc::clone(&state.abort_helper),
)
};
trace!(
"Before returning stream in {name}::execute for partition: {partition}"
);
if preserve_order {
let input_streams = rx
.into_iter()
.zip(spill_readers)
.map(|(receiver, spill_stream)| {
Box::pin(PerPartitionStream::new(
Arc::clone(&schema_captured),
receiver,
Arc::clone(&abort_helper),
Arc::clone(&reservation),
spill_stream,
1, None,
)) as SendableRecordBatchStream
})
.collect::<Vec<_>>();
let fetch = None;
let merge_reservation =
MemoryConsumer::new(format!("{name}[Merge {partition}]"))
.register(context.memory_pool());
StreamingMergeBuilder::new()
.with_streams(input_streams)
.with_schema(schema_captured)
.with_expressions(&sort_exprs.unwrap())
.with_metrics(BaselineMetrics::new(&metrics, partition))
.with_batch_size(context.session_config().batch_size())
.with_fetch(fetch)
.with_reservation(merge_reservation)
.with_spill_manager(spill_manager)
.build()
} else {
let spill_stream = spill_readers
.into_iter()
.next()
.expect("at least one spill reader should exist");
Ok(Box::pin(PerPartitionStream::new(
schema_captured,
rx.into_iter()
.next()
.expect("at least one receiver should exist"),
abort_helper,
reservation,
spill_stream,
num_input_partitions,
Some(BaselineMetrics::new(&metrics, partition)),
)) as SendableRecordBatchStream)
}
})
.try_flatten();
let stream = RecordBatchStreamAdapter::new(schema, stream);
Ok(Box::pin(stream))
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner().with_output_rows_skew())
}
fn child_stats_requests(&self, _partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(None)]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
if args.partition().is_some() {
let partition_count = self.partitioning().partition_count();
assert_or_internal_err!(
partition_count > 0,
"RepartitionExec statistics requested for a partition but the partition count is 0"
);
let mut stats = input_stats[0].as_ref().clone();
stats.num_rows = stats
.num_rows
.get_value()
.map(|rows| Precision::Inexact(rows / partition_count))
.unwrap_or(Precision::Absent);
stats.total_byte_size = stats
.total_byte_size
.get_value()
.map(|bytes| Precision::Inexact(bytes / partition_count))
.unwrap_or(Precision::Absent);
stats.column_statistics = stats
.column_statistics
.iter()
.map(|_| ColumnStatistics::new_unknown())
.collect();
Ok(Arc::new(stats))
} else {
Ok(Arc::clone(&input_stats[0]))
}
}
fn cardinality_effect(&self) -> CardinalityEffect {
CardinalityEffect::Equal
}
fn try_swapping_with_projection(
&self,
projection: &ProjectionExec,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
if projection.expr().len() >= projection.input().schema().fields().len() {
return Ok(None);
}
if projection.benefits_from_input_partitioning()[0]
|| !all_columns(projection.expr())
{
return Ok(None);
}
let new_projection = make_with_child(projection, self.input())?;
let new_partitioning = match self.partitioning() {
Partitioning::Hash(partitions, size) => {
let mut new_partitions = Vec::with_capacity(partitions.len());
for partition in partitions {
let Some(new_partition) =
update_expr(partition, projection.expr(), false)?
else {
return Ok(None);
};
new_partitions.push(new_partition);
}
Partitioning::Hash(new_partitions, *size)
}
Partitioning::Range(range_partitioning) => {
let mut sort_exprs =
Vec::with_capacity(range_partitioning.ordering().len());
for sort_expr in range_partitioning.ordering() {
let Some(new_expr) =
update_expr(&sort_expr.expr, projection.expr(), false)?
else {
return Ok(None);
};
sort_exprs.push(PhysicalSortExpr::new(new_expr, sort_expr.options));
}
let Some(ordering) = LexOrdering::new(sort_exprs) else {
return internal_err!(
"failed to create LexOrdering for range partitioning"
);
};
Partitioning::Range(RangePartitioning::try_new_with_samples(
ordering,
range_partitioning.samples().to_vec(),
range_partitioning.partition_count(),
)?)
}
others => others.clone(),
};
Ok(Some(Arc::new(RepartitionExec::try_new(
new_projection,
new_partitioning,
)?)))
}
fn gather_filters_for_pushdown(
&self,
_phase: FilterPushdownPhase,
parent_filters: Vec<Arc<dyn PhysicalExpr>>,
_config: &ConfigOptions,
) -> Result<FilterDescription> {
FilterDescription::from_children(parent_filters, &self.children())
}
fn handle_child_pushdown_result(
&self,
_phase: FilterPushdownPhase,
child_pushdown_result: ChildPushdownResult,
_config: &ConfigOptions,
) -> Result<FilterPushdownPropagation<Arc<dyn ExecutionPlan>>> {
Ok(FilterPushdownPropagation::if_all(child_pushdown_result))
}
fn try_pushdown_sort(
&self,
order: &[PhysicalSortExpr],
) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
if !self.maintains_input_order()[0] {
return Ok(SortOrderPushdownResult::Unsupported);
}
self.input.try_pushdown_sort(order)?.try_map(|new_input| {
let mut new_repartition =
RepartitionExec::try_new(new_input, self.partitioning().clone())?;
if self.preserve_order {
new_repartition = new_repartition.with_preserve_order();
}
Ok(Arc::new(new_repartition) as Arc<dyn ExecutionPlan>)
})
}
fn repartitioned(
&self,
target_partitions: usize,
_config: &ConfigOptions,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
use Partitioning::*;
let mut new_properties = PlanProperties::clone(&self.cache);
new_properties.partitioning = match new_properties.partitioning {
RoundRobinBatch(_) => RoundRobinBatch(target_partitions),
Hash(hash, _) => Hash(hash, target_partitions),
Range(range) => {
let Some(range) = range.scale(target_partitions) else {
return Ok(None);
};
let mut repartition =
Self::try_new(Arc::clone(&self.input), Range(range))?;
if self.preserve_order {
repartition = repartition.with_preserve_order();
}
repartition.batch_size = self.batch_size;
return Ok(Some(Arc::new(repartition)));
}
UnknownPartitioning(_) => UnknownPartitioning(target_partitions),
};
Ok(Some(Arc::new(Self {
input: Arc::clone(&self.input),
state: Arc::clone(&self.state),
metrics: self.metrics.clone(),
preserve_order: self.preserve_order,
cache: new_properties.into(),
batch_size: self.batch_size,
})))
}
#[cfg(feature = "proto")]
fn try_to_proto(
&self,
ctx: &crate::proto::ExecutionPlanEncodeCtx<'_>,
) -> Result<Option<protobuf::PhysicalPlanNode>> {
let Self {
input,
state: _,
metrics: _,
preserve_order,
cache,
batch_size: _,
} = self;
let input = ctx.encode_child(input)?;
let partitioning = cache.partitioning.try_to_proto(&ctx.expr_ctx())?;
Ok(Some(protobuf::PhysicalPlanNode {
physical_plan_type: Some(
protobuf::physical_plan_node::PhysicalPlanType::Repartition(Box::new(
protobuf::RepartitionExecNode {
input: Some(Box::new(input)),
partitioning: Some(partitioning),
preserve_order: *preserve_order,
},
)),
),
}))
}
}
#[cfg(feature = "proto")]
impl RepartitionExec {
pub fn try_from_proto(
node: &protobuf::PhysicalPlanNode,
ctx: &crate::proto::ExecutionPlanDecodeCtx<'_>,
) -> Result<Arc<dyn ExecutionPlan>> {
let repart = crate::expect_plan_variant!(
node,
protobuf::physical_plan_node::PhysicalPlanType::Repartition,
"RepartitionExec",
);
let protobuf::RepartitionExecNode {
input,
partitioning,
preserve_order,
} = &**repart;
let input =
ctx.decode_required_child(input.as_deref(), "RepartitionExec", "input")?;
let input_schema = input.schema();
let partitioning = partitioning
.as_ref()
.map(|partitioning| {
Partitioning::try_from_proto(
partitioning,
&ctx.expr_ctx(input_schema.as_ref()),
)
})
.transpose()?
.flatten()
.ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"RepartitionExec is missing required field 'partitioning'"
)
})?;
let mut repart_exec = RepartitionExec::try_new(input, partitioning)?;
if *preserve_order {
repart_exec = repart_exec.with_preserve_order();
}
Ok(Arc::new(repart_exec))
}
}
impl RepartitionExec {
pub fn try_new(
input: Arc<dyn ExecutionPlan>,
partitioning: Partitioning,
) -> Result<Self> {
let preserve_order = false;
let cache = Self::compute_properties(&input, partitioning, preserve_order);
Ok(RepartitionExec {
input,
state: Default::default(),
metrics: ExecutionPlanMetricsSet::new(),
preserve_order,
cache: Arc::new(cache),
batch_size: None,
})
}
fn maintains_input_order_helper(
input: &Arc<dyn ExecutionPlan>,
preserve_order: bool,
) -> Vec<bool> {
vec![preserve_order || input.output_partitioning().partition_count() <= 1]
}
fn eq_properties_helper(
input: &Arc<dyn ExecutionPlan>,
preserve_order: bool,
) -> EquivalenceProperties {
let mut eq_properties = input.equivalence_properties().clone();
if input.output_partitioning().partition_count() > 1 {
eq_properties.clear_orderings();
eq_properties.clear_per_partition_constants();
if preserve_order && let Some(ordering) = input.output_ordering() {
eq_properties.add_ordering(ordering.clone());
}
}
eq_properties
}
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
partitioning: Partitioning,
preserve_order: bool,
) -> PlanProperties {
PlanProperties::new(
Self::eq_properties_helper(input, preserve_order),
partitioning,
input.pipeline_behavior(),
input.boundedness(),
)
.with_scheduling_type(SchedulingType::Cooperative)
.with_evaluation_type(EvaluationType::Eager)
}
pub fn with_preserve_order(mut self) -> Self {
self.preserve_order =
self.input.output_ordering().is_some() &&
self.input.output_partitioning().partition_count() > 1;
let eq_properties = Self::eq_properties_helper(&self.input, self.preserve_order);
Arc::make_mut(&mut self.cache).set_eq_properties(eq_properties);
self
}
pub fn with_batch_size(mut self, batch_size: usize) -> Result<Self> {
if batch_size == 0 {
return internal_err!("batch_size must be greater than zero");
}
self.batch_size = Some(batch_size);
Ok(self)
}
fn sort_exprs(&self) -> Option<&LexOrdering> {
if self.preserve_order {
self.input.output_ordering()
} else {
None
}
}
async fn pull_from_input(
mut stream: SendableRecordBatchStream,
mut output_channels: HashMap<usize, OutputChannel>,
partitioning: Partitioning,
range_router: Option<Arc<RangeRouter>>,
metrics: RepartitionMetrics,
input_partition: usize,
num_input_partitions: usize,
) -> Result<()> {
let mut partitioner = match (partitioning, range_router) {
(Partitioning::Range(range_partitioning), Some(router)) => {
let ordering = range_partitioning.ordering().clone();
let num_partitions = range_partitioning.partition_count();
BatchPartitioner::new_range_partitioner_with_router(
ordering,
router,
num_partitions,
metrics.repartition_time.clone(),
)
}
(partitioning, _) => BatchPartitioner::try_new(
partitioning,
metrics.repartition_time.clone(),
input_partition,
num_input_partitions,
)?,
};
let mut batches_until_yield = partitioner.num_partitions();
let mut coalesced = Vec::new();
while !output_channels.is_empty() {
let timer = metrics.fetch_time.timer();
let result = stream.next().await;
timer.done();
let batch = match result {
Some(result) => result?,
None => break,
};
if batch.num_rows() == 0 {
continue;
}
for res in partitioner.partition_iter(batch)? {
let (partition, batch) = res?;
let timer = metrics.send_time[partition].timer();
if let Some(output_channel) = output_channels.get_mut(&partition) {
output_channel.coalesce(batch, &mut coalesced)?;
for batch in coalesced.drain(..) {
if output_channel.send(batch).await.is_err() {
output_channels.remove(&partition);
break;
}
}
}
timer.done();
}
if batches_until_yield == 0 {
tokio::task::yield_now().await;
batches_until_yield = partitioner.num_partitions();
} else {
batches_until_yield -= 1;
}
}
for (_, output_channel) in output_channels.drain() {
output_channel.finalize().await?;
}
Ok(())
}
async fn wait_for_task(
input_task: SpawnedTask<Result<()>>,
txs: HashMap<usize, DistributionSender<MaybeBatch>>,
) {
match input_task.join().await {
Err(e) => {
let e = Arc::new(e);
for (_, tx) in txs {
let err = Err(DataFusionError::Context(
"Join Error".to_string(),
Box::new(DataFusionError::External(Box::new(Arc::clone(&e)))),
));
tx.send(Some(err)).await.ok();
}
}
Ok(Err(e)) => {
let e = Arc::new(e);
for (_, tx) in txs {
let err = Err(DataFusionError::from(&e));
tx.send(Some(err)).await.ok();
}
}
Ok(Ok(())) => {
for (_partition, tx) in txs {
tx.send(None).await.ok();
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StreamState {
ReadingMemory,
ReadingSpilled,
}
struct PerPartitionStream {
schema: SchemaRef,
receiver: DistributionReceiver<MaybeBatch>,
_drop_helper: Arc<Vec<SpawnedTask<()>>>,
reservation: SharedMemoryReservation,
spill_stream: SendableRecordBatchStream,
state: StreamState,
remaining_partitions: usize,
baseline_metrics: Option<BaselineMetrics>,
}
impl PerPartitionStream {
fn new(
schema: SchemaRef,
receiver: DistributionReceiver<MaybeBatch>,
drop_helper: Arc<Vec<SpawnedTask<()>>>,
reservation: SharedMemoryReservation,
spill_stream: SendableRecordBatchStream,
num_input_partitions: usize,
baseline_metrics: Option<BaselineMetrics>,
) -> Self {
Self {
schema,
receiver,
_drop_helper: drop_helper,
reservation,
spill_stream,
state: StreamState::ReadingMemory,
remaining_partitions: num_input_partitions,
baseline_metrics,
}
}
fn poll_next_inner(
self: &mut Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<RecordBatch>>> {
use futures::StreamExt;
let elapsed = self
.baseline_metrics
.as_ref()
.map(|m| m.elapsed_compute().clone());
let _timer = elapsed.as_ref().map(|t| t.timer());
loop {
match self.state {
StreamState::ReadingMemory => {
let value = match self.receiver.recv().poll_unpin(cx) {
Poll::Ready(v) => v,
Poll::Pending => {
return Poll::Pending;
}
};
match value {
Some(Some(v)) => match v {
Ok(RepartitionBatch::Memory(batch)) => {
self.reservation.shrink(batch.get_array_memory_size());
return Poll::Ready(Some(Ok(batch)));
}
Ok(RepartitionBatch::Spilled) => {
self.state = StreamState::ReadingSpilled;
}
Err(e) => {
return Poll::Ready(Some(Err(e)));
}
},
Some(None) => {
self.remaining_partitions -= 1;
if self.remaining_partitions == 0 {
return Poll::Ready(None);
}
}
None => {
return Poll::Ready(None);
}
}
}
StreamState::ReadingSpilled => {
match self.spill_stream.poll_next_unpin(cx) {
Poll::Ready(Some(Ok(batch))) => {
self.state = StreamState::ReadingMemory;
return Poll::Ready(Some(Ok(batch)));
}
Poll::Ready(Some(Err(e))) => {
return Poll::Ready(Some(Err(e)));
}
Poll::Ready(None) => {
let spill_schema = self.spill_stream.schema();
self.spill_stream =
Box::pin(EmptyRecordBatchStream::new(spill_schema));
self.state = StreamState::ReadingMemory;
}
Poll::Pending => {
return Poll::Pending;
}
}
}
}
}
}
}
impl Stream for PerPartitionStream {
type Item = Result<RecordBatch>;
fn poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let poll = self.poll_next_inner(cx);
if let Some(metrics) = &self.baseline_metrics {
metrics.record_poll(poll)
} else {
poll
}
}
}
impl RecordBatchStream for PerPartitionStream {
fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
use crate::empty::EmptyExec;
use crate::projection::ProjectionExpr;
use crate::streaming::{PartitionStream, StreamingTableExec};
use crate::test::TestMemoryExec;
use crate::{
test::{
assert_is_pending,
exec::{
BarrierExec, BlockingExec, ErrorExec, MockExec,
assert_strong_count_converges_to_zero,
},
},
{collect, expressions::col},
};
use arrow::array::{
Array, ArrayRef, Decimal128Array, Int64Array, StringArray,
TimestampNanosecondArray, UInt32Array,
};
use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion_common::ScalarValue;
use datafusion_common::cast::{as_string_array, as_uint32_array};
use datafusion_common::config::SpillCompression;
use datafusion_common::exec_err;
use datafusion_common::test_util::batches_to_sort_string;
use datafusion_common_runtime::JoinSet;
use datafusion_execution::config::SessionConfig;
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_physical_expr::{
LexOrdering, PhysicalSortExpr, RangePartitioning, SplitPoint,
};
use insta::assert_snapshot;
#[derive(Debug)]
struct UnboundedTestPartition {
schema: SchemaRef,
batch: RecordBatch,
}
impl PartitionStream for UnboundedTestPartition {
fn schema(&self) -> &SchemaRef {
&self.schema
}
fn execute(&self, _ctx: Arc<TaskContext>) -> SendableRecordBatchStream {
let stream = futures::stream::iter([Ok(self.batch.clone())])
.chain(futures::stream::pending());
Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&self.schema),
stream,
))
}
}
#[test]
fn range_expr_preserves_duplicate_remapped_children() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, false),
Field::new("b", DataType::UInt32, false),
]));
let sort_options = [SortOptions::new(false, false), SortOptions::new(true, true)];
let split_points = vec![SplitPoint::new(vec![
ScalarValue::UInt32(Some(10)),
ScalarValue::UInt32(Some(20)),
])];
let range_partitioning = RangePartitioning::try_new(
[
PhysicalSortExpr::new(col("a", &schema)?, sort_options[0]),
PhysicalSortExpr::new(col("b", &schema)?, sort_options[1]),
]
.into(),
split_points.clone(),
)?;
let expr = Arc::new(RangeExpr::try_new_with_schema(
vec![col("a", &schema)?, col("b", &schema)?],
&range_partitioning,
&schema,
)?);
let remapped = col("a", &schema)?;
let rewritten =
expr.with_new_children(vec![Arc::clone(&remapped), Arc::clone(&remapped)])?;
let rewritten = rewritten
.downcast_ref::<RangeExpr>()
.expect("rewritten expression should remain a RangeExpr");
assert_eq!(rewritten.on_columns().len(), 2);
assert!(Arc::ptr_eq(
&rewritten.on_columns()[0],
&rewritten.on_columns()[1]
));
assert_eq!(rewritten.sort_options(), sort_options);
assert_eq!(rewritten.split_points(), split_points);
Ok(())
}
#[test]
fn strength_reduced_u64_remainder_matches_modulo() {
let divisors = [
1,
2,
3,
4,
5,
7,
8,
10,
16,
31,
32,
63,
64,
65,
97,
u64::from(u32::MAX),
u64::from(u32::MAX) + 1,
1_u64 << 32,
(1_u64 << 63) - 1,
1_u64 << 63,
u64::MAX - 1,
u64::MAX,
];
let values = [
0,
1,
2,
3,
4,
5,
31,
32,
33,
63,
64,
65,
u64::from(u32::MAX) - 1,
u64::from(u32::MAX),
u64::from(u32::MAX) + 1,
(1_u64 << 32) - 1,
1_u64 << 32,
(1_u64 << 32) + 1,
(1_u64 << 63) - 1,
1_u64 << 63,
(1_u64 << 63) + 1,
u64::MAX - 1,
u64::MAX,
];
for divisor in divisors {
let reducer = StrengthReducedU64::new(divisor);
for value in values {
assert_eq!(
reducer.remainder(value),
value % divisor,
"value={value} divisor={divisor}"
);
}
let mut value = 0x1234_5678_9abc_def0 ^ divisor;
for _ in 0..10_000 {
value = value
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
assert_eq!(
reducer.remainder(value),
value % divisor,
"value={value} divisor={divisor}"
);
}
}
}
#[test]
fn hash_partitioner_requires_nonzero_partitions() {
let metrics = ExecutionPlanMetricsSet::new();
let timer = MetricBuilder::new(&metrics).subset_time("test", 0);
let err = BatchPartitioner::new_hash_partitioner(vec![], 0, timer)
.err()
.expect("zero hash partitions should fail")
.to_string();
assert!(
err.contains("Hash repartition requires at least one partition"),
"actual: {err}"
);
}
#[tokio::test]
async fn one_to_many_round_robin() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition];
let output_partitions =
repartition(&schema, partitions, Partitioning::RoundRobinBatch(4)).await?;
assert_eq!(4, output_partitions.len());
for partition in &output_partitions {
assert_eq!(1, partition.len());
}
assert_eq!(13 * 8, output_partitions[0][0].num_rows());
assert_eq!(13 * 8, output_partitions[1][0].num_rows());
assert_eq!(12 * 8, output_partitions[2][0].num_rows());
assert_eq!(12 * 8, output_partitions[3][0].num_rows());
Ok(())
}
#[tokio::test]
async fn many_to_one_round_robin() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone(), partition.clone()];
let output_partitions =
repartition(&schema, partitions, Partitioning::RoundRobinBatch(1)).await?;
assert_eq!(1, output_partitions.len());
assert_eq!(150 * 8, output_partitions[0][0].num_rows());
Ok(())
}
#[tokio::test]
async fn many_to_many_round_robin() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone(), partition.clone()];
let output_partitions =
repartition(&schema, partitions, Partitioning::RoundRobinBatch(5)).await?;
let total_rows_per_partition = 8 * 50 * 3 / 5;
assert_eq!(5, output_partitions.len());
for partition in output_partitions {
assert_eq!(1, partition.len());
assert_eq!(total_rows_per_partition, partition[0].num_rows());
}
Ok(())
}
#[tokio::test]
async fn many_to_many_hash_partition() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone(), partition.clone()];
let output_partitions = repartition(
&schema,
partitions,
Partitioning::Hash(vec![col("c0", &schema)?], 8),
)
.await?;
let total_rows: usize = output_partitions
.iter()
.map(|x| x.iter().map(|x| x.num_rows()).sum::<usize>())
.sum();
assert_eq!(8, output_partitions.len());
assert_eq!(total_rows, 8 * 50 * 3);
Ok(())
}
#[tokio::test]
async fn many_to_many_range_partition() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone(), partition.clone()];
let partitioning =
u32_range_partitioning(&schema, SortOptions::default(), vec![3, 6])?;
let output_partitions = repartition(&schema, partitions, partitioning).await?;
assert_eq!(3, output_partitions.len());
assert_eq!(300, partition_row_count(&output_partitions[0]));
assert_eq!(450, partition_row_count(&output_partitions[1]));
assert_eq!(450, partition_row_count(&output_partitions[2]));
assert_eq!(
collect_partition_u32_values(&output_partitions[0])
.into_iter()
.flatten()
.collect::<HashSet<_>>(),
HashSet::from([1, 2])
);
assert_eq!(
collect_partition_u32_values(&output_partitions[1])
.into_iter()
.flatten()
.collect::<HashSet<_>>(),
HashSet::from([3, 4, 5])
);
assert_eq!(
collect_partition_u32_values(&output_partitions[2])
.into_iter()
.flatten()
.collect::<HashSet<_>>(),
HashSet::from([6, 7, 8])
);
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_compound_keys() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, false),
Field::new("b", DataType::UInt32, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![5, 10, 10, 10, 10, 15])),
Arc::new(UInt32Array::from(vec![1, 1, 3, 5, 7, 0])),
],
)?;
let partitioning = Partitioning::Range(RangePartitioning::try_new(
[
PhysicalSortExpr::new(col("a", &schema)?, SortOptions::default()),
PhysicalSortExpr::new(col("b", &schema)?, SortOptions::default()),
]
.into(),
vec![
SplitPoint::new(vec![
ScalarValue::UInt32(Some(10)),
ScalarValue::UInt32(Some(1)),
]),
SplitPoint::new(vec![
ScalarValue::UInt32(Some(10)),
ScalarValue::UInt32(Some(5)),
]),
],
)?);
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(3, output_partitions.len());
assert_eq!(
vec![(5, 1)],
collect_partition_u32_pairs(&output_partitions[0])
);
assert_eq!(
vec![(10, 1), (10, 3)],
collect_partition_u32_pairs(&output_partitions[1])
);
assert_eq!(
vec![(10, 5), (10, 7), (15, 0)],
collect_partition_u32_pairs(&output_partitions[2])
);
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_nulls_asc_nulls_last() -> Result<()> {
let schema = test_schema(true);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(vec![
None,
Some(5),
Some(10),
Some(15),
]))],
)?;
let partitioning =
u32_range_partitioning(&schema, SortOptions::new(false, false), vec![10])?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(2, output_partitions.len());
assert_eq!(
vec![Some(5)],
collect_partition_u32_values(&output_partitions[0])
);
assert_eq!(
vec![None, Some(10), Some(15)],
collect_partition_u32_values(&output_partitions[1])
);
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_nulls_asc_nulls_first() -> Result<()> {
let schema = test_schema(true);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(vec![
None,
Some(5),
Some(10),
Some(15),
]))],
)?;
let partitioning =
u32_range_partitioning(&schema, SortOptions::new(false, true), vec![10])?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(2, output_partitions.len());
assert_eq!(
vec![None, Some(5)],
collect_partition_u32_values(&output_partitions[0])
);
assert_eq!(
vec![Some(10), Some(15)],
collect_partition_u32_values(&output_partitions[1])
);
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_rows_asc() -> Result<()> {
let schema = test_schema(false);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(vec![5, 10, 15, 25]))],
)?;
let partitioning =
u32_range_partitioning(&schema, SortOptions::default(), vec![10, 20])?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(3, output_partitions.len());
assert_eq!(
vec![Some(5)],
collect_partition_u32_values(&output_partitions[0])
);
assert_eq!(
vec![Some(10), Some(15)],
collect_partition_u32_values(&output_partitions[1])
);
assert_eq!(
vec![Some(25)],
collect_partition_u32_values(&output_partitions[2])
);
Ok(())
}
#[tokio::test]
async fn range_repartitioned_scales_with_fresh_execution_state() -> Result<()> {
let schema = test_schema(false);
let ordering =
LexOrdering::new([PhysicalSortExpr::new_default(col("c0", &schema)?)])
.unwrap();
let samples = [10, 20, 30]
.into_iter()
.map(|value| SplitPoint::new(vec![ScalarValue::UInt32(Some(value))]))
.collect::<Vec<_>>();
let partitions = [vec![5, 15, 25, 35], vec![6, 16, 26, 36]]
.into_iter()
.map(|values| -> Result<_> {
Ok(vec![RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(values))],
)?])
})
.collect::<Result<Vec<_>>>()?;
for preserve_order in [false, true] {
let source = TestMemoryExec::try_new(&partitions, Arc::clone(&schema), None)?
.try_with_sort_information(vec![ordering.clone()])?;
let source = Arc::new(TestMemoryExec::update_cache(&Arc::new(source)));
let mut exec = Arc::new(
RepartitionExec::try_new(
source,
Partitioning::Range(RangePartitioning::try_new_with_samples(
ordering.clone(),
samples.clone(),
2,
)?),
)?
.with_batch_size(2)?,
);
if preserve_order {
exec = Arc::new(Arc::unwrap_or_clone(exec).with_preserve_order());
}
let context = Arc::new(TaskContext::default());
let initial = crate::collect_partitioned(
Arc::<RepartitionExec>::clone(&exec),
Arc::clone(&context),
)
.await?;
assert_eq!(
initial
.iter()
.map(|p| partition_row_count(p))
.sum::<usize>(),
8
);
for target in [4, 1, 4] {
let scaled = exec
.repartitioned(target, &ConfigOptions::default())?
.expect("retained samples support the requested partition count");
let repartition = scaled.downcast_ref::<RepartitionExec>().unwrap();
let range = expect_range_partitioning(repartition.partitioning());
assert_eq!(range.partition_count(), target);
assert_eq!(range.samples(), samples);
assert_eq!(range.ordering(), &ordering);
assert_eq!(repartition.preserve_order, preserve_order);
assert_eq!(repartition.batch_size, Some(2));
assert_eq!(
repartition.properties().output_ordering(),
exec.properties().output_ordering()
);
assert!(!Arc::ptr_eq(&repartition.state, &exec.state));
assert!(Arc::ptr_eq(&repartition.input, &exec.input));
assert_eq!(repartition.metrics().unwrap().output_rows(), None);
let output =
crate::collect_partitioned(Arc::clone(&scaled), Arc::clone(&context))
.await?;
assert_eq!(output.len(), target);
for (index, batches) in output.iter().enumerate() {
let mut values = collect_partition_u32_values(batches);
if !preserve_order {
values.sort_unstable();
}
let expected = if target == 1 {
vec![5, 6, 15, 16, 25, 26, 35, 36]
} else {
vec![index as u32 * 10 + 5, index as u32 * 10 + 6]
};
assert_eq!(
values,
expected.into_iter().map(Some).collect::<Vec<_>>()
);
}
assert_eq!(repartition.metrics().unwrap().output_rows(), Some(8));
exec = Arc::new(repartition.clone());
}
for unsupported in [0, 5] {
assert!(
exec.repartitioned(unsupported, &ConfigOptions::default())?
.is_none()
);
}
}
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_rows_desc() -> Result<()> {
let schema = test_schema(false);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(vec![5, 10, 15, 20, 25]))],
)?;
let partitioning =
u32_range_partitioning(&schema, SortOptions::new(true, false), vec![20, 10])?;
let output_partitions =
repartition(&schema, vec![vec![batch]], partitioning).await?;
assert_eq!(3, output_partitions.len());
assert_eq!(
vec![Some(25)],
collect_partition_u32_values(&output_partitions[0])
);
assert_eq!(
vec![Some(15), Some(20)],
collect_partition_u32_values(&output_partitions[1])
);
assert_eq!(
vec![Some(5), Some(10)],
collect_partition_u32_values(&output_partitions[2])
);
Ok(())
}
#[tokio::test]
async fn range_repartition_routes_string_rows() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let batch = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["bar", "baz", "foo", "qux"])) as ArrayRef,
)])?;
let schema = batch.schema();
let expr = col("my_awesome_field", &schema)?;
let input = MockExec::new(vec![Ok(batch)], Arc::clone(&schema));
let partitioning = Partitioning::Range(RangePartitioning::try_new(
[PhysicalSortExpr::new_default(expr)].into(),
vec![SplitPoint::new(vec![ScalarValue::Utf8(Some(
"foo".to_string(),
))])],
)?);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning)?;
let mut partition_0 = Vec::new();
let mut stream = exec.execute(0, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
partition_0.push(result?);
}
let mut partition_1 = Vec::new();
let mut stream = exec.execute(1, task_ctx)?;
while let Some(result) = stream.next().await {
partition_1.push(result?);
}
assert_eq!(
vec!["bar", "baz"],
collect_partition_string_values(&partition_0)
);
assert_eq!(
vec!["foo", "qux"],
collect_partition_string_values(&partition_1)
);
Ok(())
}
#[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();
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(())
}
#[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();
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(())
}
#[test]
fn range_expr_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();
let range_part = RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![ScalarValue::Decimal128(
Some(1000),
10,
2,
)])],
)?;
let expr = RangeExpr::try_new_with_schema(
vec![col("k", &schema)?],
&range_part,
&schema,
)?;
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 res = expr.evaluate(&batch)?;
let ColumnarValue::Array(array) = res else {
panic!("expected array result");
};
let partition_ids = array
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.values();
assert_eq!(partition_ids, &[0, 1]);
Ok(())
}
#[test]
fn range_expr_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();
let range_part = RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![
ScalarValue::TimestampNanosecond(Some(100), None),
ScalarValue::Int64(Some(0)),
])],
)?;
let expr = RangeExpr::try_new_with_schema(
vec![col("t", &schema)?, col("i", &schema)?],
&range_part,
&schema,
)?;
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 res = expr.evaluate(&batch)?;
let ColumnarValue::Array(array) = res else {
panic!("expected array result");
};
let partition_ids = array
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.values();
assert_eq!(partition_ids, &[0, 1]);
Ok(())
}
#[test]
#[expect(deprecated)]
fn range_expr_deprecated_try_new_routes_matching_types() -> Result<()> {
let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int64, true)]));
let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(
col("k", &schema)?,
SortOptions::default(),
)])
.unwrap();
let range_part = RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![ScalarValue::Int64(Some(100))])],
)?;
let expr = RangeExpr::try_new(vec![col("k", &schema)?], &range_part)?;
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(Int64Array::from(vec![Some(50), Some(200)]))],
)?;
let res = expr.evaluate(&batch)?;
let ColumnarValue::Array(array) = res else {
panic!("expected array result");
};
let partition_ids = array
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap()
.values();
assert_eq!(partition_ids, &[0, 1]);
Ok(())
}
#[test]
fn batch_partitioner_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();
let range_part = RangePartitioning::try_new(
ordering,
vec![SplitPoint::new(vec![ScalarValue::Decimal128(
Some(1000),
10,
2,
)])],
)?;
let mut partitioner = BatchPartitioner::try_new_range_partitioner(
&range_part,
&schema,
metrics::Time::default(),
)?;
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 mut partitioned_batches = vec![];
partitioner.partition(batch, |partition, batch| {
partitioned_batches.push((partition, batch.num_rows()));
Ok(())
})?;
assert_eq!(partitioned_batches, vec![(0, 1), (1, 1)]);
Ok(())
}
#[test]
fn range_repartition_swaps_with_projection_rewrites_key_index() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("region", DataType::Utf8, false),
Field::new("payload", DataType::UInt32, false),
]));
let ordering =
LexOrdering::new([PhysicalSortExpr::new_default(col("id", &schema)?)])
.expect("non-empty ordering");
let samples = [10, 20, 30, 40, 50]
.into_iter()
.map(|value| SplitPoint::new(vec![ScalarValue::UInt32(Some(value))]))
.collect();
let repartition = Arc::new(RepartitionExec::try_new(
Arc::new(EmptyExec::new(Arc::clone(&schema))),
Partitioning::Range(RangePartitioning::try_new_with_samples(
ordering, samples, 2,
)?),
)?);
let projection =
projection_on_columns(&(Arc::clone(&repartition) as _), &["payload", "id"])?;
let swapped = repartition
.try_swapping_with_projection(&projection)?
.expect("swap should succeed when projection keeps the range key");
let swapped_repartition = swapped
.downcast_ref::<RepartitionExec>()
.expect("top node should be RepartitionExec");
assert!(swapped_repartition.input().is::<ProjectionExec>());
let range = expect_range_partitioning(swapped_repartition.partitioning());
assert_eq!(range.ordering()[0].to_string(), "id@1 ASC");
assert_eq!(range.max_partition_count(), 6);
assert_eq!(
range.split_points(),
&[SplitPoint::new(vec![ScalarValue::UInt32(Some(30))])]
);
Ok(())
}
#[test]
fn range_repartition_does_not_swap_when_projection_drops_key() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("payload", DataType::UInt32, false),
]));
let repartition = Arc::new(RepartitionExec::try_new(
Arc::new(EmptyExec::new(Arc::clone(&schema))),
range_partitioning_on_columns(&schema, &["id"], vec![vec![10]])?,
)?);
let projection =
projection_on_columns(&(Arc::clone(&repartition) as _), &["payload"])?;
assert!(
repartition
.try_swapping_with_projection(&projection)?
.is_none()
);
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::UInt32, false),
Field::new("b", DataType::UInt32, false),
Field::new("c", DataType::UInt32, false),
]));
let repartition = Arc::new(RepartitionExec::try_new(
Arc::new(EmptyExec::new(Arc::clone(&schema))),
range_partitioning_on_columns(&schema, &["a", "b"], vec![vec![10, 1]])?,
)?);
let projection =
projection_on_columns(&(Arc::clone(&repartition) as _), &["a", "c"])?;
assert!(
repartition
.try_swapping_with_projection(&projection)?
.is_none()
);
Ok(())
}
#[test]
fn range_repartition_try_pushdown_sort_when_maintains_order() -> Result<()> {
let schema =
Arc::new(Schema::new(vec![Field::new("id", DataType::UInt32, false)]));
let ordering = LexOrdering::new([PhysicalSortExpr::new(
col("id", &schema)?,
SortOptions::default(),
)])
.expect("ordering must not be empty");
let source = Arc::new(ExactSortPushdownExec::new(
Arc::clone(&schema),
2,
ordering.clone(),
));
let repartition = Arc::new(
RepartitionExec::try_new(
source,
range_partitioning_on_columns(&schema, &["id"], vec![vec![10]])?,
)?
.with_preserve_order(),
);
assert!(repartition.maintains_input_order()[0]);
match repartition.try_pushdown_sort(ordering.as_ref())? {
SortOrderPushdownResult::Exact { inner } => {
let pushed = inner
.downcast_ref::<RepartitionExec>()
.expect("pushdown should keep RepartitionExec");
assert!(pushed.preserve_order());
assert!(pushed.maintains_input_order()[0]);
let range = expect_range_partitioning(pushed.partitioning());
assert_eq!(range.ordering()[0].to_string(), "id@0 ASC");
assert_eq!(
inner.properties().output_ordering().map(|o| o.to_string()),
Some(ordering.to_string()),
"pushed repartition output ordering should match the requested sort"
);
}
other => panic!("expected Exact sort pushdown, got {other:?}"),
}
Ok(())
}
#[test]
fn range_repartition_try_pushdown_sort_unsupported_without_order_maintenance()
-> Result<()> {
let schema =
Arc::new(Schema::new(vec![Field::new("id", DataType::UInt32, false)]));
let ordering = LexOrdering::new([PhysicalSortExpr::new(
col("id", &schema)?,
SortOptions::default(),
)])
.expect("ordering must not be empty");
let source = Arc::new(ExactSortPushdownExec::new(
Arc::clone(&schema),
2,
ordering.clone(),
));
let repartition = Arc::new(RepartitionExec::try_new(
source,
range_partitioning_on_columns(&schema, &["id"], vec![vec![10]])?,
)?);
assert!(!repartition.maintains_input_order()[0]);
assert!(matches!(
repartition.try_pushdown_sort(ordering.as_ref())?,
SortOrderPushdownResult::Unsupported
));
Ok(())
}
fn range_partitioning_on_columns(
schema: &SchemaRef,
key_columns: &[&str],
split_points: Vec<Vec<u32>>,
) -> Result<Partitioning> {
let Some(ordering) = LexOrdering::new(
key_columns
.iter()
.map(|name| {
Ok(PhysicalSortExpr::new(
col(name, schema)?,
SortOptions::default(),
))
})
.collect::<Result<Vec<_>>>()?,
) else {
return exec_err!("range ordering must not be empty");
};
Ok(Partitioning::Range(RangePartitioning::try_new(
ordering,
split_points
.into_iter()
.map(|values| {
SplitPoint::new(
values
.into_iter()
.map(|value| ScalarValue::UInt32(Some(value)))
.collect(),
)
})
.collect(),
)?))
}
fn projection_on_columns(
input: &Arc<dyn ExecutionPlan>,
names: &[&str],
) -> Result<ProjectionExec> {
let exprs = names
.iter()
.map(|name| {
Ok(ProjectionExpr {
expr: col(name, &input.schema())?,
alias: (*name).to_string(),
})
})
.collect::<Result<Vec<_>>>()?;
ProjectionExec::try_new(exprs, Arc::clone(input))
}
fn expect_range_partitioning(partitioning: &Partitioning) -> &RangePartitioning {
match partitioning {
Partitioning::Range(range) => range,
other => panic!("expected Range partitioning, got {other:?}"),
}
}
#[derive(Debug, Clone)]
struct ExactSortPushdownExec {
cache: Arc<PlanProperties>,
}
impl ExactSortPushdownExec {
fn new(schema: SchemaRef, num_partitions: usize, ordering: LexOrdering) -> Self {
use crate::execution_plan::{Boundedness, EmissionType};
Self {
cache: Arc::new(PlanProperties::new(
EquivalenceProperties::new_with_orderings(schema, [ordering]),
Partitioning::UnknownPartitioning(num_partitions),
EmissionType::Incremental,
Boundedness::Bounded,
)),
}
}
}
impl DisplayAs for ExactSortPushdownExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result {
write!(f, "ExactSortPushdownExec")
}
}
impl ExecutionPlan for ExactSortPushdownExec {
fn name(&self) -> &str {
"ExactSortPushdownExec"
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.cache
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn replace_children(
self: Arc<Self>,
_: Vec<Arc<dyn ExecutionPlan>>,
_: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
Ok(Box::pin(EmptyRecordBatchStream::new(self.schema())))
}
fn try_pushdown_sort(
&self,
_order: &[PhysicalSortExpr],
) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
Ok(SortOrderPushdownResult::Exact {
inner: Arc::new(self.clone()),
})
}
}
#[tokio::test]
async fn test_repartition_with_coalescing() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone()];
let partitioning = Partitioning::RoundRobinBatch(1);
let session_config = SessionConfig::new().with_batch_size(200);
let task_ctx = TaskContext::default().with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let exec = TestMemoryExec::try_new_exec(&partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
assert_eq!(200, batch.num_rows());
}
}
Ok(())
}
#[tokio::test]
async fn test_with_batch_size_overrides_session_config() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions = vec![partition.clone(), partition.clone()];
let partitioning = Partitioning::RoundRobinBatch(1);
let session_config = SessionConfig::new().with_batch_size(200);
let task_ctx =
Arc::new(TaskContext::default().with_session_config(session_config));
let exec = TestMemoryExec::try_new_exec(&partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?.with_batch_size(100)?;
let mut stream = exec.execute(0, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
assert_eq!(100, batch.num_rows());
}
Ok(())
}
#[tokio::test]
async fn unbounded_input_emits_before_batch_size() -> Result<()> {
let schema = test_schema(false);
let batch = create_batch();
let source = Arc::new(StreamingTableExec::try_new(
Arc::clone(&schema),
vec![Arc::new(UnboundedTestPartition {
schema: Arc::clone(&schema),
batch: batch.clone(),
})],
None,
vec![],
true,
None,
)?);
let exec = RepartitionExec::try_new(source, Partitioning::RoundRobinBatch(1))?;
let session_config = SessionConfig::new().with_batch_size(batch.num_rows() * 2);
let task_ctx =
Arc::new(TaskContext::default().with_session_config(session_config));
let mut stream = exec.execute(0, task_ctx)?;
let output =
tokio::time::timeout(std::time::Duration::from_secs(5), stream.next())
.await
.expect("unbounded repartition withheld a partial batch")
.expect("unbounded input ended unexpectedly")?;
assert_eq!(batch, output);
Ok(())
}
fn test_schema(nullable: bool) -> Arc<Schema> {
Arc::new(Schema::new(vec![Field::new(
"c0",
DataType::UInt32,
nullable,
)]))
}
fn u32_range_partitioning(
schema: &SchemaRef,
sort_options: SortOptions,
split_values: Vec<u32>,
) -> Result<Partitioning> {
let expr = col("c0", schema)?;
Ok(Partitioning::Range(RangePartitioning::try_new(
[PhysicalSortExpr::new(expr, sort_options)].into(),
split_values
.into_iter()
.map(|value| SplitPoint::new(vec![ScalarValue::UInt32(Some(value))]))
.collect(),
)?))
}
fn partition_row_count(batches: &[RecordBatch]) -> usize {
batches.iter().map(|batch| batch.num_rows()).sum()
}
fn collect_partition_u32_values(batches: &[RecordBatch]) -> Vec<Option<u32>> {
batches
.iter()
.flat_map(|batch| {
let array =
as_uint32_array(batch.column(0)).expect("expected UInt32 column");
(0..array.len())
.map(|idx| {
if array.is_null(idx) {
None
} else {
Some(array.value(idx))
}
})
.collect::<Vec<_>>()
})
.collect()
}
fn collect_partition_u32_pairs(batches: &[RecordBatch]) -> Vec<(u32, u32)> {
batches
.iter()
.flat_map(|batch| {
let a = as_uint32_array(batch.column(0)).expect("expected UInt32 column");
let b = as_uint32_array(batch.column(1)).expect("expected UInt32 column");
(0..a.len())
.map(|idx| (a.value(idx), b.value(idx)))
.collect::<Vec<_>>()
})
.collect()
}
fn collect_partition_string_values(batches: &[RecordBatch]) -> Vec<&str> {
batches
.iter()
.flat_map(|batch| {
let array =
as_string_array(batch.column(0)).expect("expected Utf8 column");
(0..array.len())
.map(|idx| array.value(idx))
.collect::<Vec<_>>()
})
.collect()
}
async fn repartition(
schema: &SchemaRef,
input_partitions: Vec<Vec<RecordBatch>>,
partitioning: Partitioning,
) -> Result<Vec<Vec<RecordBatch>>> {
let task_ctx = Arc::new(TaskContext::default());
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
let mut output_partitions = vec![];
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
let mut batches = vec![];
while let Some(result) = stream.next().await {
batches.push(result?);
}
output_partitions.push(batches);
}
Ok(output_partitions)
}
#[tokio::test]
async fn many_to_many_round_robin_within_tokio_task() -> Result<()> {
let handle: SpawnedTask<Result<Vec<Vec<RecordBatch>>>> =
SpawnedTask::spawn(async move {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let partitions =
vec![partition.clone(), partition.clone(), partition.clone()];
repartition(&schema, partitions, Partitioning::RoundRobinBatch(5)).await
});
let output_partitions = handle.join().await.unwrap().unwrap();
let total_rows_per_partition = 8 * 50 * 3 / 5;
assert_eq!(5, output_partitions.len());
for partition in output_partitions {
assert_eq!(1, partition.len());
assert_eq!(total_rows_per_partition, partition[0].num_rows());
}
Ok(())
}
#[tokio::test]
async fn unsupported_partitioning() {
let task_ctx = Arc::new(TaskContext::default());
let batch = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["foo", "bar"])) as ArrayRef,
)])
.unwrap();
let schema = batch.schema();
let input = MockExec::new(vec![Ok(batch)], schema);
let partitioning = Partitioning::UnknownPartitioning(1);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning).unwrap();
let output_stream = exec.execute(0, task_ctx).unwrap();
let result_string = crate::common::collect(output_stream)
.await
.unwrap_err()
.to_string();
assert!(
result_string
.contains("Unsupported repartitioning scheme UnknownPartitioning(1)"),
"actual: {result_string}"
);
}
#[tokio::test]
async fn error_for_input_exec() {
let task_ctx = Arc::new(TaskContext::default());
let input = ErrorExec::new();
let partitioning = Partitioning::RoundRobinBatch(1);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning).unwrap();
let result_string = exec.execute(0, task_ctx).err().unwrap().to_string();
assert!(
result_string.contains("ErrorExec, unsurprisingly, errored in partition 0"),
"actual: {result_string}"
);
}
#[tokio::test]
async fn repartition_with_error_in_stream() {
let task_ctx = Arc::new(TaskContext::default());
let batch = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["foo", "bar"])) as ArrayRef,
)])
.unwrap();
let err = exec_err!("bad data error");
let schema = batch.schema();
let input = MockExec::new(vec![Ok(batch), err], schema);
let partitioning = Partitioning::RoundRobinBatch(1);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning).unwrap();
let output_stream = exec.execute(0, task_ctx).unwrap();
let result_string = crate::common::collect(output_stream)
.await
.unwrap_err()
.to_string();
assert!(
result_string.contains("bad data error"),
"actual: {result_string}"
);
}
#[tokio::test]
async fn repartition_with_delayed_stream() {
let task_ctx = Arc::new(TaskContext::default());
let batch1 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["foo", "bar"])) as ArrayRef,
)])
.unwrap();
let batch2 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["frob", "baz"])) as ArrayRef,
)])
.unwrap();
let schema = batch1.schema();
let expected_batches = vec![batch1.clone(), batch2.clone()];
let input = MockExec::new(vec![Ok(batch1), Ok(batch2)], schema);
let partitioning = Partitioning::RoundRobinBatch(1);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning).unwrap();
assert_snapshot!(batches_to_sort_string(&expected_batches), @r"
+------------------+
| my_awesome_field |
+------------------+
| bar |
| baz |
| foo |
| frob |
+------------------+
");
let output_stream = exec.execute(0, task_ctx).unwrap();
let batches = crate::common::collect(output_stream).await.unwrap();
assert_snapshot!(batches_to_sort_string(&batches), @r"
+------------------+
| my_awesome_field |
+------------------+
| bar |
| baz |
| foo |
| frob |
+------------------+
");
}
#[tokio::test]
async fn robin_repartition_with_dropping_output_stream() {
let task_ctx = Arc::new(TaskContext::default());
let partitioning = Partitioning::RoundRobinBatch(2);
let input = Arc::new(make_barrier_exec());
let exec = RepartitionExec::try_new(
Arc::clone(&input) as Arc<dyn ExecutionPlan>,
partitioning,
)
.unwrap();
let output_stream0 = exec.execute(0, Arc::clone(&task_ctx)).unwrap();
let output_stream1 = exec.execute(1, Arc::clone(&task_ctx)).unwrap();
drop(output_stream0);
let mut background_task = JoinSet::new();
background_task.spawn(async move {
input.wait().await;
});
let batches = crate::common::collect(output_stream1).await.unwrap();
assert_snapshot!(batches_to_sort_string(&batches), @r"
+------------------+
| my_awesome_field |
+------------------+
| baz |
| frob |
| gar |
| goo |
+------------------+
");
}
#[tokio::test]
async fn hash_repartition_with_dropping_output_stream() {
let task_ctx = Arc::new(TaskContext::default());
let partitioning = Partitioning::Hash(
vec![Arc::new(crate::expressions::Column::new(
"my_awesome_field",
0,
))],
2,
);
let input = Arc::new(make_barrier_exec());
let exec = RepartitionExec::try_new(
Arc::clone(&input) as Arc<dyn ExecutionPlan>,
partitioning.clone(),
)
.unwrap();
let output_stream1 = exec.execute(1, Arc::clone(&task_ctx)).unwrap();
let mut background_task = JoinSet::new();
background_task.spawn(async move {
input.wait().await;
});
let batches_without_drop = crate::common::collect(output_stream1).await.unwrap();
let items_vec = str_batches_to_vec(&batches_without_drop);
let items_set: HashSet<&str> = items_vec.iter().copied().collect();
assert_eq!(items_vec.len(), items_set.len());
let source_str_set: HashSet<&str> =
["foo", "bar", "frob", "baz", "goo", "gar", "grob", "gaz"]
.iter()
.copied()
.collect();
assert_eq!(items_set.difference(&source_str_set).count(), 0);
let input = Arc::new(make_barrier_exec());
let exec = RepartitionExec::try_new(
Arc::clone(&input) as Arc<dyn ExecutionPlan>,
partitioning,
)
.unwrap();
let output_stream0 = exec.execute(0, Arc::clone(&task_ctx)).unwrap();
let output_stream1 = exec.execute(1, Arc::clone(&task_ctx)).unwrap();
drop(output_stream0);
let mut background_task = JoinSet::new();
background_task.spawn(async move {
input.wait().await;
});
let batches_with_drop = crate::common::collect(output_stream1).await.unwrap();
let items_vec_with_drop = str_batches_to_vec(&batches_with_drop);
let items_set_with_drop: HashSet<&str> =
items_vec_with_drop.iter().copied().collect();
assert_eq!(
items_set_with_drop.symmetric_difference(&items_set).count(),
0
);
}
fn str_batches_to_vec(batches: &[RecordBatch]) -> Vec<&str> {
batches
.iter()
.flat_map(|batch| {
assert_eq!(batch.columns().len(), 1);
let string_array = as_string_array(batch.column(0))
.expect("Unexpected type for repartitioned batch");
string_array
.iter()
.map(|v| v.expect("Unexpected null"))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
}
fn make_barrier_exec() -> BarrierExec {
let batch1 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["foo", "bar"])) as ArrayRef,
)])
.unwrap();
let batch2 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["frob", "baz"])) as ArrayRef,
)])
.unwrap();
let batch3 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["goo", "gar"])) as ArrayRef,
)])
.unwrap();
let batch4 = RecordBatch::try_from_iter(vec![(
"my_awesome_field",
Arc::new(StringArray::from(vec!["grob", "gaz"])) as ArrayRef,
)])
.unwrap();
let schema = batch1.schema();
BarrierExec::new(vec![vec![batch1, batch2], vec![batch3, batch4]], schema)
}
#[tokio::test]
async fn test_drop_cancel() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let schema =
Arc::new(Schema::new(vec![Field::new("a", DataType::Float32, true)]));
let blocking_exec = Arc::new(BlockingExec::new(Arc::clone(&schema), 2));
let refs = blocking_exec.refs();
let repartition_exec = Arc::new(RepartitionExec::try_new(
blocking_exec,
Partitioning::UnknownPartitioning(1),
)?);
let fut = collect(repartition_exec, task_ctx);
let mut fut = fut.boxed();
assert_is_pending(&mut fut);
drop(fut);
assert_strong_count_converges_to_zero(refs).await;
Ok(())
}
#[tokio::test]
async fn hash_repartition_avoid_empty_batch() -> Result<()> {
let task_ctx = Arc::new(TaskContext::default());
let batch = RecordBatch::try_from_iter(vec![(
"a",
Arc::new(StringArray::from(vec!["foo"])) as ArrayRef,
)])
.unwrap();
let partitioning = Partitioning::Hash(
vec![Arc::new(crate::expressions::Column::new("a", 0))],
2,
);
let schema = batch.schema();
let input = MockExec::new(vec![Ok(batch)], schema);
let exec = RepartitionExec::try_new(Arc::new(input), partitioning).unwrap();
let output_stream0 = exec.execute(0, Arc::clone(&task_ctx)).unwrap();
let batch0 = crate::common::collect(output_stream0).await.unwrap();
let output_stream1 = exec.execute(1, Arc::clone(&task_ctx)).unwrap();
let batch1 = crate::common::collect(output_stream1).await.unwrap();
assert!(batch0.is_empty() || batch1.is_empty());
Ok(())
}
#[tokio::test]
async fn repartition_with_spilling() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let input_partitions = vec![partition];
let partitioning = Partitioning::RoundRobinBatch(4);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(1, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
let mut total_rows = 0;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
total_rows += batch.num_rows();
}
}
assert_eq!(total_rows, 50 * 8);
let metrics = exec.metrics().unwrap();
assert!(
metrics.spill_count().unwrap() > 0,
"Expected spill_count > 0, but got {:?}",
metrics.spill_count()
);
println!("Spilled {} times", metrics.spill_count().unwrap());
assert!(
metrics.spilled_bytes().unwrap() > 0,
"Expected spilled_bytes > 0, but got {:?}",
metrics.spilled_bytes()
);
println!(
"Spilled {} bytes in {} spills",
metrics.spilled_bytes().unwrap(),
metrics.spill_count().unwrap()
);
assert!(
metrics.spilled_rows().unwrap() > 0,
"Expected spilled_rows > 0, but got {:?}",
metrics.spilled_rows()
);
println!("Spilled {} rows", metrics.spilled_rows().unwrap());
Ok(())
}
#[tokio::test]
async fn repartition_with_partial_spilling() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let input_partitions = vec![partition];
let partitioning = Partitioning::RoundRobinBatch(4);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(8 * 1024, 1.0)
.build_arc()?;
let session_config = SessionConfig::new().with_batch_size(1024);
let task_ctx = TaskContext::default()
.with_runtime(runtime)
.with_session_config(session_config);
let task_ctx = Arc::new(task_ctx);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
let mut total_rows = 0;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
total_rows += batch.num_rows();
}
}
assert_eq!(total_rows, 50 * 8);
let metrics = exec.metrics().unwrap();
let spill_count = metrics.spill_count().unwrap();
let spilled_rows = metrics.spilled_rows().unwrap();
let spilled_bytes = metrics.spilled_bytes().unwrap();
assert!(
spill_count > 0,
"Expected some spilling to occur, but got spill_count={spill_count}"
);
assert!(
spilled_rows > 0 && spilled_rows < total_rows,
"Expected partial spilling (0 < spilled_rows < {total_rows}), but got spilled_rows={spilled_rows}"
);
assert!(
spilled_bytes > 0,
"Expected some bytes to be spilled, but got spilled_bytes={spilled_bytes}"
);
println!(
"Partial spilling: spilled {} out of {} rows ({:.1}%) in {} spills, {} bytes",
spilled_rows,
total_rows,
(spilled_rows as f64 / total_rows as f64) * 100.0,
spill_count,
spilled_bytes
);
Ok(())
}
#[tokio::test]
async fn repartition_without_spilling() -> Result<()> {
let schema = test_schema(false);
let partition = create_vec_batches(50);
let input_partitions = vec![partition];
let partitioning = Partitioning::RoundRobinBatch(4);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(10 * 1024 * 1024, 1.0) .build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
let mut total_rows = 0;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
total_rows += batch.num_rows();
}
}
assert_eq!(total_rows, 50 * 8);
let metrics = exec.metrics().unwrap();
assert_eq!(
metrics.spill_count(),
Some(0),
"Expected no spilling, but got spill_count={:?}",
metrics.spill_count()
);
assert_eq!(
metrics.spilled_bytes(),
Some(0),
"Expected no bytes spilled, but got spilled_bytes={:?}",
metrics.spilled_bytes()
);
assert_eq!(
metrics.spilled_rows(),
Some(0),
"Expected no rows spilled, but got spilled_rows={:?}",
metrics.spilled_rows()
);
println!("No spilling occurred - all data processed in memory");
Ok(())
}
async fn repartition_spill_with_compression(
spill_compression: SpillCompression,
) -> Result<(usize, usize)> {
let schema = test_schema(false);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(vec![42; 8192]))],
)?;
let num_batches = 20;
let input_partitions = vec![vec![batch; num_batches]];
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(1, 1.0)
.build_arc()?;
let session_config =
SessionConfig::new().with_spill_compression(spill_compression);
let task_ctx = Arc::new(
TaskContext::default()
.with_runtime(runtime)
.with_session_config(session_config),
);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, Partitioning::RoundRobinBatch(4))?;
let mut total_rows = 0;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
let values = as_uint32_array(batch.column(0))?;
assert!(values.iter().all(|v| v == Some(42)));
total_rows += batch.num_rows();
}
}
assert_eq!(total_rows, num_batches * 8192);
let metrics = exec.metrics().unwrap();
Ok((
metrics.spilled_rows().unwrap(),
metrics.spilled_bytes().unwrap(),
))
}
#[tokio::test]
async fn repartition_spill_honors_spill_compression() -> Result<()> {
let (uncompressed_rows, uncompressed_bytes) =
repartition_spill_with_compression(SpillCompression::Uncompressed).await?;
assert!(uncompressed_rows > 0, "Expected spilling to occur");
for spill_compression in [SpillCompression::Lz4Frame, SpillCompression::Zstd] {
let (rows, bytes) =
repartition_spill_with_compression(spill_compression).await?;
assert_eq!(
rows, uncompressed_rows,
"Expected the same rows to spill with {spill_compression}"
);
assert!(
bytes * 2 < uncompressed_bytes,
"Expected {spill_compression} spill files to be much smaller than \
uncompressed ones: {bytes} vs {uncompressed_bytes} bytes"
);
}
Ok(())
}
#[tokio::test]
async fn oom() -> Result<()> {
use datafusion_execution::disk_manager::{DiskManagerBuilder, DiskManagerMode};
let schema = test_schema(false);
let partition = create_vec_batches(50);
let input_partitions = vec![partition];
let partitioning = Partitioning::RoundRobinBatch(4);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(1, 1.0)
.with_disk_manager_builder(
DiskManagerBuilder::default().with_mode(DiskManagerMode::Disabled),
)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
let err = stream.next().await.unwrap().unwrap_err();
let err = err.find_root();
assert!(
matches!(err, DataFusionError::ResourcesExhausted(_)),
"Wrong error type: {err}",
);
}
Ok(())
}
fn create_vec_batches(n: usize) -> Vec<RecordBatch> {
let batch = create_batch();
std::iter::repeat_n(batch, n).collect()
}
fn create_batch() -> RecordBatch {
let schema = test_schema(false);
RecordBatch::try_new(
schema,
vec![Arc::new(UInt32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8]))],
)
.unwrap()
}
fn create_ordered_batches(num_batches: usize) -> Vec<RecordBatch> {
let schema = test_schema(false);
(0..num_batches)
.map(|i| {
let start = (i * 8) as u32;
RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(UInt32Array::from(
(start..start + 8).collect::<Vec<_>>(),
))],
)
.unwrap()
})
.collect()
}
#[tokio::test]
async fn test_repartition_ordering_with_spilling() -> Result<()> {
let schema = test_schema(false);
let partition = create_ordered_batches(20);
let input_partitions = vec![partition];
let partitioning = Partitioning::RoundRobinBatch(2);
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(1, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec =
TestMemoryExec::try_new_exec(&input_partitions, Arc::clone(&schema), None)?;
let exec = RepartitionExec::try_new(exec, partitioning)?;
let mut all_batches = Vec::new();
for i in 0..exec.partitioning().partition_count() {
let mut partition_batches = Vec::new();
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
partition_batches.push(batch);
}
all_batches.push(partition_batches);
}
let metrics = exec.metrics().unwrap();
assert!(
metrics.spill_count().unwrap() > 0,
"Expected spilling to occur, but spill_count = 0"
);
for (partition_idx, batches) in all_batches.iter().enumerate() {
let mut last_value = None;
for batch in batches {
let array = batch
.column(0)
.as_any()
.downcast_ref::<UInt32Array>()
.unwrap();
for i in 0..array.len() {
let value = array.value(i);
if let Some(last) = last_value {
assert!(
value > last,
"Ordering violated in partition {partition_idx}: {value} is not greater than {last}"
);
}
last_value = Some(value);
}
}
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::test::TestMemoryExec;
use crate::union::UnionExec;
use arrow::array::{UInt32Array, record_batch};
use arrow::compute::SortOptions;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::assert_batches_eq;
use datafusion_common::config::ConfigNonZeroUsize;
use datafusion_physical_expr::expressions::col;
macro_rules! assert_plan {
($PLAN: expr, @ $EXPECTED: expr) => {
let formatted = crate::displayable($PLAN).indent(true).to_string();
insta::assert_snapshot!(
formatted,
@$EXPECTED
);
};
}
#[tokio::test]
async fn test_preserve_order() -> Result<()> {
let schema = test_schema();
let sort_exprs = sort_exprs(&schema);
let source1 = sorted_memory_exec(&schema, sort_exprs.clone());
let source2 = sorted_memory_exec(&schema, sort_exprs);
let union = UnionExec::try_new(vec![source1, source2])?;
let exec = RepartitionExec::try_new(union, Partitioning::RoundRobinBatch(10))?
.with_preserve_order();
assert_plan!(&exec, @r"
RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=2, preserve_order=true, sort_exprs=c0@0 ASC
UnionExec
DataSourceExec: partitions=1, partition_sizes=[0], output_ordering=c0@0 ASC
DataSourceExec: partitions=1, partition_sizes=[0], output_ordering=c0@0 ASC
");
Ok(())
}
#[tokio::test]
async fn test_preserve_order_one_partition() -> Result<()> {
let schema = test_schema();
let sort_exprs = sort_exprs(&schema);
let source = sorted_memory_exec(&schema, sort_exprs);
let exec = RepartitionExec::try_new(source, Partitioning::RoundRobinBatch(10))?
.with_preserve_order();
assert_plan!(&exec, @r"
RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=1, maintains_sort_order=true
DataSourceExec: partitions=1, partition_sizes=[0], output_ordering=c0@0 ASC
");
Ok(())
}
#[tokio::test]
async fn test_preserve_order_input_not_sorted() -> Result<()> {
let schema = test_schema();
let source1 = memory_exec(&schema);
let source2 = memory_exec(&schema);
let union = UnionExec::try_new(vec![source1, source2])?;
let exec = RepartitionExec::try_new(union, Partitioning::RoundRobinBatch(10))?
.with_preserve_order();
assert_plan!(&exec, @r"
RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=2
UnionExec
DataSourceExec: partitions=1, partition_sizes=[0]
DataSourceExec: partitions=1, partition_sizes=[0]
");
Ok(())
}
#[tokio::test]
async fn test_preserve_order_drops_per_partition_implied_ordering() -> Result<()> {
use crate::filter::FilterExec;
use crate::sorts::sort::SortExec;
use arrow::array::{Date32Array, TimestampSecondArray};
use arrow::datatypes::TimeUnit;
use datafusion_expr::Operator;
use datafusion_physical_expr::expressions::{BinaryExpr, CastExpr, lit};
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Date32, true),
Field::new("c", DataType::Timestamp(TimeUnit::Second, None), true),
]));
let partition = |k: i32, days: [i32; 2]| -> Result<Arc<dyn ExecutionPlan>> {
let times = days.map(|day| i64::from(day) * 86_400 + 3_600);
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Date32Array::from(days.to_vec())),
Arc::new(TimestampSecondArray::from(times.to_vec())),
],
)?;
let source =
TestMemoryExec::try_new_exec(&[vec![batch]], Arc::clone(&schema), None)?;
Ok(Arc::new(ProjectionExec::try_new(
vec![
(lit(ScalarValue::Int32(Some(k))), "k".to_string()),
(col("a", &schema)?, "a".to_string()),
(col("c", &schema)?, "c".to_string()),
],
source,
)?))
};
let union =
UnionExec::try_new(vec![partition(0, [10, 11])?, partition(1, [1, 2])?])?;
let union_schema = union.schema();
let cast_c = Arc::new(CastExpr::new_with_target_field(
col("c", &union_schema)?,
Arc::new(Field::new("c", DataType::Date32, true)),
None,
));
let filter = Arc::new(FilterExec::try_new(
Arc::new(BinaryExpr::new(
col("a", &union_schema)?,
Operator::Eq,
cast_c,
)),
union,
)?);
let ordering = |names: &[&str]| {
names
.iter()
.map(|name| Ok(PhysicalSortExpr::new_default(col(name, &union_schema)?)))
.collect::<Result<Vec<_>>>()
};
let sort = Arc::new(
SortExec::new(
LexOrdering::new(ordering(&["k", "a", "c"])?).unwrap(),
filter,
)
.with_preserve_partitioning(true),
);
assert!(
sort.properties()
.equivalence_properties()
.ordering_satisfy(ordering(&["c"])?)?
);
let exec = Arc::new(
RepartitionExec::try_new(sort, Partitioning::RoundRobinBatch(1))?
.with_preserve_order(),
);
let properties = exec.properties().equivalence_properties();
assert!(properties.ordering_satisfy(ordering(&["k", "a", "c"])?)?);
assert!(!properties.ordering_satisfy(ordering(&["c"])?)?);
let batches = crate::collect(exec, Arc::new(TaskContext::default())).await?;
assert_batches_eq!(
[
"+---+------------+---------------------+",
"| k | a | c |",
"+---+------------+---------------------+",
"| 0 | 1970-01-11 | 1970-01-11T01:00:00 |",
"| 0 | 1970-01-12 | 1970-01-12T01:00:00 |",
"| 1 | 1970-01-02 | 1970-01-02T01:00:00 |",
"| 1 | 1970-01-03 | 1970-01-03T01:00:00 |",
"+---+------------+---------------------+",
],
&batches
);
Ok(())
}
#[tokio::test]
async fn test_preserve_order_with_spilling() -> Result<()> {
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
let batch1 = record_batch!(("c0", UInt32, [1, 3])).unwrap();
let batch2 = record_batch!(("c0", UInt32, [2, 4])).unwrap();
let batch3 = record_batch!(("c0", UInt32, [5, 7])).unwrap();
let batch4 = record_batch!(("c0", UInt32, [6, 8])).unwrap();
let batch5 = record_batch!(("c0", UInt32, [9, 11])).unwrap();
let batch6 = record_batch!(("c0", UInt32, [10, 12])).unwrap();
let schema = batch1.schema();
let sort_exprs = LexOrdering::new([PhysicalSortExpr {
expr: col("c0", &schema).unwrap(),
options: SortOptions::default().asc(),
}])
.unwrap();
let partition1 = vec![batch1.clone(), batch3.clone(), batch5.clone()];
let partition2 = vec![batch2.clone(), batch4.clone(), batch6.clone()];
let input_partitions = vec![partition1, partition2];
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(608, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec = TestMemoryExec::try_new(&input_partitions, Arc::clone(&schema), None)?
.try_with_sort_information(vec![sort_exprs.clone(), sort_exprs])?;
let exec = Arc::new(exec);
let exec = Arc::new(TestMemoryExec::update_cache(&exec));
let exec = RepartitionExec::try_new(exec, Partitioning::RoundRobinBatch(3))?
.with_preserve_order();
let mut batches = vec![];
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
let batch = result?;
batches.push(batch);
}
}
#[rustfmt::skip]
let expected = [
[
"+----+",
"| c0 |",
"+----+",
"| 1 |",
"| 2 |",
"| 3 |",
"| 4 |",
"+----+",
],
[
"+----+",
"| c0 |",
"+----+",
"| 5 |",
"| 6 |",
"| 7 |",
"| 8 |",
"+----+",
],
[
"+----+",
"| c0 |",
"+----+",
"| 9 |",
"| 10 |",
"| 11 |",
"| 12 |",
"+----+",
],
];
for (batch, expected) in batches.iter().zip(expected.iter()) {
assert_batches_eq!(expected, std::slice::from_ref(batch));
}
let metrics = exec.metrics().unwrap();
assert!(
metrics.spill_count().unwrap() > 0,
"Expected spilling to occur for order-preserving repartition at this \
memory limit. If this fails, the memory limit may need adjustment."
);
Ok(())
}
#[tokio::test]
async fn test_preserve_order_with_spill_file_rotation() -> Result<()> {
use datafusion_execution::config::SessionConfig;
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
let batch1 = record_batch!(("c0", UInt32, [1, 3])).unwrap();
let batch2 = record_batch!(("c0", UInt32, [2, 4])).unwrap();
let batch3 = record_batch!(("c0", UInt32, [5, 7])).unwrap();
let batch4 = record_batch!(("c0", UInt32, [6, 8])).unwrap();
let batch5 = record_batch!(("c0", UInt32, [9, 11])).unwrap();
let batch6 = record_batch!(("c0", UInt32, [10, 12])).unwrap();
let schema = batch1.schema();
let sort_exprs = LexOrdering::new([PhysicalSortExpr {
expr: col("c0", &schema).unwrap(),
options: SortOptions::default().asc(),
}])
.unwrap();
let partition1 = vec![batch1, batch3, batch5];
let partition2 = vec![batch2, batch4, batch6];
let input_partitions = vec![partition1, partition2];
let mut session_config = SessionConfig::new();
session_config
.options_mut()
.execution
.max_spill_file_size_bytes = ConfigNonZeroUsize::try_new(1).unwrap();
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(608, 1.0)
.build_arc()?;
let task_ctx = Arc::new(
TaskContext::default()
.with_session_config(session_config)
.with_runtime(runtime),
);
let exec = TestMemoryExec::try_new(&input_partitions, Arc::clone(&schema), None)?
.try_with_sort_information(vec![sort_exprs.clone(), sort_exprs])?;
let exec = Arc::new(TestMemoryExec::update_cache(&Arc::new(exec)));
let exec = RepartitionExec::try_new(exec, Partitioning::RoundRobinBatch(3))?
.with_preserve_order();
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
let mut last: Option<u32> = None;
while let Some(result) = stream.next().await {
let batch = result?;
let col = batch
.column(0)
.as_any()
.downcast_ref::<UInt32Array>()
.unwrap();
for r in 0..col.len() {
let v = col.value(r);
if let Some(prev) = last {
assert!(
prev <= v,
"output partition {i} not sorted: {prev} came before {v}"
);
}
last = Some(v);
}
}
}
let metrics = exec.metrics().unwrap();
assert!(
metrics.spill_count().unwrap() > 0,
"Expected spilling to occur for order-preserving repartition at this \
memory limit. If this fails, the memory limit may need adjustment."
);
Ok(())
}
#[tokio::test]
async fn test_hash_partitioning_with_spilling() -> Result<()> {
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
let batch1 = record_batch!(("c0", UInt32, [1, 3])).unwrap();
let batch2 = record_batch!(("c0", UInt32, [2, 4])).unwrap();
let batch3 = record_batch!(("c0", UInt32, [5, 7])).unwrap();
let batch4 = record_batch!(("c0", UInt32, [6, 8])).unwrap();
let schema = batch1.schema();
let partition1 = vec![batch1.clone(), batch3.clone()];
let partition2 = vec![batch2.clone(), batch4.clone()];
let input_partitions = vec![partition1, partition2];
let runtime = RuntimeEnvBuilder::default()
.with_memory_limit(1, 1.0)
.build_arc()?;
let task_ctx = TaskContext::default().with_runtime(runtime);
let task_ctx = Arc::new(task_ctx);
let exec = TestMemoryExec::try_new(&input_partitions, Arc::clone(&schema), None)?;
let exec = Arc::new(exec);
let exec = Arc::new(TestMemoryExec::update_cache(&exec));
let hash_expr = col("c0", &schema)?;
let exec =
RepartitionExec::try_new(exec, Partitioning::Hash(vec![hash_expr], 2))?;
let mut join_set = tokio::task::JoinSet::new();
for i in 0..exec.partitioning().partition_count() {
let stream = exec.execute(i, Arc::clone(&task_ctx))?;
join_set.spawn(async move {
let mut count = 0;
futures::pin_mut!(stream);
while let Some(result) = stream.next().await {
let batch = result?;
count += batch.num_rows();
}
Ok::<usize, DataFusionError>(count)
});
}
let mut total_rows = 0;
while let Some(result) = join_set.join_next().await {
total_rows += result.unwrap()?;
}
let all_batches = [batch1, batch2, batch3, batch4];
let expected_rows: usize = all_batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(total_rows, expected_rows);
let metrics = exec.metrics().unwrap();
let spill_count = metrics.spill_count().unwrap_or(0);
assert!(spill_count > 0);
let spilled_bytes = metrics.spilled_bytes().unwrap_or(0);
assert!(spilled_bytes > 0);
let spilled_rows = metrics.spilled_rows().unwrap_or(0);
assert!(spilled_rows > 0);
Ok(())
}
#[tokio::test]
async fn test_repartition() -> Result<()> {
let schema = test_schema();
let sort_exprs = sort_exprs(&schema);
let source = sorted_memory_exec(&schema, sort_exprs);
let exec = RepartitionExec::try_new(source, Partitioning::RoundRobinBatch(10))?
.repartitioned(20, &Default::default())?
.unwrap();
assert_plan!(exec.as_ref(), @r"
RepartitionExec: partitioning=RoundRobinBatch(20), input_partitions=1, maintains_sort_order=true
DataSourceExec: partitions=1, partition_sizes=[0], output_ordering=c0@0 ASC
");
Ok(())
}
#[test]
fn test_range_repartitioned_returns_none() -> Result<()> {
let schema = test_schema();
let source = memory_exec(&schema);
let partitioning = Partitioning::Range(RangePartitioning::try_new(
[PhysicalSortExpr::new(
col("c0", &schema)?,
SortOptions::default(),
)]
.into(),
vec![
SplitPoint::new(vec![ScalarValue::UInt32(Some(10))]),
SplitPoint::new(vec![ScalarValue::UInt32(Some(20))]),
],
)?);
let exec = RepartitionExec::try_new(source, partitioning)?;
let mut expressions = vec![];
exec.apply_expressions(&mut |expr| {
expressions.push(expr.to_string());
Ok(TreeNodeRecursion::Continue)
})?;
assert_eq!(expressions, ["c0@0"]);
let result = exec.repartitioned(10, &Default::default())?;
assert!(
result.is_none(),
"range repartitioning should reject counts above sample capacity"
);
Ok(())
}
fn test_schema() -> Arc<Schema> {
Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)]))
}
fn sort_exprs(schema: &Schema) -> LexOrdering {
[PhysicalSortExpr {
expr: col("c0", schema).unwrap(),
options: SortOptions::default(),
}]
.into()
}
fn memory_exec(schema: &SchemaRef) -> Arc<dyn ExecutionPlan> {
TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(schema), None).unwrap()
}
fn sorted_memory_exec(
schema: &SchemaRef,
sort_exprs: LexOrdering,
) -> Arc<dyn ExecutionPlan> {
let exec = TestMemoryExec::try_new(&[vec![]], Arc::clone(schema), None)
.unwrap()
.try_with_sort_information(vec![sort_exprs])
.unwrap();
let exec = Arc::new(exec);
Arc::new(TestMemoryExec::update_cache(&exec))
}
#[tokio::test]
async fn test_preserve_order_output_rows_not_double_counted() -> Result<()> {
use datafusion_execution::TaskContext;
let batch1 = record_batch!(("c0", UInt32, [1, 3])).unwrap();
let batch2 = record_batch!(("c0", UInt32, [2, 4])).unwrap();
let schema = batch1.schema();
let sort_exprs = sort_exprs(&schema);
let input_partitions = vec![vec![batch1], vec![batch2]];
let exec = TestMemoryExec::try_new(&input_partitions, Arc::clone(&schema), None)?
.try_with_sort_information(vec![sort_exprs.clone(), sort_exprs])?;
let exec = Arc::new(exec);
let exec = Arc::new(TestMemoryExec::update_cache(&exec));
let exec = RepartitionExec::try_new(exec, Partitioning::RoundRobinBatch(3))?
.with_preserve_order();
let task_ctx = Arc::new(TaskContext::default());
let mut total_rows = 0;
for i in 0..exec.partitioning().partition_count() {
let mut stream = exec.execute(i, Arc::clone(&task_ctx))?;
while let Some(result) = stream.next().await {
total_rows += result?.num_rows();
}
}
assert_eq!(total_rows, 4, "actual rows collected should be 4");
let metrics = exec.metrics().unwrap();
let reported_output_rows = metrics.output_rows().unwrap();
assert_eq!(
reported_output_rows, total_rows,
"metrics output_rows ({reported_output_rows}) should match \
actual rows collected ({total_rows}), not double-count"
);
Ok(())
}
}
#[cfg(all(test, feature = "proto"))]
mod range_expr_proto_tests {
use std::sync::Arc;
use arrow::compute::SortOptions;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::{Result, ScalarValue, SplitPoint};
use datafusion_physical_expr::expressions::col;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use super::*;
use crate::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
use crate::proto_test_util::{StubPlanDecoder, StubPlanEncoder};
fn schema() -> Schema {
Schema::new(vec![
Field::new("a", DataType::Int32, false),
Field::new("b", DataType::Int32, false),
])
}
fn split_points() -> Vec<SplitPoint> {
vec![SplitPoint::new(vec![
ScalarValue::Int32(Some(10)),
ScalarValue::Int32(Some(20)),
])]
}
fn sort_options() -> [SortOptions; 2] {
[
SortOptions {
descending: true,
nulls_first: false,
},
SortOptions {
descending: false,
nulls_first: true,
},
]
}
#[test]
fn range_expr_round_trip_preserves_sort_options_and_split_points() -> Result<()> {
let schema = schema();
let sort_opts = sort_options();
let split_pts = split_points();
let on_columns = vec![col("a", &schema)?, col("b", &schema)?];
let range_partitioning = RangePartitioning::try_new(
[
PhysicalSortExpr::new(Arc::clone(&on_columns[0]), sort_opts[0]),
PhysicalSortExpr::new(Arc::clone(&on_columns[1]), sort_opts[1]),
]
.into(),
split_pts.clone(),
)?;
let expr =
RangeExpr::try_new_with_schema(on_columns, &range_partitioning, &schema)?;
let encoder = StubPlanEncoder::ok();
let encode_ctx = ExecutionPlanEncodeCtx::new(&encoder);
let node = PhysicalExpr::try_to_proto(&expr, &encode_ctx.expr_ctx())
.unwrap()
.expect("RangeExpr should encode to Some(node)");
let decoder = StubPlanDecoder::ok();
let decode_ctx = ExecutionPlanDecodeCtx::new(&decoder);
let decoded = RangeExpr::try_from_proto(&node, &decode_ctx.expr_ctx(&schema))?;
let decoded = decoded
.downcast_ref::<RangeExpr>()
.expect("decoded expression should be a RangeExpr");
assert_eq!(decoded.sort_options(), sort_opts);
assert_eq!(decoded.split_points(), split_pts);
Ok(())
}
}