use ballista_core::client_pool::BallistaClientPool;
use ballista_core::execution_plans::sort_shuffle::SortShuffleWriterExec;
use ballista_core::execution_plans::{
RangeShuffleReaderExec, RangeShuffleWriterExec, ShuffleReaderExec, ShuffleWriterExec,
};
use ballista_core::serde::protobuf::{ShuffleWritePartition, TaskColumnStats};
use ballista_core::serde::scheduler::PartitionStats;
use ballista_core::{JobId, utils};
use datafusion::arrow::array::{
Array, StringArray, StructArray, UInt32Array, UInt64Array,
};
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::context::TaskContext;
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::display::DisplayableExecutionPlan;
use datafusion::physical_plan::metrics::MetricsSet;
use datafusion::prelude::SessionConfig;
use futures::stream::TryStreamExt;
use log::debug;
use std::fmt::{Debug, Display};
use std::sync::Arc;
pub trait ExecutionEngine: Sync + Send {
#[allow(clippy::too_many_arguments)]
fn create_query_stage_exec(
&self,
job_id: JobId,
stage_id: usize,
task_id: usize,
global_output_partition_ids: Vec<usize>,
plan: Arc<dyn ExecutionPlan>,
work_dir: &str,
config: &SessionConfig,
) -> Result<Arc<dyn QueryStageExecutor>>;
}
#[async_trait::async_trait]
pub trait QueryStageExecutor: Sync + Send + Debug + Display {
async fn execute_query_stage(
&self,
task_id: usize,
context: Arc<TaskContext>,
) -> Result<Vec<ShuffleWritePartition>>;
fn collect_plan_metrics(&self) -> Vec<MetricsSet>;
fn collect_runtime_stats_reports(
&self,
) -> Vec<ballista_core::serde::protobuf::RuntimeStatsReport> {
Vec::new()
}
fn collect_window_state_reports(
&self,
) -> Result<Vec<ballista_core::serde::protobuf::WindowStateReport>> {
Ok(Vec::new())
}
fn collect_column_stats(&self) -> Vec<TaskColumnStats> {
Vec::new()
}
}
#[derive(Default)]
pub struct DefaultExecutionEngine {
client_pool: Option<Arc<dyn BallistaClientPool>>,
}
impl DefaultExecutionEngine {
pub fn new() -> Self {
Self { client_pool: None }
}
pub fn with_client_pool(client_pool: Arc<dyn BallistaClientPool>) -> Self {
Self {
client_pool: Some(client_pool),
}
}
}
impl ExecutionEngine for DefaultExecutionEngine {
fn create_query_stage_exec(
&self,
job_id: JobId,
stage_id: usize,
task_id: usize,
global_output_partition_ids: Vec<usize>,
plan: Arc<dyn ExecutionPlan>,
work_dir: &str,
_config: &SessionConfig,
) -> Result<Arc<dyn QueryStageExecutor>> {
let plan = plan
.transform(|p| {
if let Some(reader) = p.downcast_ref::<ShuffleReaderExec>() {
match &self.client_pool {
Some(client_pool) => Ok(Transformed::yes(Arc::new(
reader
.with_work_dir(work_dir.to_string())
.with_client_pool(client_pool.clone()),
))),
None => Ok(Transformed::yes(Arc::new(
reader.with_work_dir(work_dir.to_string()),
))),
}
} else if let Some(reader) = p.downcast_ref::<RangeShuffleReaderExec>() {
match &self.client_pool {
Some(client_pool) => Ok(Transformed::yes(Arc::new(
reader
.with_work_dir(work_dir.to_string())
.with_client_pool(client_pool.clone()),
))),
None => Ok(Transformed::yes(Arc::new(
reader.with_work_dir(work_dir.to_string()),
))),
}
} else {
Ok(Transformed::no(p))
}
})?
.data;
if plan.downcast_ref::<ShuffleWriterExec>().is_some() {
let exec = ShuffleWriterExec::try_new(
job_id,
stage_id,
plan.children()[0].clone(),
work_dir.to_string(),
)?
.with_task_id(task_id)
.with_global_output_partition_ids(global_output_partition_ids);
Ok(Arc::new(DefaultQueryStageExec::new(
ShuffleWriterVariant::Passthrough(exec),
)))
} else if plan.downcast_ref::<RangeShuffleWriterExec>().is_some() {
let exec = RangeShuffleWriterExec::try_new(
job_id,
stage_id,
plan.children()[0].clone(),
work_dir.to_string(),
)?
.with_task_id(task_id);
Ok(Arc::new(DefaultQueryStageExec::new(
ShuffleWriterVariant::Range(exec),
)))
} else if let Some(sort_shuffle_writer) =
plan.downcast_ref::<SortShuffleWriterExec>()
{
let exec = SortShuffleWriterExec::try_new(
job_id,
stage_id,
plan.children()[0].clone(),
work_dir.to_string(),
sort_shuffle_writer.shuffle_output_partitioning().clone(),
sort_shuffle_writer.config().clone(),
)?
.with_task_id(task_id)
.with_global_output_partition_ids(global_output_partition_ids);
Ok(Arc::new(DefaultQueryStageExec::new(
ShuffleWriterVariant::Sort(exec),
)))
} else {
Err(DataFusionError::Internal(
"Plan passed to new_query_stage_exec is not a ShuffleWriterExec, \
RangeShuffleWriterExec, or SortShuffleWriterExec"
.to_string(),
))
}
}
}
#[derive(Debug, Clone)]
pub enum ShuffleWriterVariant {
Passthrough(ShuffleWriterExec),
Range(RangeShuffleWriterExec),
Sort(SortShuffleWriterExec),
}
#[derive(Debug)]
pub struct DefaultQueryStageExec {
shuffle_writer: ShuffleWriterVariant,
}
impl DefaultQueryStageExec {
pub fn new(shuffle_writer: ShuffleWriterVariant) -> Self {
Self { shuffle_writer }
}
}
impl Display for DefaultQueryStageExec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.shuffle_writer {
ShuffleWriterVariant::Passthrough(writer) => {
let stage_metrics: Vec<String> = writer
.metrics()
.unwrap_or_default()
.iter()
.map(|m| m.to_string())
.collect();
write!(
f,
"DefaultQueryStageExec(Passthrough): ({})\n{}",
stage_metrics.join(", "),
writer
)
}
ShuffleWriterVariant::Range(writer) => {
let stage_metrics: Vec<String> = writer
.metrics()
.unwrap_or_default()
.iter()
.map(|m| m.to_string())
.collect();
write!(
f,
"DefaultQueryStageExec(Range): ({})\n{}",
stage_metrics.join(", "),
writer
)
}
ShuffleWriterVariant::Sort(writer) => {
let stage_metrics: Vec<String> = writer
.metrics()
.unwrap_or_default()
.iter()
.map(|m| m.to_string())
.collect();
write!(
f,
"DefaultQueryStageExec(Sort): ({})\n{}",
stage_metrics.join(", "),
writer
)
}
}
}
}
#[async_trait::async_trait]
impl QueryStageExecutor for DefaultQueryStageExec {
async fn execute_query_stage(
&self,
task_id: usize,
context: Arc<TaskContext>,
) -> Result<Vec<ShuffleWritePartition>> {
let (plan_arc, is_sort_shuffle): (Arc<dyn ExecutionPlan>, bool) =
match &self.shuffle_writer {
ShuffleWriterVariant::Passthrough(writer) => {
(Arc::new(writer.clone()), false)
}
ShuffleWriterVariant::Range(writer) => (Arc::new(writer.clone()), false),
ShuffleWriterVariant::Sort(writer) => (Arc::new(writer.clone()), true),
};
debug!(
"executor plan pre-run (task_id={task_id}):\n{}",
DisplayableExecutionPlan::new(plan_arc.as_ref()).indent(true)
);
let result =
drive_shuffle_writer_stage(plan_arc.clone(), context, is_sort_shuffle).await;
debug!(
"executor plan post-run (task_id={task_id}, ok={}):\n{}",
result.is_ok(),
DisplayableExecutionPlan::with_metrics(plan_arc.as_ref()).indent(true)
);
result
}
fn collect_plan_metrics(&self) -> Vec<MetricsSet> {
match &self.shuffle_writer {
ShuffleWriterVariant::Passthrough(writer) => {
utils::collect_plan_metrics(writer)
}
ShuffleWriterVariant::Range(writer) => utils::collect_plan_metrics(writer),
ShuffleWriterVariant::Sort(writer) => utils::collect_plan_metrics(writer),
}
}
fn collect_runtime_stats_reports(
&self,
) -> Vec<ballista_core::serde::protobuf::RuntimeStatsReport> {
let plan: Arc<dyn ExecutionPlan> = match &self.shuffle_writer {
ShuffleWriterVariant::Passthrough(writer) => Arc::new(writer.clone()),
ShuffleWriterVariant::Range(writer) => Arc::new(writer.clone()),
ShuffleWriterVariant::Sort(writer) => Arc::new(writer.clone()),
};
match ballista_core::execution_plans::collect_runtime_stats_reports(&plan) {
Ok(reports) => reports,
Err(e) => {
log::warn!(
"collect_runtime_stats_reports failed, task will report empty stats: {e}"
);
Vec::new()
}
}
}
fn collect_window_state_reports(
&self,
) -> Result<Vec<ballista_core::serde::protobuf::WindowStateReport>> {
let captured = match &self.shuffle_writer {
ShuffleWriterVariant::Passthrough(writer) => writer.collect_window_state()?,
ShuffleWriterVariant::Range(writer) => writer.collect_window_state(),
ShuffleWriterVariant::Sort(_) => return Ok(Vec::new()),
};
captured
.iter()
.map(|(global_partition, observed)| {
ballista_core::execution_plans::window_state_to_proto(
*global_partition,
observed,
)
})
.collect()
}
fn collect_column_stats(&self) -> Vec<TaskColumnStats> {
match &self.shuffle_writer {
ShuffleWriterVariant::Sort(writer) => writer
.column_null_counts()
.into_iter()
.enumerate()
.map(|(column, null_count)| TaskColumnStats {
column: column as u32,
null_count,
sketches: vec![],
})
.collect(),
_ => vec![],
}
}
}
async fn drive_shuffle_writer_stage(
plan: Arc<dyn ExecutionPlan>,
context: Arc<TaskContext>,
is_sort_shuffle: bool,
) -> Result<Vec<ShuffleWritePartition>> {
let k = plan.properties().output_partitioning().partition_count();
let mut stream_futures = Vec::with_capacity(k);
for n in 0..k {
let plan = plan.clone();
let ctx = context.clone();
stream_futures.push(tokio::spawn(async move {
let mut stream = plan.execute(n, ctx)?;
let mut batches = Vec::new();
while let Some(batch) = stream.try_next().await? {
batches.push(batch);
}
metadata_batches_to_summaries(batches, is_sort_shuffle)
}));
}
let mut summaries = Vec::with_capacity(k);
for handle in stream_futures {
let per_partition = handle.await.map_err(|e| {
DataFusionError::Execution(format!("shuffle writer drain panicked: {e}"))
})??;
summaries.extend(per_partition);
}
summaries.retain(|s| s.num_bytes > 0);
Ok(summaries)
}
fn metadata_batches_to_summaries(
batches: Vec<datafusion::arrow::record_batch::RecordBatch>,
is_sort_shuffle: bool,
) -> Result<Vec<ShuffleWritePartition>> {
let stats_fields = PartitionStats::default().arrow_struct_fields();
let num_rows_idx = stats_fields
.iter()
.position(|f| f.name() == "num_rows")
.expect("num_rows field present in PartitionStats");
let num_batches_idx = stats_fields
.iter()
.position(|f| f.name() == "num_batches")
.expect("num_batches field present in PartitionStats");
let num_bytes_idx = stats_fields
.iter()
.position(|f| f.name() == "num_bytes")
.expect("num_bytes field present in PartitionStats");
let mut out = Vec::new();
for batch in batches {
let partition_col = batch
.column(0)
.as_any()
.downcast_ref::<UInt32Array>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata batch: partition column not UInt32".into(),
)
})?;
let _path_col = batch
.column(1)
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata batch: path column not Utf8".into(),
)
})?;
let file_id_col = batch
.column(2)
.as_any()
.downcast_ref::<UInt64Array>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata batch: file_id column not UInt64".into(),
)
})?;
let stats_col = batch
.column(3)
.as_any()
.downcast_ref::<StructArray>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata batch: stats column not Struct".into(),
)
})?;
let num_rows_arr = stats_col
.column(num_rows_idx)
.as_any()
.downcast_ref::<UInt64Array>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata stats.num_rows not UInt64".into(),
)
})?;
let num_batches_arr = stats_col
.column(num_batches_idx)
.as_any()
.downcast_ref::<UInt64Array>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata stats.num_batches not UInt64".into(),
)
})?;
let num_bytes_arr = stats_col
.column(num_bytes_idx)
.as_any()
.downcast_ref::<UInt64Array>()
.ok_or_else(|| {
DataFusionError::Internal(
"shuffle metadata stats.num_bytes not UInt64".into(),
)
})?;
for row in 0..batch.num_rows() {
let file_id = if file_id_col.is_null(row) {
None
} else {
Some(file_id_col.value(row))
};
out.push(ShuffleWritePartition {
partition_id: partition_col.value(row) as u64,
num_batches: num_batches_arr.value(row),
num_rows: num_rows_arr.value(row),
num_bytes: num_bytes_arr.value(row),
file_id,
is_sort_shuffle,
});
}
}
Ok(out)
}