Apache DataFusion SQL Query Engine
ARROW-9716: [Rust] [DataFusion] Implement limit on concurrent threads in MergeExec
Andy Grove2ed3b34e6b4d
diff --git a/rust/benchmarks/src/main.rs b/rust/benchmarks/src/main.rsindex eec58ca483..3aa25d2104 100644--- a/rust/benchmarks/src/main.rs+++ b/rust/benchmarks/src/main.rs@@ -25,7 +25,7 @@ use std::time::Instant;use arrow::datatypes::{DataType, Field, Schema};use arrow::util::pretty;use datafusion::error::Result;-use datafusion::execution::context::ExecutionContext;+use datafusion::execution::context::{ExecutionConfig, ExecutionContext};use datafusion::execution::physical_plan::csv::CsvReadOptions;use structopt::StructOpt;@@ -41,6 +41,10 @@ struct Opt {#[structopt(short = "i", long = "iterations", default_value = "3")]iterations: usize,+ /// Number of threads for query execution+ #[structopt(short = "c", long = "concurrency", default_value = "2")]+ concurrency: usize,+/// Batch size when reading CSV or Parquet files#[structopt(short = "s", long = "batch-size", default_value = "4096")]batch_size: usize,@@ -58,7 +62,8 @@ fn main() -> Result<()> {let opt = Opt::from_args();println!("Running benchmarks with the following options: {:?}", opt);- let mut ctx = ExecutionContext::new();+ let config = ExecutionConfig::new().with_concurrency(opt.concurrency);+ let mut ctx = ExecutionContext::with_config(config);let path = opt.path.to_str().unwrap();diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex 3d12f93e64..3ea4a45618 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -52,6 +52,7 @@ clap = "2.33"rustyline = {version = "6.0", optional = true}crossbeam = "0.7"paste = "0.1"+num_cpus = "1.13.0"[dev-dependencies]criterion = "0.3"diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex c6fb38c070..9d581bb3ea 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -62,10 +62,35 @@ use crate::sql::{};use crate::table::Table;+/// Configuration options for execution context+#[derive(Copy, Clone)]+pub struct ExecutionConfig {+ /// Number of concurrent threads for query execution.+ concurrency: usize,+}++impl ExecutionConfig {+ /// Create an execution config with default settings+ pub fn new() -> Self {+ Self {+ concurrency: num_cpus::get(),+ }+ }++ /// Customize max_concurrency+ pub fn with_concurrency(mut self, n: usize) -> Self {+ // concurrency must be greater than zero+ assert!(n > 0);+ self.concurrency = n;+ self+ }+}+/// Execution context for registering data sources and executing queriespub struct ExecutionContext {datasources: HashMap<String, Box<dyn TableProvider + Send + Sync>>,scalar_functions: HashMap<String, Box<ScalarFunction>>,+ config: ExecutionConfig,}fn tuple_err<T, R>(value: (Result<T>, Result<R>)) -> Result<(T, R)> {@@ -78,11 +103,17 @@ fn tuple_err<T, R>(value: (Result<T>, Result<R>)) -> Result<(T, R)> {}impl ExecutionContext {- /// Create a new execution context for in-memory queries+ /// Create a new execution context for in-memory queries using default configspub fn new() -> Self {+ Self::with_config(ExecutionConfig::new())+ }++ /// Create a new execution context for in-memory queries using provided configs+ pub fn with_config(config: ExecutionConfig) -> Self {let mut ctx = Self {datasources: HashMap::new(),scalar_functions: HashMap::new(),+ config,};register_math_functions(&mut ctx);ctx@@ -364,7 +395,11 @@ impl ExecutionContext {return Ok(Arc::new(initial_aggr));}- let merge = Arc::new(MergeExec::new(schema.clone(), partitions));+ let merge = Arc::new(MergeExec::new(+ schema.clone(),+ partitions,+ self.config.concurrency,+ ));// construct the expressions for the final aggregationlet (final_group, final_aggr) = initial_aggr.make_final_expr(@@ -419,7 +454,11 @@ impl ExecutionContext {}).collect::<Result<Vec<_>>>()?;- Ok(Arc::new(SortExec::try_new(sort_expr, input)?))+ Ok(Arc::new(SortExec::try_new(+ sort_expr,+ input,+ self.config.concurrency,+ )?))}LogicalPlan::Limit { input, n, .. } => {let input = self.create_physical_plan(input, batch_size)?;@@ -429,6 +468,7 @@ impl ExecutionContext {input_schema.clone(),input.partitions()?,*n,+ self.config.concurrency,)))}_ => Err(ExecutionError::General(@@ -552,7 +592,11 @@ impl ExecutionContext {}_ => {// merge into a single partition- let plan = MergeExec::new(plan.schema().clone(), partitions);+ let plan = MergeExec::new(+ plan.schema().clone(),+ partitions,+ self.config.concurrency,+ );let partitions = plan.partitions()?;if partitions.len() == 1 {common::collect(partitions[0].execute()?)diff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex 0b20c8df57..d7366395ca 100644--- a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs@@ -733,7 +733,7 @@ mod tests {aggregates.iter().map(|x| x.1.clone()).collect(),);- let merge = Arc::new(MergeExec::new(schema.clone(), partitions));+ let merge = Arc::new(MergeExec::new(schema.clone(), partitions, 2));let merged_aggregate = HashAggregateExec::try_new(final_groupdiff --git a/rust/datafusion/src/execution/physical_plan/limit.rs b/rust/datafusion/src/execution/physical_plan/limit.rsindex 45dba73a1e..6d1cffd77b 100644--- a/rust/datafusion/src/execution/physical_plan/limit.rs+++ b/rust/datafusion/src/execution/physical_plan/limit.rs@@ -39,6 +39,8 @@ pub struct GlobalLimitExec {partitions: Vec<Arc<dyn Partition>>,/// Maximum number of rows to returnlimit: usize,+ /// Number of threads to run parallel LocalLimitExec on+ concurrency: usize,}impl GlobalLimitExec {@@ -47,11 +49,13 @@ impl GlobalLimitExec {schema: SchemaRef,partitions: Vec<Arc<dyn Partition>>,limit: usize,+ concurrency: usize,) -> Self {GlobalLimitExec {schema,partitions,limit,+ concurrency,}}}@@ -66,6 +70,7 @@ impl ExecutionPlan for GlobalLimitExec {schema: self.schema.clone(),partitions: self.partitions.clone(),limit: self.limit,+ concurrency: self.concurrency,})])}}@@ -78,6 +83,8 @@ struct LimitPartition {partitions: Vec<Arc<dyn Partition>>,/// Maximum number of rows to returnlimit: usize,+ /// Number of threads to run parallel LocalLimitExec on+ concurrency: usize,}impl Partition for LimitPartition {@@ -96,7 +103,7 @@ impl Partition for LimitPartition {.collect();// limit needs to collapse inputs down to a single partition- let merge = MergeExec::new(self.schema.clone(), local_limit);+ let merge = MergeExec::new(self.schema.clone(), local_limit, self.concurrency);let merge_partitions = merge.partitions()?;// MergeExec must always produce a single partitionassert_eq!(1, merge_partitions.len());@@ -226,7 +233,7 @@ mod tests {let input = csv.partitions()?;assert_eq!(input.len(), num_partitions);- let limit = GlobalLimitExec::new(schema.clone(), input, 7);+ let limit = GlobalLimitExec::new(schema.clone(), input, 7, 2);let partitions = limit.partitions()?;// the result should contain 4 batches (one per input partition)diff --git a/rust/datafusion/src/execution/physical_plan/merge.rs b/rust/datafusion/src/execution/physical_plan/merge.rsindex dfb4f578c8..97614bdab0 100644--- a/rust/datafusion/src/execution/physical_plan/merge.rs+++ b/rust/datafusion/src/execution/physical_plan/merge.rs@@ -18,15 +18,16 @@//! Defines the merge plan for executing partitions in parallel and then merging the results//! into a single partition+use std::sync::{Arc, Mutex};+use std::thread::{self, JoinHandle};+use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common::RecordBatchIterator;use crate::execution::physical_plan::Partition;use crate::execution::physical_plan::{common, ExecutionPlan};+use arrow::datatypes::SchemaRef;use arrow::record_batch::{RecordBatch, RecordBatchReader};-use std::sync::{Arc, Mutex};-use std::thread;-use std::thread::JoinHandle;/// Merge execution plan executes partitions in parallel and combines them into a single/// partition. No guarantees are made about the order of the resulting partition.@@ -36,12 +37,22 @@ pub struct MergeExec {schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,+ /// Maximum number of concurrent threads+ concurrency: usize,}impl MergeExec {/// Create a new MergeExec- pub fn new(schema: SchemaRef, partitions: Vec<Arc<dyn Partition>>) -> Self {- MergeExec { schema, partitions }+ pub fn new(+ schema: SchemaRef,+ partitions: Vec<Arc<dyn Partition>>,+ max_concurrency: usize,+ ) -> Self {+ MergeExec {+ schema,+ partitions,+ concurrency: max_concurrency,+ }}}@@ -54,6 +65,7 @@ impl ExecutionPlan for MergeExec {Ok(vec![Arc::new(MergePartition {schema: self.schema.clone(),partitions: self.partitions.clone(),+ concurrency: self.concurrency,})])}}@@ -64,39 +76,70 @@ struct MergePartition {schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,+ /// Maximum number of concurrent threads+ concurrency: usize,+}++fn collect_from_thread(+ thread: JoinHandle<Result<Vec<RecordBatch>>>,+ combined_results: &mut Vec<Arc<RecordBatch>>,+) -> Result<()> {+ match thread.join() {+ Ok(join) => {+ join?+ .iter()+ .for_each(|batch| combined_results.push(Arc::new(batch.clone())));+ Ok(())+ }+ Err(e) => Err(ExecutionError::General(format!(+ "Error collecting batches from thread: {:?}",+ e+ ))),+ }}impl Partition for MergePartition {fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {- let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self- .partitions- .iter()- .map(|p| {- let p = p.clone();- thread::spawn(move || {- let it = p.execute()?;- common::collect(it)- })- })- .collect();-- // combine the results from each thread- let mut combined_results: Vec<Arc<RecordBatch>> = vec![];- for thread in threads {- match thread.join() {- Ok(join) => {- join?- .iter()- .for_each(|batch| combined_results.push(Arc::new(batch.clone())));+ match self.partitions.len() {+ 0 => Err(ExecutionError::General(+ "MergeExec requires at least one input partition".to_owned(),+ )),+ 1 => {+ // bypass any threading if there is a single partition+ self.partitions[0].execute()+ }+ _ => {+ let partitions_per_thread =+ (self.partitions.len() / self.concurrency).max(1);+ let chunks = self.partitions.chunks(partitions_per_thread);+ let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = chunks+ .map(|chunk| {+ let chunk = chunk.to_vec();+ thread::spawn(move || {+ let mut batches = vec![];+ for partition in chunk {+ let it = partition.execute()?;+ common::collect(it).iter().for_each(|b| {+ b.iter().for_each(|b| batches.push(b.clone()))+ });+ }+ Ok(batches)+ })+ })+ .collect();++ // combine the results from each thread+ let mut combined_results: Vec<Arc<RecordBatch>> = vec![];+ for thread in threads {+ collect_from_thread(thread, &mut combined_results)?;}- Err(e) => return Err(ExecutionError::General(format!("{:?}", e))),++ Ok(Arc::new(Mutex::new(RecordBatchIterator::new(+ self.schema.clone(),+ combined_results,+ ))))}}-- Ok(Arc::new(Mutex::new(RecordBatchIterator::new(- self.schema.clone(),- combined_results,- ))))}}@@ -123,7 +166,7 @@ mod tests {let input = csv.partitions()?;assert_eq!(input.len(), num_partitions);- let merge = MergeExec::new(schema.clone(), input);+ let merge = MergeExec::new(schema.clone(), input, 2);// output of MergeExec should have a single partitionlet merged = merge.partitions()?;diff --git a/rust/datafusion/src/execution/physical_plan/sort.rs b/rust/datafusion/src/execution/physical_plan/sort.rsindex 5f31d48f99..e86d6cc35a 100644--- a/rust/datafusion/src/execution/physical_plan/sort.rs+++ b/rust/datafusion/src/execution/physical_plan/sort.rs@@ -37,6 +37,8 @@ pub struct SortExec {/// Input schemainput: Arc<dyn ExecutionPlan>,expr: Vec<PhysicalSortExpr>,+ /// Number of threads to execute input partitions on before combining into a single partition+ concurrency: usize,}impl SortExec {@@ -44,8 +46,13 @@ impl SortExec {pub fn try_new(expr: Vec<PhysicalSortExpr>,input: Arc<dyn ExecutionPlan>,+ concurrency: usize,) -> Result<Self> {- Ok(Self { expr, input })+ Ok(Self {+ expr,+ input,+ concurrency,+ })}}@@ -60,6 +67,7 @@ impl ExecutionPlan for SortExec {input: self.input.partitions()?,expr: self.expr.clone(),schema: self.schema(),+ concurrency: self.concurrency,})),])}@@ -71,13 +79,16 @@ struct SortPartition {schema: SchemaRef,expr: Vec<PhysicalSortExpr>,input: Vec<Arc<dyn Partition>>,+ /// Number of threads to execute input partitions on before combining into a single partition+ concurrency: usize,}impl Partition for SortPartition {/// Execute the sortfn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {// sort needs to operate on a single partition currently- let merge = MergeExec::new(self.schema.clone(), self.input.clone());+ let merge =+ MergeExec::new(self.schema.clone(), self.input.clone(), self.concurrency);let merge_partitions = merge.partitions()?;// MergeExec must always produce a single partitionassert_eq!(1, merge_partitions.len());@@ -174,6 +185,7 @@ mod tests {},],Arc::new(csv),+ 2,)?;let result: Vec<RecordBatch> = test::execute(&sort_exec)?;