Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 169 additions & 2 deletions vortex-datafusion/src/persistent/cache.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,91 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::sync::Arc;
use std::sync::Weak;

use datafusion_common::HashMap;
use datafusion_execution::cache::cache_manager::CachedFileMetadataEntry;
use datafusion_execution::cache::cache_manager::FileMetadata;
use object_store::ObjectMeta;
use object_store::ObjectStore;
use object_store::path::Path;
use vortex::file::Footer;
use vortex::file::VortexFile;
use vortex_utils::aliases::dash_map::DashMap;

/// Per-file cache bounded to one entry per path, invalidated when [`ObjectGeneration`] changes.
pub(crate) type FileCache<V> = DashMap<Path, (ObjectGeneration, V)>;
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

/// Identifies a specific object generation for per-file caches on [`super::source::VortexSource`].
///
/// Built from the non-path identity fields of [`ObjectMeta`]: `size`, `last_modified`, `e_tag`,
/// and `version`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ObjectGeneration {
size: u64,
last_modified_secs: i64,
last_modified_nanos: u32,
e_tag: Option<String>,
version: Option<String>,
}

impl ObjectGeneration {
/// Extracts the non-path identity fields from `meta`.
pub(crate) fn from_meta(meta: &ObjectMeta) -> Self {
Self {
size: meta.size,
last_modified_secs: meta.last_modified.timestamp(),
last_modified_nanos: meta.last_modified.timestamp_subsec_nanos(),
e_tag: meta.e_tag.clone(),
version: meta.version.clone(),
}
}

/// Returns whether this cached generation matches `meta` without allocating.
pub(crate) fn matches_meta(&self, meta: &ObjectMeta) -> bool {
self.size == meta.size
&& self.last_modified_secs == meta.last_modified.timestamp()
&& self.last_modified_nanos == meta.last_modified.timestamp_subsec_nanos()
&& self.e_tag == meta.e_tag
&& self.version == meta.version
}
}

/// Returns whether a cached [`CachedFileMetadataEntry`] is still valid for `meta`.
///
/// Extends DataFusion's size and `last_modified` check with `e_tag` and `version` equality so
/// same-size replacements within the same timestamp tick invalidate cached footers when the store
/// supplies `e_tag` or `version`.
pub(crate) fn is_cached_metadata_valid(entry: &CachedFileMetadataEntry, meta: &ObjectMeta) -> bool {
entry.is_valid_for(meta) && entry.meta.e_tag == meta.e_tag && entry.meta.version == meta.version
}

/// Cached Vortex file metadata for use with DataFusion's [`FileMetadataCache`].
///
/// [`FileMetadataCache`]: datafusion_execution::cache::cache_manager::FileMetadataCache
pub struct CachedVortexMetadata {
footer: Footer,
store: Weak<dyn ObjectStore>,
}

