datafusion_execution/spill_file.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
5use async_trait::async_trait;
6use bytes::Bytes;
7use datafusion_common::Result;
8use futures::Stream;
9use std::io::Write;
10use std::path::Path;
11use std::pin::Pin;
12use std::sync::Arc;
13
14/// Abstraction over a spill file backend.
15/// Implementations handle their own quota enforcement and blocking concerns.
16#[async_trait]
17pub trait SpillFile: Send + Sync {
18 /// Returns the OS path if this is a local file, None otherwise.
19 fn path(&self) -> Option<&Path> {
20 None
21 }
22
23 /// Returns current size in bytes if cheaply available.
24 fn size(&self) -> Option<u64>;
25
26 /// Returns file contents as an async stream of byte chunks.
27 fn read_stream(&self) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes>> + Send>>>;
28
29 /// Opens a writer for appending data to this file.
30 fn open_writer(&self) -> Result<Box<dyn SpillWriter>>;
31
32 /// Opens an asynchronous writer for appending data to this file.
33 ///
34 /// The default implementation adapts [`Self::open_writer`] for backwards
35 /// compatibility. Backends with native asynchronous I/O should override
36 /// this method to avoid blocking an async executor.
37 async fn open_async_writer(&self) -> Result<Box<dyn AsyncSpillWriter>> {
38 Ok(Box::new(BlockingSpillWriterAdapter {
39 inner: self.open_writer()?,
40 }))
41 }
42}
43
44/// Writer for spill file backends.
45pub trait SpillWriter: Write + Send {
46 /// Intended for close/sync/commit operations.
47 fn finish(&mut self) -> Result<()>;
48}
49
50/// Asynchronous writer for spill file backends.
51///
52/// The writer accepts owned [`Bytes`] so asynchronous backends can retain a
53/// buffer across an await within [`Self::write_all`] without copying it. Calls
54/// are made sequentially and buffers must be persisted in the order received.
55/// After `write_all` returns, implementations must not retain the input's
56/// backing allocation unless that retained memory is accounted for separately.
57/// Backends that buffer a tail for a later call should copy that tail into an
58/// allocation sized for the retained bytes.
59///
60/// DataFusion makes a best-effort attempt to abort writers dropped by query
61/// cancellation. Backends should still configure lifecycle cleanup for
62/// abandoned uploads because cleanup cannot run after process termination.
63#[async_trait]
64pub trait AsyncSpillWriter: Send {
65 /// Writes all bytes in `data` to the spill file.
66 async fn write_all(&mut self, data: Bytes) -> Result<()>;
67
68 /// Flushes buffered data, if supported by the backend.
69 ///
70 /// This does not finish the writer or require the spill file to become
71 /// visible to readers. [`Self::finish`] is the commit boundary.
72 async fn flush(&mut self) -> Result<()> {
73 Ok(())
74 }
75
76 /// Finishes and commits the spill file.
77 ///
78 /// A successful call is terminal. If committing returns an error, the
79 /// caller will invoke [`Self::abort`] before dropping the writer.
80 async fn finish(&mut self) -> Result<()>;
81
82 /// Aborts an uncommitted spill write and cleans up backend resources.
83 ///
84 /// Multipart backends should override this method to explicitly abort an
85 /// in-progress upload. A successful call is terminal. DataFusion may retry
86 /// an abort that returns an error, including during best-effort drop cleanup.
87 ///
88 /// Implementations should bound their own abort latency to avoid holding
89 /// DataFusion's limited cleanup slots indefinitely. DataFusion does not
90 /// impose a timeout because the caller's runtime may not have a time driver.
91 async fn abort(&mut self) -> Result<()> {
92 Ok(())
93 }
94}
95
96struct BlockingSpillWriterAdapter {
97 inner: Box<dyn SpillWriter>,
98}
99
100#[async_trait]
101impl AsyncSpillWriter for BlockingSpillWriterAdapter {
102 async fn write_all(&mut self, data: Bytes) -> Result<()> {
103 self.inner.write_all(&data)?;
104 Ok(())
105 }
106
107 async fn flush(&mut self) -> Result<()> {
108 self.inner.flush()?;
109 Ok(())
110 }
111
112 async fn finish(&mut self) -> Result<()> {
113 self.inner.flush()?;
114 self.inner.finish()
115 }
116}
117
118/// Factory for creating spill files.
119pub trait TempFileFactory: Send + Sync {
120 fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>>;
121}