datafusion_execution/cache/
cache_manager.rs1use 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; pub const DEFAULT_LIST_FILES_CACHE_TTL: Option<Duration> = None; pub const DEFAULT_FILE_STATISTICS_MEMORY_LIMIT: usize = 20 * 1024 * 1024; pub const DEFAULT_METADATA_CACHE_LIMIT: usize = 50 * 1024 * 1024; pub type FileStatisticsCache = dyn Cache<TableScopedPath, CachedFileMetadata>;
46
47pub type ListFilesCache = dyn Cache<TableScopedPath, CachedFileList>;
60
61pub type FileMetadataCache = dyn Cache<Path, CachedFileMetadataEntry>;
78
79#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct CachedFileMetadata {
85 pub meta: ObjectMeta,
87 pub schema_fingerprint: Arc<SchemaFingerprint>,
89 pub statistics: Arc<Statistics>,
91 pub ordering: Option<LexOrdering>,
93}
94
95impl CachedFileMetadata {
96 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 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 }
145}
146
147#[derive(Debug, Clone, PartialEq)]
151pub struct CachedFileList {
152 pub files: Arc<Vec<ObjectMeta>>,
154}
155
156impl CachedFileList {
157 pub fn new(files: Vec<ObjectMeta>) -> Self {
159 Self {
160 files: Arc::new(files),
161 }
162 }
163
164 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 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
201pub 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
228pub trait FileMetadata: Any + Send + Sync {
235 fn as_any(&self) -> &dyn Any;
238
239 fn memory_size(&self) -> usize;
241
242 fn extra_info(&self) -> HashMap<String, String>;
244}
245
246#[derive(Clone)]
248pub struct CachedFileMetadataEntry {
249 pub meta: ObjectMeta,
251 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 pub fn new(meta: ObjectMeta, file_metadata: Arc<dyn FileMetadata>) -> Self {
264 Self {
265 meta,
266 file_metadata,
267 }
268 }
269
270 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#[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 lfc.update_cache_limit(config.list_files_cache_limit);
322 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 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 pub fn get_file_statistic_cache(&self) -> Option<Arc<FileStatisticsCache>> {
361 self.file_statistic_cache.clone()
362 }
363
364 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 pub fn get_list_files_cache(&self) -> Option<Arc<ListFilesCache>> {
373 self.list_files_cache.clone()
374 }
375
376 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 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 pub fn get_file_metadata_cache(&self) -> Arc<FileMetadataCache> {
390 Arc::clone(&self.file_metadata_cache)
391 }
392
393 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 pub file_statistics_cache: Option<Arc<FileStatisticsCache>>,
405 pub file_statistics_cache_limit: usize,
407 pub list_files_cache: Option<Arc<ListFilesCache>>,
415 pub list_files_cache_limit: usize,
417 pub list_files_cache_ttl: Option<Duration>,
421 pub file_metadata_cache: Option<Arc<FileMetadataCache>>,
425 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 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 pub fn with_file_statistics_cache_limit(mut self, limit: usize) -> Self {
455 self.file_statistics_cache_limit = limit;
456 self
457 }
458
459 pub fn with_list_files_cache(mut self, cache: Option<Arc<ListFilesCache>>) -> Self {
463 self.list_files_cache = cache;
464 self
465 }
466
467 pub fn with_list_files_cache_limit(mut self, limit: usize) -> Self {
471 self.list_files_cache_limit = limit;
472 self
473 }
474
475 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 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 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]
507 fn test_ttl_preserved_when_not_set_in_config() {
508 let list_file_cache =
510 DefaultCache::new_with_ttl(1024, Some(Duration::from_secs(1)));
511
512 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 let config = CacheManagerConfig::default()
521 .with_list_files_cache(Some(Arc::new(list_file_cache)));
522
523 let cache_manager = CacheManager::try_new(&config).unwrap();
525
526 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 assert_eq!(
536 cache_ttl,
537 Some(Duration::from_secs(1)),
538 "TTL should be exactly 1 second"
539 );
540 }
541
542 #[test]
544 fn test_ttl_overridden_when_set_in_config() {
545 let list_file_cache =
547 DefaultCache::new_with_ttl(1024, Some(Duration::from_secs(1)));
548
549 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 let cache_manager = CacheManager::try_new(&config).unwrap();
556
557 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}