Skip to main content

datafusion_execution/
runtime_env.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//! Execution [`RuntimeEnv`] environment that manages access to object
6//! store, memory manager, disk manager.
7
8use crate::disk_manager::SpillingProgress;
9use crate::{
10    disk_manager::{DiskManager, DiskManagerBuilder, DiskManagerMode},
11    memory_pool::{
12        GreedyMemoryPool, MemoryPool, TrackConsumersPool, UnboundedMemoryPool,
13    },
14    object_store::{DefaultObjectStoreRegistry, ObjectStoreRegistry},
15};
16
17use crate::cache::cache_manager::{CacheManager, CacheManagerConfig};
18#[cfg(feature = "parquet_encryption")]
19use crate::parquet_encryption::{EncryptionFactory, EncryptionFactoryRegistry};
20use datafusion_common::{Result, config::ConfigEntry};
21use object_store::ObjectStore;
22use std::sync::Arc;
23use std::{
24    fmt::{Debug, Formatter},
25    num::NonZeroUsize,
26};
27use std::{path::PathBuf, time::Duration};
28use url::Url;
29
30#[derive(Clone)]
31/// Execution runtime environment that manages system resources such
32/// as memory, disk, cache and storage.
33///
34/// A [`RuntimeEnv`] can be created using [`RuntimeEnvBuilder`] and has the
35/// following resource management functionality:
36///
37/// * [`MemoryPool`]: Manage memory
38/// * [`DiskManager`]: Manage temporary files on local disk
39/// * [`CacheManager`]: Manage temporary cache data during the session lifetime
40/// * [`ObjectStoreRegistry`]: Manage mapping URLs to object store instances
41///
42/// # Example: Create default `RuntimeEnv`
43/// ```
44/// # use datafusion_execution::runtime_env::RuntimeEnv;
45/// let runtime_env = RuntimeEnv::default();
46/// ```
47///
48/// # Example: Create a `RuntimeEnv` from [`RuntimeEnvBuilder`] with a new memory pool
49/// ```
50/// # use std::sync::Arc;
51/// # use datafusion_execution::memory_pool::GreedyMemoryPool;
52/// # use datafusion_execution::runtime_env::{RuntimeEnv, RuntimeEnvBuilder};
53/// // restrict to using at most 100MB of memory
54/// let pool_size = 100 * 1024 * 1024;
55/// let runtime_env = RuntimeEnvBuilder::new()
56///     .with_memory_pool(Arc::new(GreedyMemoryPool::new(pool_size)))
57///     .build()
58///     .unwrap();
59/// ```
60pub struct RuntimeEnv {
61    /// Runtime memory management
62    pub memory_pool: Arc<dyn MemoryPool>,
63    /// Manage temporary files during query execution
64    pub disk_manager: Arc<DiskManager>,
65    /// Manage temporary cache during query execution
66    pub cache_manager: Arc<CacheManager>,
67    /// Object Store Registry
68    pub object_store_registry: Arc<dyn ObjectStoreRegistry>,
69    /// Parquet encryption factory registry
70    #[cfg(feature = "parquet_encryption")]
71    pub parquet_encryption_factory_registry: Arc<EncryptionFactoryRegistry>,
72}
73
74impl Debug for RuntimeEnv {
75    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
76        write!(f, "RuntimeEnv")
77    }
78}
79
80struct RuntimeConfigValues {
81    memory_limit: Option<String>,
82    max_temp_directory_size: Option<String>,
83    max_spill_merge_fan_in: Option<String>,
84    temp_directory: Option<String>,
85    metadata_cache_limit: Option<String>,
86    list_files_cache_limit: Option<String>,
87    list_files_cache_ttl: Option<String>,
88    file_statistics_cache_limit: Option<String>,
89}
90
91impl RuntimeConfigValues {
92    /// Creates runtime configuration entries with the provided values.
93    ///
94    /// This defines the structure and metadata for all runtime configuration
95    /// entries to avoid duplication between `RuntimeEnv::config_entries()` and
96    /// `RuntimeEnvBuilder::entries()`.
97    fn into_config_entries(self) -> Vec<ConfigEntry> {
98        let Self {
99            memory_limit,
100            max_temp_directory_size,
101            max_spill_merge_fan_in,
102            temp_directory,
103            metadata_cache_limit,
104            list_files_cache_limit,
105            list_files_cache_ttl,
106            file_statistics_cache_limit,
107        } = self;
108        vec![
109            ConfigEntry {
110                key: "datafusion.runtime.memory_limit".to_string(),
111                value: memory_limit,
112                description: "Maximum memory limit for query execution. Supports suffixes K (kilobytes), M (megabytes), and G (gigabytes) or '0' for 0. Example: '2G' for 2 gigabytes.",
113            },
114            ConfigEntry {
115                key: "datafusion.runtime.max_temp_directory_size".to_string(),
116                value: max_temp_directory_size,
117                description: "Maximum temporary file directory size. Supports suffixes K (kilobytes), M (megabytes), and G (gigabytes) or '0' for 0. Example: '2G' for 2 gigabytes.",
118            },
119            ConfigEntry {
120                key: "datafusion.runtime.max_spill_merge_fan_in".to_string(),
121                value: max_spill_merge_fan_in,
122                description: "Maximum number of spill files opened by one external merge pass. Use 0 for unlimited. Values below 2 still use 2 so a merge can make progress.",
123            },
124            ConfigEntry {
125                key: "datafusion.runtime.temp_directory".to_string(),
126                value: temp_directory,
127                description: "The path to the temporary file directory.",
128            },
129            ConfigEntry {
130                key: "datafusion.runtime.metadata_cache_limit".to_string(),
131                value: metadata_cache_limit,
132                description: "Maximum memory to use for file metadata cache such as Parquet metadata. Supports suffixes K (kilobytes), M (megabytes), and G (gigabytes) or '0' for 0. Example: '2G' for 2 gigabytes.",
133            },
134            ConfigEntry {
135                key: "datafusion.runtime.list_files_cache_limit".to_string(),
136                value: list_files_cache_limit,
137                description: "Maximum memory to use for list files cache. Supports suffixes K (kilobytes), M (megabytes), and G (gigabytes) or '0' for 0. Example: '2G' for 2 gigabytes.",
138            },
139            ConfigEntry {
140                key: "datafusion.runtime.list_files_cache_ttl".to_string(),
141                value: list_files_cache_ttl,
142                description: "TTL (time-to-live) of the entries in the list file cache. Supports units m (minutes), and s (seconds). Example: '2m' for 2 minutes.",
143            },
144            ConfigEntry {
145                key: "datafusion.runtime.file_statistics_cache_limit".to_string(),
146                value: file_statistics_cache_limit,
147                description: "Maximum memory to use for file statistics cache. Supports suffixes K (kilobytes), M (megabytes), and G (gigabytes) or '0' for 0. Example: '2G' for 2 gigabytes.",
148            },
149        ]
150    }
151}
152
153impl RuntimeEnv {
154    /// Registers a custom `ObjectStore` to be used with a specific url.
155    /// This allows DataFusion to create external tables from urls that do not have
156    /// built in support such as `hdfs://namenode:port/...`.
157    ///
158    /// Returns the [`ObjectStore`] previously registered for this
159    /// scheme, if any.
160    ///
161    /// See [`ObjectStoreRegistry`] for more details
162    ///
163    /// # Example: Register local file system object store
164    /// ```
165    /// # use std::sync::Arc;
166    /// # use url::Url;
167    /// # use datafusion_execution::runtime_env::RuntimeEnv;
168    /// # let runtime_env = RuntimeEnv::default();
169    /// let url = Url::try_from("file://").unwrap();
170    /// let object_store = object_store::local::LocalFileSystem::new();
171    /// // register the object store with the runtime environment
172    /// runtime_env.register_object_store(&url, Arc::new(object_store));
173    /// ```
174    ///
175    /// # Example: Register remote URL object store like [Github](https://github.com)
176    /// ```
177    /// # use std::sync::Arc;
178    /// # use url::Url;
179    /// # use datafusion_execution::runtime_env::RuntimeEnv;
180    /// # let runtime_env = RuntimeEnv::default();
181    /// # // use local store for example as http feature is not enabled
182    /// # let http_store = object_store::local::LocalFileSystem::new();
183    /// // create a new object store via object_store::http::HttpBuilder;
184    /// let base_url = Url::parse("https://github.com").unwrap();
185    /// // (note this example can't depend on the http feature)
186    /// // let http_store = HttpBuilder::new()
187    /// //    .with_url(base_url.clone())
188    /// //    .build()
189    /// //    .unwrap();
190    /// // register the object store with the runtime environment
191    /// runtime_env.register_object_store(&base_url, Arc::new(http_store));
192    /// ```
193    pub fn register_object_store(
194        &self,
195        url: &Url,
196        object_store: Arc<dyn ObjectStore>,
197    ) -> Option<Arc<dyn ObjectStore>> {
198        self.object_store_registry.register_store(url, object_store)
199    }
200
201    /// Deregisters a custom `ObjectStore` previously registered for a specific url.
202    /// See [`ObjectStoreRegistry::deregister_store`] for more details.
203    pub fn deregister_object_store(&self, url: &Url) -> Result<Arc<dyn ObjectStore>> {
204        self.object_store_registry.deregister_store(url)
205    }
206
207    /// Retrieves a `ObjectStore` instance for a url by consulting the
208    /// registry. See [`ObjectStoreRegistry::get_store`] for more
209    /// details.
210    pub fn object_store(&self, url: impl AsRef<Url>) -> Result<Arc<dyn ObjectStore>> {
211        self.object_store_registry.get_store(url.as_ref())
212    }
213
214    /// Returns the current spilling progress
215    pub fn spilling_progress(&self) -> SpillingProgress {
216        self.disk_manager.spilling_progress()
217    }
218
219    /// Register an [`EncryptionFactory`] with an associated identifier that can be later
220    /// used to configure encryption when reading or writing Parquet.
221    /// If an encryption factory with the same identifier was already registered, it is replaced and returned.
222    #[cfg(feature = "parquet_encryption")]
223    pub fn register_parquet_encryption_factory(
224        &self,
225        id: &str,
226        encryption_factory: Arc<dyn EncryptionFactory>,
227    ) -> Option<Arc<dyn EncryptionFactory>> {
228        self.parquet_encryption_factory_registry
229            .register_factory(id, encryption_factory)
230    }
231
232    /// Retrieve an [`EncryptionFactory`] by its identifier
233    #[cfg(feature = "parquet_encryption")]
234    pub fn parquet_encryption_factory(
235        &self,
236        id: &str,
237    ) -> Result<Arc<dyn EncryptionFactory>> {
238        self.parquet_encryption_factory_registry.get_factory(id)
239    }
240
241    /// Returns the current runtime configuration entries
242    pub fn config_entries(&self) -> Vec<ConfigEntry> {
243        use crate::memory_pool::MemoryLimit;
244
245        /// Convert bytes to a human-readable format
246        fn format_byte_size(size: u64) -> String {
247            const GB: u64 = 1024 * 1024 * 1024;
248            const MB: u64 = 1024 * 1024;
249            const KB: u64 = 1024;
250
251            match size {
252                s if s >= GB => format!("{}G", s / GB),
253                s if s >= MB => format!("{}M", s / MB),
254                s if s >= KB => format!("{}K", s / KB),
255                s => format!("{s}"),
256            }
257        }
258
259        fn format_duration(duration: Duration) -> String {
260            let total = duration.as_secs();
261            let mins = total / 60;
262            let secs = total % 60;
263
264            format!("{mins}m{secs}s")
265        }
266
267        let memory_limit_value = match self.memory_pool.memory_limit() {
268            MemoryLimit::Finite(size) => Some(format_byte_size(
269                size.try_into()
270                    .expect("Memory limit size conversion failed"),
271            )),
272            MemoryLimit::Infinite => Some("unlimited".to_string()),
273            MemoryLimit::Unknown => None,
274        };
275
276        let max_temp_dir_size = self.disk_manager.max_temp_directory_size();
277        let max_temp_dir_value = format_byte_size(max_temp_dir_size);
278        let max_spill_merge_fan_in =
279            self.disk_manager.max_spill_merge_fan_in().to_string();
280
281        let temp_paths = self.disk_manager.temp_dir_paths();
282        let temp_dir_value = if temp_paths.is_empty() {
283            None
284        } else {
285            Some(
286                temp_paths
287                    .iter()
288                    .map(|p| p.display().to_string())
289                    .collect::<Vec<_>>()
290                    .join(","),
291            )
292        };
293
294        let metadata_cache_limit = self.cache_manager.get_metadata_cache_limit();
295        let metadata_cache_value = format_byte_size(
296            metadata_cache_limit
297                .try_into()
298                .expect("Metadata cache size conversion failed"),
299        );
300
301        let list_files_cache_limit = self.cache_manager.get_list_files_cache_limit();
302        let list_files_cache_value = format_byte_size(
303            list_files_cache_limit
304                .try_into()
305                .expect("List files cache size conversion failed"),
306        );
307
308        let list_files_cache_ttl = self
309            .cache_manager
310            .get_list_files_cache_ttl()
311            .map(format_duration);
312
313        let file_statistics_cache_limit =
314            self.cache_manager.get_file_statistic_cache_limit();
315        let file_statistics_cache_value = format_byte_size(
316            file_statistics_cache_limit
317                .try_into()
318                .expect("File statistics cache size conversion failed"),
319        );
320
321        RuntimeConfigValues {
322            memory_limit: memory_limit_value,
323            max_temp_directory_size: Some(max_temp_dir_value),
324            max_spill_merge_fan_in: Some(max_spill_merge_fan_in),
325            temp_directory: temp_dir_value,
326            metadata_cache_limit: Some(metadata_cache_value),
327            list_files_cache_limit: Some(list_files_cache_value),
328            list_files_cache_ttl,
329            file_statistics_cache_limit: Some(file_statistics_cache_value),
330        }
331        .into_config_entries()
332    }
333}
334
335impl Default for RuntimeEnv {
336    fn default() -> Self {
337        RuntimeEnvBuilder::new().build().unwrap()
338    }
339}
340
341/// Execution runtime configuration builder.
342///
343/// See example on [`RuntimeEnv`]
344#[derive(Clone)]
345pub struct RuntimeEnvBuilder {
346    /// DiskManager to manage temporary disk file usage
347    pub disk_manager: Option<Arc<DiskManager>>,
348    /// DiskManager builder to manager temporary disk file usage
349    pub disk_manager_builder: Option<DiskManagerBuilder>,
350    /// [`MemoryPool`] from which to allocate memory
351    ///
352    /// Defaults to using an [`UnboundedMemoryPool`] if `None`
353    pub memory_pool: Option<Arc<dyn MemoryPool>>,
354    /// CacheManager to manage cache data
355    pub cache_manager: CacheManagerConfig,
356    /// ObjectStoreRegistry to get object store based on url
357    pub object_store_registry: Arc<dyn ObjectStoreRegistry>,
358    /// Parquet encryption factory registry
359    #[cfg(feature = "parquet_encryption")]
360    pub parquet_encryption_factory_registry: Arc<EncryptionFactoryRegistry>,
361}
362
363impl Default for RuntimeEnvBuilder {
364    fn default() -> Self {
365        Self::new()
366    }
367}
368
369impl RuntimeEnvBuilder {
370    /// New with default values
371    pub fn new() -> Self {
372        Self {
373            disk_manager: Default::default(),
374            disk_manager_builder: Default::default(),
375            memory_pool: Default::default(),
376            cache_manager: Default::default(),
377            object_store_registry: Arc::new(DefaultObjectStoreRegistry::default()),
378            #[cfg(feature = "parquet_encryption")]
379            parquet_encryption_factory_registry: Default::default(),
380        }
381    }
382
383    /// Customize the disk manager builder
384    pub fn with_disk_manager_builder(mut self, disk_manager: DiskManagerBuilder) -> Self {
385        self.disk_manager_builder = Some(disk_manager);
386        self
387    }
388
389    /// Customize memory policy
390    pub fn with_memory_pool(mut self, memory_pool: Arc<dyn MemoryPool>) -> Self {
391        self.memory_pool = Some(memory_pool);
392        self
393    }
394
395    /// Customize cache policy
396    pub fn with_cache_manager(mut self, cache_manager: CacheManagerConfig) -> Self {
397        self.cache_manager = cache_manager;
398        self
399    }
400
401    /// Customize object store registry
402    pub fn with_object_store_registry(
403        mut self,
404        object_store_registry: Arc<dyn ObjectStoreRegistry>,
405    ) -> Self {
406        self.object_store_registry = object_store_registry;
407        self
408    }
409
410    /// Specify the total memory to use while running the DataFusion
411    /// plan to `max_memory * memory_fraction` in bytes.
412    ///
413    /// This defaults to using [`GreedyMemoryPool`] wrapped in the
414    /// [`TrackConsumersPool`] with a maximum of 5 consumers.
415    ///
416    /// Note DataFusion does not yet respect this limit in all cases.
417    pub fn with_memory_limit(self, max_memory: usize, memory_fraction: f64) -> Self {
418        let pool_size = (max_memory as f64 * memory_fraction) as usize;
419        self.with_memory_pool(Arc::new(TrackConsumersPool::new(
420            GreedyMemoryPool::new(pool_size),
421            NonZeroUsize::new(5).unwrap(),
422        )))
423    }
424
425    /// Use the specified path to create any needed temporary files
426    pub fn with_temp_file_path(mut self, path: impl Into<PathBuf>) -> Self {
427        let builder = self.disk_manager_builder.take().unwrap_or_default();
428        self.with_disk_manager_builder(
429            builder.with_mode(DiskManagerMode::Directories(vec![path.into()])),
430        )
431    }
432
433    /// Specify a limit on the size of the temporary file directory in bytes
434    pub fn with_max_temp_directory_size(mut self, size: u64) -> Self {
435        let builder = self.disk_manager_builder.take().unwrap_or_default();
436        self.with_disk_manager_builder(builder.with_max_temp_directory_size(size))
437    }
438
439    /// Limit the number of spill files opened by one external merge pass.
440    ///
441    /// A value of 0 means unlimited.
442    pub fn with_max_spill_merge_fan_in(mut self, fan_in: usize) -> Self {
443        let builder = self.disk_manager_builder.take().unwrap_or_default();
444        self.with_disk_manager_builder(builder.with_max_spill_merge_fan_in(fan_in))
445    }
446
447    /// Specify the limit of the file-embedded metadata cache, in bytes.
448    pub fn with_metadata_cache_limit(mut self, limit: usize) -> Self {
449        self.cache_manager = self.cache_manager.with_metadata_cache_limit(limit);
450        self
451    }
452
453    /// Specifies the memory limit for the object list cache, in bytes.
454    pub fn with_object_list_cache_limit(mut self, limit: usize) -> Self {
455        self.cache_manager = self.cache_manager.with_list_files_cache_limit(limit);
456        self
457    }
458
459    /// Specifies the duration entries in the object list cache will be considered valid.
460    pub fn with_object_list_cache_ttl(mut self, ttl: Option<Duration>) -> Self {
461        self.cache_manager = self.cache_manager.with_list_files_cache_ttl(ttl);
462        self
463    }
464
465    pub fn with_file_statistics_cache_limit(mut self, limit: usize) -> Self {
466        self.cache_manager = self.cache_manager.with_file_statistics_cache_limit(limit);
467        self
468    }
469
470    /// Build a RuntimeEnv
471    pub fn build(self) -> Result<RuntimeEnv> {
472        let Self {
473            disk_manager,
474            disk_manager_builder,
475            memory_pool,
476            cache_manager,
477            object_store_registry,
478            #[cfg(feature = "parquet_encryption")]
479            parquet_encryption_factory_registry,
480        } = self;
481        let memory_pool =
482            memory_pool.unwrap_or_else(|| Arc::new(UnboundedMemoryPool::default()));
483
484        let disk_manager: Arc<DiskManager> = match (disk_manager, disk_manager_builder) {
485            (_, Some(builder)) => Arc::new(builder.build()?),
486            (Some(manager), None) => manager,
487            (None, None) => Arc::new(DiskManagerBuilder::default().build()?),
488        };
489
490        Ok(RuntimeEnv {
491            memory_pool,
492            disk_manager,
493            cache_manager: CacheManager::try_new(&cache_manager)?,
494            object_store_registry,
495            #[cfg(feature = "parquet_encryption")]
496            parquet_encryption_factory_registry,
497        })
498    }
499
500    /// Convenience method to create a new `Arc<RuntimeEnv>`
501    pub fn build_arc(self) -> Result<Arc<RuntimeEnv>> {
502        self.build().map(Arc::new)
503    }
504
505    /// Create a new RuntimeEnvBuilder from an existing RuntimeEnv
506    pub fn from_runtime_env(runtime_env: &RuntimeEnv) -> Self {
507        let cache_config = CacheManagerConfig {
508            file_statistics_cache: runtime_env.cache_manager.get_file_statistic_cache(),
509            file_statistics_cache_limit: runtime_env
510                .cache_manager
511                .get_file_statistic_cache_limit(),
512            list_files_cache: runtime_env.cache_manager.get_list_files_cache(),
513            list_files_cache_limit: runtime_env
514                .cache_manager
515                .get_list_files_cache_limit(),
516            list_files_cache_ttl: runtime_env.cache_manager.get_list_files_cache_ttl(),
517            file_metadata_cache: Some(
518                runtime_env.cache_manager.get_file_metadata_cache(),
519            ),
520            metadata_cache_limit: runtime_env.cache_manager.get_metadata_cache_limit(),
521        };
522
523        Self {
524            disk_manager: Some(Arc::clone(&runtime_env.disk_manager)),
525            disk_manager_builder: None,
526            memory_pool: Some(Arc::clone(&runtime_env.memory_pool)),
527            cache_manager: cache_config,
528            object_store_registry: Arc::clone(&runtime_env.object_store_registry),
529            #[cfg(feature = "parquet_encryption")]
530            parquet_encryption_factory_registry: Arc::clone(
531                &runtime_env.parquet_encryption_factory_registry,
532            ),
533        }
534    }
535
536    /// Returns a list of all available runtime configurations with their current values and descriptions
537    pub fn entries(&self) -> Vec<ConfigEntry> {
538        RuntimeConfigValues {
539            memory_limit: None,
540            max_temp_directory_size: Some("100G".to_string()),
541            max_spill_merge_fan_in: Some("0".to_string()),
542            temp_directory: None,
543            metadata_cache_limit: Some("50M".to_owned()),
544            list_files_cache_limit: Some("1M".to_owned()),
545            list_files_cache_ttl: None,
546            file_statistics_cache_limit: Some("20M".to_owned()),
547        }
548        .into_config_entries()
549    }
550
551    /// Generate documentation that can be included in the user guide
552    pub fn generate_config_markdown() -> String {
553        use std::fmt::Write as _;
554
555        let s = Self::default();
556
557        let mut docs = "| key | default | description |\n".to_string();
558        docs += "|-----|---------|-------------|\n";
559        let mut entries = s.entries();
560        entries.sort_unstable_by(|a, b| a.key.cmp(&b.key));
561
562        for entry in &entries {
563            let _ = writeln!(
564                &mut docs,
565                "| {} | {} | {} |",
566                entry.key,
567                entry.value.as_deref().unwrap_or("NULL"),
568                entry.description
569            );
570        }
571        docs
572    }
573}