impl CachedVortexMetadata {
/// Create a new cached metadata entry from a VortexFile.
pub fn new(vortex_file: &VortexFile) -> Self {
/// Create a new cached metadata entry scoped to `store`.
pub fn new(vortex_file: &VortexFile, store: &Arc<dyn ObjectStore>) -> Self {
let footer = vortex_file.footer();
Self {
footer: footer.clone(),
store: Arc::downgrade(store),
}
}

/// Returns whether this cached entry belongs to `store`.
pub(crate) fn matches_store(&self, store: &Arc<dyn ObjectStore>) -> bool {
self.store
.upgrade()
.is_some_and(|cached| Arc::ptr_eq(&cached, store))
}

/// Get the cached footer.
pub fn footer(&self) -> &Footer {
&self.footer
Expand All @@ -45,3 +109,106 @@ impl FileMetadata for CachedVortexMetadata {
Default::default()
}
}

#[cfg(test)]
mod tests {
use std::any::Any;
use std::sync::Arc;
use std::time::Duration;
use std::time::SystemTime;

use datafusion_common::HashMap;
use datafusion_execution::cache::cache_manager::CachedFileMetadataEntry;
use datafusion_execution::cache::cache_manager::FileMetadata;
use object_store::ObjectMeta;
use object_store::path::Path;

use super::*;

struct DummyFileMetadata;

impl FileMetadata for DummyFileMetadata {
fn as_any(&self) -> &dyn Any {
self
}

fn memory_size(&self) -> usize {
1
}

fn extra_info(&self) -> HashMap<String, String> {
Default::default()
}
}

fn meta(
path: &str,
size: u64,
secs: u64,
e_tag: Option<&str>,
version: Option<&str>,
) -> ObjectMeta {
ObjectMeta {
location: Path::from(path),
last_modified: (SystemTime::UNIX_EPOCH + Duration::from_secs(secs)).into(),
size,
e_tag: e_tag.map(str::to_owned),
version: version.map(str::to_owned),
}
}

#[test]
fn test_object_generation_distinguishes_all_identity_fields() {
let base = meta("a.vortex", 128, 1_700_000_000, Some("\"1\""), Some("v1"));
let base_gen = ObjectGeneration::from_meta(&base);
assert!(base_gen.matches_meta(&base));

let variants = [
meta("a.vortex", 256, 1_700_000_000, Some("\"1\""), Some("v1")),
meta("a.vortex", 128, 1_700_000_001, Some("\"1\""), Some("v1")),
meta("a.vortex", 128, 1_700_000_000, Some("\"2\""), Some("v1")),
meta("a.vortex", 128, 1_700_000_000, Some("\"1\""), Some("v2")),
meta("a.vortex", 128, 1_700_000_000, None, Some("v1")),
meta("a.vortex", 128, 1_700_000_000, Some("\"1\""), None),
];

for variant in variants {
let variant_gen = ObjectGeneration::from_meta(&variant);
assert_ne!(base_gen, variant_gen);
assert!(!base_gen.matches_meta(&variant));
}
}

#[test]
fn test_is_cached_metadata_valid() {
let base = meta("a.vortex", 128, 1_700_000_000, Some("\"1\""), Some("v1"));
let entry = CachedFileMetadataEntry::new(base.clone(), Arc::new(DummyFileMetadata));

assert!(is_cached_metadata_valid(&entry, &base));
assert!(!is_cached_metadata_valid(
&entry,
&meta("a.vortex", 128, 1_700_000_000, Some("\"2\""), Some("v1"))
));
assert!(!is_cached_metadata_valid(
&entry,
&meta("a.vortex", 128, 1_700_000_000, Some("\"1\""), Some("v2"))
));
assert!(!is_cached_metadata_valid(
&entry,
&meta("a.vortex", 256, 1_700_000_000, Some("\"1\""), Some("v1"))
));
assert!(!is_cached_metadata_valid(
&entry,
&meta("a.vortex", 128, 1_700_000_001, Some("\"1\""), Some("v1"))
));

let no_tokens = meta("a.vortex", 128, 0, None, None);
let no_tokens_entry =
CachedFileMetadataEntry::new(no_tokens.clone(), Arc::new(DummyFileMetadata));
assert!(is_cached_metadata_valid(&no_tokens_entry, &no_tokens));
assert!(!is_cached_metadata_valid(
&no_tokens_entry,
&meta("a.vortex", 256, 0, None, None)
));
}
}
15 changes: 9 additions & 6 deletions vortex-datafusion/src/persistent/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ use vortex::session::VortexSession;
use vortex_arrow::ArrowSessionExt;

use super::cache::CachedVortexMetadata;
use super::cache::is_cached_metadata_valid;
use super::sink::VortexSink;
use super::source::VortexSource;
use crate::PrecisionExt as _;
Expand Down Expand Up @@ -522,11 +523,12 @@ impl FileFormat for VortexFormat {
SpawnedTask::spawn(async move {
// Check if we have entry metadata for this file
if let Some(entry) = cache.get(&object.location)
&& entry.is_valid_for(&object)
&& is_cached_metadata_valid(&entry, &object)
&& let Some(cached_vortex) = entry
.file_metadata
.as_any()
.downcast_ref::<CachedVortexMetadata>()
&& cached_vortex.matches_store(&store)
{
let inferred_schema = session
.arrow()
Expand All @@ -536,7 +538,7 @@ impl FileFormat for VortexFormat {

// Not entry or invalid - open the file
let reader = Arc::new(ObjectStoreReadAt::new_with_allocator(
store,
Arc::clone(&store),
object.location.clone(),
session.handle(),
session.allocator(),
Expand All @@ -550,7 +552,7 @@ impl FileFormat for VortexFormat {
.await?;

// Cache the metadata
let cached_metadata = Arc::new(CachedVortexMetadata::new(&vxf));
let cached_metadata = Arc::new(CachedVortexMetadata::new(&vxf, &store));
let entry = CachedFileMetadataEntry::new(object.clone(), cached_metadata);
cache.put(&object.location, entry);

Expand Down Expand Up @@ -595,12 +597,13 @@ impl FileFormat for VortexFormat {
// Try to get entry metadata first
let cached_metadata = file_metadata_cache
.get(&object.location)
.filter(|entry| entry.is_valid_for(&object))
.filter(|entry| is_cached_metadata_valid(entry, &object))
.and_then(|entry| {
entry
.file_metadata
.as_any()
.downcast_ref::<CachedVortexMetadata>()
.filter(|m| m.matches_store(&store))
.map(|m| {
(
m.footer().dtype().clone(),
Expand All @@ -615,7 +618,7 @@ impl FileFormat for VortexFormat {
None => {
// Not entry - open the file
let reader = Arc::new(ObjectStoreReadAt::new_with_allocator(
store,
Arc::clone(&store),
object.location.clone(),
session.handle(),
session.allocator(),
Expand All @@ -635,7 +638,7 @@ impl FileFormat for VortexFormat {
})?;

// Cache the metadata
let file_metadata = Arc::new(CachedVortexMetadata::new(&vxf));
let file_metadata = Arc::new(CachedVortexMetadata::new(&vxf, &store));
let entry = CachedFileMetadataEntry::new(object.clone(), file_metadata);
file_metadata_cache.put(&object.location, entry);

Expand Down
Loading
Loading