diff --git a/ballista/scheduler/src/state/aqe/adapter.rs b/ballista/scheduler/src/state/aqe/adapter.rs index 2d842080c5..3c30970352 100644 --- a/ballista/scheduler/src/state/aqe/adapter.rs +++ b/ballista/scheduler/src/state/aqe/adapter.rs @@ -16,16 +16,18 @@ // under the License. use crate::planner::create_shuffle_writer_with_config; +use crate::state::aqe::adaptive_rules::AdaptiveRules; use crate::state::aqe::execution_plan::{ AdaptiveDatafusionExec, ExchangeExec, RangeRepartitionRouting, }; +use crate::state::aqe::optimizer_rule::coalesce_partitions::tolerates_partition_count_change; use crate::state::aqe::planner::AdaptiveStageInfo; use crate::state::aqe::skew_join::sort_mapper_outputs; use crate::state::execution_graph::StageOutput; use ballista_core::JobId; use ballista_core::execution_plans::sort_shuffle::ShuffleRouting; use ballista_core::execution_plans::{ - OrderedRangeRepartitionExec, RangeFilterExec, RangeShuffleReaderExec, + CoalescePlan, OrderedRangeRepartitionExec, RangeFilterExec, RangeShuffleReaderExec, RangeShuffleWriterExec, ShuffleReaderExec, ShuffleWriter, ShuffleWriterExec, UnorderedRangeRepartitionExec, }; @@ -105,6 +107,9 @@ fn use_range_shuffle_writer( #[derive(Debug, Clone, Default)] pub(crate) struct BallistaAdapter { inputs: HashMap, + /// The scheduler embedder's rules, which rebuild operators of their own + /// over coalesced shuffles. + rules: Option>, } /// @@ -227,6 +232,10 @@ impl BallistaAdapter { &mut self, plan: Arc, ) -> datafusion::error::Result>> { + if let Some(rebuilt) = self.rebuild_over_coalesced_shuffles(&plan)? { + return Ok(Transformed::new(rebuilt, true, TreeNodeRecursion::Jump)); + } + // A merge with a row limit on top of an exchange: build the reader // with the limit already set. Both merge on the same ordering, so the // consumer's first `n` rows come from the reader's first `n`. @@ -248,16 +257,57 @@ impl BallistaAdapter { Ok(Transformed::no(plan)) } + /// Rebuilds `plan`, an operator of the embedder's own above a coalesced + /// shuffle of this stage, with its [`AdaptiveRules::with_coalesced_children`], + /// over its children adapted as usual. `None` for any other node. + fn rebuild_over_coalesced_shuffles( + &mut self, + plan: &Arc, + ) -> datafusion::error::Result>> { + let Some(rules) = self.rules.clone() else { + return Ok(None); + }; + if plan.is::() + || tolerates_partition_count_change(plan.as_ref()) + || !rules.tolerates_partition_count_change(plan.as_ref()) + { + return Ok(None); + } + let Some(coalesce) = coalesce_of_stage_inputs(plan) else { + return Ok(None); + }; + let children = plan + .children() + .into_iter() + .map(|child| { + Arc::clone(child) + .transform_down(|node| self.transform_children(node)) + .map(|transformed| transformed.data) + }) + .collect::>>()?; + match rules.with_coalesced_children(plan, children.clone(), &coalesce) { + Some(rebuilt) => rebuilt.map(Some), + None => replace_children_if_necessary(Arc::clone(plan), children).map(Some), + } + } + /// Converts Adaptive plan to plan which ballista expects /// This is to be used to convert [ExchangeExec] to /// ShuffleWriterExec/SortShuffleWriterExec and [ShuffleReaderExec] + /// + /// `rules` are the scheduler embedder's, which rebuild operators of their + /// own over coalesced shuffles. pub fn adapt_to_ballista( plan: Arc, job_id: &JobId, config: &ConfigOptions, + rules: Option>, ) -> datafusion::error::Result { + let mut adapter = BallistaAdapter { + rules, + ..Default::default() + }; if let Some(root) = plan.downcast_ref::() { - let mut adapter = BallistaAdapter::default(); resolve_range_filter_cuts(root.input())?; let plan = root .input() @@ -287,7 +337,6 @@ impl BallistaAdapter { inputs: adapter.inputs, }) } else if let Some(root) = plan.downcast_ref::() { - let mut adapter = BallistaAdapter::default(); resolve_range_filter_cuts(root.input())?; let plan = root .input() @@ -317,6 +366,27 @@ impl BallistaAdapter { } } +/// The coalesce decision on the shuffles `plan` reads in its stage, which +/// [`CoalescePartitionsRule`](crate::state::aqe::optimizer_rule::CoalescePartitionsRule) +/// shares across all of them, or `None` if they are read as written. +fn coalesce_of_stage_inputs(plan: &Arc) -> Option> { + let mut coalesce = None; + let _ = plan.apply_children(|child| { + child.apply(|node| { + let Some(exchange) = node.downcast_ref::() else { + return Ok(TreeNodeRecursion::Continue); + }; + coalesce = exchange.coalesce(); + Ok(if coalesce.is_some() { + TreeNodeRecursion::Stop + } else { + TreeNodeRecursion::Jump + }) + }) + }); + coalesce +} + /// Hand every [`RangeShuffleReaderExec`] the value range its output /// partitions cover, taken from the [`RangeFilterExec`] above it. /// diff --git a/ballista/scheduler/src/state/aqe/adaptive_rules.rs b/ballista/scheduler/src/state/aqe/adaptive_rules.rs index ce673ff283..44745bfb45 100644 --- a/ballista/scheduler/src/state/aqe/adaptive_rules.rs +++ b/ballista/scheduler/src/state/aqe/adaptive_rules.rs @@ -17,7 +17,10 @@ //! Rules a scheduler embedder adds to adaptive query planning. +use ballista_core::execution_plans::CoalescePlan; +use datafusion::common::Result; use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::ExecutionPlan; use std::fmt::Debug; use std::sync::Arc; use std::sync::atomic::AtomicUsize; @@ -52,4 +55,43 @@ pub trait AdaptiveRules: Debug + Send + Sync { fn replan_rules(&self, _plan_ids: Arc) -> Vec { vec![] } + + /// Whether `plan`, a node of your own between a stage's root and the + /// shuffles it reads, produces the same rows when those shuffles are read + /// with fewer, coalesced partitions (`ballista.planner.coalesce.enabled`). + /// + /// Coalescing groups neighbouring upstream partitions with one mapping + /// for every shuffle the stage reads, so hash co-partitioning is kept. A + /// node that only needs that, such as a join or an aggregate over hash + /// partitioned inputs, tolerates it. A node that depends on the partition + /// count or index itself does not. The default, `false`, leaves every + /// stage with such a node uncoalesced. + /// + /// Asked only about nodes Ballista doesn't know, as the plan is + /// optimized after each stage completes. + fn tolerates_partition_count_change(&self, _plan: &dyn ExecutionPlan) -> bool { + false + } + + /// Rebuilds `plan`, a node [`Self::tolerates_partition_count_change`] + /// accepted, over `children` once the shuffles below it are read as + /// `coalesce` describes, or returns `None` to rebuild it with + /// [`ExecutionPlan::with_new_children`]. + /// + /// A node that keeps per-partition state of its own beside its inputs, + /// such as a child with one row per partition, rebuilds that state for + /// `coalesce.groups.len()` partitions here. Upstream partition `i` is + /// read by the output partition whose group lists `i`. + /// + /// `children` are already rebuilt, with every shuffle reader in them + /// coalesced. Called when the stage is turned into the plan its tasks + /// run. + fn with_coalesced_children( + &self, + _plan: &Arc, + _children: Vec>, + _coalesce: &CoalescePlan, + ) -> Option>> { + None + } } diff --git a/ballista/scheduler/src/state/aqe/mod.rs b/ballista/scheduler/src/state/aqe/mod.rs index 05e4bcd4cc..3995c6a8d7 100644 --- a/ballista/scheduler/src/state/aqe/mod.rs +++ b/ballista/scheduler/src/state/aqe/mod.rs @@ -36,6 +36,7 @@ use ballista_core::execution_plans::{ PartitionedBoundedWindowAggExec, PrefixMergeExec, RangeFilterExec, cut_partitions, merge_runtime_stats_reports, prefix_merge_window_state, repartition_routing_expr, }; +use ballista_core::serde::BallistaPhysicalExtensionCodec; use ballista_core::serde::protobuf::failed_task::FailedReason; use ballista_core::serde::protobuf::job_status::Status; use ballista_core::serde::protobuf::{ @@ -151,28 +152,48 @@ pub(crate) struct AdaptiveExecutionGraph { logical_plan: Option, } +/// What the scheduler, rather than the job's session, adds to planning a job +/// adaptively. +#[derive(Debug, Clone)] +pub(crate) struct SchedulerExtensions { + /// The codec the scheduler ships stages with, which exchange reuse + /// matches stages on. + pub(crate) physical_codec: Arc, + /// See [`SchedulerConfig::adaptive_rules`](crate::config::SchedulerConfig::adaptive_rules). + pub(crate) adaptive_rules: Option>, +} + +impl Default for SchedulerExtensions { + fn default() -> Self { + Self { + physical_codec: Arc::new(BallistaPhysicalExtensionCodec::default()), + adaptive_rules: None, + } + } +} + impl AdaptiveExecutionGraph { /// Creates a new `ExecutionGraph` from a physical execution plan. /// /// This will use the `DistributedPlanner` to break the plan into stages /// and build the DAG structure needed for distributed execution. - /// - /// `physical_codec` is the codec the scheduler ships stages with, which - /// exchange reuse matches stages on. - #[allow(clippy::too_many_arguments)] - pub async fn try_new( + pub(crate) async fn try_new( scheduler_id: &str, job_id: &JobId, job_name: &str, ctx: &SessionContext, logical_plan: &LogicalPlan, queued_at: u64, - rules: Option<&dyn AdaptiveRules>, - physical_codec: Arc, + extensions: SchedulerExtensions, ) -> ballista_core::error::Result { - let planner = AdaptivePlanner::try_new(ctx, logical_plan, job_id.clone(), rules) - .await? - .with_physical_codec(physical_codec); + let planner = AdaptivePlanner::try_new( + ctx, + logical_plan, + job_id.clone(), + extensions.adaptive_rules, + ) + .await? + .with_physical_codec(extensions.physical_codec); let logical_plan = Some(logical_plan.display_indent().to_string()); Self::try_new_with_planner( @@ -189,26 +210,23 @@ impl AdaptiveExecutionGraph { /// Creates a new `ExecutionGraph` from an already-built physical plan. /// /// The plan is prepared and staged by [`AdaptivePlanner::try_new_from_physical`]; - /// the graph has no logical plan to display. `physical_codec` is as in - /// [`Self::try_new`]. - #[allow(clippy::too_many_arguments)] - pub fn try_new_from_physical( + /// the graph has no logical plan to display. + pub(crate) fn try_new_from_physical( scheduler_id: &str, job_id: &JobId, job_name: &str, ctx: &SessionContext, physical_plan: Arc, queued_at: u64, - rules: Option<&dyn AdaptiveRules>, - physical_codec: Arc, + extensions: SchedulerExtensions, ) -> ballista_core::error::Result { let planner = AdaptivePlanner::try_new_from_physical( ctx, physical_plan, job_id.clone(), - rules, + extensions.adaptive_rules, )? - .with_physical_codec(physical_codec); + .with_physical_codec(extensions.physical_codec); Self::try_new_with_planner( scheduler_id, diff --git a/ballista/scheduler/src/state/aqe/optimizer_rule/coalesce_partitions.rs b/ballista/scheduler/src/state/aqe/optimizer_rule/coalesce_partitions.rs index 4bb45b3f76..dde140989a 100644 --- a/ballista/scheduler/src/state/aqe/optimizer_rule/coalesce_partitions.rs +++ b/ballista/scheduler/src/state/aqe/optimizer_rule/coalesce_partitions.rs @@ -147,6 +147,7 @@ use datafusion::physical_plan::windows::{BoundedWindowAggExec, WindowAggExec}; use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties}; use log::debug; +use crate::state::aqe::adaptive_rules::AdaptiveRules; use crate::state::aqe::coalesce::{ split_size_list_by_target_size, start_indices_to_partition_groups, }; @@ -160,7 +161,19 @@ use crate::state::aqe::execution_plan::{ /// /// See module docs for design intent. #[derive(Debug, Default)] -pub struct CoalescePartitionsRule; +pub struct CoalescePartitionsRule { + /// Asked about operators Ballista doesn't know, see + /// [`AdaptiveRules::tolerates_partition_count_change`]. + rules: Option>, +} + +impl CoalescePartitionsRule { + /// A rule that asks `rules` whether operators Ballista doesn't know + /// tolerate a coalesced partition count. + pub fn new(rules: Option>) -> Self { + Self { rules } + } +} impl PhysicalOptimizerRule for CoalescePartitionsRule { fn optimize( @@ -213,7 +226,7 @@ impl PhysicalOptimizerRule for CoalescePartitionsRule { // checks every operator between the stage root and a leaf, since each // of them runs over the coalesced partition count. let mut leaves: Vec> = Vec::new(); - if !collect_alignment_group(&input, &mut leaves) { + if !collect_alignment_group(&input, self.rules.as_deref(), &mut leaves) { debug!( "[coalesce-rule] an operator of unknown partition-count sensitivity consumes a leaf; bail" ); @@ -369,10 +382,12 @@ impl PhysicalOptimizerRule for CoalescePartitionsRule { /// Collects the leaf `ExchangeExec`s under `node` into `leaves`. /// /// Returns `false` when an operator between `node` and one of those leaves -/// is not known to [`tolerates_partition_count_change`]: the rule then has no -/// basis for changing the partition count that operator sees. +/// is neither on [`tolerates_partition_count_change`]'s list nor accepted by +/// the embedder's `rules`: the rule then has no basis for changing the +/// partition count that operator sees. fn collect_alignment_group( node: &Arc, + rules: Option<&dyn AdaptiveRules>, leaves: &mut Vec>, ) -> bool { if node.is::() { @@ -381,12 +396,15 @@ fn collect_alignment_group( } let leaves_before = leaves.len(); for child in node.children() { - if !collect_alignment_group(child, leaves) { + if !collect_alignment_group(child, rules, leaves) { return false; } } let consumes_leaf = leaves.len() > leaves_before; - !consumes_leaf || tolerates_partition_count_change(node.as_ref()) + !consumes_leaf + || tolerates_partition_count_change(node.as_ref()) + || rules + .is_some_and(|rules| rules.tolerates_partition_count_change(node.as_ref())) } /// Operators that produce the same rows over any partitioning of their @@ -396,9 +414,11 @@ fn collect_alignment_group( /// `ExecutionPlan` has no way to declare this, so the list is maintained by /// hand, like the whitelists in `ballista_core::execution_plans::plan_algebra`. /// Anything else, in particular an extension operator from a client that -/// submitted its own physical plan, is assumed to depend on the count. +/// submitted its own physical plan, is assumed to depend on the count unless +/// the scheduler embedder's [`AdaptiveRules::tolerates_partition_count_change`] +/// accepts it. #[allow(deprecated)] -fn tolerates_partition_count_change(plan: &dyn ExecutionPlan) -> bool { +pub(crate) fn tolerates_partition_count_change(plan: &dyn ExecutionPlan) -> bool { plan.is::() || plan.is::() || plan.is::() diff --git a/ballista/scheduler/src/state/aqe/planner.rs b/ballista/scheduler/src/state/aqe/planner.rs index fb6383a2eb..179c7c74e9 100644 --- a/ballista/scheduler/src/state/aqe/planner.rs +++ b/ballista/scheduler/src/state/aqe/planner.rs @@ -110,6 +110,9 @@ pub struct AdaptivePlanner { /// [`reuse_key`] encodes them with too. The session's codec unless /// [`Self::with_physical_codec`] sets the scheduler's. physical_codec: Arc, + /// The scheduler embedder's rules, if any, which partition coalescing + /// asks about operators of their own. + adaptive_rules: Option>, runtime_filters: Option, } @@ -154,6 +157,7 @@ impl AdaptivePlanner { Ok(Self { runtime_filters, physical_codec, + adaptive_rules: None, stage_id_generator: 0, // FIXME: compatibility issue with static where stages start from 1 session_state, physical_planner: planner.into(), @@ -181,7 +185,7 @@ impl AdaptivePlanner { ctx: &SessionContext, logical_plan: &LogicalPlan, job_id: JobId, - rules: Option<&dyn AdaptiveRules>, + rules: Option>, ) -> common::Result { // session state with very limited set of optimizers. // this optimizer set will be executed only once, before @@ -192,7 +196,7 @@ impl AdaptivePlanner { let mut preparation_optimizers = Self::plan_preparation_optimizers(plan_id_generator.clone()); let mut replan_optimizers = vec![]; - if let Some(rules) = rules { + if let Some(rules) = &rules { preparation_optimizers .extend(rules.preparation_rules(plan_id_generator.clone())); replan_optimizers = rules.replan_rules(plan_id_generator.clone()); @@ -220,12 +224,14 @@ impl AdaptivePlanner { .map_err(|e| DataFusionError::Execution(e.to_string()))?; let state_builder = SessionStateBuilder::from(ctx.state()); - Self::try_new_with_optimizers( + let mut planner = Self::try_new_with_optimizers( state_builder, plan, job_id, Self::default_optimizers_with(plan_id_generator, replan_optimizers), - ) + )?; + planner.adaptive_rules = rules; + Ok(planner) } /// Creates a new `AdaptivePlanner` over an already-built physical plan, @@ -254,14 +260,14 @@ impl AdaptivePlanner { ctx: &SessionContext, plan: Arc, job_id: JobId, - rules: Option<&dyn AdaptiveRules>, + rules: Option>, ) -> common::Result { let plan_id_generator = Arc::new(AtomicUsize::new(0)); let mut preparation_optimizers = Self::plan_preparation_optimizers(plan_id_generator.clone()); let mut replan_optimizers = vec![]; - if let Some(rules) = rules { + if let Some(rules) = &rules { preparation_optimizers .extend(rules.preparation_rules(plan_id_generator.clone())); replan_optimizers = rules.replan_rules(plan_id_generator.clone()); @@ -281,12 +287,14 @@ impl AdaptivePlanner { |_, _| {}, )?; - Self::try_new_with_optimizers( + let mut planner = Self::try_new_with_optimizers( SessionStateBuilder::from(ctx.state()), plan, job_id, Self::default_optimizers_with(plan_id_generator, replan_optimizers), - ) + )?; + planner.adaptive_rules = rules; + Ok(planner) } /// Matches stages for exchange reuse on their encoding under `codec`, the @@ -531,6 +539,7 @@ impl AdaptivePlanner { filters.discover(&self.plan)?; } let config = self.session_state.config().options(); + let coalesce = CoalescePartitionsRule::new(self.adaptive_rules.clone()); let (stage_ids, shuffle_writers) = stages .into_iter() .map(|plan| { @@ -540,14 +549,19 @@ impl AdaptivePlanner { // group. This avoids cross-stage gluing and stale state // that would arise if the rule walked the entire residual // plan in `default_optimizers()`. - let plan = CoalescePartitionsRule.optimize(plan, config)?; + let plan = coalesce.optimize(plan, config)?; let plan = OptimizeSkewedJoinRule.optimize(plan, config)?; let plan = match &mut self.runtime_filters { Some(filters) => filters.instrument(plan)?, None => plan, }; - BallistaAdapter::adapt_to_ballista(plan, &self.job_id, config) - .map(|w| (w.plan.stage_id(), w)) + BallistaAdapter::adapt_to_ballista( + plan, + &self.job_id, + config, + self.adaptive_rules.clone(), + ) + .map(|w| (w.plan.stage_id(), w)) }) .collect::, Vec<_>)>>()?; diff --git a/ballista/scheduler/src/state/aqe/test/adaptive_rules.rs b/ballista/scheduler/src/state/aqe/test/adaptive_rules.rs index 2bc6ea27f4..57bcc48360 100644 --- a/ballista/scheduler/src/state/aqe/test/adaptive_rules.rs +++ b/ballista/scheduler/src/state/aqe/test/adaptive_rules.rs @@ -34,7 +34,7 @@ async fn two_stage_planner( AdaptivePlanner::from_logical_sql( &ctx, "select c, count(*) from (select a, c from t group by a, c) group by c", - Some(embedder), + Some(Arc::new(embedder.clone())), ) .await } diff --git a/ballista/scheduler/src/state/aqe/test/job_failure.rs b/ballista/scheduler/src/state/aqe/test/job_failure.rs index d1de208129..ab9405dfb5 100644 --- a/ballista/scheduler/src/state/aqe/test/job_failure.rs +++ b/ballista/scheduler/src/state/aqe/test/job_failure.rs @@ -19,6 +19,7 @@ use crate::scheduler_server::event::QueryStageSchedulerEvent; use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::test::{mock_batch, mock_context}; use crate::state::execution_graph::ExecutionGraph; use crate::state::execution_stage::ExecutionStage; @@ -27,13 +28,11 @@ use crate::test_utils::{ mock_failed_task, revive_graph_and_complete_next_stage_with_executor, }; use ballista_core::error::Result; -use ballista_core::serde::BallistaPhysicalExtensionCodec; use ballista_core::serde::protobuf::{ FailedTask, JobStatus, ShuffleWritePartition, SuccessfulTask, failed_task, job_status, task_status, }; use datafusion::execution::context::{SessionConfig, SessionContext}; -use std::sync::Arc; /// Builds an adaptive graph for a join (two concurrent leaf stages). async fn test_join_plan(partition: usize) -> AdaptiveExecutionGraph { @@ -53,8 +52,7 @@ async fn test_join_plan(partition: usize) -> AdaptiveExecutionGraph { &ctx, &logical_plan, 0, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await .unwrap() @@ -74,8 +72,7 @@ async fn test_aggregation_plan() -> AdaptiveExecutionGraph { &ctx, &plan, 0, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await .unwrap() diff --git a/ballista/scheduler/src/state/aqe/test/job_success.rs b/ballista/scheduler/src/state/aqe/test/job_success.rs index 4fbf39eb0c..348c6f5d9d 100644 --- a/ballista/scheduler/src/state/aqe/test/job_success.rs +++ b/ballista/scheduler/src/state/aqe/test/job_success.rs @@ -18,6 +18,7 @@ //! Job-success lifecycle tests for the adaptive execution graph. use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::test::{mock_batch, mock_context}; use crate::state::execution_graph::ExecutionGraph; use crate::state::execution_stage::ExecutionStage; @@ -25,11 +26,9 @@ use crate::test_utils::{ mock_completed_task, mock_executor, revive_graph_and_complete_next_stage, }; use ballista_core::error::Result; -use ballista_core::serde::BallistaPhysicalExtensionCodec; use ballista_core::serde::protobuf::{OperatorMetricsSet, job_status}; use ballista_core::utils::collect_plan_metrics; use std::collections::{HashMap, HashSet}; -use std::sync::Arc; /// Plans `sql` as an adaptive job and completes its stages one by one until /// the job succeeds. While the job is running no stage may be reported as @@ -62,8 +61,7 @@ async fn plan_job(sql: &str) -> Result { &ctx, &logical_plan, 0, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await } diff --git a/ballista/scheduler/src/state/aqe/test/mod.rs b/ballista/scheduler/src/state/aqe/test/mod.rs index 9498a82a87..0bc908311a 100644 --- a/ballista/scheduler/src/state/aqe/test/mod.rs +++ b/ballista/scheduler/src/state/aqe/test/mod.rs @@ -114,7 +114,7 @@ impl AdaptivePlanner { pub(super) async fn from_logical_sql( ctx: &SessionContext, sql: &str, - rules: Option<&dyn AdaptiveRules>, + rules: Option>, ) -> datafusion::common::Result { let plan = ctx.sql(sql).await?.into_optimized_plan()?; Self::try_new(ctx, &plan, "test_job".into(), rules).await @@ -462,7 +462,7 @@ impl PhysicalOptimizerRule for Recording { /// A scheduler embedder whose preparation and replan rules are [`Recording`] /// rules. Its replan rule holds back the stages that haven't run when `hold` /// is set. -#[derive(Debug)] +#[derive(Debug, Clone)] pub(crate) struct Embedder { pub(crate) seen: Arc, pub(crate) hold: bool, diff --git a/ballista/scheduler/src/state/aqe/test/physical_submission.rs b/ballista/scheduler/src/state/aqe/test/physical_submission.rs index dc1cecd150..6daf3ffbb1 100644 --- a/ballista/scheduler/src/state/aqe/test/physical_submission.rs +++ b/ballista/scheduler/src/state/aqe/test/physical_submission.rs @@ -22,16 +22,28 @@ //! must keep those shuffles as stage boundaries and must not make decisions //! that assume it knows what an extension operator does with its input. +use crate::state::aqe::adaptive_rules::AdaptiveRules; use crate::state::aqe::planner::AdaptivePlanner; use crate::state::aqe::test::{ Embedder, Seen, coalesce_config, mock_batch, partitions_with_byte_sizes, }; use crate::test_utils::PassThroughExec; use ballista_core::assert_plan; +use ballista_core::execution_plans::CoalescePlan; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::common::{internal_datafusion_err, internal_err}; +use datafusion::execution::{SendableRecordBatchStream, TaskContext}; use datafusion::physical_expr::expressions::Column; +use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr}; +use datafusion::physical_plan::empty::EmptyExec; +use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType}; use datafusion::physical_plan::repartition::RepartitionExec; -use datafusion::physical_plan::{ExecutionPlan, Partitioning}; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, Partitioning, + PlanProperties, +}; use datafusion::prelude::SessionContext; +use std::fmt::Formatter; use std::sync::Arc; use std::sync::atomic::Ordering; @@ -177,7 +189,7 @@ async fn should_run_an_embedders_rules_on_a_submitted_plan() &ctx, plan, "test_job".into(), - Some(&embedder), + Some(Arc::new(embedder)), )?; assert_eq!(seen.preparation_runs.load(Ordering::Relaxed), 1); @@ -199,3 +211,214 @@ async fn should_run_an_embedders_rules_on_a_submitted_plan() Ok(()) } + +/// An operator over a descriptor with one partition per partition of the +/// operator, and an input with as many partitions, as Comet's +/// `CometFragmentExec` is. It can't be built over an input whose partition +/// count differs from its descriptor's. +#[derive(Debug)] +struct AlignedExec { + children: Vec>, + properties: Arc, +} + +impl AlignedExec { + fn try_new( + descriptor: Arc, + input: Arc, + ) -> datafusion::common::Result> { + let partitions = descriptor.output_partitioning().partition_count(); + let actual = input.output_partitioning().partition_count(); + if actual != partitions { + return internal_err!( + "AlignedExec input has {actual} partitions, expected {partitions}" + ); + } + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(input.schema()), + Partitioning::UnknownPartitioning(partitions), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Ok(Arc::new(Self { + children: vec![descriptor, input], + properties, + })) + } +} + +impl DisplayAs for AlignedExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result { + write!(f, "AlignedExec") + } +} + +impl ExecutionPlan for AlignedExec { + fn name(&self) -> &str { + "AlignedExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + self.children.iter().collect() + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut( + &Arc, + ) -> datafusion::common::Result, + ) -> datafusion::common::Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> datafusion::common::Result> { + let [descriptor, input] = <[_; 2]>::try_from(children) + .map_err(|_| internal_datafusion_err!("AlignedExec has two children"))?; + Self::try_new(descriptor, input) + } + + fn execute( + &self, + _partition: usize, + _context: Arc, + ) -> datafusion::common::Result { + internal_err!("AlignedExec is only planned") + } +} + +/// An embedder whose operators, [`PassThroughExec`]s and [`AlignedExec`]s, +/// tolerate a coalesced partition count. With `rebuild_descriptors`, it +/// rebuilds an `AlignedExec`'s descriptor for the coalesced count. +#[derive(Debug)] +struct ToleratingEmbedder { + rebuild_descriptors: bool, +} + +impl AdaptiveRules for ToleratingEmbedder { + fn tolerates_partition_count_change(&self, plan: &dyn ExecutionPlan) -> bool { + plan.is::() || plan.is::() + } + + fn with_coalesced_children( + &self, + plan: &Arc, + children: Vec>, + coalesce: &CoalescePlan, + ) -> Option>> { + if !self.rebuild_descriptors || !plan.is::() { + return None; + } + let descriptor = Arc::new( + EmptyExec::new(children[0].schema()).with_partitions(coalesce.groups.len()), + ); + Some(AlignedExec::try_new(descriptor, Arc::clone(&children[1]))) + } +} + +/// Plans `plan` with `embedder`'s rules, finishes its first stage with 8 +/// partitions of 50 bytes, which pack to 2 at the 200-byte target, and +/// returns the stage that runs next. +fn next_stage_after_coalescing( + ctx: &SessionContext, + plan: Arc, + embedder: ToleratingEmbedder, +) -> datafusion::common::Result> { + let mut planner = AdaptivePlanner::try_new_from_physical( + ctx, + plan, + "test_job".into(), + Some(Arc::new(embedder)), + )?; + let _ = planner.runnable_stages()?.unwrap(); + planner.finalise_stage_internal(0, partitions_with_byte_sizes(&[50; 8]))?; + let mut stages = planner.runnable_stages()?.unwrap(); + assert_eq!(stages.len(), 1); + Ok(Arc::clone(&stages.remove(0).plan) as Arc) +} + +/// An extension operator the embedder's rules declare tolerant has the +/// shuffle it reads coalesced, as a DataFusion operator would. +#[tokio::test] +async fn should_coalesce_shuffle_feeding_tolerated_extension_operator() +-> datafusion::common::Result<()> { + let ctx = physical_context(true); + let plan = hand_built_plan(&ctx, |shuffle| { + Arc::new(PassThroughExec::new("OpaqueExec", shuffle)) + }) + .await?; + let embedder = ToleratingEmbedder { + rebuild_descriptors: false, + }; + + let stage = next_stage_after_coalescing(&ctx, plan, embedder)?; + + assert_plan!(stage.as_ref(), @r" + ShuffleWriterExec: partitioning: Hash([c@2], 2) + OpaqueExec + ShuffleReaderExec: upstream_stage: 0, partitioning: Hash([c@2], 2), coalesce: 2 of 8 + "); + + Ok(()) +} + +/// An operator with per-partition state beside its inputs is rebuilt for the +/// coalesced partition count by the embedder's rules. +#[tokio::test] +async fn should_rebuild_extension_operator_over_coalesced_shuffle() +-> datafusion::common::Result<()> { + let ctx = physical_context(true); + let plan = hand_built_plan(&ctx, |shuffle| { + let descriptor = Arc::new(EmptyExec::new(shuffle.schema()).with_partitions(8)); + AlignedExec::try_new(descriptor, shuffle).unwrap() + }) + .await?; + let embedder = ToleratingEmbedder { + rebuild_descriptors: true, + }; + + let stage = next_stage_after_coalescing(&ctx, plan, embedder)?; + + // `AlignedExec` checks that its descriptor has as many partitions as the + // coalesced reader, so building it shows the descriptor was rebuilt. + assert_plan!(stage.as_ref(), @r" + ShuffleWriterExec: partitioning: UnknownPartitioning(2) + AlignedExec + EmptyExec + ShuffleReaderExec: upstream_stage: 0, partitioning: Hash([c@2], 2), coalesce: 2 of 8 + "); + + Ok(()) +} + +/// Without the embedder rebuilding it, the operator is rebuilt over the +/// coalesced shuffle with its descriptor as it was, which it rejects. +#[tokio::test] +async fn should_fail_extension_operator_its_rules_do_not_rebuild() +-> datafusion::common::Result<()> { + let ctx = physical_context(true); + let plan = hand_built_plan(&ctx, |shuffle| { + let descriptor = Arc::new(EmptyExec::new(shuffle.schema()).with_partitions(8)); + AlignedExec::try_new(descriptor, shuffle).unwrap() + }) + .await?; + let embedder = ToleratingEmbedder { + rebuild_descriptors: false, + }; + + let err = next_stage_after_coalescing(&ctx, plan, embedder).unwrap_err(); + + assert!( + err.to_string() + .contains("AlignedExec input has 2 partitions, expected 8"), + "{err}" + ); + + Ok(()) +} diff --git a/ballista/scheduler/src/state/aqe/test/plan_to_stages.rs b/ballista/scheduler/src/state/aqe/test/plan_to_stages.rs index 738f78b19c..a3a4124c0e 100644 --- a/ballista/scheduler/src/state/aqe/test/plan_to_stages.rs +++ b/ballista/scheduler/src/state/aqe/test/plan_to_stages.rs @@ -16,6 +16,7 @@ // under the License. use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::execution_plan::ExchangeExec; use crate::state::aqe::planner::AdaptivePlanner; use crate::state::aqe::test::{ @@ -26,7 +27,6 @@ use crate::state::execution_graph::ExecutionGraph; use ballista_core::JobId; use ballista_core::assert_plan; use ballista_core::execution_plans::SortShuffleWriterExec; -use ballista_core::serde::BallistaPhysicalExtensionCodec; use ballista_core::serde::protobuf::job_status::Status; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::physical_plan::ExecutionPlan; @@ -459,8 +459,7 @@ async fn newly_built_adaptive_graph_has_expected_state() &ctx, &logical_plan, 7, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await?; diff --git a/ballista/scheduler/src/state/aqe/test/reuse_exchange.rs b/ballista/scheduler/src/state/aqe/test/reuse_exchange.rs index 7ed2aa0100..4ae95d2397 100644 --- a/ballista/scheduler/src/state/aqe/test/reuse_exchange.rs +++ b/ballista/scheduler/src/state/aqe/test/reuse_exchange.rs @@ -19,6 +19,7 @@ //! `crate::state::aqe::reuse_exchange`). use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::execution_plan::{AdaptiveDatafusionExec, ExchangeExec}; use crate::state::aqe::planner::AdaptivePlanner; use crate::state::aqe::test::{ @@ -31,7 +32,6 @@ use crate::test_utils::{ revive_graph_and_complete_next_stage_with_executor, }; use ballista_core::extension::SessionConfigExt; -use ballista_core::serde::BallistaPhysicalExtensionCodec; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion::config::ConfigOptions; @@ -79,8 +79,7 @@ async fn graph(ctx: &SessionContext, sql: &str) -> AdaptiveExecutionGraph { ctx, &plan, 0, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await .unwrap() diff --git a/ballista/scheduler/src/state/aqe/test/stage_transitions.rs b/ballista/scheduler/src/state/aqe/test/stage_transitions.rs index 7a4820ff98..651113e796 100644 --- a/ballista/scheduler/src/state/aqe/test/stage_transitions.rs +++ b/ballista/scheduler/src/state/aqe/test/stage_transitions.rs @@ -19,12 +19,12 @@ //! graph unchanged, matching the static graph. use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::test::{mock_batch, mock_context}; use crate::state::execution_graph::ExecutionGraph; use crate::state::execution_stage::ExecutionStage; use crate::test_utils::{fail_plan_rewrites, revive_graph_and_complete_next_stage}; use ballista_core::error::Result; -use ballista_core::serde::BallistaPhysicalExtensionCodec; use std::collections::HashSet; use std::sync::Arc; @@ -45,8 +45,7 @@ async fn test_aggregation_plan() -> Result { &ctx, &logical_plan, 0, - None, - Arc::new(BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await } diff --git a/ballista/scheduler/src/state/task_manager.rs b/ballista/scheduler/src/state/task_manager.rs index 1369ebfcf3..547155a82e 100644 --- a/ballista/scheduler/src/state/task_manager.rs +++ b/ballista/scheduler/src/state/task_manager.rs @@ -22,6 +22,7 @@ use crate::physical_optimizer::file_group_balance::BalanceAndPruneFileGroups; use crate::planner::DefaultDistributedPlanner; use crate::scheduler_server::event::{QueryStageSchedulerEvent, SubmitPlan}; use crate::state::aqe::AdaptiveExecutionGraph; +use crate::state::aqe::SchedulerExtensions; use crate::state::aqe::adaptive_rules::AdaptiveRules; use crate::state::distributed_explain::handle_explain_plan; use crate::state::execution_graph::{ @@ -391,8 +392,7 @@ impl TaskManager &ctx, logical_plan, queued_at, - self.adaptive_rules.as_deref(), - self.codec.physical_extension_codec_arc(), + self.scheduler_extensions(), ) .await?, ) as ExecutionGraphBox @@ -433,8 +433,7 @@ impl TaskManager &ctx, physical_plan.clone(), queued_at, - self.adaptive_rules.as_deref(), - self.codec.physical_extension_codec_arc(), + self.scheduler_extensions(), )?) as ExecutionGraphBox } else { debug!("Using static query planner for physical-plan job submission"); @@ -475,6 +474,14 @@ impl TaskManager Ok(()) } + /// What this scheduler adds to planning a job adaptively. + fn scheduler_extensions(&self) -> SchedulerExtensions { + SchedulerExtensions { + physical_codec: self.codec.physical_extension_codec_arc(), + adaptive_rules: self.adaptive_rules.clone(), + } + } + /// Submit a logical plan for distributed execution. #[allow(clippy::too_many_arguments)] pub async fn submit_job( @@ -1663,8 +1670,7 @@ mod tests { &ctx, &plan, 0, - None, - Arc::new(ballista_core::serde::BallistaPhysicalExtensionCodec::default()), + SchedulerExtensions::default(), ) .await?; graph.revive(); diff --git a/docs/source/contributors-guide/architecture.md b/docs/source/contributors-guide/architecture.md index add10c185b..eeec19f2d3 100644 --- a/docs/source/contributors-guide/architecture.md +++ b/docs/source/contributors-guide/architecture.md @@ -276,7 +276,9 @@ re-derive them from operator requirements), and runs the same optimizer rules. T and Ballista operators by type and leave any other operator in place. An extension operator must declare what it needs from its input through `required_input_distribution`, as DataFusion re-derives `CoalescePartitionsExec` from that, and partition coalescing is skipped for a stage whose shuffles feed an -operator the rule does not know. +operator the rule does not know. A scheduler embedder can declare its own operators tolerant of a coalesced +partition count with `AdaptiveRules::tolerates_partition_count_change`, and rebuild one that keeps +per-partition state beside its inputs with `AdaptiveRules::with_coalesced_children`. ### How re-optimization works