Skip to main content

datafusion_datasource/write/
orchestration.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Module containing helper methods/traits related to
6//! orchestrating file serialization, streaming to object store,
7//! parallelization, and abort handling
8
9use std::sync::Arc;
10
11use super::demux::DemuxedStreamReceiver;
12use super::{BatchSerializer, ObjectWriterBuilder};
13use crate::file_compression_type::FileCompressionType;
14use datafusion_common::error::Result;
15use datafusion_common::{
16    DataFusionError, exec_datafusion_err, internal_datafusion_err, internal_err,
17};
18use datafusion_common_runtime::{JoinSet, SpawnedTask};
19use datafusion_execution::TaskContext;
20
21use arrow::array::RecordBatch;
22use bytes::Bytes;
23use futures::join;
24use object_store::ObjectStore;
25use tokio::io::{AsyncWrite, AsyncWriteExt};
26use tokio::sync::mpsc::{self, Receiver};
27
28type WriterType = Box<dyn AsyncWrite + Send + Unpin>;
29type SerializerType = Arc<dyn BatchSerializer>;
30
31/// Result of calling [`serialize_rb_stream_to_object_store`]
32pub(crate) enum SerializedRecordBatchResult {
33    Success {
34        /// the writer
35        writer: WriterType,
36
37        /// the number of rows successfully written
38        row_count: usize,
39    },
40    Failure {
41        /// As explained in [`serialize_rb_stream_to_object_store`]:
42        /// - If an IO error occurred that involved the ObjectStore writer, then the writer will not be returned to the caller
43        /// - Otherwise, the writer is returned to the caller
44        writer: Option<WriterType>,
45
46        /// the actual error that occurred
47        err: DataFusionError,
48    },
49}
50
51impl SerializedRecordBatchResult {
52    /// Create the success variant
53    pub fn success(writer: WriterType, row_count: usize) -> Self {
54        Self::Success { writer, row_count }
55    }
56
57    pub fn failure(writer: Option<WriterType>, err: DataFusionError) -> Self {
58        Self::Failure { writer, err }
59    }
60}
61
62/// Serializes a single data stream in parallel and writes to an ObjectStore concurrently.
63/// Data order is preserved.
64///
65/// In the event of a non-IO error which does not involve the ObjectStore writer,
66/// the writer returned to the caller in addition to the error,
67/// so that failed writes may be aborted.
68///
69/// In the event of an IO error involving the ObjectStore writer,
70/// the writer is dropped to avoid calling further methods on it which might panic.
71pub(crate) async fn serialize_rb_stream_to_object_store(
72    mut data_rx: Receiver<RecordBatch>,
73    serializer: Arc<dyn BatchSerializer>,
74    mut writer: WriterType,
75) -> SerializedRecordBatchResult {
76    let (tx, mut rx) =
77        mpsc::channel::<SpawnedTask<Result<(usize, Bytes), DataFusionError>>>(100);
78    let serialize_task = SpawnedTask::spawn(async move {
79        // Some serializers (like CSV) handle the first batch differently than
80        // subsequent batches, so we track that here.
81        let mut initial = true;
82        while let Some(batch) = data_rx.recv().await {
83            let serializer_clone = Arc::clone(&serializer);
84            let task = SpawnedTask::spawn(async move {
85                let num_rows = batch.num_rows();
86                let bytes = serializer_clone.serialize(batch, initial)?;
87                Ok((num_rows, bytes))
88            });
89            if initial {
90                initial = false;
91            }
92            tx.send(task).await.map_err(|_| {
93                internal_datafusion_err!("Unknown error writing to object store")
94            })?;
95        }
96        Ok(())
97    });
98
99    let mut row_count = 0;
100    while let Some(task) = rx.recv().await {
101        match task.join().await {
102            Ok(Ok((cnt, bytes))) => {
103                match writer.write_all(&bytes).await {
104                    Ok(_) => (),
105                    Err(e) => {
106                        return SerializedRecordBatchResult::failure(
107                            None,
108                            exec_datafusion_err!("Error writing to object store: {e}"),
109                        );
110                    }
111                }
112                row_count += cnt;
113            }
114            Ok(Err(e)) => {
115                // Return the writer along with the error
116                return SerializedRecordBatchResult::failure(Some(writer), e);
117            }
118            Err(e) => {
119                // Handle task panic or cancellation
120                return SerializedRecordBatchResult::failure(
121                    Some(writer),
122                    exec_datafusion_err!(
123                        "Serialization task panicked or was cancelled: {e}"
124                    ),
125                );
126            }
127        }
128    }
129
130    match serialize_task.join().await {
131        Ok(Ok(_)) => (),
132        Ok(Err(e)) => return SerializedRecordBatchResult::failure(Some(writer), e),
133        Err(_) => {
134            return SerializedRecordBatchResult::failure(
135                Some(writer),
136                internal_datafusion_err!("Unknown error writing to object store"),
137            );
138        }
139    }
140    SerializedRecordBatchResult::success(writer, row_count)
141}
142
143type FileWriteBundle = (Receiver<RecordBatch>, SerializerType, WriterType);
144/// Contains the common logic for serializing RecordBatches and
145/// writing the resulting bytes to an ObjectStore.
146/// Serialization is assumed to be stateless, i.e.
147/// each RecordBatch can be serialized without any
148/// dependency on the RecordBatches before or after.
149pub(crate) async fn stateless_serialize_and_write_files(
150    mut rx: Receiver<FileWriteBundle>,
151    tx: tokio::sync::oneshot::Sender<u64>,
152) -> Result<()> {
153    let mut row_count = 0;
154    // tracks if any writers encountered an error triggering the need to abort
155    let mut any_errors = false;
156    // tracks the specific error triggering abort
157    let mut triggering_error = None;
158    // tracks if any errors were encountered in the process of aborting writers.
159    // if true, we may not have a guarantee that all written data was cleaned up.
160    let mut any_abort_errors = false;
161    let mut join_set = JoinSet::new();
162    while let Some((data_rx, serializer, writer)) = rx.recv().await {
163        join_set.spawn(async move {
164            serialize_rb_stream_to_object_store(data_rx, serializer, writer).await
165        });
166    }
167    let mut finished_writers = Vec::with_capacity(join_set.len());
168    while let Some(result) = join_set.join_next().await {
169        match result {
170            Ok(res) => match res {
171                SerializedRecordBatchResult::Success {
172                    writer,
173                    row_count: cnt,
174                } => {
175                    finished_writers.push(writer);
176                    row_count += cnt;
177                }
178                SerializedRecordBatchResult::Failure { writer, err } => {
179                    finished_writers.extend(writer);
180                    any_errors = true;
181                    triggering_error = Some(err);
182                }
183            },
184            Err(e) => {
185                // Don't panic, instead try to clean up as many writers as possible.
186                // If we hit this code, ownership of a writer was not joined back to
187                // this thread, so we cannot clean it up (hence any_abort_errors is true)
188                any_errors = true;
189                any_abort_errors = true;
190                triggering_error = Some(internal_datafusion_err!(
191                    "Unexpected join error while serializing file {e}"
192                ));
193            }
194        }
195    }
196
197    // Finalize or abort writers as appropriate
198    for mut writer in finished_writers.into_iter() {
199        writer.shutdown()
200                    .await
201                    .map_err(|_| internal_datafusion_err!("Error encountered while finalizing writes! Partial results may have been written to ObjectStore!"))?;
202    }
203
204    if any_errors {
205        match any_abort_errors {
206            true => {
207                return internal_err!(
208                    "Error encountered during writing to ObjectStore and failed to abort all writers. Partial result may have been written."
209                );
210            }
211            false => match triggering_error {
212                Some(e) => return Err(e),
213                None => {
214                    return internal_err!(
215                        "Unknown Error encountered during writing to ObjectStore. All writers successfully aborted."
216                    );
217                }
218            },
219        }
220    }
221
222    tx.send(row_count as u64).map_err(|_| {
223        internal_datafusion_err!(
224            "Error encountered while sending row count back to file sink!"
225        )
226    })?;
227    Ok(())
228}
229
230/// Orchestrates multipart put of a dynamic number of output files from a single input stream
231/// for any statelessly serialized file type. That is, any file type for which each [RecordBatch]
232/// can be serialized independently of all other [RecordBatch]s.
233pub async fn spawn_writer_tasks_and_join(
234    context: &Arc<TaskContext>,
235    serializer: Arc<dyn BatchSerializer>,
236    compression: FileCompressionType,
237    compression_level: Option<u32>,
238    object_store: Arc<dyn ObjectStore>,
239    demux_task: SpawnedTask<Result<()>>,
240    mut file_stream_rx: DemuxedStreamReceiver,
241) -> Result<u64> {
242    let rb_buffer_size = &context
243        .session_config()
244        .options()
245        .execution
246        .max_buffered_batches_per_output_file;
247
248    let (tx_file_bundle, rx_file_bundle) = mpsc::channel(rb_buffer_size.get() / 2);
249    let (tx_row_cnt, rx_row_cnt) = tokio::sync::oneshot::channel();
250    let write_coordinator_task = SpawnedTask::spawn(async move {
251        stateless_serialize_and_write_files(rx_file_bundle, tx_row_cnt).await
252    });
253    while let Some((file_metadata, rb_stream)) = file_stream_rx.recv().await {
254        let writer = ObjectWriterBuilder::new(
255            compression,
256            &file_metadata.path,
257            Arc::clone(&object_store),
258        )
259        .with_buffer_size(Some(
260            context
261                .session_config()
262                .options()
263                .execution
264                .objectstore_writer_buffer_size,
265        ))
266        .with_compression_level(compression_level)
267        .with_bytes_written_counter(file_metadata.size)
268        .build()?;
269
270        if tx_file_bundle
271            .send((rb_stream, Arc::clone(&serializer), writer))
272            .await
273            .is_err()
274        {
275            internal_datafusion_err!(
276                "Writer receive file bundle channel closed unexpectedly!"
277            );
278        }
279    }
280
281    // Signal to the write coordinator that no more files are coming
282    drop(tx_file_bundle);
283
284    let (r1, r2) = join!(
285        write_coordinator_task.join_unwind(),
286        demux_task.join_unwind()
287    );
288    r1.map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))??;
289    r2.map_err(|e| DataFusionError::ExecutionJoin(Box::new(e)))??;
290
291    // Return total row count:
292    rx_row_cnt.await.map_err(|_| {
293        internal_datafusion_err!("Did not receive row count from write coordinator")
294    })
295}