Skip to main content

datafusion_execution/cache/
cache_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
5use crate::cache::default_cache::DefaultCache;
6pub use crate::cache::{Cache, CacheValue, SchemaFingerprint, TableScopedPath};
7use datafusion_common::HashMap;
8use datafusion_common::heap_size::{DFHeapSize, DFHeapSizeCtx};
9use datafusion_common::{Result, Statistics};
10use datafusion_physical_expr_common::sort_expr::LexOrdering;
11use object_store::ObjectMeta;
12use object_store::path::Path;
13use std::any::Any;
14use std::fmt::{Debug, Formatter};
15use std::ops::Deref;
16use std::sync::Arc;
17use std::time::Duration;
18
19pub const DEFAULT_LIST_FILES_CACHE_MEMORY_LIMIT: usize = 1024 * 1024; // 1MiB
20
21pub const DEFAULT_LIST_FILES_CACHE_TTL: Option<Duration> = None; // Infinite
22
23pub const DEFAULT_FILE_STATISTICS_MEMORY_LIMIT: usize = 20 * 1024 * 1024; // 20MiB
24
25pub const DEFAULT_METADATA_CACHE_LIMIT: usize = 50 * 1024 * 1024; // 50M
26
27/// A cache for file statistics and orderings.
28///
29/// This cache stores [`CachedFileMetadata`] which includes:
30/// - File metadata for validation (size, last_modified)
31/// - Statistics for the file
32/// - Ordering information for the file
33///
34/// If enabled via [`CacheManagerConfig::with_file_statistics_cache`] this
35/// cache avoids inferring the same file statistics repeatedly during the
36/// session lifetime.
37///
38/// The typical usage pattern is:
39/// 1. Call `get(path)` to check for cached value
40/// 2. If `Some(cached)`, validate with
41///    `cached.is_valid_for(&current_meta, &current_schema_fingerprint)`
42/// 3. If invalid or missing, compute new value and call `put(path, new_value)`
43///
44/// See [`crate::runtime_env::RuntimeEnv`] for more details
45pub type FileStatisticsCache = dyn Cache<TableScopedPath, CachedFileMetadata>;
46
47/// A cache for storing the [`ObjectMeta`]s that result from listing a path.
48///
49/// Listing a path means doing an object store "list" operation or `ls`
50/// command on the local filesystem. This operation can be expensive,
51/// especially when done over remote object stores.
52///
53/// The cache key is always the table's base path, ensuring a stable cache key.
54/// The cached value is a [`CachedFileList`] containing the files and a timestamp.
55///
56/// Partition filtering is done after retrieval using [`CachedFileList::files_matching_prefix`].
57///
58/// See [`crate::runtime_env::RuntimeEnv`] for more details.
59pub type ListFilesCache = dyn Cache<TableScopedPath, CachedFileList>;
60
61/// A cache for storing file-embedded metadata.
62///
63/// This cache stores per-file metadata in the form of [`CachedFileMetadataEntry`],
64/// which includes the [`ObjectMeta`] for validation.
65///
66/// For example, the built in [`ListingTable`] uses this cache to avoid parsing
67/// Parquet footers multiple times for the same file.
68///
69/// The typical usage pattern is:
70/// 1. Call `get(path)` to check for cached value
71/// 2. If `Some(cached)`, validate with `cached.is_valid_for(&current_meta)`
72/// 3. If invalid or missing, compute new value and call `put(path, new_value)`
73///
74/// See [`crate::runtime_env::RuntimeEnv`] for more details.
75///
76/// [`ListingTable`]: https://docs.rs/datafusion/latest/datafusion/datasource/listing/struct.ListingTable.html
77pub type FileMetadataCache = dyn Cache<Path, CachedFileMetadataEntry>;
78
79/// Cached metadata for a file, including statistics and ordering.
80///
81/// This struct embeds the [`ObjectMeta`] used for cache validation,
82/// the `file_schema` fingerprint, cached statistics, and ordering information.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct CachedFileMetadata {
85    /// File metadata used for cache validation (size, last_modified).
86    pub meta: ObjectMeta,
87    /// Fingerprint of the `file_schema` used to compute `statistics`.
88    pub schema_fingerprint: Arc<SchemaFingerprint>,
89    /// Cached statistics for the file, if available.
90    pub statistics: Arc<Statistics>,
91    /// Cached ordering for the file.
92    pub ordering: Option<LexOrdering>,
93}
94
95impl CachedFileMetadata {
96    /// Create a new cached file metadata entry.
97    pub fn new(
98        meta: ObjectMeta,
99        schema_fingerprint: Arc<SchemaFingerprint>,
100        statistics: Arc<Statistics>,
101        ordering: Option<LexOrdering>,
102    ) -> Self {
103        Self {
104            meta,
105            schema_fingerprint,
106            statistics,
107            ordering,
108        }
109    }
110
111    /// Check if this cached entry is still valid for the given metadata.
112    ///
113    /// Returns true if the file size, last modified time, and schema match.
114    pub fn is_valid_for(
115        &self,
116        current_meta: &ObjectMeta,
117        current_schema_fingerprint: &Arc<SchemaFingerprint>,
118    ) -> bool {
119        self.meta.size == current_meta.size
120            && self.meta.last_modified == current_meta.last_modified
121            && (Arc::ptr_eq(&self.schema_fingerprint, current_schema_fingerprint)
122                || self.schema_fingerprint.as_ref()
123                    == current_schema_fingerprint.as_ref())
124    }
125}
126
127impl CacheValue for CachedFileMetadata {
128    fn size(&self) -> usize {
129        DFHeapSize::heap_size(self, &mut DFHeapSizeCtx::default())
130    }
131}
132
133impl DFHeapSize for CachedFileMetadata {
134    fn heap_size(&self, ctx: &mut DFHeapSizeCtx) -> usize {
135        self.meta.size.heap_size(ctx)
136            + self.meta.last_modified.heap_size(ctx)
137            + self.meta.version.heap_size(ctx)
138            + self.meta.e_tag.heap_size(ctx)
139            + self.meta.location.as_ref().heap_size(ctx)
140            + self.statistics.heap_size(ctx)
141        // Do not deep-count `schema_fingerprint`: each ListingTable shares one
142        // fingerprint across all cached files.
143        //TODO add ordering once LexOrdering/PhysicalExpr implements DFHeapSize
144    }
145}
146
147/// Cached file listing.
148///
149/// TTL expiration is handled internally by the cache implementation.
150#[derive(Debug, Clone, PartialEq)]
151pub struct CachedFileList {
152    /// The cached file list.
153    pub files: Arc<Vec<ObjectMeta>>,
154}
155
156impl CachedFileList {
157    /// Create a new cached file list.
158    pub fn new(files: Vec<ObjectMeta>) -> Self {
159        Self {
160            files: Arc::new(files),
161        }
162    }
163
164    /// Filter the files by prefix.
165    fn filter_by_prefix(&self, prefix: Option<&Path>) -> Vec<ObjectMeta> {
166        match prefix {
167            Some(prefix) => self
168                .files
169                .iter()
170                .filter(|meta| meta.location.as_ref().starts_with(prefix.as_ref()))
171                .cloned()
172                .collect(),
173            None => self.files.as_ref().clone(),
174        }
175    }
176
177    /// Returns files matching the given prefix.
178    ///
179    /// When prefix is `None`, returns a clone of the `Arc` (no data copy).
180    /// When filtering is needed, returns a new `Arc` with filtered results (clones each matching [`ObjectMeta`]).
181    pub fn files_matching_prefix(&self, prefix: &Option<Path>) -> Arc<Vec<ObjectMeta>> {
182        match prefix {
183            None => Arc::clone(&self.files),
184            Some(p) => Arc::new(self.filter_by_prefix(Some(p))),
185        }
186    }
187}
188
189impl CacheValue for CachedFileList {
190    fn size(&self) -> usize {
191        self.files.capacity() * size_of::<ObjectMeta>()
192            + self
193                .files
194                .iter()
195                .map(meta_heap_bytes)
196                .reduce(|acc, b| acc + b)
197                .unwrap_or(0)
198    }
199}
200
201/// Calculates the number of bytes an [`ObjectMeta`] occupies in the heap.
202pub fn meta_heap_bytes(object_meta: &ObjectMeta) -> usize {
203    let mut size = object_meta.location.as_ref().len();
204
205    if let Some(e) = &object_meta.e_tag {
206        size += e.len();
207    }
208    if let Some(v) = &object_meta.version {
209        size += v.len();
210    }
211
212    size
213}
214
215impl Deref for CachedFileList {
216    type Target = Arc<Vec<ObjectMeta>>;
217    fn deref(&self) -> &Self::Target {
218        &self.files
219    }
220}
221
222impl From<Vec<ObjectMeta>> for CachedFileList {
223    fn from(files: Vec<ObjectMeta>) -> Self {
224        Self::new(files)
225    }
226}
227
228/// Generic file-embedded metadata used with [`FileMetadataCache`].
229///
230/// For example, Parquet footers and page metadata can be represented
231/// using this trait.
232///
233/// See [`crate::runtime_env::RuntimeEnv`] for more details
234pub trait FileMetadata: Any + Send + Sync {
235    /// Returns the file metadata as [`Any`] so that it can be downcast to a specific
236    /// implementation.
237    fn as_any(&self) -> &dyn Any;
238
239    /// Returns the size of the metadata in bytes.
240    fn memory_size(&self) -> usize;
241
242    /// Returns extra information about this entry
243    fn extra_info(&self) -> HashMap<String, String>;
244}
245
246/// Cached file metadata entry with validation information.
247#[derive(Clone)]
248pub struct CachedFileMetadataEntry {
249    /// File metadata used for cache validation (size, last_modified).
250    pub meta: ObjectMeta,
251    /// The cached file metadata.
252    pub file_metadata: Arc<dyn FileMetadata>,
253}
254
255impl CacheValue for CachedFileMetadataEntry {
256    fn size(&self) -> usize {
257        self.file_metadata.memory_size()
258    }
259}
260
261impl CachedFileMetadataEntry {
262    /// Create a new cached file metadata entry.
263    pub fn new(meta: ObjectMeta, file_metadata: Arc<dyn FileMetadata>) -> Self {
264        Self {
265            meta,
266            file_metadata,
267        }
268    }
269
270    /// Check if this cached entry is still valid for the given metadata.
271    pub fn is_valid_for(&self, current_meta: &ObjectMeta) -> bool {
272        self.meta.size == current_meta.size
273            && self.meta.last_modified == current_meta.last_modified
274    }
275}
276
277impl Debug for CachedFileMetadataEntry {
278    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
279        f.debug_struct("CachedFileMetadataEntry")
280            .field("meta", &self.meta)
281            .field("memory_size", &self.file_metadata.memory_size())
282            .finish()
283    }
284}
285
286/// Manages various caches used in DataFusion.
287///
288/// Following DataFusion design principles, DataFusion provides default cache
289/// implementations, while also allowing users to provide their own custom cache
290/// implementations by implementing the relevant traits.
291///
292/// See [`CacheManagerConfig`] for configuration options.
293#[derive(Debug)]
294pub struct CacheManager {
295    file_statistic_cache: Option<Arc<FileStatisticsCache>>,
296    list_files_cache: Option<Arc<ListFilesCache>>,
297    file_metadata_cache: Arc<FileMetadataCache>,
298}
299
300impl CacheManager {
301    pub fn try_new(config: &CacheManagerConfig) -> Result<Arc<Self>> {
302        let file_statistic_cache: Option<Arc<FileStatisticsCache>> =
303            match &config.file_statistics_cache {
304                Some(fsc) if config.file_statistics_cache_limit > 0 => {
305                    fsc.update_cache_limit(config.file_statistics_cache_limit);
306                    Some(Arc::clone(fsc))
307                }
308                None if config.file_statistics_cache_limit > 0 => Some(Arc::new(
309                    DefaultCache::<TableScopedPath, CachedFileMetadata>::new(
310                        config.file_statistics_cache_limit,
311                    )
312                    .with_name("DefaultFileStatisticsCache"),
313                )),
314                _ => None,
315            };
316
317        let list_files_cache: Option<Arc<ListFilesCache>> = match &config.list_files_cache
318        {
319            Some(lfc) if config.list_files_cache_limit > 0 => {
320                // the cache memory limit or ttl might have changed, ensure they are updated
321                lfc.update_cache_limit(config.list_files_cache_limit);
322                // Only update TTL if explicitly set in config, otherwise preserve the cache's existing TTL
323                if let Some(ttl) = config.list_files_cache_ttl {
324                    lfc.update_cache_ttl(Some(ttl));
325                }
326                Some(Arc::clone(lfc))
327            }
328            None if config.list_files_cache_limit > 0 => Some(Arc::new(
329                DefaultCache::<TableScopedPath, CachedFileList>::new_with_ttl(
330                    config.list_files_cache_limit,
331                    config.list_files_cache_ttl,
332                )
333                .with_name("DefaultListFilesCache"),
334            )),
335            _ => None,
336        };
337
338        let file_metadata_cache = config
339            .file_metadata_cache
340            .as_ref()
341            .map(Arc::clone)
342            .unwrap_or_else(|| {
343                Arc::new(
344                    DefaultCache::new(config.metadata_cache_limit)
345                        .with_name("DefaultFileMetadataCache"),
346                )
347            });
348
349        // the cache memory limit might have changed, ensure the limit is updated
350        file_metadata_cache.update_cache_limit(config.metadata_cache_limit);
351
352        Ok(Arc::new(CacheManager {
353            file_statistic_cache,
354            list_files_cache,
355            file_metadata_cache,
356        }))
357    }
358
359    /// Get the file statistics cache.
360    pub fn get_file_statistic_cache(&self) -> Option<Arc<FileStatisticsCache>> {
361        self.file_statistic_cache.clone()
362    }
363
364    /// Get the memory limit of the file statistics cache.
365    pub fn get_file_statistic_cache_limit(&self) -> usize {
366        self.file_statistic_cache
367            .as_ref()
368            .map_or(0, |c| c.cache_limit())
369    }
370
371    /// Get the cache for storing the result of listing [`ObjectMeta`]s under the same path.
372    pub fn get_list_files_cache(&self) -> Option<Arc<ListFilesCache>> {
373        self.list_files_cache.clone()
374    }
375
376    /// Get the memory limit of the list files cache.
377    pub fn get_list_files_cache_limit(&self) -> usize {
378        self.list_files_cache
379            .as_ref()
380            .map_or(0, |c| c.cache_limit())
381    }
382
383    /// Get the TTL (time-to-live) of the list files cache.
384    pub fn get_list_files_cache_ttl(&self) -> Option<Duration> {
385        self.list_files_cache.as_ref().and_then(|c| c.cache_ttl())
386    }
387
388    /// Get the file embedded metadata cache.
389    pub fn get_file_metadata_cache(&self) -> Arc<FileMetadataCache> {
390        Arc::clone(&self.file_metadata_cache)
391    }
392
393    /// Get the limit of the file embedded metadata cache.
394    pub fn get_metadata_cache_limit(&self) -> usize {
395        self.file_metadata_cache.cache_limit()
396    }
397}
398
399#[derive(Clone)]
400pub struct CacheManagerConfig {
401    /// Enable caching of file statistics when listing files.
402    /// Enabling the cache avoids repeatedly reading file statistics in a DataFusion session.
403    /// Default is enabled. Currently only Parquet files are supported.
404    pub file_statistics_cache: Option<Arc<FileStatisticsCache>>,
405    /// Limit of the file statistics cache, in bytes. Default: 20MiB.
406    pub file_statistics_cache_limit: usize,
407    /// Enable caching of file metadata when listing files.
408    /// Enabling the cache avoids repeat list and object metadata fetch operations, which may be
409    /// expensive in certain situations (e.g. remote object storage), for objects under paths that
410    /// are cached.
411    /// Note that if this option is enabled, DataFusion will not see any updates to the underlying
412    /// storage for at least `list_files_cache_ttl` duration.
413    /// Default is enabled.
414    pub list_files_cache: Option<Arc<ListFilesCache>>,
415    /// Limit of the `list_files_cache`, in bytes. Default: 1MiB.
416    pub list_files_cache_limit: usize,
417    /// The duration the list files cache will consider an entry valid after insertion. Note that
418    /// changes to the underlying storage system, such as adding or removing data, will not be
419    /// visible until an entry expires. Default: None (infinite).
420    pub list_files_cache_ttl: Option<Duration>,
421    /// Cache of file-embedded metadata, used to avoid reading it multiple times when processing a
422    /// data file (e.g., Parquet footer and page metadata).
423    /// If not provided, the [`CacheManager`] will create it.
424    pub file_metadata_cache: Option<Arc<FileMetadataCache>>,
425    /// Limit of the file-embedded metadata cache, in bytes.
426    pub metadata_cache_limit: usize,
427}
428
429impl Default for CacheManagerConfig {
430    fn default() -> Self {
431        Self {
432            file_statistics_cache: Default::default(),
433            file_statistics_cache_limit: DEFAULT_FILE_STATISTICS_MEMORY_LIMIT,
434            list_files_cache: Default::default(),
435            list_files_cache_limit: DEFAULT_LIST_FILES_CACHE_MEMORY_LIMIT,
436            list_files_cache_ttl: DEFAULT_LIST_FILES_CACHE_TTL,
437            file_metadata_cache: Default::default(),
438            metadata_cache_limit: DEFAULT_METADATA_CACHE_LIMIT,
439        }
440    }
441}
442
443impl CacheManagerConfig {
444    /// Set the cache for file statistics.
445    pub fn with_file_statistics_cache(
446        mut self,
447        cache: Option<Arc<FileStatisticsCache>>,
448    ) -> Self {
449        self.file_statistics_cache = cache;
450        self
451    }
452
453    /// Specifies the memory limit for the file statistics cache, in bytes.
454    pub fn with_file_statistics_cache_limit(mut self, limit: usize) -> Self {
455        self.file_statistics_cache_limit = limit;
456        self
457    }
458
459    /// Set the cache for listing files.
460    ///
461    /// Default is `None` (disabled).
462    pub fn with_list_files_cache(mut self, cache: Option<Arc<ListFilesCache>>) -> Self {
463        self.list_files_cache = cache;
464        self
465    }
466
467    /// Sets the limit of the list files cache, in bytes.
468    ///
469    /// Default: 1MiB (1,048,576 bytes).
470    pub fn with_list_files_cache_limit(mut self, limit: usize) -> Self {
471        self.list_files_cache_limit = limit;
472        self
473    }
474
475    /// Sets the TTL (time-to-live) for entries in the list files cache.
476    ///
477    /// Default: None (infinite).
478    pub fn with_list_files_cache_ttl(mut self, ttl: Option<Duration>) -> Self {
479        self.list_files_cache_ttl = ttl;
480        self
481    }
482
483    /// Sets the cache for file-embedded metadata.
484    pub fn with_file_metadata_cache(
485        mut self,
486        cache: Option<Arc<FileMetadataCache>>,
487    ) -> Self {
488        self.file_metadata_cache = cache;
489        self
490    }
491
492    /// Sets the limit of the file-embedded metadata cache, in bytes.
493    pub fn with_metadata_cache_limit(mut self, limit: usize) -> Self {
494        self.metadata_cache_limit = limit;
495        self
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502
503    /// Test to verify that TTL is preserved when not explicitly set in config.
504    /// This fixes issue #19396 where TTL was being unset from DefaultListFilesCache
505    /// when CacheManagerConfig::list_files_cache_ttl was not set explicitly.
506    #[test]
507    fn test_ttl_preserved_when_not_set_in_config() {
508        // Create a cache with TTL = 1 second
509        let list_file_cache =
510            DefaultCache::new_with_ttl(1024, Some(Duration::from_secs(1)));
511
512        // Verify the cache has TTL set initially
513        assert_eq!(
514            list_file_cache.cache_ttl(),
515            Some(Duration::from_secs(1)),
516            "Cache should have TTL = 1 second initially"
517        );
518
519        // Put cache in config WITHOUT setting list_files_cache_ttl
520        let config = CacheManagerConfig::default()
521            .with_list_files_cache(Some(Arc::new(list_file_cache)));
522
523        // Create CacheManager from config
524        let cache_manager = CacheManager::try_new(&config).unwrap();
525
526        // Verify TTL is preserved (not unset)
527        let cache_ttl = cache_manager.get_list_files_cache().unwrap().cache_ttl();
528
529        assert!(
530            cache_ttl.is_some(),
531            "TTL should be preserved when not set in config. Expected Some(Duration::from_secs(1)), got {cache_ttl:?}"
532        );
533
534        // Verify it's the correct TTL value
535        assert_eq!(
536            cache_ttl,
537            Some(Duration::from_secs(1)),
538            "TTL should be exactly 1 second"
539        );
540    }
541
542    /// Test to verify that TTL can still be overridden when explicitly set in config.
543    #[test]
544    fn test_ttl_overridden_when_set_in_config() {
545        // Create a cache with TTL = 1 second
546        let list_file_cache =
547            DefaultCache::new_with_ttl(1024, Some(Duration::from_secs(1)));
548
549        // Put cache in config WITH a different TTL set
550        let config = CacheManagerConfig::default()
551            .with_list_files_cache(Some(Arc::new(list_file_cache)))
552            .with_list_files_cache_ttl(Some(Duration::from_mins(1)));
553
554        // Create CacheManager from config
555        let cache_manager = CacheManager::try_new(&config).unwrap();
556
557        // Verify TTL is overridden to the config value
558        let cache_ttl = cache_manager.get_list_files_cache().unwrap().cache_ttl();
559
560        assert_eq!(
561            cache_ttl,
562            Some(Duration::from_mins(1)),
563            "TTL should be overridden to 60 seconds when set in config"
564        );
565    }
566}