Skip to main content

datafusion_datasource/write/
demux.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Module containing helper methods/traits related to enabling
19//! dividing input stream into multiple output files at execution time
20
21use std::borrow::Cow;
22use std::collections::HashMap;
23use std::sync::Arc;
24
25use crate::url::ListingTableUrl;
26use crate::write::FileSinkConfig;
27use datafusion_common::error::Result;
28use datafusion_physical_plan::SendableRecordBatchStream;
29
30use arrow::array::{
31    ArrayAccessor, RecordBatch, StringArray, StructArray, builder::UInt64Builder,
32    cast::AsArray, downcast_dictionary_array,
33};
34use arrow::datatypes::{DataType, Schema};
35use datafusion_common::cast::{
36    as_boolean_array, as_date32_array, as_date64_array, as_float16_array,
37    as_float32_array, as_float64_array, as_int8_array, as_int16_array, as_int32_array,
38    as_int64_array, as_large_string_array, as_string_array, as_string_view_array,
39    as_uint8_array, as_uint16_array, as_uint32_array, as_uint64_array,
40};
41use datafusion_common::{
42    exec_datafusion_err, exec_err, internal_datafusion_err, not_impl_err,
43};
44use datafusion_common_runtime::SpawnedTask;
45
46use chrono::NaiveDate;
47use datafusion_execution::TaskContext;
48use futures::StreamExt;
49use object_store::path::Path;
50use rand::distr::SampleString;
51use tokio::sync::mpsc::{self, Receiver, Sender, UnboundedReceiver, UnboundedSender};
52
53const HIVE_DEFAULT_PARTITION_NAME: &str = "__HIVE_DEFAULT_PARTITION__";
54
55type RecordBatchReceiver = Receiver<RecordBatch>;
56pub type DemuxedStreamReceiver = UnboundedReceiver<(Path, RecordBatchReceiver)>;
57
58/// Splits a single [SendableRecordBatchStream] into a dynamically determined
59/// number of partitions at execution time.
60///
61/// The partitions are determined by factors known only at execution time, such
62/// as total number of rows and partition column values. The demuxer task
63/// communicates to the caller by sending channels over a channel. The inner
64/// channels send RecordBatches which should be contained within the same output
65/// file. The outer channel is used to send a dynamic number of inner channels,
66/// representing a dynamic number of total output files.
67///
68/// The caller is also responsible to monitor the demux task for errors and
69/// abort accordingly.
70///
71/// A path with an extension will force only a single file to
72/// be written with the extension from the path. Otherwise the default extension
73/// will be used and the output will be split into multiple files.
74///
75/// Output file guarantees:
76///  - Partitioned files: Files are created only for non-empty partitions.
77///  - Single-file output: 1 file is always written, even when the stream is empty.
78///  - Multi-file output: Depending on the number of record batches, 0 or more files are written.
79///
80/// Examples of `base_output_path`
81///  * `tmp/dataset/` -> is a folder since it ends in `/`
82///  * `tmp/dataset` -> is still a folder since it does not end in `/` but has no valid file extension
83///  * `tmp/file.parquet` -> is a file since it does not end in `/` and has a valid file extension `.parquet`
84///  * `tmp/file.parquet/` -> is a folder since it ends in `/`
85///
86/// The `partition_by` parameter will additionally split the input based on the
87/// unique values of a specific column, see
88/// <https://github.com/apache/datafusion/issues/7744>
89///
90/// ```text
91///                                                                              ┌───────────┐               ┌────────────┐    ┌─────────────┐
92///                                                                     ┌──────▶ │  batch 1  ├────▶...──────▶│   Batch a  │    │ Output File1│
93///                                                                     │        └───────────┘               └────────────┘    └─────────────┘
94///                                                                     │
95///                                                 ┌──────────┐        │        ┌───────────┐               ┌────────────┐    ┌─────────────┐
96/// ┌───────────┐               ┌────────────┐      │          │        ├──────▶ │  batch a+1├────▶...──────▶│   Batch b  │    │ Output File2│
97/// │  batch 1  ├────▶...──────▶│   Batch N  ├─────▶│  Demux   ├────────┤ ...    └───────────┘               └────────────┘    └─────────────┘
98/// └───────────┘               └────────────┘      │          │        │
99///                                                 └──────────┘        │        ┌───────────┐               ┌────────────┐    ┌─────────────┐
100///                                                                     └──────▶ │  batch d  ├────▶...──────▶│   Batch n  │    │ Output FileN│
101///                                                                              └───────────┘               └────────────┘    └─────────────┘
102/// ```
103pub(crate) fn start_demuxer_task(
104    config: &FileSinkConfig,
105    data: SendableRecordBatchStream,
106    context: &Arc<TaskContext>,
107) -> (SpawnedTask<Result<()>>, DemuxedStreamReceiver) {
108    let (tx, rx) = mpsc::unbounded_channel();
109    let context = Arc::clone(context);
110    let file_extension = config.file_extension.clone();
111    let base_output_path = config.table_paths[0].clone();
112    let task = if config.table_partition_cols.is_empty() {
113        let single_file_output = config
114            .file_output_mode
115            .single_file_output(&base_output_path);
116        SpawnedTask::spawn(async move {
117            row_count_demuxer(
118                tx,
119                data,
120                context,
121                base_output_path,
122                file_extension,
123                single_file_output,
124            )
125            .await
126        })
127    } else {
128        // There could be an arbitrarily large number of parallel hive style partitions being written to, so we cannot
129        // bound this channel without risking a deadlock.
130        let partition_by = config.table_partition_cols.clone();
131        let keep_partition_by_columns = config.keep_partition_by_columns;
132        SpawnedTask::spawn(async move {
133            hive_style_partitions_demuxer(
134                tx,
135                data,
136                context,
137                partition_by,
138                base_output_path,
139                file_extension,
140                keep_partition_by_columns,
141            )
142            .await
143        })
144    };
145
146    (task, rx)
147}
148
149/// Dynamically partitions input stream to achieve desired maximum rows per file
150async fn row_count_demuxer(
151    mut tx: UnboundedSender<(Path, Receiver<RecordBatch>)>,
152    mut input: SendableRecordBatchStream,
153    context: Arc<TaskContext>,
154    base_output_path: ListingTableUrl,
155    file_extension: String,
156    single_file_output: bool,
157) -> Result<()> {
158    let exec_options = &context.session_config().options().execution;
159
160    let max_rows_per_file = exec_options.soft_max_rows_per_output_file.get();
161    let max_buffered_batches = exec_options.max_buffered_batches_per_output_file.get();
162    let minimum_parallel_files = exec_options.minimum_parallel_output_files.get();
163    let mut part_idx = 0;
164    let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
165
166    let mut open_file_streams = Vec::with_capacity(minimum_parallel_files);
167
168    let mut next_send_steam = 0;
169    let mut row_counts = Vec::with_capacity(minimum_parallel_files);
170
171    // Overrides if single_file_output is set
172    let minimum_parallel_files = if single_file_output {
173        1
174    } else {
175        minimum_parallel_files
176    };
177
178    let max_rows_per_file = if single_file_output {
179        usize::MAX
180    } else {
181        max_rows_per_file
182    };
183
184    if single_file_output {
185        // ensure we have one file open, even when the input stream is empty
186        open_file_streams.push(create_new_file_stream(
187            &base_output_path,
188            &write_id,
189            part_idx,
190            &file_extension,
191            single_file_output,
192            max_buffered_batches,
193            &mut tx,
194        )?);
195        row_counts.push(0);
196        part_idx += 1;
197    }
198
199    let schema = input.schema();
200    let mut is_batch_received = false;
201
202    while let Some(rb) = input.next().await.transpose()? {
203        is_batch_received = true;
204        // ensure we have at least minimum_parallel_files open
205        if open_file_streams.len() < minimum_parallel_files {
206            open_file_streams.push(create_new_file_stream(
207                &base_output_path,
208                &write_id,
209                part_idx,
210                &file_extension,
211                single_file_output,
212                max_buffered_batches,
213                &mut tx,
214            )?);
215            row_counts.push(0);
216            part_idx += 1;
217        } else if row_counts[next_send_steam] >= max_rows_per_file {
218            row_counts[next_send_steam] = 0;
219            open_file_streams[next_send_steam] = create_new_file_stream(
220                &base_output_path,
221                &write_id,
222                part_idx,
223                &file_extension,
224                single_file_output,
225                max_buffered_batches,
226                &mut tx,
227            )?;
228            part_idx += 1;
229        }
230        row_counts[next_send_steam] += rb.num_rows();
231        open_file_streams[next_send_steam]
232            .send(rb)
233            .await
234            .map_err(|_| {
235                exec_datafusion_err!("Error sending RecordBatch to file stream!")
236            })?;
237
238        next_send_steam = (next_send_steam + 1) % minimum_parallel_files;
239    }
240
241    // if there is no batch send but with a single file, send an empty batch
242    if single_file_output && !is_batch_received {
243        open_file_streams
244            .first_mut()
245            .ok_or_else(|| internal_datafusion_err!("Expected a single output file"))?
246            .send(RecordBatch::new_empty(schema))
247            .await
248            .map_err(|_| {
249                exec_datafusion_err!("Error sending empty RecordBatch to file stream!")
250            })?;
251    }
252
253    Ok(())
254}
255
256/// Helper for row count demuxer
257fn generate_file_path(
258    base_output_path: &ListingTableUrl,
259    write_id: &str,
260    part_idx: usize,
261    file_extension: &str,
262    single_file_output: bool,
263) -> Path {
264    if !single_file_output {
265        base_output_path
266            .prefix()
267            .clone()
268            .join(format!("{write_id}_{part_idx}.{file_extension}"))
269    } else {
270        base_output_path.prefix().to_owned()
271    }
272}
273
274/// Helper for row count demuxer
275fn create_new_file_stream(
276    base_output_path: &ListingTableUrl,
277    write_id: &str,
278    part_idx: usize,
279    file_extension: &str,
280    single_file_output: bool,
281    max_buffered_batches: usize,
282    tx: &mut UnboundedSender<(Path, Receiver<RecordBatch>)>,
283) -> Result<Sender<RecordBatch>> {
284    let file_path = generate_file_path(
285        base_output_path,
286        write_id,
287        part_idx,
288        file_extension,
289        single_file_output,
290    );
291    let (tx_file, rx_file) = mpsc::channel(max_buffered_batches / 2);
292    tx.send((file_path, rx_file))
293        .map_err(|_| exec_datafusion_err!("Error sending RecordBatch to file stream!"))?;
294    Ok(tx_file)
295}
296
297/// Splits an input stream based on the distinct values of a set of columns
298/// Assumes standard hive style partition paths such as
299/// /col1=val1/col2=val2/outputfile.parquet
300async fn hive_style_partitions_demuxer(
301    tx: UnboundedSender<(Path, Receiver<RecordBatch>)>,
302    mut input: SendableRecordBatchStream,
303    context: Arc<TaskContext>,
304    partition_by: Vec<(String, DataType)>,
305    base_output_path: ListingTableUrl,
306    file_extension: String,
307    keep_partition_by_columns: bool,
308) -> Result<()> {
309    let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
310
311    let exec_options = &context.session_config().options().execution;
312    let max_buffered_recordbatches =
313        exec_options.max_buffered_batches_per_output_file.get();
314
315    // To support non string partition col types, cast the type to &str first
316    let mut value_map: HashMap<Vec<String>, Sender<RecordBatch>> = HashMap::new();
317
318    while let Some(rb) = input.next().await.transpose()? {
319        // First compute partition key for each row of batch, e.g. (col1=val1, col2=val2, ...)
320        let all_partition_values = compute_partition_keys_by_row(&rb, &partition_by)?;
321
322        // Next compute how the batch should be split up to take each distinct key to its own batch
323        let take_map = compute_take_arrays(&rb, &all_partition_values);
324
325        // Divide up the batch into distinct partition key batches and send each batch
326        for (part_key, mut builder) in take_map.into_iter() {
327            // Take method adapted from https://github.com/lancedb/lance/pull/1337/files
328            // TODO: upstream RecordBatch::take to arrow-rs
329            let take_indices = builder.finish();
330            let struct_array: StructArray = rb.clone().into();
331            let parted_batch = RecordBatch::from(
332                arrow::compute::take(&struct_array, &take_indices, None)?.as_struct(),
333            );
334
335            // Get or create channel for this batch
336            let part_tx = match value_map.get_mut(&part_key) {
337                Some(part_tx) => part_tx,
338                None => {
339                    // Create channel for previously unseen distinct partition key and notify consumer of new file
340                    let (part_tx, part_rx) =
341                        mpsc::channel::<RecordBatch>(max_buffered_recordbatches);
342                    let file_path = compute_hive_style_file_path(
343                        &part_key,
344                        &partition_by,
345                        &write_id,
346                        &file_extension,
347                        &base_output_path,
348                    );
349
350                    tx.send((file_path, part_rx)).map_err(|_| {
351                        exec_datafusion_err!("Error sending new file stream!")
352                    })?;
353
354                    value_map.insert(part_key.clone(), part_tx);
355                    value_map.get_mut(&part_key).ok_or_else(|| {
356                        exec_datafusion_err!("Key must exist since it was just inserted!")
357                    })?
358                }
359            };
360
361            let final_batch_to_send = if keep_partition_by_columns {
362                parted_batch
363            } else {
364                remove_partition_by_columns(&parted_batch, &partition_by)?
365            };
366
367            // Finally send the partial batch partitioned by distinct value!
368            part_tx.send(final_batch_to_send).await.map_err(|_| {
369                internal_datafusion_err!("Unexpected error sending parted batch!")
370            })?;
371        }
372    }
373
374    Ok(())
375}
376
377fn compute_partition_keys_by_row<'a>(
378    rb: &'a RecordBatch,
379    partition_by: &'a [(String, DataType)],
380) -> Result<Vec<Vec<Cow<'a, str>>>> {
381    let mut all_partition_values = vec![];
382
383    const EPOCH_DAYS_FROM_CE: i32 = 719_163;
384
385    // For the purposes of writing partitioned data, we can rely on schema inference
386    // to determine the type of the partition cols in order to provide a more ergonomic
387    // UI which does not require specifying DataTypes manually. So, we ignore the
388    // DataType within the partition_by array and infer the correct type from the
389    // batch schema instead.
390    let schema = rb.schema();
391    for (col, _) in partition_by.iter() {
392        let mut partition_values = vec![];
393
394        let dtype = schema.field_with_name(col)?.data_type();
395        let col_array = rb.column_by_name(col).ok_or(exec_datafusion_err!(
396            "PartitionBy Column {} does not exist in source data! Got schema {schema}.",
397            col
398        ))?;
399
400        match dtype {
401            DataType::Utf8 => {
402                let array = as_string_array(col_array)?;
403                for i in 0..rb.num_rows() {
404                    partition_values.push(Cow::from(array.value(i)));
405                }
406            }
407            DataType::LargeUtf8 => {
408                let array = as_large_string_array(col_array)?;
409                for i in 0..rb.num_rows() {
410                    partition_values.push(Cow::from(array.value(i)));
411                }
412            }
413            DataType::Utf8View => {
414                let array = as_string_view_array(col_array)?;
415                for i in 0..rb.num_rows() {
416                    partition_values.push(Cow::from(array.value(i)));
417                }
418            }
419            DataType::Boolean => {
420                let array = as_boolean_array(col_array)?;
421                for i in 0..rb.num_rows() {
422                    partition_values.push(Cow::from(array.value(i).to_string()));
423                }
424            }
425            DataType::Date32 => {
426                let array = as_date32_array(col_array)?;
427                // ISO-8601/RFC3339 format - yyyy-mm-dd
428                let format = "%Y-%m-%d";
429                for i in 0..rb.num_rows() {
430                    let date = NaiveDate::from_num_days_from_ce_opt(
431                        EPOCH_DAYS_FROM_CE + array.value(i),
432                    )
433                    .unwrap()
434                    .format(format)
435                    .to_string();
436                    partition_values.push(Cow::from(date));
437                }
438            }
439            DataType::Date64 => {
440                let array = as_date64_array(col_array)?;
441                // ISO-8601/RFC3339 format - yyyy-mm-dd
442                let format = "%Y-%m-%d";
443                for i in 0..rb.num_rows() {
444                    let date = NaiveDate::from_num_days_from_ce_opt(
445                        EPOCH_DAYS_FROM_CE + (array.value(i) / 86_400_000) as i32,
446                    )
447                    .unwrap()
448                    .format(format)
449                    .to_string();
450                    partition_values.push(Cow::from(date));
451                }
452            }
453            DataType::Int8 => {
454                let array = as_int8_array(col_array)?;
455                for i in 0..rb.num_rows() {
456                    partition_values.push(Cow::from(array.value(i).to_string()));
457                }
458            }
459            DataType::Int16 => {
460                let array = as_int16_array(col_array)?;
461                for i in 0..rb.num_rows() {
462                    partition_values.push(Cow::from(array.value(i).to_string()));
463                }
464            }
465            DataType::Int32 => {
466                let array = as_int32_array(col_array)?;
467                for i in 0..rb.num_rows() {
468                    partition_values.push(Cow::from(array.value(i).to_string()));
469                }
470            }
471            DataType::Int64 => {
472                let array = as_int64_array(col_array)?;
473                for i in 0..rb.num_rows() {
474                    partition_values.push(Cow::from(array.value(i).to_string()));
475                }
476            }
477            DataType::UInt8 => {
478                let array = as_uint8_array(col_array)?;
479                for i in 0..rb.num_rows() {
480                    partition_values.push(Cow::from(array.value(i).to_string()));
481                }
482            }
483            DataType::UInt16 => {
484                let array = as_uint16_array(col_array)?;
485                for i in 0..rb.num_rows() {
486                    partition_values.push(Cow::from(array.value(i).to_string()));
487                }
488            }
489            DataType::UInt32 => {
490                let array = as_uint32_array(col_array)?;
491                for i in 0..rb.num_rows() {
492                    partition_values.push(Cow::from(array.value(i).to_string()));
493                }
494            }
495            DataType::UInt64 => {
496                let array = as_uint64_array(col_array)?;
497                for i in 0..rb.num_rows() {
498                    partition_values.push(Cow::from(array.value(i).to_string()));
499                }
500            }
501            DataType::Float16 => {
502                let array = as_float16_array(col_array)?;
503                for i in 0..rb.num_rows() {
504                    partition_values.push(Cow::from(array.value(i).to_string()));
505                }
506            }
507            DataType::Float32 => {
508                let array = as_float32_array(col_array)?;
509                for i in 0..rb.num_rows() {
510                    partition_values.push(Cow::from(array.value(i).to_string()));
511                }
512            }
513            DataType::Float64 => {
514                let array = as_float64_array(col_array)?;
515                for i in 0..rb.num_rows() {
516                    partition_values.push(Cow::from(array.value(i).to_string()));
517                }
518            }
519            DataType::Dictionary(_, _) => {
520                downcast_dictionary_array!(
521                    col_array =>  {
522                        let array = col_array.downcast_dict::<StringArray>()
523                            .ok_or(exec_datafusion_err!("it is not yet supported to write to hive partitions with datatype {}",
524                            dtype))?;
525
526                        for i in 0..rb.num_rows() {
527                            partition_values.push(Cow::from(array.value(i)));
528                        }
529                    },
530                    _ => unreachable!(),
531                )
532            }
533            _ => {
534                return not_impl_err!(
535                    "it is not yet supported to write to hive partitions with datatype {}",
536                    dtype
537                );
538            }
539        }
540
541        if partition_values
542            .iter()
543            .any(|v| v == HIVE_DEFAULT_PARTITION_NAME)
544        {
545            return exec_err!(
546                "Cannot write value '{HIVE_DEFAULT_PARTITION_NAME}' for partition column '{col}': \
547                 it is the null partition name and would be read back as NULL"
548            );
549        }
550
551        all_partition_values.push(partition_values);
552    }
553
554    Ok(all_partition_values)
555}
556
557fn compute_take_arrays(
558    rb: &RecordBatch,
559    all_partition_values: &[Vec<Cow<str>>],
560) -> HashMap<Vec<String>, UInt64Builder> {
561    let mut take_map = HashMap::new();
562    for i in 0..rb.num_rows() {
563        let mut part_key = vec![];
564        for vals in all_partition_values.iter() {
565            part_key.push(vals[i].clone().into());
566        }
567        let builder = take_map.entry(part_key).or_insert_with(UInt64Builder::new);
568        builder.append_value(i as u64);
569    }
570    take_map
571}
572
573fn remove_partition_by_columns(
574    parted_batch: &RecordBatch,
575    partition_by: &[(String, DataType)],
576) -> Result<RecordBatch> {
577    let partition_names: Vec<_> = partition_by.iter().map(|(s, _)| s).collect();
578    let (non_part_cols, non_part_fields): (Vec<_>, Vec<_>) = parted_batch
579        .columns()
580        .iter()
581        .zip(parted_batch.schema().fields())
582        .filter_map(|(a, f)| {
583            if !partition_names.contains(&f.name()) {
584                Some((Arc::clone(a), (**f).clone()))
585            } else {
586                None
587            }
588        })
589        .unzip();
590
591    let non_part_schema = Schema::new(non_part_fields);
592    let final_batch_to_send =
593        RecordBatch::try_new(Arc::new(non_part_schema), non_part_cols)?;
594
595    Ok(final_batch_to_send)
596}
597
598fn compute_hive_style_file_path(
599    part_key: &[String],
600    partition_by: &[(String, DataType)],
601    write_id: &str,
602    file_extension: &str,
603    base_output_path: &ListingTableUrl,
604) -> Path {
605    let mut file_path = base_output_path.prefix().clone();
606    for j in 0..part_key.len() {
607        file_path = file_path.join(format!("{}={}", partition_by[j].0, part_key[j]));
608    }
609
610    file_path.join(format!("{write_id}.{file_extension}"))
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use arrow::array::{ArrayRef, DictionaryArray, Int32Array};
617    use arrow::datatypes::Int32Type;
618
619    fn partition_batch(column: ArrayRef) -> RecordBatch {
620        RecordBatch::try_from_iter_with_nullable([("p", column, true)]).unwrap()
621    }
622
623    #[test]
624    fn partition_keys_reject_null_partition_name() {
625        let columns: Vec<ArrayRef> = vec![
626            Arc::new(StringArray::from(vec!["a", HIVE_DEFAULT_PARTITION_NAME])),
627            Arc::new(DictionaryArray::<Int32Type>::new(
628                Int32Array::from(vec![0, 1]),
629                Arc::new(StringArray::from(vec!["a", HIVE_DEFAULT_PARTITION_NAME])),
630            )),
631        ];
632        for column in columns {
633            let partition_by = vec![("p".to_string(), column.data_type().clone())];
634            let batch = partition_batch(column);
635            let err = compute_partition_keys_by_row(&batch, &partition_by).unwrap_err();
636            assert_eq!(
637                err.strip_backtrace(),
638                "Execution error: Cannot write value '__HIVE_DEFAULT_PARTITION__' for partition column 'p': it is the null partition name and would be read back as NULL"
639            );
640        }
641    }
642
643    #[test]
644    fn partition_keys_accept_other_partition_names() {
645        let column = StringArray::from(vec!["MY_NULL"]);
646        let batch = partition_batch(Arc::new(column));
647        let partition_by = vec![("p".to_string(), DataType::Utf8)];
648        let keys = compute_partition_keys_by_row(&batch, &partition_by).unwrap();
649        assert_eq!(keys, vec![vec![Cow::Borrowed("MY_NULL")]]);
650    }
651}