Skip to content

Apache DataFusion SQL Query Engine

feat: concurrent physical planning (#6138)

Marco Neumann69c822b199a5
diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs
index a89bc2f8fd..753d0ccaab 100644
--- a/datafusion/common/src/config.rs
+++ b/datafusion/common/src/config.rs
@@ -212,7 +212,9 @@ config_namespace! {
pub collect_statistics: bool, default = false
/// Number of partitions for query execution. Increasing partitions can increase
- /// concurrency. Defaults to the number of CPU cores on the system
+ /// concurrency.
+ ///
+ /// Defaults to the number of CPU cores on the system
pub target_partitions: usize, default = num_cpus::get()
/// The default time zone
@@ -226,6 +228,13 @@ config_namespace! {
/// Aggregate options
pub aggregate: AggregateOptions, default = Default::default()
+
+ /// Fan-out during initial physical planning.
+ ///
+ /// This is mostly use to plan `UNION` children in parallel.
+ ///
+ /// Defaults to the number of CPU cores on the system
+ pub planning_concurrency: usize, default = num_cpus::get()
}
}
@@ -569,7 +578,10 @@ impl ConfigOptions {
use std::fmt::Write as _;
let mut s = Self::default();
- s.execution.target_partitions = 0; // Normalize for display
+
+ // Normalize for display
+ s.execution.target_partitions = 0;
+ s.execution.planning_concurrency = 0;
let mut docs = "| key | default | description |\n".to_string();
docs += "|-----|---------|-------------|\n";
diff --git a/datafusion/core/Cargo.toml b/datafusion/core/Cargo.toml
index 023848641f..f24e200e26 100644
--- a/datafusion/core/Cargo.toml
+++ b/datafusion/core/Cargo.toml
@@ -99,7 +99,7 @@ zstd = { version = "0.12", optional = true, default-features = false }
[dev-dependencies]
async-trait = "0.1.53"
bigdecimal = "0.3.0"
-criterion = "0.4"
+criterion = { version = "0.4", features = ["async_tokio"] }
csv = "1.1.6"
ctor = "0.2.0"
doc-comment = "0.3"
@@ -152,6 +152,10 @@ name = "parquet_query_sql"
harness = false
name = "sql_planner"
+[[bench]]
+harness = false
+name = "sql_query_with_io"
+
[[bench]]
harness = false
name = "sort"
diff --git a/datafusion/core/benches/sql_query_with_io.rs b/datafusion/core/benches/sql_query_with_io.rs
new file mode 100644
index 0000000000..1d96df0cec
--- /dev/null
+++ b/datafusion/core/benches/sql_query_with_io.rs
@@ -0,0 +1,263 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::{fmt::Write, sync::Arc, time::Duration};
+
+use arrow::array::{Int64Builder, UInt64Builder};
+use arrow_array::RecordBatch;
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use bytes::Bytes;
+use criterion::{criterion_group, criterion_main, Criterion, SamplingMode};
+use datafusion::{
+ datasource::{
+ file_format::parquet::ParquetFormat,
+ listing::{ListingOptions, ListingTableUrl},
+ },
+ prelude::{SessionConfig, SessionContext},
+};
+use datafusion_execution::runtime_env::RuntimeEnv;
+use itertools::Itertools;
+use object_store::{
+ memory::InMemory,
+ path::Path,
+ throttle::{ThrottleConfig, ThrottledStore},
+ ObjectStore,
+};
+use parquet::arrow::ArrowWriter;
+use rand::{rngs::StdRng, Rng, SeedableRng};
+use tokio::runtime::Runtime;
+use url::Url;
+
+const THREADS: usize = 4;
+const TABLES: usize = 3;
+const TABLE_PARTITIONS: usize = 10;
+const PARTITION_FILES: usize = 2;
+const FILE_ROWS: usize = 1_000_000;
+const RNG_SEED: u64 = 1234;
+const STORE_LATENCY: Duration = Duration::from_millis(100);
+
+fn table_name(table_id: usize) -> String {
+ format!("table_{table_id}")
+}
+
+fn schema() -> SchemaRef {
+ Arc::new(Schema::new(vec![
+ Field::new("id", DataType::UInt64, false),
+ Field::new("payload", DataType::Int64, false),
+ ]))
+}
+
+fn create_parquet_file(rng: &mut StdRng, id_offset: usize) -> Bytes {
+ let schema = schema();
+ let mut id_builder = UInt64Builder::new();
+ let mut payload_builder = Int64Builder::new();
+ for row in 0..FILE_ROWS {
+ id_builder.append_value((row + id_offset) as u64);
+ payload_builder.append_value(rng.gen());
+ }
+ let batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(id_builder.finish()),
+ Arc::new(payload_builder.finish()),
+ ],
+ )
+ .unwrap();
+
+ let mut data = Vec::<u8>::new();
+ let mut writer = ArrowWriter::try_new(&mut data, schema, Default::default()).unwrap();
+ writer.write(&batch).unwrap();
+ writer.close().unwrap();
+
+ data.into()
+}
+
+async fn setup_files(store: Arc<dyn ObjectStore>) {
+ let mut rng = StdRng::seed_from_u64(RNG_SEED);
+ for table_id in 0..TABLES {
+ let table_name = table_name(table_id);
+ for partition in 0..TABLE_PARTITIONS {
+ for file in 0..PARTITION_FILES {
+ let data = create_parquet_file(&mut rng, file * FILE_ROWS);
+ let location = Path::try_from(format!(
+ "{table_name}/partition={partition}/{file}.parquet"
+ ))
+ .unwrap();
+ store.put(&location, data).await.unwrap();
+ }
+ }
+ }
+}
+
+fn make_store_slow<S>(object_store: S) -> Arc<dyn ObjectStore>
+where
+ S: ObjectStore,
+{
+ let config = ThrottleConfig {
+ wait_get_per_call: STORE_LATENCY,
+ wait_list_per_call: STORE_LATENCY,
+ wait_list_with_delimiter_per_call: STORE_LATENCY,
+ ..Default::default()
+ };
+ Arc::new(ThrottledStore::new(object_store, config))
+}
+
+async fn setup_context(object_store: Arc<dyn ObjectStore>) -> SessionContext {
+ let config = SessionConfig::new().with_target_partitions(THREADS);
+ let rt = Arc::new(RuntimeEnv::default());
+ rt.register_object_store(&Url::parse("data://my_store").unwrap(), object_store);
+ let context = SessionContext::with_config_rt(config, rt);
+
+ for table_id in 0..TABLES {
+ let table_name = table_name(table_id);
+ let file_format = ParquetFormat::default().with_enable_pruning(Some(true));
+ let options = ListingOptions::new(Arc::new(file_format))
+ .with_table_partition_cols(vec![(String::from("partition"), DataType::UInt8)])
+ .with_target_partitions(THREADS);
+
+ // make sure we actually find the data
+ let path = format!("data://my_store/{table_name}/");
+ let schema2 = options
+ .infer_schema(&context.state(), &ListingTableUrl::parse(&path).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(schema2, schema());
+
+ context
+ .register_listing_table(&table_name, &path, options, Some(schema2), None)
+ .await
+ .unwrap();
+ }
+
+ context
+}
+
+async fn bench(ctx: &SessionContext, query: &str, output_rows: Option<usize>) {
+ let df = ctx.sql(query).await.unwrap();
+
+ let batches = df.collect().await.unwrap();
+ if let Some(expected) = output_rows {
+ let actual = batches.iter().map(|b| b.num_rows()).sum::<usize>();
+ assert_eq!(actual, expected);
+ }
+}
+
+fn bench_query(
+ c: &mut Criterion,
+ ctx: &SessionContext,
+ rt: &Runtime,
+ group_name: &str,
+ query: &str,
+ output_rows: usize,
+) {
+ let mut g = c.benchmark_group(group_name);
+ g.sampling_mode(SamplingMode::Flat);
+ g.sample_size(10);
+ g.measurement_time(Duration::from_secs(10));
+ g.bench_function("explain", |b| {
+ let query = format!("EXPLAIN {query}");
+ b.to_async(rt).iter(|| bench(ctx, &query, None));
+ });
+ g.bench_function("run", |b| {
+ b.to_async(rt).iter(|| bench(ctx, query, Some(output_rows)));
+ });
+ g.finish();
+}
+
+fn criterion_benchmark(c: &mut Criterion) {
+ env_logger::try_init().ok();
+ let store = make_store_slow(InMemory::new());
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(THREADS)
+ .enable_time()
+ .build()
+ .unwrap();
+
+ rt.block_on(setup_files(Arc::clone(&store)));
+ let ctx = rt.block_on(setup_context(store));
+
+ let table0_name = table_name(0);
+ let select_query = format!("SELECT * FROM {table0_name}");
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: SELECT, one table, all partitions",
+ &select_query,
+ TABLE_PARTITIONS * PARTITION_FILES * FILE_ROWS,
+ );
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: SELECT, one table, single partition",
+ &format!("{select_query} WHERE partition = 0"),
+ PARTITION_FILES * FILE_ROWS,
+ );
+
+ let union_query = (0..TABLES)
+ .map(|table_id| format!("(SELECT * FROM {})", table_name(table_id)))
+ .join("UNION ALL");
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: UNION ALL, all tables, all partitions",
+ &union_query,
+ TABLES * TABLE_PARTITIONS * PARTITION_FILES * FILE_ROWS,
+ );
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: UNION ALL, all tables, single partitions",
+ &union_query.replace(')', " WHERE partition = 0)"),
+ TABLES * PARTITION_FILES * FILE_ROWS,
+ );
+
+ let mut join_query = "SELECT * FROM".to_owned();
+ for table_id in 0..TABLES {
+ let table_name = table_name(table_id);
+ if table_id == 0 {
+ write!(join_query, " {table_name}").unwrap();
+ } else {
+ write!(
+ join_query,
+ " INNER JOIN {table_name} on {table_name}.id = {table0_name}.id AND {table_name}.partition = {table0_name}.partition",
+ ).unwrap();
+ }
+ }
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: INNER JOIN, all tables, all partitions",
+ &join_query,
+ TABLE_PARTITIONS * PARTITION_FILES * FILE_ROWS,
+ );
+ bench_query(
+ c,
+ &ctx,
+ &rt,
+ "IO: INNER JOIN, all tables, single partition",
+ &format!("{join_query} WHERE {table0_name}.partition = 0"),
+ PARTITION_FILES * FILE_ROWS,
+ );
+}
+
+criterion_group!(benches, criterion_benchmark);
+criterion_main!(benches);
diff --git a/datafusion/core/src/datasource/listing/helpers.rs b/datafusion/core/src/datasource/listing/helpers.rs
index 184b9cd1a3..de7e243e3b 100644
--- a/datafusion/core/src/datasource/listing/helpers.rs
+++ b/datafusion/core/src/datasource/listing/helpers.rs
@@ -377,7 +377,16 @@ fn parse_partitions_for_path<'a>(
for (part, pn) in subpath.zip(table_partition_cols) {
match part.split_once('=') {
Some((name, val)) if name == pn => part_values.push(val),
- _ => return None,
+ _ => {
+ debug!(
+ "Ignoring file: file_path='{}', table_path='{}', part='{}', partition_col='{}'",
+ file_path,
+ table_path,
+ part,
+ pn,
+ );
+ return None;
+ }
}
}
Some(part_values)
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index 087545a644..2d616d5a7d 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -466,6 +466,51 @@ impl DefaultPhysicalPlanner {
Self { extension_planners }
}
+ /// Create a physical plans for multiple logical plans.
+ ///
+ /// This is the same as [`create_initial_plan`](Self::create_initial_plan) but runs the planning concurrently.
+ ///
+ /// The result order is the same as the input order.
+ fn create_initial_plan_multi<'a>(
+ &'a self,
+ logical_plans: impl IntoIterator<Item = &'a LogicalPlan> + Send + 'a,
+ session_state: &'a SessionState,
+ ) -> BoxFuture<'a, Result<Vec<Arc<dyn ExecutionPlan>>>> {
+ async move {
+ // First build futures with as little references as possible, then performing some stream magic.
+ // Otherwise rustc bails out w/:
+ //
+ // error: higher-ranked lifetime error
+ // ...
+ // note: could not prove `[async block@...]: std::marker::Send`
+ let futures = logical_plans
+ .into_iter()
+ .enumerate()
+ .map(|(idx, lp)| async move {
+ let plan = self.create_initial_plan(lp, session_state).await?;
+ Ok((idx, plan)) as Result<_>
+ })
+ .collect::<Vec<_>>();
+
+ let mut physical_plans = futures::stream::iter(futures)
+ .buffer_unordered(
+ session_state
+ .config_options()
+ .execution
+ .planning_concurrency,
+ )
+ .try_collect::<Vec<(usize, Arc<dyn ExecutionPlan>)>>()
+ .await?;
+ physical_plans.sort_by_key(|(idx, _plan)| *idx);
+ let physical_plans = physical_plans
+ .into_iter()
+ .map(|(_idx, plan)| plan)
+ .collect::<Vec<_>>();
+ Ok(physical_plans)
+ }
+ .boxed()
+ }
+
/// Create a physical plan from a logical plan
fn create_initial_plan<'a>(
&'a self,
@@ -771,10 +816,8 @@ impl DefaultPhysicalPlanner {
Ok(Arc::new(FilterExec::try_new(runtime_expr, physical_input)?))
}
LogicalPlan::Union(Union { inputs, schema }) => {
- let physical_plans = futures::stream::iter(inputs)
- .then(|lp| self.create_initial_plan(lp, session_state))
- .try_collect::<Vec<_>>()
- .await?;
+ let physical_plans = self.create_initial_plan_multi(inputs.iter().map(|lp| lp.as_ref()), session_state).await?;
+
if schema.fields().len() < physical_plans[0].schema().fields().len() {
// `schema` could be a subset of the child schema. For example
// for query "select count(*) from (select a from t union all select a from t)"
@@ -929,10 +972,10 @@ impl DefaultPhysicalPlanner {
}
// All equi-join keys are columns now, create physical join plan
+ let left_right = self.create_initial_plan_multi([left.as_ref(), right.as_ref()], session_state).await?;
+ let [physical_left, physical_right]: [Arc<dyn ExecutionPlan>; 2] = left_right.try_into().map_err(|_| DataFusionError::Internal("`create_initial_plan_multi` is broken".to_string()))?;
let left_df_schema = left.schema();
- let physical_left = self.create_initial_plan(left, session_state).await?;
let right_df_schema = right.schema();
- let physical_right = self.create_initial_plan(right, session_state).await?;
let join_on = keys
.iter()
.map(|(l, r)| {
@@ -1064,8 +1107,8 @@ impl DefaultPhysicalPlanner {
}
}
LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {
- let left = self.create_initial_plan(left, session_state).await?;
- let right = self.create_initial_plan(right, session_state).await?;
+ let left_right = self.create_initial_plan_multi([left.as_ref(), right.as_ref()], session_state).await?;
+ let [left, right]: [Arc<dyn ExecutionPlan>; 2] = left_right.try_into().map_err(|_| DataFusionError::Internal("`create_initial_plan_multi` is broken".to_string()))?;
Ok(Arc::new(CrossJoinExec::new(left, right)))
}
LogicalPlan::Subquery(_) => todo!(),
@@ -1154,10 +1197,7 @@ impl DefaultPhysicalPlanner {
Ok(Arc::new(AnalyzeExec::new(a.verbose, input, schema)))
}
LogicalPlan::Extension(e) => {
- let physical_inputs = futures::stream::iter(e.node.inputs())
- .then(|lp| self.create_initial_plan(lp, session_state))
- .try_collect::<Vec<_>>()
- .await?;
+ let physical_inputs = self.create_initial_plan_multi(e.node.inputs(), session_state).await?;
let mut maybe_plan = None;
for planner in &self.extension_planners {
diff --git a/datafusion/core/tests/sqllogictests/test_files/information_schema.slt b/datafusion/core/tests/sqllogictests/test_files/information_schema.slt
index 290f7182c8..86011f8931 100644
--- a/datafusion/core/tests/sqllogictests/test_files/information_schema.slt
+++ b/datafusion/core/tests/sqllogictests/test_files/information_schema.slt
@@ -125,6 +125,12 @@ drop table t2
statement ok
SET datafusion.execution.target_partitions=7
+# planning_concurrency defaults to num_cores, so set
+# to a known value that is unlikely to be
+# the real number of cores on a system
+statement ok
+SET datafusion.execution.planning_concurrency=13
+
# show all variables
query TT rowsort
SHOW ALL
@@ -146,6 +152,7 @@ datafusion.execution.parquet.pruning true
datafusion.execution.parquet.pushdown_filters false
datafusion.execution.parquet.reorder_filters false
datafusion.execution.parquet.skip_metadata true
+datafusion.execution.planning_concurrency 13
datafusion.execution.target_partitions 7
datafusion.execution.time_zone +00:00
datafusion.explain.logical_plan_only false
diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md
index decab6a719..e0e72e11b6 100644
--- a/docs/source/user-guide/configs.md
+++ b/docs/source/user-guide/configs.md
@@ -56,6 +56,7 @@ Environment variables are read during `SessionConfig` initialisation so they mus
| datafusion.execution.parquet.pushdown_filters | false | If true, filter expressions are be applied during the parquet decoding operation to reduce the number of rows decoded |
| datafusion.execution.parquet.reorder_filters | false | If true, filter expressions evaluated during the parquet decoding operation will be reordered heuristically to minimize the cost of evaluation. If false, the filters are applied in the same order as written in the query |
| datafusion.execution.aggregate.scalar_update_factor | 10 | Specifies the threshold for using `ScalarValue`s to update accumulators during high-cardinality aggregations for each input batch. The aggregation is considered high-cardinality if the number of affected groups is greater than or equal to `batch_size / scalar_update_factor`. In such cases, `ScalarValue`s are utilized for updating accumulators, rather than the default batch-slice approach. This can lead to performance improvements. By adjusting the `scalar_update_factor`, you can balance the trade-off between more efficient accumulator updates and the number of groups affected. |
+| datafusion.execution.planning_concurrency | 0 | Fan-out during initial physical planning. This is mostly use to plan `UNION` children in parallel. Defaults to the number of CPU cores on the system |
| datafusion.optimizer.enable_round_robin_repartition | true | When set to true, the physical plan optimizer will try to add round robin repartitioning to increase parallelism to leverage more CPU cores |
| datafusion.optimizer.filter_null_join_keys | false | When set to true, the optimizer will insert filters before a join between a nullable and non-nullable column to filter out nulls on the nullable side. This filter can add additional overhead when the file format does not fully support predicate push down. |
| datafusion.optimizer.repartition_aggregations | true | Should DataFusion repartition data using the aggregate keys to execute aggregates in parallel using the provided `target_partitions` level |