Apache DataFusion SQL Query Engine
feat: Add option to adjust writer buffer size for query output (#15747)
m09526bc41cee13983
diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rsindex 6b885f7c0a..25f555cd86 100644--- a/datafusion/common/src/config.rs+++ b/datafusion/common/src/config.rs@@ -405,6 +405,13 @@ config_namespace! {/// in joins can reduce memory usage when joining large/// tables with a highly-selective join filter, but is also slightly slower.pub enforce_batch_size_in_joins: bool, default = false++ /// Size (bytes) of data buffer DataFusion uses when writing output files.+ /// This affects the size of the data chunks that are uploaded to remote+ /// object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being+ /// written, it may be necessary to increase this size to avoid errors from+ /// the remote end point.+ pub objectstore_writer_buffer_size: usize, default = 10 * 1024 * 1024}}diff --git a/datafusion/core/src/datasource/file_format/arrow.rs b/datafusion/core/src/datasource/file_format/arrow.rsindex 7fc27453d1..12d86a471e 100644--- a/datafusion/core/src/datasource/file_format/arrow.rs+++ b/datafusion/core/src/datasource/file_format/arrow.rs@@ -27,7 +27,7 @@ use std::sync::Arc;use super::file_compression_type::FileCompressionType;use super::write::demux::DemuxedStreamReceiver;-use super::write::{create_writer, SharedBuffer};+use super::write::SharedBuffer;use super::FileFormatFactory;use crate::datasource::file_format::write::get_writer_schema;use crate::datasource::file_format::FileFormat;@@ -51,6 +51,7 @@ use datafusion_datasource::display::FileGroupDisplay;use datafusion_datasource::file::FileSource;use datafusion_datasource::file_scan_config::{FileScanConfig, FileScanConfigBuilder};use datafusion_datasource::sink::{DataSink, DataSinkExec};+use datafusion_datasource::write::ObjectWriterBuilder;use datafusion_execution::{SendableRecordBatchStream, TaskContext};use datafusion_expr::dml::InsertOp;use datafusion_physical_expr::PhysicalExpr;@@ -223,7 +224,7 @@ impl FileSink for ArrowFileSink {async fn spawn_writer_tasks_and_join(&self,- _context: &Arc<TaskContext>,+ context: &Arc<TaskContext>,demux_task: SpawnedTask<Result<()>>,mut file_stream_rx: DemuxedStreamReceiver,object_store: Arc<dyn ObjectStore>,@@ -241,12 +242,19 @@ impl FileSink for ArrowFileSink {&get_writer_schema(&self.config),ipc_options.clone(),)?;- let mut object_store_writer = create_writer(+ let mut object_store_writer = ObjectWriterBuilder::new(FileCompressionType::UNCOMPRESSED,&path,Arc::clone(&object_store),)- .await?;+ .with_buffer_size(Some(+ context+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size,+ ))+ .build()?;file_write_tasks.spawn(async move {let mut row_count = 0;while let Some(batch) = rx.recv().await {diff --git a/datafusion/datasource-csv/src/source.rs b/datafusion/datasource-csv/src/source.rsindex 2c7a851159..830b9e4cdf 100644--- a/datafusion/datasource-csv/src/source.rs+++ b/datafusion/datasource-csv/src/source.rs@@ -747,6 +747,11 @@ pub async fn plan_to_csv(let parsed = ListingTableUrl::parse(path)?;let object_store_url = parsed.object_store();let store = task_ctx.runtime_env().object_store(&object_store_url)?;+ let writer_buffer_size = task_ctx+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size;let mut join_set = JoinSet::new();for i in 0..plan.output_partitioning().partition_count() {let storeref = Arc::clone(&store);@@ -756,7 +761,8 @@ pub async fn plan_to_csv(let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;join_set.spawn(async move {- let mut buf_writer = BufWriter::new(storeref, file.clone());+ let mut buf_writer =+ BufWriter::with_capacity(storeref, file.clone(), writer_buffer_size);let mut buffer = Vec::with_capacity(1024);//only write headers on first iterationlet mut write_headers = true;diff --git a/datafusion/datasource-json/src/source.rs b/datafusion/datasource-json/src/source.rsindex ee96d05096..0db962a5e9 100644--- a/datafusion/datasource-json/src/source.rs+++ b/datafusion/datasource-json/src/source.rs@@ -399,6 +399,11 @@ pub async fn plan_to_json(let parsed = ListingTableUrl::parse(path)?;let object_store_url = parsed.object_store();let store = task_ctx.runtime_env().object_store(&object_store_url)?;+ let writer_buffer_size = task_ctx+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size;let mut join_set = JoinSet::new();for i in 0..plan.output_partitioning().partition_count() {let storeref = Arc::clone(&store);@@ -408,7 +413,8 @@ pub async fn plan_to_json(let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;join_set.spawn(async move {- let mut buf_writer = BufWriter::new(storeref, file.clone());+ let mut buf_writer =+ BufWriter::with_capacity(storeref, file.clone(), writer_buffer_size);let mut buffer = Vec::with_capacity(1024);while let Some(batch) = stream.next().await.transpose()? {diff --git a/datafusion/datasource-parquet/src/file_format.rs b/datafusion/datasource-parquet/src/file_format.rsindex ee4db50a6e..a0ca464227 100644--- a/datafusion/datasource-parquet/src/file_format.rs+++ b/datafusion/datasource-parquet/src/file_format.rs@@ -27,7 +27,9 @@ use arrow::array::RecordBatch;use arrow::datatypes::{Fields, Schema, SchemaRef, TimeUnit};use datafusion_datasource::file_compression_type::FileCompressionType;use datafusion_datasource::file_sink_config::{FileSink, FileSinkConfig};-use datafusion_datasource::write::{create_writer, get_writer_schema, SharedBuffer};+use datafusion_datasource::write::{+ get_writer_schema, ObjectWriterBuilder, SharedBuffer,+};use datafusion_datasource::file_format::{FileFormat, FileFormatFactory, FilePushdownSupport,@@ -1102,9 +1104,18 @@ impl ParquetSink {&self,location: &Path,object_store: Arc<dyn ObjectStore>,+ context: &Arc<TaskContext>,parquet_props: WriterProperties,) -> Result<AsyncArrowWriter<BufWriter>> {- let buf_writer = BufWriter::new(object_store, location.clone());+ let buf_writer = BufWriter::with_capacity(+ object_store,+ location.clone(),+ context+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size,+ );let options = ArrowWriterOptions::new().with_properties(parquet_props).with_skip_arrow_metadata(self.parquet_options.global.skip_arrow_metadata);@@ -1160,6 +1171,7 @@ impl FileSink for ParquetSink {.create_async_arrow_writer(&path,Arc::clone(&object_store),+ context,parquet_props.clone(),).await?;@@ -1178,14 +1190,21 @@ impl FileSink for ParquetSink {Ok((path, file_metadata))});} else {- let writer = create_writer(+ let writer = ObjectWriterBuilder::new(// Parquet files as a whole are never compressed, since they// manage compressed blocks themselves.FileCompressionType::UNCOMPRESSED,&path,Arc::clone(&object_store),)- .await?;+ .with_buffer_size(Some(+ context+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size,+ ))+ .build()?;let schema = get_writer_schema(&self.config);let props = parquet_props.clone();let parallel_options_clone = parallel_options.clone();diff --git a/datafusion/datasource-parquet/src/writer.rs b/datafusion/datasource-parquet/src/writer.rsindex 64eb37c81f..d37b6e26a7 100644--- a/datafusion/datasource-parquet/src/writer.rs+++ b/datafusion/datasource-parquet/src/writer.rs@@ -46,7 +46,15 @@ pub async fn plan_to_parquet(let propclone = writer_properties.clone();let storeref = Arc::clone(&store);- let buf_writer = BufWriter::new(storeref, file.clone());+ let buf_writer = BufWriter::with_capacity(+ storeref,+ file.clone(),+ task_ctx+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size,+ );let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;join_set.spawn(async move {let mut writer =diff --git a/datafusion/datasource/src/write/mod.rs b/datafusion/datasource/src/write/mod.rsindex f581126095..3694568682 100644--- a/datafusion/datasource/src/write/mod.rs+++ b/datafusion/datasource/src/write/mod.rs@@ -77,15 +77,18 @@ pub trait BatchSerializer: Sync + Send {/// Returns an [`AsyncWrite`] which writes to the given object store location/// with the specified compression.+///+/// The writer will have a default buffer size as chosen by [`BufWriter::new`].+////// We drop the `AbortableWrite` struct and the writer will not try to cleanup on failure./// Users can configure automatic cleanup with their cloud provider.+#[deprecated(since = "48.0.0", note = "Use ObjectWriterBuilder::new(...) instead")]pub async fn create_writer(file_compression_type: FileCompressionType,location: &Path,object_store: Arc<dyn ObjectStore>,) -> Result<Box<dyn AsyncWrite + Send + Unpin>> {- let buf_writer = BufWriter::new(object_store, location.clone());- file_compression_type.convert_async_writer(buf_writer)+ ObjectWriterBuilder::new(file_compression_type, location, object_store).build()}/// Converts table schema to writer schema, which may differ in the case@@ -109,3 +112,108 @@ pub fn get_writer_schema(config: &FileSinkConfig) -> Arc<Schema> {Arc::clone(config.output_schema())}}++/// A builder for an [`AsyncWrite`] that writes to an object store location.+///+/// This can be used to specify file compression on the writer. The writer+/// will have a default buffer size unless altered. The specific default size+/// is chosen by [`BufWriter::new`].+///+/// We drop the `AbortableWrite` struct and the writer will not try to cleanup on failure.+/// Users can configure automatic cleanup with their cloud provider.+#[derive(Debug)]+pub struct ObjectWriterBuilder {+ /// Compression type for object writer.+ file_compression_type: FileCompressionType,+ /// Output path+ location: Path,+ /// The related store that handles the given path+ object_store: Arc<dyn ObjectStore>,+ /// The size of the buffer for the object writer.+ buffer_size: Option<usize>,+}++impl ObjectWriterBuilder {+ /// Create a new [`ObjectWriterBuilder`] for the specified path and compression type.+ pub fn new(+ file_compression_type: FileCompressionType,+ location: &Path,+ object_store: Arc<dyn ObjectStore>,+ ) -> Self {+ Self {+ file_compression_type,+ location: location.clone(),+ object_store,+ buffer_size: None,+ }+ }++ /// Set buffer size in bytes for object writer.+ ///+ /// # Example+ /// ```+ /// # use datafusion_datasource::file_compression_type::FileCompressionType;+ /// # use datafusion_datasource::write::ObjectWriterBuilder;+ /// # use object_store::memory::InMemory;+ /// # use object_store::path::Path;+ /// # use std::sync::Arc;+ /// # let compression_type = FileCompressionType::UNCOMPRESSED;+ /// # let location = Path::from("/foo/bar");+ /// # let object_store = Arc::new(InMemory::new());+ /// let mut builder = ObjectWriterBuilder::new(compression_type, &location, object_store);+ /// builder.set_buffer_size(Some(20 * 1024 * 1024)); //20 MiB+ /// assert_eq!(builder.get_buffer_size(), Some(20 * 1024 * 1024), "Internal error: Builder buffer size doesn't match");+ /// ```+ pub fn set_buffer_size(&mut self, buffer_size: Option<usize>) {+ self.buffer_size = buffer_size;+ }++ /// Set buffer size in bytes for object writer, returning the builder.+ ///+ /// # Example+ /// ```+ /// # use datafusion_datasource::file_compression_type::FileCompressionType;+ /// # use datafusion_datasource::write::ObjectWriterBuilder;+ /// # use object_store::memory::InMemory;+ /// # use object_store::path::Path;+ /// # use std::sync::Arc;+ /// # let compression_type = FileCompressionType::UNCOMPRESSED;+ /// # let location = Path::from("/foo/bar");+ /// # let object_store = Arc::new(InMemory::new());+ /// let builder = ObjectWriterBuilder::new(compression_type, &location, object_store)+ /// .with_buffer_size(Some(20 * 1024 * 1024)); //20 MiB+ /// assert_eq!(builder.get_buffer_size(), Some(20 * 1024 * 1024), "Internal error: Builder buffer size doesn't match");+ /// ```+ pub fn with_buffer_size(mut self, buffer_size: Option<usize>) -> Self {+ self.buffer_size = buffer_size;+ self+ }++ /// Currently specified buffer size in bytes.+ pub fn get_buffer_size(&self) -> Option<usize> {+ self.buffer_size+ }++ /// Return a writer object that writes to the object store location.+ ///+ /// If a buffer size has not been set, the default buffer buffer size will+ /// be used.+ ///+ /// # Errors+ /// If there is an error applying the compression type.+ pub fn build(self) -> Result<Box<dyn AsyncWrite + Send + Unpin>> {+ let Self {+ file_compression_type,+ location,+ object_store,+ buffer_size,+ } = self;++ let buf_writer = match buffer_size {+ Some(size) => BufWriter::with_capacity(object_store, location, size),+ None => BufWriter::new(object_store, location),+ };++ file_compression_type.convert_async_writer(buf_writer)+ }+}diff --git a/datafusion/datasource/src/write/orchestration.rs b/datafusion/datasource/src/write/orchestration.rsindex 0ac1d26c6c..a09509ac58 100644--- a/datafusion/datasource/src/write/orchestration.rs+++ b/datafusion/datasource/src/write/orchestration.rs@@ -22,7 +22,7 @@use std::sync::Arc;use super::demux::DemuxedStreamReceiver;-use super::{create_writer, BatchSerializer};+use super::{BatchSerializer, ObjectWriterBuilder};use crate::file_compression_type::FileCompressionType;use datafusion_common::error::Result;@@ -257,7 +257,15 @@ pub async fn spawn_writer_tasks_and_join(});while let Some((location, rb_stream)) = file_stream_rx.recv().await {let writer =- create_writer(compression, &location, Arc::clone(&object_store)).await?;+ ObjectWriterBuilder::new(compression, &location, Arc::clone(&object_store))+ .with_buffer_size(Some(+ context+ .session_config()+ .options()+ .execution+ .objectstore_writer_buffer_size,+ ))+ .build()?;if tx_file_bundle.send((rb_stream, Arc::clone(&serializer), writer))diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.sltindex 87abaadb51..6f6ef1270c 100644--- a/datafusion/sqllogictest/test_files/information_schema.slt+++ b/datafusion/sqllogictest/test_files/information_schema.slt@@ -224,6 +224,7 @@ datafusion.execution.listing_table_ignore_subdirectory truedatafusion.execution.max_buffered_batches_per_output_file 2datafusion.execution.meta_fetch_concurrency 32datafusion.execution.minimum_parallel_output_files 4+datafusion.execution.objectstore_writer_buffer_size 10485760datafusion.execution.parquet.allow_single_file_parallelism truedatafusion.execution.parquet.binary_as_string falsedatafusion.execution.parquet.bloom_filter_fpp NULL@@ -324,6 +325,7 @@ datafusion.execution.listing_table_ignore_subdirectory true Should sub directoridatafusion.execution.max_buffered_batches_per_output_file 2 This is the maximum number of RecordBatches buffered for each output file being worked. Higher values can potentially give faster write performance at the cost of higher peak memory consumptiondatafusion.execution.meta_fetch_concurrency 32 Number of files to read in parallel when inferring schema and statisticsdatafusion.execution.minimum_parallel_output_files 4 Guarantees a minimum level of output files running in parallel. RecordBatches will be distributed in round robin fashion to each parallel writer. Each writer is closed and a new file opened once soft_max_rows_per_output_file is reached.+datafusion.execution.objectstore_writer_buffer_size 10485760 Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point.datafusion.execution.parquet.allow_single_file_parallelism true (writing) Controls whether DataFusion will attempt to speed up writing parquet files by serializing them in parallel. Each column in each row group in each output file are serialized in parallel leveraging a maximum possible core count of n_files*n_row_groups*n_columns.datafusion.execution.parquet.binary_as_string false (reading) If true, parquet reader will read columns of `Binary/LargeBinary` with `Utf8`, and `BinaryView` with `Utf8View`. Parquet files generated by some legacy writers do not correctly set the UTF8 flag for strings, causing string columns to be loaded as BLOB instead.datafusion.execution.parquet.bloom_filter_fpp NULL (writing) Sets bloom filter false positive probability. If NULL, uses default parquet writer settingdiff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.mdindex 7a46d59d89..63f8c711bd 100644--- a/docs/source/user-guide/configs.md+++ b/docs/source/user-guide/configs.md@@ -97,6 +97,7 @@ Environment variables are read during `SessionConfig` initialisation so they mus| datafusion.execution.skip_partial_aggregation_probe_rows_threshold | 100000 | Number of input rows partial aggregation partition should process, before aggregation ratio check and trying to switch to skipping aggregation mode || datafusion.execution.use_row_number_estimates_to_optimize_partitioning | false | Should DataFusion use row number estimates at the input to decide whether increasing parallelism is beneficial or not. By default, only exact row numbers (not estimates) are used for this decision. Setting this flag to `true` will likely produce better plans. if the source of statistics is accurate. We plan to make this the default in the future. || datafusion.execution.enforce_batch_size_in_joins | false | Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. |+| datafusion.execution.objectstore_writer_buffer_size | 10485760 | Size (bytes) of data buffer DataFusion uses when writing output files. This affects the size of the data chunks that are uploaded to remote object stores (e.g. AWS S3). If very large (>= 100 GiB) output files are being written, it may be necessary to increase this size to avoid errors from the remote end point. || datafusion.optimizer.enable_distinct_aggregation_soft_limit | true | When set to true, the optimizer will push a limit operation into grouped aggregations which have no aggregate expressions, as a soft limit, emitting groups once the limit is reached, before all rows in the group are read. || 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.enable_topk_aggregation | true | When set to true, the optimizer will attempt to perform limit operations during aggregations, if possible |