Skip to main content

datafusion_execution/
disk_manager.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//! [`DiskManager`]: Manages files generated during query execution
6
7use crate::spill_file::{SpillFile, SpillWriter, TempFileFactory};
8use bytes::Bytes;
9use datafusion_common::human_readable_size;
10use datafusion_common::{DataFusionError, Result, config_err, resources_datafusion_err};
11#[cfg(not(target_arch = "wasm32"))]
12use futures::StreamExt;
13use log::debug;
14use parking_lot::Mutex;
15use rand::{Rng, rng};
16use std::fmt::Debug;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
20use tempfile::{Builder, NamedTempFile, TempDir};
21pub const DEFAULT_MAX_TEMP_DIRECTORY_SIZE: u64 = 100 * 1024 * 1024 * 1024; // 100GB
22pub const DEFAULT_MAX_SPILL_MERGE_FAN_IN: usize = 0;
23
24/// Builder pattern for the [DiskManager] structure
25#[derive(Clone)]
26pub struct DiskManagerBuilder {
27    /// The storage mode of the disk manager
28    mode: DiskManagerMode,
29    /// The maximum amount of data (in bytes) stored inside the temporary directories.
30    /// Default to 100GB
31    max_temp_directory_size: u64,
32    /// Maximum number of spill files opened by one external merge pass.
33    /// A value of 0 means unlimited.
34    max_spill_merge_fan_in: usize,
35}
36impl Debug for DiskManagerBuilder {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("DiskManagerBuilder")
39            .field("mode", &self.mode)
40            .field("max_temp_directory_size", &self.max_temp_directory_size)
41            .finish()
42    }
43}
44impl Default for DiskManagerBuilder {
45    fn default() -> Self {
46        Self {
47            mode: DiskManagerMode::OsTmpDirectory,
48            max_temp_directory_size: DEFAULT_MAX_TEMP_DIRECTORY_SIZE,
49            max_spill_merge_fan_in: DEFAULT_MAX_SPILL_MERGE_FAN_IN,
50        }
51    }
52}
53
54impl DiskManagerBuilder {
55    pub fn set_mode(&mut self, mode: DiskManagerMode) {
56        self.mode = mode;
57    }
58
59    pub fn with_mode(mut self, mode: DiskManagerMode) -> Self {
60        self.set_mode(mode);
61        self
62    }
63
64    /// Configure a custom factory for creating temporary spill files.
65    ///
66    /// This sets the disk manager mode to [`DiskManagerMode::Custom`], so
67    /// operators that spill during query execution create files through the
68    /// provided [`TempFileFactory`] instead of using local temporary files.
69    pub fn set_temp_file_factory(&mut self, temp_file_factory: Arc<dyn TempFileFactory>) {
70        self.mode = DiskManagerMode::Custom(temp_file_factory);
71    }
72
73    /// Configure a custom factory for creating temporary spill files.
74    ///
75    /// See details on [`Self::set_temp_file_factory`].
76    pub fn with_temp_file_factory(
77        mut self,
78        temp_file_factory: Arc<dyn TempFileFactory>,
79    ) -> Self {
80        self.set_temp_file_factory(temp_file_factory);
81        self
82    }
83
84    pub fn set_max_temp_directory_size(&mut self, value: u64) {
85        self.max_temp_directory_size = value;
86    }
87
88    pub fn with_max_temp_directory_size(mut self, value: u64) -> Self {
89        self.set_max_temp_directory_size(value);
90        self
91    }
92
93    pub fn set_max_spill_merge_fan_in(&mut self, value: usize) {
94        self.max_spill_merge_fan_in = value;
95    }
96
97    pub fn with_max_spill_merge_fan_in(mut self, value: usize) -> Self {
98        self.set_max_spill_merge_fan_in(value);
99        self
100    }
101
102    /// Create a DiskManager given the builder
103    pub fn build(self) -> Result<DiskManager> {
104        match self.mode {
105            DiskManagerMode::OsTmpDirectory => Ok(DiskManager {
106                local_dirs: Mutex::new(Some(vec![])),
107                conf_dirs: vec![],
108                max_temp_directory_size: AtomicU64::new(self.max_temp_directory_size),
109                max_spill_merge_fan_in: AtomicUsize::new(self.max_spill_merge_fan_in),
110                used_disk_space: Arc::new(AtomicU64::new(0)),
111                active_files_count: Arc::new(AtomicUsize::new(0)),
112                factory: None,
113            }),
114            DiskManagerMode::Directories(conf_dirs) => Ok(DiskManager {
115                // Created on the first `create_tmp_file`, as `OsTmpDirectory`
116                // already does, so building a `DiskManager` that never spills
117                // costs no directory syscalls.
118                local_dirs: Mutex::new(Some(vec![])),
119                conf_dirs,
120                max_temp_directory_size: AtomicU64::new(self.max_temp_directory_size),
121                max_spill_merge_fan_in: AtomicUsize::new(self.max_spill_merge_fan_in),
122                used_disk_space: Arc::new(AtomicU64::new(0)),
123                active_files_count: Arc::new(AtomicUsize::new(0)),
124                factory: None,
125            }),
126            DiskManagerMode::Disabled => Ok(DiskManager {
127                local_dirs: Mutex::new(None),
128                conf_dirs: vec![],
129                max_temp_directory_size: AtomicU64::new(self.max_temp_directory_size),
130                max_spill_merge_fan_in: AtomicUsize::new(self.max_spill_merge_fan_in),
131                used_disk_space: Arc::new(AtomicU64::new(0)),
132                active_files_count: Arc::new(AtomicUsize::new(0)),
133                factory: None,
134            }),
135            DiskManagerMode::Custom(factory) => Ok(DiskManager {
136                local_dirs: Mutex::new(None),
137                conf_dirs: vec![],
138                max_temp_directory_size: AtomicU64::new(self.max_temp_directory_size),
139                max_spill_merge_fan_in: AtomicUsize::new(self.max_spill_merge_fan_in),
140                used_disk_space: Arc::new(AtomicU64::new(0)),
141                active_files_count: Arc::new(AtomicUsize::new(0)),
142                factory: Some(factory),
143            }),
144        }
145    }
146}
147
148#[derive(Clone, Default)]
149pub enum DiskManagerMode {
150    /// Create a new [DiskManager] that creates temporary files within
151    /// a temporary directory chosen by the OS
152    #[default]
153    OsTmpDirectory,
154
155    /// Create a new [DiskManager] that creates temporary files within
156    /// the specified directories. One of the directories will be chosen
157    /// at random for each temporary file created.
158    Directories(Vec<PathBuf>),
159
160    /// Create a new [DiskManager] with a cutstom backend
161    Custom(Arc<dyn TempFileFactory>),
162
163    /// Disable disk manager, attempts to create temporary files will error
164    Disabled,
165}
166
167impl Debug for DiskManagerMode {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        match self {
170            Self::OsTmpDirectory => write!(f, "OsTmpDirectory"),
171            Self::Directories(dirs) => f.debug_tuple("Directories").field(dirs).finish(),
172            Self::Disabled => write!(f, "Disabled"),
173            Self::Custom(_) => write!(f, "Custom(Arc<dyn TempFileFactory>)"),
174        }
175    }
176}
177
178/// Manages files generated during query execution, e.g. spill files generated
179/// while processing dataset larger than available memory.
180pub struct DiskManager {
181    /// TempDirs to put temporary files in.
182    ///
183    /// If `Some(vec![])` a new OS specified temporary directory will be created
184    /// If `None` an error will be returned (configured not to spill)
185    local_dirs: Mutex<Option<Vec<Arc<TempDir>>>>,
186    /// Directories configured by [`DiskManagerMode::Directories`], whose working
187    /// directories are created on the first `create_tmp_file`. Empty in every
188    /// other mode, where an OS temporary directory is used instead.
189    conf_dirs: Vec<PathBuf>,
190    /// The maximum amount of data (in bytes) stored inside the temporary directories.
191    /// Default to 100GB. Stored as `AtomicU64` so it can be adjusted at runtime
192    /// without requiring exclusive (`&mut`) access to the `DiskManager`.
193    max_temp_directory_size: AtomicU64,
194    /// Maximum number of spill files opened by one external merge pass.
195    /// A value of 0 preserves the memory-driven, unbounded behavior.
196    max_spill_merge_fan_in: AtomicUsize,
197    /// Used disk space in the temporary directories. Now only spilled data for
198    /// external executors are counted.
199    used_disk_space: Arc<AtomicU64>,
200    /// Number of active temporary files created by this disk manager
201    active_files_count: Arc<AtomicUsize>,
202    /// Factory
203    factory: Option<Arc<dyn TempFileFactory>>,
204}
205impl Debug for DiskManager {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("DiskManager")
208            .field("local_dirs", &self.local_dirs)
209            .field("max_temp_directory_size", &self.max_temp_directory_size)
210            .field("used_disk_space", &self.used_disk_space)
211            .field("active_files_count", &self.active_files_count)
212            .field("factory", &self.factory.is_some())
213            .finish()
214    }
215}
216/// Information about the current disk usage for spilling
217#[derive(Debug, Clone, Copy)]
218pub struct SpillingProgress {
219    /// Total bytes currently used on disk for spilling
220    pub current_bytes: u64,
221    /// Total number of active spill files
222    pub active_files_count: usize,
223}
224
225impl DiskManager {
226    /// Creates a builder for [DiskManager]
227    pub fn builder() -> DiskManagerBuilder {
228        DiskManagerBuilder::default()
229    }
230
231    /// Atomically set the max temp directory size at runtime.
232    ///
233    /// Takes `&self`, so it works through `Arc<DiskManager>` without requiring
234    /// exclusive access. Takes effect immediately for subsequent spill writes.
235    ///
236    /// Use this when you need to adjust the limit dynamically while queries
237    /// are running (e.g., adapting to available disk space).
238    pub fn set_max_temp_directory_size(
239        &self,
240        max_temp_directory_size: u64,
241    ) -> Result<()> {
242        // If the disk manager is disabled and `max_temp_directory_size` is not 0,
243        // this operation is not meaningful, fail early.
244        if self.local_dirs.lock().is_none()
245            && max_temp_directory_size != 0
246            && self.factory.is_none()
247        {
248            return config_err!(
249                "Cannot set max temp directory size for a disk manager that spilling is disabled"
250            );
251        }
252
253        self.max_temp_directory_size
254            .store(max_temp_directory_size, Ordering::Relaxed);
255        Ok(())
256    }
257
258    #[deprecated(
259        since = "54.0.0",
260        note = "Use `set_max_temp_directory_size` directly, it now takes &self"
261    )]
262    pub fn set_arc_max_temp_directory_size(
263        this: &Arc<Self>,
264        max_temp_directory_size: u64,
265    ) -> Result<()> {
266        this.set_max_temp_directory_size(max_temp_directory_size)
267    }
268
269    pub fn with_max_temp_directory_size(
270        self,
271        max_temp_directory_size: u64,
272    ) -> Result<Self> {
273        self.set_max_temp_directory_size(max_temp_directory_size)?;
274        Ok(self)
275    }
276
277    pub fn used_disk_space(&self) -> u64 {
278        self.used_disk_space.load(Ordering::Relaxed)
279    }
280
281    /// Returns the maximum temporary directory size in bytes
282    pub fn max_temp_directory_size(&self) -> u64 {
283        self.max_temp_directory_size.load(Ordering::Relaxed)
284    }
285
286    /// Atomically set the maximum spill merge fan-in.
287    ///
288    /// A value of 0 disables the cap. Values of 1 are accepted but external
289    /// merge code will still merge at least two spill streams to make progress.
290    pub fn set_max_spill_merge_fan_in(&self, max_spill_merge_fan_in: usize) {
291        self.max_spill_merge_fan_in
292            .store(max_spill_merge_fan_in, Ordering::Relaxed);
293    }
294
295    /// Returns the maximum number of spill files opened by one merge pass.
296    ///
297    /// A value of 0 means unlimited.
298    pub fn max_spill_merge_fan_in(&self) -> usize {
299        self.max_spill_merge_fan_in.load(Ordering::Relaxed)
300    }
301
302    /// Returns the current spilling progress
303    pub fn spilling_progress(&self) -> SpillingProgress {
304        SpillingProgress {
305            current_bytes: self.used_disk_space.load(Ordering::Relaxed),
306            active_files_count: self.active_files_count.load(Ordering::Relaxed),
307        }
308    }
309
310    /// Returns the temporary directory paths
311    pub fn temp_dir_paths(&self) -> Vec<PathBuf> {
312        self.local_dirs
313            .lock()
314            .as_ref()
315            .map(|dirs| {
316                dirs.iter()
317                    .map(|temp_dir| temp_dir.path().to_path_buf())
318                    .collect()
319            })
320            .unwrap_or_default()
321    }
322
323    /// Return true if this disk manager supports creating temporary
324    /// files. If this returns false, any call to `create_tmp_file`
325    /// will error.
326    pub fn tmp_files_enabled(&self) -> bool {
327        self.factory.is_some() || self.local_dirs.lock().is_some()
328    }
329
330    /// Return a temporary file from a randomized choice in the configured locations
331    ///
332    /// If the file can not be created for some reason, returns an
333    /// error message referencing the request description
334    pub fn create_tmp_file(
335        self: &Arc<Self>,
336        request_description: &str,
337    ) -> Result<Arc<dyn SpillFile>> {
338        // Delegate to custom backend if configured
339        if let Some(factory) = &self.factory {
340            return factory.create_temp_file(request_description);
341        }
342        let mut guard = self.local_dirs.lock();
343        let local_dirs = guard.as_mut().ok_or_else(|| {
344            resources_datafusion_err!(
345                "Memory Exhausted while {request_description} (DiskManager is disabled)"
346            )
347        })?;
348
349        // Create the working directories if needed
350        if local_dirs.is_empty() {
351            if self.conf_dirs.is_empty() {
352                let tempdir = tempfile::tempdir().map_err(DataFusionError::IoError)?;
353
354                debug!(
355                    "Created directory '{:?}' as DataFusion tempfile directory for {}",
356                    tempdir.path().to_string_lossy(),
357                    request_description,
358                );
359
360                local_dirs.push(Arc::new(tempdir));
361            } else {
362                let created = create_local_dirs(&self.conf_dirs)?;
363                debug!("Created local dirs {created:?} as DataFusion working directory");
364                local_dirs.extend(created);
365            }
366        }
367
368        let dir_index = rng().random_range(0..local_dirs.len());
369        self.active_files_count.fetch_add(1, Ordering::Relaxed);
370        Ok(Arc::new(RefCountedTempFile {
371            parent_temp_dir: Arc::clone(&local_dirs[dir_index]),
372            tempfile: Arc::new(
373                Builder::new()
374                    .prefix(&escape_for_temp_file_name_prefix(request_description))
375                    .tempfile_in(local_dirs[dir_index].as_ref())
376                    .map_err(DataFusionError::IoError)?,
377            ),
378            current_file_disk_usage: Arc::new(AtomicU64::new(0)),
379            disk_manager: Arc::clone(self),
380        }))
381    }
382}
383
384/// A wrapper around a [`NamedTempFile`] that also contains
385/// a reference to its parent temporary directory.
386///
387/// This type is Clone-able, allowing multiple references to the same underlying file.
388/// The file is deleted only when the last reference is dropped.
389///
390/// The parent temporary directory is also kept alive as long as any reference to
391/// this file exists, preventing premature cleanup of the directory.
392///
393/// Once all references to this file are dropped, the file is deleted, and the
394/// disk usage is subtracted from the disk manager's total.
395#[derive(Debug)]
396pub struct RefCountedTempFile {
397    /// The reference to the directory in which temporary files are created to ensure
398    /// it is not cleaned up prior to the NamedTempFile
399    parent_temp_dir: Arc<TempDir>,
400    /// The underlying temporary file, wrapped in Arc to allow cloning
401    tempfile: Arc<NamedTempFile>,
402    /// Tracks the current disk usage of this temporary file.
403    ///
404    /// This is wrapped in `Arc<AtomicU64>` so that all clones share the same
405    /// disk usage tracking, preventing incorrect accounting when clones are dropped.
406    current_file_disk_usage: Arc<AtomicU64>,
407    /// The disk manager that created and manages this temporary file
408    disk_manager: Arc<DiskManager>,
409}
410
411impl Clone for RefCountedTempFile {
412    fn clone(&self) -> Self {
413        Self {
414            parent_temp_dir: Arc::clone(&self.parent_temp_dir),
415            tempfile: Arc::clone(&self.tempfile),
416            current_file_disk_usage: Arc::clone(&self.current_file_disk_usage),
417            disk_manager: Arc::clone(&self.disk_manager),
418        }
419    }
420}
421
422impl RefCountedTempFile {
423    pub fn path(&self) -> &Path {
424        self.tempfile.path()
425    }
426
427    pub fn inner(&self) -> &NamedTempFile {
428        self.tempfile.as_ref()
429    }
430
431    fn current_disk_usage(&self) -> u64 {
432        self.current_file_disk_usage.load(Ordering::Relaxed)
433    }
434}
435
436/// When the temporary file is dropped, subtract its disk usage from the disk manager's total
437impl Drop for RefCountedTempFile {
438    fn drop(&mut self) {
439        // Only subtract disk usage when this is the last reference to the file
440        // Check if we're the last one by seeing if there's only one strong reference
441        // left to the underlying tempfile (the one we're holding)
442        if Arc::strong_count(&self.tempfile) == 1 {
443            let current_usage = self.current_file_disk_usage.load(Ordering::Relaxed);
444            self.disk_manager
445                .used_disk_space
446                .fetch_sub(current_usage, Ordering::Relaxed);
447            self.disk_manager
448                .active_files_count
449                .fetch_sub(1, Ordering::Relaxed);
450        }
451    }
452}
453
454/// Setup local dirs by creating one new dir in each of the given dirs
455fn create_local_dirs(local_dirs: &[PathBuf]) -> Result<Vec<Arc<TempDir>>> {
456    local_dirs
457        .iter()
458        .map(|root| {
459            if !Path::new(root).exists() {
460                std::fs::create_dir(root)?;
461            }
462            Builder::new()
463                .prefix("datafusion-")
464                .tempdir_in(root)
465                .map_err(DataFusionError::IoError)
466        })
467        .map(|result| result.map(Arc::new))
468        .collect()
469}
470
471pub struct FileSpillWriter {
472    file: std::fs::File,
473    disk_manager: Arc<DiskManager>,
474    current_file_disk_usage: Arc<AtomicU64>,
475}
476
477impl std::io::Write for FileSpillWriter {
478    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
479        let len = buf.len() as u64;
480        if len == 0 {
481            return Ok(0);
482        }
483
484        let new_global = self
485            .disk_manager
486            .used_disk_space
487            .fetch_add(len, Ordering::Relaxed)
488            + len;
489
490        let limit = self.disk_manager.max_temp_directory_size();
491
492        if new_global > limit {
493            self.disk_manager
494                .used_disk_space
495                .fetch_sub(len, Ordering::Relaxed);
496
497            return Err(std::io::Error::other(format!(
498                "The used disk space during the spilling process has exceeded the allowable limit of {}. \
499                        Please try increasing the config: `datafusion.runtime.max_temp_directory_size`.",
500                human_readable_size(limit as usize)
501            )));
502        }
503
504        self.file.write_all(buf).map_err(DataFusionError::IoError)?;
505
506        self.current_file_disk_usage
507            .fetch_add(len, Ordering::Relaxed);
508
509        Ok(buf.len())
510    }
511
512    fn flush(&mut self) -> std::io::Result<()> {
513        self.file.flush()
514    }
515}
516
517impl SpillWriter for FileSpillWriter {
518    fn finish(&mut self) -> Result<()> {
519        // flush() is handled by Arrow, nothing left to do here
520        Ok(())
521    }
522}
523
524impl SpillFile for RefCountedTempFile {
525    fn path(&self) -> Option<&Path> {
526        Some(self.tempfile.path())
527    }
528
529    fn size(&self) -> Option<u64> {
530        Some(self.current_disk_usage())
531    }
532    #[cfg(not(target_arch = "wasm32"))]
533    fn read_stream(
534        &self,
535    ) -> Result<std::pin::Pin<Box<dyn futures::Stream<Item = Result<Bytes>> + Send>>>
536    {
537        let path = self.path().to_owned();
538
539        let stream =
540            futures::stream::once(async move {
541                tokio::fs::File::open(&path)
542                    .await
543                    .map_err(DataFusionError::IoError)
544            })
545            .flat_map(
546                |open_result| -> std::pin::Pin<
547                    Box<dyn futures::Stream<Item = Result<Bytes>> + Send>,
548                > {
549                    match open_result {
550                        Ok(file) => Box::pin(
551                            // Use a 128KB read buffer. The default 8KB causes excessive async
552                            // poll overhead when reading multi-MB spill files back into memory.
553                            tokio_util::io::ReaderStream::with_capacity(file, 128 * 1024)
554                                .map(|r| r.map_err(DataFusionError::IoError)),
555                        ),
556                        Err(e) => Box::pin(futures::stream::once(async move { Err(e) })),
557                    }
558                },
559            );
560
561        Ok(Box::pin(stream))
562    }
563
564    #[cfg(target_arch = "wasm32")]
565    fn read_stream(
566        &self,
567    ) -> Result<std::pin::Pin<Box<dyn futures::Stream<Item = Result<Bytes>> + Send>>>
568    {
569        datafusion_common::exec_err!(
570            "Default OS file spilling is not supported on WASM. Configure DiskManager with a Custom TempFileFactory."
571        )
572    }
573
574    fn open_writer(&self) -> Result<Box<dyn SpillWriter>> {
575        let file = self
576            .tempfile
577            .as_file()
578            .try_clone()
579            .map_err(DataFusionError::IoError)?;
580        Ok(Box::new(FileSpillWriter {
581            file,
582            disk_manager: Arc::clone(&self.disk_manager),
583            current_file_disk_usage: Arc::clone(&self.current_file_disk_usage),
584        }))
585    }
586}
587
588/// Escape a string to be safe to use in a temp file name prefix.
589///
590/// All non-alphanumeric characters are replaced by `_` and characters are put in lowercase.
591/// A `.tmp.` is added at the beginning and a last `.` is set at the end.
592///
593/// For example "This kind.of /input" becomes ".tmp.this_kind_of_input."
594///
595/// The output is also truncated to fit in 128 bytes.
596fn escape_for_temp_file_name_prefix(text: &str) -> String {
597    let mut output = String::with_capacity(text.len() + 6);
598    output.push_str(".tmp.");
599    let mut add_separator = false;
600    for c in text.chars() {
601        if c.is_alphanumeric() {
602            if add_separator && !output.is_empty() {
603                output.push('_');
604                add_separator = false;
605            }
606            output.extend(c.to_lowercase());
607        } else {
608            add_separator = true;
609        }
610        if output.len() >= 123 {
611            break; // We limit the output at 128 bytes and keep the space for an extra UTF-8 char and the final dot
612        }
613    }
614    output.push('.');
615    output
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621
622    #[test]
623    fn lazy_temp_dir_creation() -> Result<()> {
624        // A default configuration should not create temp files until requested
625        let dm = Arc::new(DiskManagerBuilder::default().build()?);
626
627        assert_eq!(0, local_dir_snapshot(&dm).len());
628
629        // can still create a tempfile however:
630        let actual = dm.create_tmp_file("Testing")?;
631
632        // Now the tempdir has been created on demand
633        assert_eq!(1, local_dir_snapshot(&dm).len());
634
635        // the returned tempfile file should be in the temp directory
636        let local_dirs = local_dir_snapshot(&dm);
637        assert_path_in_dirs(
638            actual.path().unwrap(),
639            local_dirs.iter().map(|p| p.as_path()),
640        );
641
642        Ok(())
643    }
644
645    fn local_dir_snapshot(dm: &DiskManager) -> Vec<PathBuf> {
646        dm.local_dirs
647            .lock()
648            .iter()
649            .flatten()
650            .map(|p| p.path().into())
651            .collect()
652    }
653
654    #[test]
655    fn file_in_right_dir_and_with_description() -> Result<()> {
656        let local_dir1 = TempDir::new()?;
657        let local_dir2 = TempDir::new()?;
658        let local_dir3 = TempDir::new()?;
659        let local_dirs = vec![local_dir1.path(), local_dir2.path(), local_dir3.path()];
660        let dm = Arc::new(
661            DiskManagerBuilder::default()
662                .with_mode(DiskManagerMode::Directories(
663                    local_dirs.iter().map(|p| p.into()).collect(),
664                ))
665                .build()?,
666        );
667
668        assert!(dm.tmp_files_enabled());
669        let actual = dm.create_tmp_file("Testing with./spécial")?;
670
671        // the file should be in one of the specified local directories
672        assert_path_in_dirs(actual.path().unwrap(), local_dirs.into_iter());
673
674        let file_name = actual
675            .path()
676            .unwrap()
677            .file_name()
678            .unwrap()
679            .to_str()
680            .unwrap();
681        assert!(
682            file_name.starts_with(".tmp.testing_with_spécial."),
683            "{file_name}"
684        );
685
686        Ok(())
687    }
688
689    #[test]
690    fn test_disabled_disk_manager() {
691        let manager = Arc::new(
692            DiskManagerBuilder::default()
693                .with_mode(DiskManagerMode::Disabled)
694                .build()
695                .unwrap(),
696        );
697        assert!(!manager.tmp_files_enabled());
698        match manager.create_tmp_file("Testing") {
699            Err(e) => {
700                assert_eq!(
701                    e.strip_backtrace(),
702                    "Resources exhausted: Memory Exhausted while Testing (DiskManager is disabled)"
703                );
704            }
705            Ok(_) => {
706                panic!("Expected DiskManager to fail creating a file when disabled!")
707            }
708        }
709    }
710
711    #[test]
712    fn test_disk_manager_create_spill_folder() {
713        let dir = TempDir::new().unwrap();
714        DiskManagerBuilder::default()
715            .with_mode(DiskManagerMode::Directories(vec![dir.path().to_path_buf()]))
716            .build()
717            .unwrap();
718    }
719
720    #[test]
721    fn test_directories_mode_creates_dirs_lazily() {
722        let dir = TempDir::new().unwrap();
723        let root = dir.path().to_path_buf();
724
725        let manager = Arc::new(
726            DiskManagerBuilder::default()
727                .with_mode(DiskManagerMode::Directories(vec![root.clone()]))
728                .build()
729                .unwrap(),
730        );
731
732        // Nothing has spilled, so no working directory should exist yet.
733        let entries: Vec<_> = std::fs::read_dir(&root).unwrap().collect();
734        assert!(
735            entries.is_empty(),
736            "expected no directories before the first spill, found {entries:?}"
737        );
738        assert!(manager.temp_dir_paths().is_empty());
739
740        // The first temporary file creates the working directory under the
741        // configured path.
742        let spill_file = manager.create_tmp_file("lazy dir test").unwrap();
743        let spill_path = spill_file.path().expect("spill file should have a path");
744        assert_path_in_dirs(spill_path, std::iter::once(root.as_path()));
745
746        let temp_dir_paths = manager.temp_dir_paths();
747        assert_eq!(temp_dir_paths.len(), 1);
748        assert!(temp_dir_paths[0].starts_with(&root));
749    }
750
751    /// Asserts that `file_path` is found anywhere in any of `dir` directories
752    fn assert_path_in_dirs<'a>(
753        file_path: &'a Path,
754        dirs: impl Iterator<Item = &'a Path>,
755    ) {
756        let dirs: Vec<&Path> = dirs.collect();
757
758        let found = dirs.iter().any(|dir_path| {
759            file_path
760                .ancestors()
761                .any(|candidate_path| *dir_path == candidate_path)
762        });
763
764        assert!(found, "Can't find {file_path:?} in dirs: {dirs:?}");
765    }
766
767    #[test]
768    fn test_temp_file_still_alive_after_disk_manager_dropped() -> Result<()> {
769        // Test for the case using OS arranged temporary directory
770        let dm = Arc::new(DiskManagerBuilder::default().build()?);
771        let temp_file = dm.create_tmp_file("Testing")?;
772        let temp_file_path = temp_file.path().unwrap().to_owned();
773        assert!(temp_file_path.exists());
774
775        drop(dm);
776        assert!(temp_file_path.exists());
777
778        drop(temp_file);
779        assert!(!temp_file_path.exists());
780
781        // Test for the case using specified directories
782        let local_dir1 = TempDir::new()?;
783        let local_dir2 = TempDir::new()?;
784        let local_dir3 = TempDir::new()?;
785        let local_dirs = [local_dir1.path(), local_dir2.path(), local_dir3.path()];
786        let dm = Arc::new(
787            DiskManagerBuilder::default()
788                .with_mode(DiskManagerMode::Directories(
789                    local_dirs.iter().map(|p| p.into()).collect(),
790                ))
791                .build()?,
792        );
793        let temp_file = dm.create_tmp_file("Testing")?;
794        let temp_file_path = temp_file.path().unwrap().to_owned();
795        assert!(temp_file_path.exists());
796
797        drop(dm);
798        assert!(temp_file_path.exists());
799
800        drop(temp_file);
801        assert!(!temp_file_path.exists());
802
803        Ok(())
804    }
805
806    #[test]
807    fn test_disk_usage_basic() -> Result<()> {
808        let dm = Arc::new(DiskManagerBuilder::default().build()?);
809        let temp_file = dm.create_tmp_file("Testing")?;
810        let mut writer = temp_file.open_writer()?;
811        // Initially, disk usage should be 0
812        assert_eq!(dm.used_disk_space(), 0);
813        assert_eq!(temp_file.size().unwrap(), 0);
814
815        // Write some data to the file
816        writer.write_all(b"hello world")?;
817
818        // Disk usage should now reflect the written data
819        let expected_usage = temp_file.size().unwrap();
820        assert!(expected_usage > 0);
821        assert_eq!(dm.used_disk_space(), expected_usage);
822
823        // Write more data
824        writer.write_all(b"more_data")?;
825
826        // Disk usage should increase
827        let new_usage = temp_file.size().unwrap();
828        assert!(new_usage > expected_usage);
829        assert_eq!(dm.used_disk_space(), new_usage);
830
831        // Drop the file
832        drop(temp_file);
833
834        // Disk usage should return to 0
835        assert_eq!(dm.used_disk_space(), 0);
836
837        Ok(())
838    }
839
840    #[test]
841    fn test_disk_usage_with_clones() -> Result<()> {
842        let dm = Arc::new(DiskManagerBuilder::default().build()?);
843        let temp_file = dm.create_tmp_file("Testing")?;
844
845        // Write some data
846        let mut writer = temp_file.open_writer()?;
847        writer.write_all(b"test data")?;
848
849        let usage_after_write = temp_file.size().unwrap();
850        assert!(usage_after_write > 0);
851        assert_eq!(dm.used_disk_space(), usage_after_write);
852
853        // Clone the file
854        let clone1 = Arc::clone(&temp_file);
855        let clone2 = Arc::clone(&temp_file);
856
857        // All clones should see the same disk usage
858        assert_eq!(clone1.size().unwrap(), usage_after_write);
859        assert_eq!(clone2.size().unwrap(), usage_after_write);
860        // Global disk usage should still be the same (not multiplied by number of clones)
861        assert_eq!(dm.used_disk_space(), usage_after_write);
862
863        // Write more data through one clone
864        let mut clone_writer = clone1.open_writer()?;
865        clone_writer.write_all(b" more data")?;
866
867        let new_usage = clone1.size().unwrap();
868        assert!(new_usage > usage_after_write);
869        // All clones should see the updated disk usage
870        assert_eq!(temp_file.size().unwrap(), new_usage);
871        assert_eq!(clone2.size().unwrap(), new_usage);
872        assert_eq!(clone1.size().unwrap(), new_usage);
873
874        // Global disk usage should reflect the new size (not multiplied)
875        assert_eq!(dm.used_disk_space(), new_usage);
876
877        // Drop one clone
878        drop(clone_writer);
879        drop(clone1);
880
881        // Disk usage should NOT change (other clones still exist)
882        assert_eq!(dm.used_disk_space(), new_usage);
883        assert_eq!(temp_file.size().unwrap(), new_usage);
884        assert_eq!(clone2.size().unwrap(), new_usage);
885
886        // Drop another clone
887        drop(clone2);
888
889        // Disk usage should still NOT change (original still exists)
890        assert_eq!(dm.used_disk_space(), new_usage);
891        assert_eq!(temp_file.size().unwrap(), new_usage);
892
893        // Drop the original
894        drop(writer);
895        drop(temp_file);
896        // Now disk usage should return to 0 (last reference dropped)
897        assert_eq!(dm.used_disk_space(), 0);
898
899        Ok(())
900    }
901
902    #[test]
903    fn test_disk_usage_clones_dropped_out_of_order() -> Result<()> {
904        let dm = Arc::new(DiskManagerBuilder::default().build()?);
905        let temp_file = dm.create_tmp_file("Testing")?;
906        let mut writer = temp_file.open_writer()?;
907
908        // Write data
909        writer.write_all(b"test")?;
910
911        let usage = temp_file.size().unwrap();
912        assert_eq!(dm.used_disk_space(), usage);
913
914        // Create multiple clones
915        let clone1 = Arc::clone(&temp_file);
916        let clone2 = Arc::clone(&temp_file);
917        let clone3 = Arc::clone(&temp_file);
918
919        // Drop the original first (out of order)
920        drop(temp_file);
921
922        // Disk usage should still be tracked (clones exist)
923        assert_eq!(dm.used_disk_space(), usage);
924        assert_eq!(clone1.size().unwrap(), usage);
925
926        // Drop clones in different order
927        drop(clone2);
928        assert_eq!(dm.used_disk_space(), usage);
929
930        drop(clone1);
931        assert_eq!(dm.used_disk_space(), usage);
932
933        // Drop the last clone
934        drop(clone3);
935
936        // Now disk usage should be 0
937        assert_eq!(dm.used_disk_space(), 0);
938
939        Ok(())
940    }
941
942    #[test]
943    fn test_disk_usage_multiple_files() -> Result<()> {
944        let dm = Arc::new(DiskManagerBuilder::default().build()?);
945
946        // Create multiple temp files
947        let file1 = dm.create_tmp_file("Testing1")?;
948        let file2 = dm.create_tmp_file("Testing2")?;
949
950        let mut writer1 = file1.open_writer()?;
951        let mut writer2 = file2.open_writer()?;
952
953        // Write to first file
954        writer1.write_all(b"file1")?;
955        let usage1 = file1.size().unwrap();
956
957        assert_eq!(dm.used_disk_space(), usage1);
958
959        // Write to second file
960        writer2.write_all(b"file2 data")?;
961        let usage2 = file2.size().unwrap();
962
963        // Global usage should be sum of both files
964        assert_eq!(dm.used_disk_space(), usage1 + usage2);
965
966        // Drop first file
967        drop(file1);
968
969        // Usage should only reflect second file
970        assert_eq!(dm.used_disk_space(), usage2);
971
972        // Drop second file
973        drop(file2);
974
975        // Usage should be 0
976        assert_eq!(dm.used_disk_space(), 0);
977
978        Ok(())
979    }
980
981    #[test]
982    fn test_dynamic_limit_adjustment_through_shared_ref() -> Result<()> {
983        // Verify that set_max_temp_directory_size works through &self (not &mut self).
984        // This is the key behavioral change: the limit can be adjusted at runtime
985        // without exclusive access, enabling dynamic resize while queries are running.
986        let dm = DiskManager::builder()
987            .with_max_temp_directory_size(1024)
988            .build()?;
989        let dm = Arc::new(dm);
990
991        assert_eq!(dm.max_temp_directory_size(), 1024);
992
993        // Adjust through shared reference (simulates concurrent access via Arc)
994        dm.set_max_temp_directory_size(2048)?;
995        assert_eq!(dm.max_temp_directory_size(), 2048);
996
997        // Can also decrease
998        dm.set_max_temp_directory_size(512)?;
999        assert_eq!(dm.max_temp_directory_size(), 512);
1000
1001        Ok(())
1002    }
1003
1004    #[test]
1005    fn test_dynamic_limit_concurrent_access() -> Result<()> {
1006        // Verify that multiple threads can read and write the limit concurrently
1007        let dm = Arc::new(
1008            DiskManager::builder()
1009                .with_max_temp_directory_size(1000)
1010                .build()?,
1011        );
1012
1013        let handles: Vec<_> = (0..8)
1014            .map(|i| {
1015                let dm = Arc::clone(&dm);
1016                std::thread::spawn(move || {
1017                    // Each thread sets a different limit and reads it back
1018                    let new_limit = (i + 1) * 1000;
1019                    dm.set_max_temp_directory_size(new_limit).unwrap();
1020                    // Read should return SOME value set by one of the threads
1021                    let current = dm.max_temp_directory_size();
1022                    assert!((1000..=8000).contains(&current));
1023                })
1024            })
1025            .collect();
1026
1027        for h in handles {
1028            h.join().unwrap();
1029        }
1030
1031        // Final value should be one of the values set by threads
1032        let final_val = dm.max_temp_directory_size();
1033        assert!((1000..=8000).contains(&final_val));
1034
1035        Ok(())
1036    }
1037
1038    #[test]
1039    fn test_max_spill_merge_fan_in_builder_and_dynamic_update() -> Result<()> {
1040        let dm = Arc::new(
1041            DiskManager::builder()
1042                .with_max_spill_merge_fan_in(8)
1043                .build()?,
1044        );
1045
1046        assert_eq!(dm.max_spill_merge_fan_in(), 8);
1047
1048        dm.set_max_spill_merge_fan_in(4);
1049        assert_eq!(dm.max_spill_merge_fan_in(), 4);
1050
1051        dm.set_max_spill_merge_fan_in(0);
1052        assert_eq!(dm.max_spill_merge_fan_in(), 0);
1053
1054        Ok(())
1055    }
1056
1057    #[test]
1058    fn test_disabled_disk_manager_rejects_nonzero_limit() -> Result<()> {
1059        let dm = DiskManager::builder()
1060            .with_mode(DiskManagerMode::Disabled)
1061            .build()?;
1062        let dm = Arc::new(dm);
1063
1064        // Setting non-zero limit on disabled DiskManager should error
1065        let result = dm.set_max_temp_directory_size(1024);
1066        assert!(result.is_err());
1067
1068        // Setting zero is OK
1069        assert!(dm.set_max_temp_directory_size(0).is_ok());
1070
1071        Ok(())
1072    }
1073
1074    #[test]
1075    fn test_limit_decrease_below_current_usage() -> Result<()> {
1076        // Scenario: DiskManager has 100GB limit, currently using 80GB.
1077        // Admin lowers limit to 60GB. What happens?
1078        //
1079        // Expected behavior:
1080        // - Existing spill files remain on disk (not deleted)
1081        // - used_disk_space still reports 80GB
1082        // - New spill writes FAIL immediately (80GB > 60GB new limit)
1083        // - Once old queries complete and release their files (used drops below 60GB),
1084        //   new spill writes succeed again
1085        //
1086        // This demonstrates graceful degradation: lowering the limit doesn't
1087        // reclaim existing files (would break running queries), but prevents
1088        // additional spilling until usage drops naturally.
1089        let dm = DiskManager::builder()
1090            .with_max_temp_directory_size(100 * 1024 * 1024 * 1024) // 100GB
1091            .build()?;
1092        let dm = Arc::new(dm);
1093
1094        // Simulate 80GB of existing spill usage
1095        dm.used_disk_space
1096            .store(80 * 1024 * 1024 * 1024, Ordering::Relaxed);
1097
1098        assert_eq!(dm.max_temp_directory_size(), 100 * 1024 * 1024 * 1024);
1099        assert_eq!(dm.used_disk_space(), 80 * 1024 * 1024 * 1024);
1100
1101        // Lower the limit to 60GB (below current usage)
1102        dm.set_max_temp_directory_size(60 * 1024 * 1024 * 1024)?;
1103        assert_eq!(dm.max_temp_directory_size(), 60 * 1024 * 1024 * 1024);
1104
1105        // Current usage (80GB) now exceeds the new limit (60GB).
1106        // The used_disk_space is NOT reclaimed — existing files stay.
1107        assert_eq!(dm.used_disk_space(), 80 * 1024 * 1024 * 1024);
1108
1109        // Any attempt to write MORE would be rejected at the SpillWriter level
1110        // because used_disk_space(80GB) > max_temp_directory_size(60GB).
1111        // (SpillWriter check: `global_disk_usage > limit` returns ResourcesExhausted)
1112
1113        // Simulate old queries completing: usage drops to 50GB
1114        dm.used_disk_space
1115            .store(50 * 1024 * 1024 * 1024, Ordering::Relaxed);
1116
1117        // Now usage (50GB) < limit (60GB) — new spill writes would succeed again
1118        assert!(dm.used_disk_space() < dm.max_temp_directory_size());
1119
1120        Ok(())
1121    }
1122
1123    #[test]
1124    fn test_limit_decrease_with_concurrent_queries() -> Result<()> {
1125        // Scenario: Multiple threads spilling while limit is lowered concurrently.
1126        // Demonstrates that:
1127        // 1. In-flight spills that started before the limit change complete normally
1128        //    (they already incremented used_disk_space)
1129        // 2. New spills after the limit change respect the new lower limit
1130        // 3. No data corruption or panics from concurrent access
1131        let dm = Arc::new(
1132            DiskManager::builder()
1133                .with_max_temp_directory_size(100 * 1024 * 1024) // 100MB
1134                .build()?,
1135        );
1136
1137        let barrier = Arc::new(std::sync::Barrier::new(5));
1138
1139        // 4 threads simulate concurrent spilling
1140        let spill_handles: Vec<_> = (0..4)
1141            .map(|_| {
1142                let dm = Arc::clone(&dm);
1143                let barrier = Arc::clone(&barrier);
1144                std::thread::spawn(move || {
1145                    barrier.wait();
1146                    // Simulate spill: increment used_disk_space
1147                    dm.used_disk_space
1148                        .fetch_add(10 * 1024 * 1024, Ordering::Relaxed);
1149                    std::thread::sleep(std::time::Duration::from_millis(10));
1150                    // Simulate cleanup
1151                    dm.used_disk_space
1152                        .fetch_sub(10 * 1024 * 1024, Ordering::Relaxed);
1153                })
1154            })
1155            .collect();
1156
1157        // 1 thread lowers the limit mid-flight
1158        let dm_resize = Arc::clone(&dm);
1159        let resize_barrier = Arc::clone(&barrier);
1160        let resize_handle = std::thread::spawn(move || {
1161            resize_barrier.wait();
1162            // Lower limit while spills are in progress
1163            dm_resize
1164                .set_max_temp_directory_size(30 * 1024 * 1024) // 30MB
1165                .unwrap();
1166        });
1167
1168        for h in spill_handles {
1169            h.join().unwrap();
1170        }
1171        resize_handle.join().unwrap();
1172
1173        // After all threads complete:
1174        // - Limit is 30MB (last set by resize thread)
1175        // - used_disk_space is 0 (all spills cleaned up)
1176        // - No panics, no corruption
1177        assert_eq!(dm.max_temp_directory_size(), 30 * 1024 * 1024);
1178        assert_eq!(dm.used_disk_space(), 0);
1179
1180        Ok(())
1181    }
1182
1183    #[test]
1184    fn test_rollback_on_limit_exceeded_then_drop_returns_to_zero() -> Result<()> {
1185        // This test verifies that lowering the limit, failing a spill write,
1186        // and then dropping the file leaves used_disk_space at zero.
1187        //
1188        // Without the rollback fix, the global counter would be permanently
1189        // inflated by the delta between the new and old file sizes.
1190
1191        let dm = Arc::new(
1192            DiskManager::builder()
1193                .with_max_temp_directory_size(10 * 1024 * 1024) // 10MB
1194                .build()?,
1195        );
1196
1197        let file = dm.create_tmp_file("test_rollback")?;
1198
1199        let mut writer = file.open_writer()?;
1200
1201        // Create a temp file and write some data
1202        {
1203            let data = vec![0u8; 1024]; // 1KB
1204            writer.write_all(&data)?;
1205        }
1206
1207        let usage_after_first_write = dm.used_disk_space();
1208        assert!(usage_after_first_write > 0);
1209
1210        // Write more data to grow the file
1211        {
1212            let data = vec![0u8; 4 * 1024]; // 4KB more
1213            writer.write_all(&data)?;
1214        }
1215
1216        let usage_after_second_write = dm.used_disk_space();
1217        assert!(usage_after_second_write > usage_after_first_write);
1218
1219        // Now lower the limit to 1 byte — below current usage
1220        dm.set_max_temp_directory_size(1)?;
1221
1222        // Write even more data
1223        {
1224            let data = vec![0u8; 2 * 1024]; // 2KB more
1225
1226            // This write should FAIL (exceeds new 1-byte limit)
1227            let result = writer.write_all(&data);
1228
1229            assert!(result.is_err());
1230            assert!(
1231                result
1232                    .unwrap_err()
1233                    .to_string()
1234                    .contains("exceeded the allowable limit")
1235            );
1236        }
1237
1238        // Critical check: used_disk_space should still equal the LAST
1239        // successful update (before the failed one), not be inflated
1240        assert_eq!(dm.used_disk_space(), usage_after_second_write);
1241
1242        // Drop the writer and file — should subtract the last successful file size
1243        drop(writer);
1244        drop(file);
1245
1246        // After drop: used_disk_space must be zero (no leak)
1247        assert_eq!(dm.used_disk_space(), 0);
1248
1249        Ok(())
1250    }
1251
1252    #[test]
1253    fn test_escape_for_temp_file_name_prefix() {
1254        assert_eq!(escape_for_temp_file_name_prefix("foo"), ".tmp.foo.");
1255        assert_eq!(escape_for_temp_file_name_prefix("fooé \nt"), ".tmp.fooé_t.");
1256        assert_eq!(
1257            escape_for_temp_file_name_prefix(&"a".repeat(200)),
1258            format!(".tmp.{}.", "a".repeat(118))
1259        );
1260    }
1261}