Skip to content

Apache DataFusion SQL Query Engine

Refactor QueryStageExec in preparation for implementing map-side shuffle (#459)

Andy Grovee5264f60a461
diff --git a/ballista/rust/core/Cargo.toml b/ballista/rust/core/Cargo.toml
index 1fc0e0c78b..99822cfe2a 100644
--- a/ballista/rust/core/Cargo.toml
+++ b/ballista/rust/core/Cargo.toml
@@ -45,6 +45,7 @@ arrow-flight = { version = "4.0" }
datafusion = { path = "../../../datafusion" }
[dev-dependencies]
+tempfile = "3"
[build-dependencies]
tonic-build = { version = "0.4" }
diff --git a/ballista/rust/core/src/execution_plans/query_stage.rs b/ballista/rust/core/src/execution_plans/query_stage.rs
index e95a5d8b51..233dee5b9b 100644
--- a/ballista/rust/core/src/execution_plans/query_stage.rs
+++ b/ballista/rust/core/src/execution_plans/query_stage.rs
@@ -15,13 +15,27 @@
// specific language governing permissions and limitations
// under the License.
+//! QueryStageExec represents a section of a query plan that has consistent partitioning and
+//! can be executed as one unit with each partition being executed in parallel. The output of
+//! a query stage either forms the input of another query stage or can be the final result of
+//! a query.
+
+use std::path::PathBuf;
use std::sync::Arc;
+use std::time::Instant;
use std::{any::Any, pin::Pin};
+use crate::error::BallistaError;
+use crate::memory_stream::MemoryStream;
+use crate::utils;
+
use async_trait::async_trait;
-use datafusion::arrow::datatypes::SchemaRef;
-use datafusion::physical_plan::{ExecutionPlan, Partitioning};
-use datafusion::{error::Result, physical_plan::RecordBatchStream};
+use datafusion::arrow::array::{ArrayRef, StringBuilder};
+use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use datafusion::arrow::record_batch::RecordBatch;
+use datafusion::error::{DataFusionError, Result};
+use datafusion::physical_plan::{ExecutionPlan, Partitioning, RecordBatchStream};
+use log::info;
use uuid::Uuid;
/// QueryStageExec represents a section of a query plan that has consistent partitioning and
@@ -31,11 +45,15 @@ use uuid::Uuid;
#[derive(Debug, Clone)]
pub struct QueryStageExec {
/// Unique ID for the job (query) that this stage is a part of
- pub job_id: String,
+ job_id: String,
/// Unique query stage ID within the job
- pub stage_id: usize,
+ stage_id: usize,
/// Physical execution plan for this query stage
- pub child: Arc<dyn ExecutionPlan>,
+ plan: Arc<dyn ExecutionPlan>,
+ /// Path to write output streams to
+ work_dir: String,
+ /// Optional shuffle output partitioning
+ shuffle_output_partitioning: Option<Partitioning>,
}
impl QueryStageExec {
@@ -43,14 +61,28 @@ impl QueryStageExec {
pub fn try_new(
job_id: String,
stage_id: usize,
- child: Arc<dyn ExecutionPlan>,
+ plan: Arc<dyn ExecutionPlan>,
+ work_dir: String,
+ shuffle_output_partitioning: Option<Partitioning>,
) -> Result<Self> {
Ok(Self {
job_id,
stage_id,
- child,
+ plan,
+ work_dir,
+ shuffle_output_partitioning,
})
}
+
+ /// Get the Job ID for this query stage
+ pub fn job_id(&self) -> &str {
+ &self.job_id
+ }
+
+ /// Get the Stage ID for this query stage
+ pub fn stage_id(&self) -> usize {
+ self.stage_id
+ }
}
#[async_trait]
@@ -60,15 +92,15 @@ impl ExecutionPlan for QueryStageExec {
}
fn schema(&self) -> SchemaRef {
- self.child.schema()
+ self.plan.schema()
}
fn output_partitioning(&self) -> Partitioning {
- self.child.output_partitioning()
+ self.plan.output_partitioning()
}
fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
- vec![self.child.clone()]
+ vec![self.plan.clone()]
}
fn with_new_children(
@@ -80,6 +112,8 @@ impl ExecutionPlan for QueryStageExec {
self.job_id.clone(),
self.stage_id,
children[0].clone(),
+ self.work_dir.clone(),
+ None,
)?))
}
@@ -87,6 +121,132 @@ impl ExecutionPlan for QueryStageExec {
&self,
partition: usize,
) -> Result<Pin<Box<dyn RecordBatchStream + Send + Sync>>> {
- self.child.execute(partition).await
+ let now = Instant::now();
+
+ let mut stream = self.plan.execute(partition).await?;
+
+ let mut path = PathBuf::from(&self.work_dir);
+ path.push(&self.job_id);
+ path.push(&format!("{}", self.stage_id));
+
+ match &self.shuffle_output_partitioning {
+ None => {
+ path.push(&format!("{}", partition));
+ std::fs::create_dir_all(&path)?;
+
+ path.push("data.arrow");
+ let path = path.to_str().unwrap();
+ info!("Writing results to {}", path);
+
+ // stream results to disk
+ let stats = utils::write_stream_to_disk(&mut stream, &path)
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
+
+ info!(
+ "Executed partition {} in {} seconds. Statistics: {:?}",
+ partition,
+ now.elapsed().as_secs(),
+ stats
+ );
+
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("path", DataType::Utf8, false),
+ stats.arrow_struct_repr(),
+ ]));
+
+ // build result set with summary of the partition execution status
+ let mut c0 = StringBuilder::new(1);
+ c0.append_value(&path).unwrap();
+ let path: ArrayRef = Arc::new(c0.finish());
+
+ let stats: ArrayRef = stats
+ .to_arrow_arrayref()
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
+ let batch = RecordBatch::try_new(schema.clone(), vec![path, stats])
+ .map_err(DataFusionError::ArrowError)?;
+
+ Ok(Box::pin(MemoryStream::try_new(vec![batch], schema, None)?))
+ }
+
+ Some(Partitioning::Hash(_, _)) => {
+ //TODO re-use code from RepartitionExec to split each batch into
+ // partitions and write to one IPC file per partition
+ // See https://github.com/apache/arrow-datafusion/issues/456
+ Err(DataFusionError::NotImplemented(
+ "Shuffle partitioning not implemented yet".to_owned(),
+ ))
+ }
+
+ _ => Err(DataFusionError::Execution(
+ "Invalid shuffle partitioning scheme".to_owned(),
+ )),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use datafusion::arrow::array::{StringArray, StructArray, UInt32Array, UInt64Array};
+ use datafusion::physical_plan::memory::MemoryExec;
+ use tempfile::TempDir;
+
+ #[tokio::test]
+ async fn test() -> Result<()> {
+ let input_plan = create_input_plan()?;
+ let work_dir = TempDir::new()?;
+ let query_stage = QueryStageExec::try_new(
+ "jobOne".to_owned(),
+ 1,
+ input_plan,
+ work_dir.into_path().to_str().unwrap().to_owned(),
+ None,
+ )?;
+ let mut stream = query_stage.execute(0).await?;
+ let batches = utils::collect_stream(&mut stream)
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
+ assert!(batches.len() == 1);
+ let batch = &batches[0];
+ assert_eq!(2, batch.num_columns());
+ assert_eq!(1, batch.num_rows());
+ let path = batch.columns()[0]
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ let file = path.value(0);
+ assert!(file.ends_with("data.arrow"));
+ let stats = batch.columns()[1]
+ .as_any()
+ .downcast_ref::<StructArray>()
+ .unwrap();
+ let num_rows = stats
+ .column_by_name("num_rows")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<UInt64Array>()
+ .unwrap();
+ assert_eq!(4, num_rows.value(0));
+ Ok(())
+ }
+
+ fn create_input_plan() -> Result<Arc<dyn ExecutionPlan>> {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::UInt32, true),
+ Field::new("b", DataType::Utf8, true),
+ ]));
+
+ // define data.
+ let batch = RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(UInt32Array::from(vec![Some(1), Some(2)])),
+ Arc::new(StringArray::from(vec![Some("hello"), Some("world")])),
+ ],
+ )?;
+ let partition = vec![batch.clone(), batch];
+ let partitions = vec![partition.clone(), partition];
+ Ok(Arc::new(MemoryExec::try_new(&partitions, schema, None)?))
}
}
diff --git a/ballista/rust/core/src/utils.rs b/ballista/rust/core/src/utils.rs
index 85d1161795..4ba6ec40fe 100644
--- a/ballista/rust/core/src/utils.rs
+++ b/ballista/rust/core/src/utils.rs
@@ -112,13 +112,13 @@ pub fn produce_diagram(filename: &str, stages: &[Arc<QueryStageExec>]) -> Result
// draw stages and entities
for stage in stages {
- writeln!(w, "\tsubgraph cluster{} {{", stage.stage_id)?;
- writeln!(w, "\t\tlabel = \"Stage {}\";", stage.stage_id)?;
+ writeln!(w, "\tsubgraph cluster{} {{", stage.stage_id())?;
+ writeln!(w, "\t\tlabel = \"Stage {}\";", stage.stage_id())?;
let mut id = AtomicUsize::new(0);
build_exec_plan_diagram(
&mut w,
- stage.child.as_ref(),
- stage.stage_id,
+ stage.children()[0].as_ref(),
+ stage.stage_id(),
&mut id,
true,
)?;
@@ -130,8 +130,8 @@ pub fn produce_diagram(filename: &str, stages: &[Arc<QueryStageExec>]) -> Result
let mut id = AtomicUsize::new(0);
build_exec_plan_diagram(
&mut w,
- stage.child.as_ref(),
- stage.stage_id,
+ stage.children()[0].as_ref(),
+ stage.stage_id(),
&mut id,
false,
)?;
diff --git a/ballista/rust/executor/src/executor.rs b/ballista/rust/executor/src/executor.rs
index e2945bf8e8..90c39277e2 100644
--- a/ballista/rust/executor/src/executor.rs
+++ b/ballista/rust/executor/src/executor.rs
@@ -17,17 +17,13 @@
//! Ballista executor logic
-use std::path::PathBuf;
use std::sync::Arc;
-use std::time::Instant;
use ballista_core::error::BallistaError;
+use ballista_core::execution_plans::QueryStageExec;
use ballista_core::utils;
-use datafusion::arrow::array::{ArrayRef, StringBuilder};
-use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::physical_plan::ExecutionPlan;
-use log::info;
/// Ballista executor
pub struct Executor {
@@ -55,43 +51,13 @@ impl Executor {
part: usize,
plan: Arc<dyn ExecutionPlan>,
) -> Result<RecordBatch, BallistaError> {
- let mut path = PathBuf::from(&self.work_dir);
- path.push(&job_id);
- path.push(&format!("{}", stage_id));
- path.push(&format!("{}", part));
- std::fs::create_dir_all(&path)?;
-
- path.push("data.arrow");
- let path = path.to_str().unwrap();
- info!("Writing results to {}", path);
-
- let now = Instant::now();
-
- // execute the query partition
- let mut stream = plan.execute(part).await?;
-
- // stream results to disk
- let stats = utils::write_stream_to_disk(&mut stream, &path).await?;
-
- info!(
- "Executed partition {} in {} seconds. Statistics: {:?}",
- part,
- now.elapsed().as_secs(),
- stats
- );
-
- let schema = Arc::new(Schema::new(vec![
- Field::new("path", DataType::Utf8, false),
- stats.arrow_struct_repr(),
- ]));
-
- // build result set with summary of the partition execution status
- let mut c0 = StringBuilder::new(1);
- c0.append_value(&path).unwrap();
- let path: ArrayRef = Arc::new(c0.finish());
-
- let stats: ArrayRef = stats.to_arrow_arrayref()?;
- RecordBatch::try_new(schema, vec![path, stats]).map_err(BallistaError::ArrowError)
+ let exec =
+ QueryStageExec::try_new(job_id, stage_id, plan, self.work_dir.clone(), None)?;
+ let mut stream = exec.execute(part).await?;
+ let batches = utils::collect_stream(&mut stream).await?;
+ // the output should be a single batch containing metadata (path and statistics)
+ assert!(batches.len() == 1);
+ Ok(batches[0].clone())
}
pub fn work_dir(&self) -> &str {
diff --git a/ballista/rust/scheduler/src/lib.rs b/ballista/rust/scheduler/src/lib.rs
index 3dc8df29bd..99c7be66a6 100644
--- a/ballista/rust/scheduler/src/lib.rs
+++ b/ballista/rust/scheduler/src/lib.rs
@@ -388,8 +388,8 @@ impl SchedulerGrpc for SchedulerServer {
fail_job!(state
.save_stage_plan(
&job_id_spawn,
- stage.stage_id,
- stage.child.clone()
+ stage.stage_id(),
+ stage.children()[0].clone()
)
.await
.map_err(|e| {
@@ -402,7 +402,7 @@ impl SchedulerGrpc for SchedulerServer {
let pending_status = TaskStatus {
partition_id: Some(PartitionId {
job_id: job_id_spawn.clone(),
- stage_id: stage.stage_id as u32,
+ stage_id: stage.stage_id() as u32,
partition_id: partition_id as u32,
}),
status: None,
diff --git a/ballista/rust/scheduler/src/planner.rs b/ballista/rust/scheduler/src/planner.rs
index b1d999b733..445ef9a077 100644
--- a/ballista/rust/scheduler/src/planner.rs
+++ b/ballista/rust/scheduler/src/planner.rs
@@ -71,11 +71,7 @@ impl DistributedPlanner {
info!("planning query stages");
let (new_plan, mut stages) =
self.plan_query_stages_internal(job_id, execution_plan)?;
- stages.push(create_query_stage(
- job_id.to_string(),
- self.next_stage_id(),
- new_plan,
- )?);
+ stages.push(create_query_stage(job_id, self.next_stage_id(), new_plan)?);
Ok(stages)
}
@@ -112,12 +108,12 @@ impl DistributedPlanner {
Ok((ctx.create_physical_plan(&adapter.logical_plan)?, stages))
} else if let Some(merge) = execution_plan.as_any().downcast_ref::<MergeExec>() {
let query_stage = create_query_stage(
- job_id.to_string(),
+ job_id,
self.next_stage_id(),
merge.children()[0].clone(),
)?;
let unresolved_shuffle = Arc::new(UnresolvedShuffleExec::new(
- vec![query_stage.stage_id],
+ vec![query_stage.stage_id()],
query_stage.schema(),
query_stage.output_partitioning().partition_count(),
));
@@ -133,12 +129,12 @@ impl DistributedPlanner {
let mut new_children: Vec<Arc<dyn ExecutionPlan>> = vec![];
for child in &children {
let new_stage = create_query_stage(
- job_id.to_string(),
+ job_id,
self.next_stage_id(),
child.clone(),
)?;
new_children.push(Arc::new(UnresolvedShuffleExec::new(
- vec![new_stage.stage_id],
+ vec![new_stage.stage_id()],
new_stage.schema().clone(),
new_stage.output_partitioning().partition_count(),
)));
@@ -165,13 +161,10 @@ impl DistributedPlanner {
{
let mut new_children: Vec<Arc<dyn ExecutionPlan>> = vec![];
for child in &children {
- let new_stage = create_query_stage(
- job_id.to_string(),
- self.next_stage_id(),
- child.clone(),
- )?;
+ let new_stage =
+ create_query_stage(job_id, self.next_stage_id(), child.clone())?;
new_children.push(Arc::new(UnresolvedShuffleExec::new(
- vec![new_stage.stage_id],
+ vec![new_stage.stage_id()],
new_stage.schema().clone(),
new_stage.output_partitioning().partition_count(),
)));
@@ -229,11 +222,17 @@ pub fn remove_unresolved_shuffles(
}
fn create_query_stage(
- job_id: String,
+ job_id: &str,
stage_id: usize,
plan: Arc<dyn ExecutionPlan>,
) -> Result<Arc<QueryStageExec>> {
- Ok(Arc::new(QueryStageExec::try_new(job_id, stage_id, plan)?))
+ Ok(Arc::new(QueryStageExec::try_new(
+ job_id.to_owned(),
+ stage_id,
+ plan,
+ "".to_owned(), // executor will decide on the work_dir path
+ None,
+ )?))
}
#[cfg(test)]