diff --git a/datafusion/physical-plan/src/repartition/mod.rs b/datafusion/physical-plan/src/repartition/mod.rs index 129154c24e9fa..f1d2e1a9e1770 100644 --- a/datafusion/physical-plan/src/repartition/mod.rs +++ b/datafusion/physical-plan/src/repartition/mod.rs @@ -9,7 +9,7 @@ use std::fmt::{Debug, Display, Formatter}; use std::pin::Pin; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; use std::task::{Context, Poll}; use std::vec; @@ -21,6 +21,7 @@ use super::{ use crate::coalesce::LimitedBatchCoalescer; use crate::execution_plan::{CardinalityEffect, EvaluationType, SchedulingType}; use crate::hash_utils::create_hashes; +use crate::joins::utils::OnceFut; use crate::metrics::{BaselineMetrics, SpillMetrics}; use crate::projection::{ProjectionExec, all_columns, make_with_child, update_expr}; use crate::sorts::streaming_merge::StreamingMergeBuilder; @@ -69,6 +70,7 @@ 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::channel::oneshot; use futures::stream::Stream; use futures::{FutureExt, StreamExt, TryStreamExt}; use log::trace; @@ -353,67 +355,128 @@ struct PartitionChannels { spill_readers: Vec, } -struct ConsumingInputStreamsState { - /// Channels for sending batches from input partitions to output partitions. - /// Key is the partition number. - channels: HashMap, - +/// Resources claimed by one output stream after shared initialization completes. +struct RepartitionOutput { + rx: InputPartitionsToCurrentPartitionReceiver, + reservation: SharedMemoryReservation, + spill_readers: Vec, /// Last drop of this Arc will abort any running producer tasks. - /// Reset once all streams are started. producer_tasks: Arc>>, } -impl Debug for ConsumingInputStreamsState { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ConsumingInputStreamsState") - .field("num_channels", &self.channels.len()) - .field("producer_tasks", &self.producer_tasks) - .finish() +/// Shared initialization result. Each output takes a distinct slot, avoiding a +/// global lock when output streams begin polling concurrently. +struct InitializedRepartition { + outputs: Vec>>, +} + +impl InitializedRepartition { + fn take_output(&self, partition: usize) -> RepartitionOutput { + self.outputs + .get(partition) + .expect("invalid output partition") + .lock() + .take() + .expect("partition not used yet") } } -/// Inner state of [`RepartitionExec`]. -#[derive(Default)] -enum RepartitionExecState { - /// Not initialized yet. This is the default state stored in the RepartitionExec node - /// upon instantiation. - #[default] - NotInitialized, - /// Input streams are initialized, but they are still not being consumed. The node - /// transitions to this state when the arrow's RecordBatch stream is created in - /// RepartitionExec::execute(), but before any message is polled. - InputStreamsInitialized(Vec<(SendableRecordBatchStream, RepartitionMetrics)>), - /// The input streams are being consumed. The node transitions to this state when - /// the first message in the arrow's RecordBatch stream is consumed. - ConsumingInputStreams(ConsumingInputStreamsState), +struct RepartitionStartupInput { + streams_and_metrics: Vec<(SendableRecordBatchStream, RepartitionMetrics)>, + input: Arc, + partitioning: Partitioning, + preserve_order: bool, + name: String, + context: Arc, + spill_manager: SpillManager, + coalescer_batch_size: usize, } -impl Debug for RepartitionExecState { +type RepartitionStartupSender = oneshot::Sender>; + +/// Coordinates startup without holding a blocking mutex while child streams +/// are created. One caller wins `claim`; all others wait on `future`. +struct RepartitionStartup { + claimed: AtomicBool, + sender: Mutex>, + future: OnceFut, +} + +impl Debug for RepartitionStartup { 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:?})") - } + write!(f, "RepartitionStartup") + } +} + +impl Default for RepartitionStartup { + fn default() -> Self { + let (sender, receiver) = oneshot::channel(); + let future = OnceFut::new(async move { + let startup = receiver.await.map_err(|_| { + internal_datafusion_err!("RepartitionExec startup was cancelled") + })??; + let RepartitionStartupInput { + streams_and_metrics, + input, + partitioning, + preserve_order, + name, + context, + spill_manager, + coalescer_batch_size, + } = startup; + RepartitionExec::start_input_streams( + streams_and_metrics, + &input, + &partitioning, + preserve_order, + &name, + &context, + spill_manager, + coalescer_batch_size, + ) + }); + Self { + claimed: AtomicBool::new(false), + sender: Mutex::new(Some(sender)), + future, } } } -impl RepartitionExecState { - fn ensure_input_streams_initialized( - &mut self, +impl RepartitionStartup { + /// Returns the publisher to exactly one caller. Taking the sender before + /// running child `execute` also wakes waiters with cancellation if that + /// caller unwinds. + fn claim(&self) -> Option { + self.claimed + .compare_exchange( + false, + true, + AtomicOrdering::AcqRel, + AtomicOrdering::Acquire, + ) + .is_ok() + .then(|| { + self.sender + .lock() + .take() + .expect("startup sender must exist before it is claimed") + }) + } + + fn future(&self) -> OnceFut { + self.future.clone() + } +} + +impl RepartitionExec { + fn initialize_input_streams( input: &Arc, metrics: &ExecutionPlanMetricsSet, output_partitions: usize, ctx: &Arc, - ) -> Result<()> { - if !matches!(self, RepartitionExecState::NotInitialized) { - return Ok(()); - } - + ) -> Result> { let num_input_partitions = input.output_partitioning().partition_count(); let mut streams_and_metrics = Vec::with_capacity(num_input_partitions); @@ -426,43 +489,20 @@ impl RepartitionExecState { streams_and_metrics.push((stream, metrics)); } - *self = RepartitionExecState::InputStreamsInitialized(streams_and_metrics); - Ok(()) + Ok(streams_and_metrics) } #[expect(clippy::too_many_arguments)] - fn consume_input_streams( - &mut self, + fn start_input_streams( + streams_and_metrics: Vec<(SendableRecordBatchStream, RepartitionMetrics)>, input: &Arc, - metrics: &ExecutionPlanMetricsSet, partitioning: &Partitioning, preserve_order: bool, name: &str, context: &Arc, 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 { - // This cannot happen, as ensure_input_streams_initialized() was just called, - // but the compiler does not know. - 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, - }; - + ) -> Result { let num_input_partitions = streams_and_metrics.len(); let num_output_partitions = partitioning.partition_count(); let coalesce_batches = !preserve_order && !input.boundedness().is_unbounded(); @@ -578,9 +618,7 @@ impl RepartitionExecState { // launch one async task per *input* partition let mut spawned_tasks = Vec::with_capacity(num_input_partitions); - for (i, (stream, metrics)) in - std::mem::take(streams_and_metrics).into_iter().enumerate() - { + for (i, (stream, metrics)) in streams_and_metrics.into_iter().enumerate() { let txs: HashMap<_, _> = channels .iter_mut() .map(|(partition, channels)| { @@ -622,14 +660,28 @@ impl RepartitionExecState { SpawnedTask::spawn(RepartitionExec::wait_for_task(input_task, senders)); spawned_tasks.push(wait_for_task); } - *self = Self::ConsumingInputStreams(ConsumingInputStreamsState { - channels, - producer_tasks: Arc::new(spawned_tasks), - }); - match self { - RepartitionExecState::ConsumingInputStreams(value) => Ok(value), - _ => unreachable!(), - } + + let producer_tasks = Arc::new(spawned_tasks); + let outputs = (0..num_output_partitions) + .map(|partition| { + let PartitionChannels { + rx, + reservation, + spill_readers, + .. + } = channels + .remove(&partition) + .expect("output partition must have channels"); + Mutex::new(Some(RepartitionOutput { + rx, + reservation, + spill_readers, + producer_tasks: Arc::clone(&producer_tasks), + })) + }) + .collect(); + + Ok(InitializedRepartition { outputs }) } } @@ -1528,9 +1580,8 @@ impl BatchPartitioner { pub struct RepartitionExec { /// Input execution plan input: Arc, - /// Inner state that is initialized when the parent calls .execute() on this node - /// and consumed as soon as the parent starts consuming this node. - state: Arc>, + /// Shared lazy initialization for input tasks and output channels. + state: Arc, /// Execution metrics metrics: ExecutionPlanMetricsSet, /// Boolean flag to decide whether to preserve ordering. If true means @@ -1774,55 +1825,45 @@ impl ExecutionPlan for RepartitionExec { 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( + let num_input_partitions = input.output_partitioning().partition_count(); + if let Some(sender) = state.claim() { + let streams_and_metrics = match RepartitionExec::initialize_input_streams( &input, &metrics, partitioning.partition_count(), &context, - )?; + ) { + Ok(streams_and_metrics) => streams_and_metrics, + Err(error) => { + let error = Arc::new(error); + let _ = sender.send(Err(DataFusionError::Shared(Arc::clone(&error)))); + return Err(DataFusionError::Shared(error)); + } + }; + let startup = RepartitionStartupInput { + streams_and_metrics, + input, + partitioning, + preserve_order, + name: name.clone(), + context: Arc::clone(&context), + spill_manager: spill_manager.clone(), + coalescer_batch_size, + }; + if sender.send(Ok(startup)).is_err() { + return internal_err!("RepartitionExec startup receiver was dropped"); + } } - - let num_input_partitions = input.output_partitioning().partition_count(); + let mut state = state.future(); let stream = futures::stream::once(async move { - // lock scope - let (rx, reservation, spill_readers, producer_tasks) = { - // lock mutexes - let mut state = state.lock(); - let state = state.consume_input_streams( - &input, - &metrics, - &partitioning, - preserve_order, - &name, - &context, - spill_manager.clone(), - coalescer_batch_size, - )?; - - // now return stream for the specified *output* partition which will - // read from the channel - let PartitionChannels { - rx, - reservation, - spill_readers, - .. - } = state - .channels - .remove(&partition) - .expect("partition not used yet"); - - // The last output partition takes the handle. Otherwise the plan node - // keeps the input tasks alive after every output stream drops. - let producer_tasks = if state.channels.is_empty() { - std::mem::take(&mut state.producer_tasks) - } else { - Arc::clone(&state.producer_tasks) - }; - - (rx, reservation, spill_readers, producer_tasks) - }; + let initialized = std::future::poll_fn(|cx| state.get_shared(cx)).await?; + let RepartitionOutput { + rx, + reservation, + spill_readers, + producer_tasks, + } = initialized.take_output(partition); trace!( "Before returning stream in {name}::execute for partition: {partition}" @@ -2649,6 +2690,7 @@ impl RecordBatchStream for PerPartitionStream { #[cfg(test)] mod tests { use std::collections::HashSet; + use std::sync::Barrier; use super::*; use crate::empty::EmptyExec; @@ -4233,6 +4275,123 @@ mod tests { ); } + #[derive(Debug)] + struct DeferredErrorExec { + error: ErrorExec, + entered: Arc, + release: Arc, + } + + impl DisplayAs for DeferredErrorExec { + fn fmt_as( + &self, + _t: DisplayFormatType, + f: &mut Formatter<'_>, + ) -> std::fmt::Result { + write!(f, "DeferredErrorExec") + } + } + + impl ExecutionPlan for DeferredErrorExec { + fn name(&self) -> &'static str { + "DeferredErrorExec" + } + + fn properties(&self) -> &Arc { + self.error.properties() + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn replace_children( + self: Arc, + _children: Vec>, + _options: ReplaceChildrenOptions, + ) -> Result> { + Ok(self) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + self.replace_children( + children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.entered.wait(); + self.release.wait(); + self.error.execute(partition, context) + } + } + + #[tokio::test] + async fn deferred_initialization_error_fans_out_to_racing_output() -> Result<()> { + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + let input = Arc::new(DeferredErrorExec { + error: ErrorExec::new(), + entered: Arc::clone(&entered), + release: Arc::clone(&release), + }); + let exec = Arc::new(RepartitionExec::try_new( + input, + Partitioning::RoundRobinBatch(2), + )?); + let task_ctx = Arc::new(TaskContext::default()); + + let winner_exec = Arc::clone(&exec); + let winner_ctx = Arc::clone(&task_ctx); + let winner = std::thread::spawn(move || winner_exec.execute(0, winner_ctx)); + + // The first caller has won startup and is blocked inside child `execute`. + entered.wait(); + + let (loser_tx, loser_rx) = std::sync::mpsc::sync_channel(1); + let loser_exec = Arc::clone(&exec); + let loser_ctx = Arc::clone(&task_ctx); + let loser = std::thread::spawn(move || { + let result = loser_exec.execute(1, loser_ctx); + assert!(loser_tx.send(result).is_ok()); + }); + + let loser_result = loser_rx.recv_timeout(std::time::Duration::from_secs(2)); + release.wait(); + + let winner_error = winner + .join() + .expect("winning execute thread panicked") + .err() + .expect("winning execute call should fail") + .to_string(); + loser.join().expect("losing execute thread panicked"); + let loser_stream = loser_result + .expect("losing execute call blocked behind child initialization")?; + let loser_error = crate::common::collect(loser_stream) + .await + .expect_err("losing output should receive the shared initialization error") + .to_string(); + + assert_eq!(winner_error, loser_error); + Ok(()) + } + #[tokio::test] async fn repartition_with_error_in_stream() { let task_ctx = Arc::new(TaskContext::default());