diff --git a/vortex-duckdb/cpp/multi_file_reader.cpp b/vortex-duckdb/cpp/multi_file_reader.cpp index 57d15fefc06..faed3fef5ee 100644 --- a/vortex-duckdb/cpp/multi_file_reader.cpp +++ b/vortex-duckdb/cpp/multi_file_reader.cpp @@ -55,6 +55,9 @@ VortexMultiFileReader::InitializeReader(MultiFileReaderData &reader_data, D_ASSERT(gstate.global_state != nullptr); VortexBaseReader &reader = reader_data.reader->Cast(); + if (duckdb_reader_is_pruned(reader.ffi_file->DataPtr())) { + return ReaderInitializeType::SKIP_READING_FILE; + } const VortexBindData &bind = bind_data.bind_data->Cast(); const void *const ffi_bind = bind.ffi_bind_data->DataPtr(); @@ -230,13 +233,13 @@ VortexReaderInterface::InitializeLocalState(ClientContext &, GlobalTableFunction return result; } -static shared_ptr OpenReader(const OpenFileInfo &file) { +static shared_ptr OpenReader(const OpenFileInfo &file, const void *global = nullptr) { duckdb_vx_error error = nullptr; const char *const ffi_file_path = file.path.c_str(); const size_t ffi_file_size = file.path.size(); - duckdb_vx_data ffi_file = duckdb_reader_open(ffi_file_path, ffi_file_size, &error); + duckdb_vx_data ffi_file = duckdb_reader_open(ffi_file_path, ffi_file_size, global, &error); if (error) { throw IOException(IntoErrString(error)); } @@ -246,11 +249,12 @@ static shared_ptr OpenReader(const OpenFileInfo &file) { } shared_ptr VortexReaderInterface::CreateReader(ClientContext &, - GlobalTableFunctionState &, + GlobalTableFunctionState &gstate, const OpenFileInfo &file, idx_t, const MultiFileBindData &) { - return OpenReader(file); + const auto &global = gstate.Cast(); + return OpenReader(file, global.ffi_global_state->DataPtr()); } shared_ptr VortexReaderInterface::CreateReader(ClientContext &, diff --git a/vortex-duckdb/include/vortex.h b/vortex-duckdb/include/vortex.h index 0ab3e1baac7..b8a654a6c9e 100644 --- a/vortex-duckdb/include/vortex.h +++ b/vortex-duckdb/include/vortex.h @@ -72,8 +72,11 @@ duckdb_vx_data duckdb_reader_bind(const void *first_file, extern duckdb_vx_data duckdb_reader_open(const char *file_path, size_t file_path_len, + const void *global, duckdb_vx_error *error); +extern bool duckdb_reader_is_pruned(const void *file); + extern bool duckdb_reader_get_statistics(const void *file, const void *bind, diff --git a/vortex-duckdb/src/e2e_test/vortex_scan_test.rs b/vortex-duckdb/src/e2e_test/vortex_scan_test.rs index a28a6002d20..2de174566a6 100644 --- a/vortex-duckdb/src/e2e_test/vortex_scan_test.rs +++ b/vortex-duckdb/src/e2e_test/vortex_scan_test.rs @@ -5,6 +5,7 @@ use std::slice; use std::sync::Arc; +use std::sync::Mutex; use anyhow::Result; use geo_types::LineString; @@ -546,8 +547,14 @@ fn test_vortex_scan_float_top_n_keeps_all_nans() -> Result<()> { /// Runs `query` on the file at `path` and collects its single BIGINT output column. fn query_i64_column(path: &str, query: &str) -> Result> { - let conn = database_connection(); - let result = conn.query(&query.replace('?', &format!("'{path}'")))?; + query_i64( + &database_connection(), + &query.replace('?', &format!("'{path}'")), + ) +} + +fn query_i64(conn: &Connection, query: &str) -> Result> { + let result = conn.query(query)?; let mut values = Vec::new(); for chunk in result { let vec = chunk.get_vector(0); @@ -583,12 +590,81 @@ fn test_vortex_scan_v2_matches_v1(#[case] query: &str) -> Result<()> { )); let path = file.path().to_string_lossy(); - crate::set_scan_v2(false); - let v1 = query_i64_column(&path, query)?; - crate::set_scan_v2(true); - let v2 = query_i64_column(&path, query); - crate::set_scan_v2(false); - - assert_eq!(v2?, v1); + let v1 = with_scan_v2(false, || query_i64_column(&path, query))?; + let v2 = with_scan_v2(true, || query_i64_column(&path, query))?; + assert_eq!(v2, v1); Ok(()) } + +// Serialize tests that change the process-wide scan mode, restoring it even on failure. +fn with_scan_v2(enabled: bool, run: impl FnOnce() -> T) -> T { + static LOCK: Mutex<()> = Mutex::new(()); + let _lock = LOCK.lock().unwrap(); + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + crate::set_scan_v2(self.0); + } + } + let _restore = Restore(crate::scan_v2()); + crate::set_scan_v2(enabled); + run() +} + +#[rstest] +fn test_vortex_scan_prunes_multiple_cached_files( + #[values(false, true)] scan_v2: bool, +) -> Result<()> { + let (dir, _files) = RUNTIME.block_on(async { + let dir = tempfile::tempdir().unwrap(); + let mut files = Vec::new(); + for values in [buffer![1i64, 2], buffer![3i64, 4], buffer![5i64, 6]] { + files.push(write_vortex_file_to_dir(dir.path(), "numbers", values).await); + } + (dir, files) + }); + with_scan_v2(scan_v2, || { + let conn = database_connection(); + conn.query("SET disabled_optimizers = 'statistics_propagation'")?; + let table = format!("'{}/*.vortex'", dir.path().display()); + // Populate the existing footer cache before evaluating static predicates. + assert_eq!( + query_i64( + &conn, + &format!("SELECT numbers FROM {table} ORDER BY numbers") + )?, + vec![1, 2, 3, 4, 5, 6] + ); + assert_eq!( + query_i64( + &conn, + &format!("SELECT numbers FROM {table} WHERE numbers > 4 ORDER BY numbers") + )?, + vec![5, 6] + ); + assert!( + query_i64( + &conn, + &format!("SELECT numbers FROM {table} WHERE numbers > 6") + )? + .is_empty() + ); + assert_eq!( + query_i64( + &conn, + &format!("SELECT count(*) FROM {table} WHERE numbers > 6") + )?, + vec![0] + ); + assert_eq!( + query_i64( + &conn, + &format!( + "SELECT coalesce(sum(numbers), -1)::BIGINT FROM {table} WHERE numbers > 6" + ) + )?, + vec![-1] + ); + Ok(()) + }) +} diff --git a/vortex-duckdb/src/ffi.rs b/vortex-duckdb/src/ffi.rs index dd3f822adf1..1365151f69d 100644 --- a/vortex-duckdb/src/ffi.rs +++ b/vortex-duckdb/src/ffi.rs @@ -235,17 +235,26 @@ pub unsafe extern "C-unwind" fn duckdb_reader_bind( pub unsafe extern "C-unwind" fn duckdb_reader_open( file_path: *const c_char, file_path_len: usize, + global: *const c_void, error: *mut cpp::duckdb_vx_error, ) -> cpp::duckdb_vx_data { let path = unsafe { std::slice::from_raw_parts(file_path.cast::(), file_path_len) }; try_or_null(error, || { let path = str::from_utf8(path).map_err(|_| vortex_err!("invalid utf-8"))?; - let file = reader_open(path)?; + let global = unsafe { global.cast::().as_ref() }; + let predicate = global.and_then(|global| global.file_pruning_predicate.as_ref()); + let file = reader_open(path, predicate)?; Ok(Data::from(Box::new(file)).as_ptr()) }) } +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn duckdb_reader_is_pruned(file: *const c_void) -> bool { + let file = unsafe { file.cast::().as_ref() }.vortex_expect("null pointer"); + file.is_pruned() +} + #[unsafe(no_mangle)] pub unsafe extern "C-unwind" fn duckdb_reader_get_statistics( file: *const c_void, @@ -264,7 +273,7 @@ pub unsafe extern "C-unwind" fn duckdb_reader_get_statistics( return false; }; let stats_out = unsafe { &mut *stats_out }; - stats_out.row_count = file.reader().row_count(); + stats_out.row_count = file.row_count(); stats_out.min = stats.min.map_or(ptr::null_mut(), |v| v.into_ptr()); stats_out.max = stats.max.map_or(ptr::null_mut(), |v| v.into_ptr()); stats_out.max_string_length = stats.max_string_length; diff --git a/vortex-duckdb/src/file_reader.rs b/vortex-duckdb/src/file_reader.rs index ffbc75d8362..5409497a7ed 100644 --- a/vortex-duckdb/src/file_reader.rs +++ b/vortex-duckdb/src/file_reader.rs @@ -113,8 +113,8 @@ fn resolve_filesystem(url: &Url) -> VortexResult<(FileSystemRef, String)> { } pub struct OpenFileReader { - /// The layout reader and conversion cache of the file. `None` after the file is skipped or - /// all its splits are taken. + /// The layout reader and conversion cache of the file. `None` when a cached footer prunes + /// the file before opening, after it is skipped, or after all its splits are taken. /// /// DuckDB releases its last reference to a file while it holds the global lock of the /// multi-file scan, and dropping this state takes long. So every local state that scans the @@ -168,6 +168,14 @@ impl OpenFileReader { &self.scan_state().reader } + pub(crate) fn row_count(&self) -> u64 { + self.scan_state().file.row_count() + } + + pub(crate) fn is_pruned(&self) -> bool { + self.scan_state.is_none() + } + fn can_skip( &self, filter: &Filter, @@ -196,7 +204,20 @@ impl OpenFileReader { /// Called once per file while initializing the scan under file-local lock. /// Files are opened lazily. -pub fn reader_open(file_path: &str) -> VortexResult { +pub fn reader_open( + file_path: &str, + predicate: Option<&FilePruningPredicate>, +) -> VortexResult { + if let Some(predicate) = predicate + && let Some(footer) = SESSION.get::().get_footer(file_path) + && predicate.can_prune_footer(&footer, &SESSION)? + { + return Ok(OpenFileReader { + scan_state: None, + splits: Vec::new(), + total_splits: 0, + }); + } RUNTIME.block_on(OpenFileReader::open(file_path.to_owned())) } @@ -227,6 +248,9 @@ pub fn reader_bind(file: &OpenFileReader, result: &mut BindResultRef) -> VortexR /// whether the opened file should be skipped. If this function returns false, /// duckdb closes the file and doesn't call reader_try_initialize_scan on it. pub fn reader_initialize(file: &mut OpenFileReader, global: &GlobalState) -> VortexResult { + if file.is_pruned() { + return Ok(true); + } if file.can_skip( &global.filter, global.file_pruning_predicate.as_ref(), @@ -516,3 +540,58 @@ pub fn footer_get_statistics(footer: &Footer, column: &str) -> Option vortex_panic!(e), } } + +#[cfg(test)] +mod tests { + use std::fs; + + use tempfile::tempdir; + use vortex::array::IntoArray; + use vortex::array::arrays::StructArray; + use vortex::buffer::ByteBufferMut; + use vortex::buffer::buffer; + use vortex::expr::col; + use vortex::expr::gt; + use vortex::expr::lit; + use vortex::file::WriteOptionsSessionExt; + use vortex::io::runtime::BlockingRuntime as _; + + use super::*; + + #[test] + fn cached_footer_prunes_before_opening_the_file() -> VortexResult<()> { + let array = StructArray::from_fields(&[("value", buffer![1_i32, 2, 3].into_array())])?; + let mut bytes = ByteBufferMut::empty(); + RUNTIME.block_on( + SESSION + .write_options() + .write(&mut bytes, array.into_array().to_array_stream()), + )?; + let dir = tempdir()?; + let path = dir.path().join("cached.vortex"); + let path = path.to_str().vortex_expect("temporary path is UTF-8"); + fs::write(path, bytes.as_slice())?; + let opened = reader_open(path, None)?; + let dtype = opened.scan_state().file.dtype(); + let exclude = + FilePruningPredicate::try_new(gt(col("value"), lit(9_i32)).bind(dtype)?, &SESSION)? + .vortex_expect("comparison supports file pruning"); + let retain = + FilePruningPredicate::try_new(gt(col("value"), lit(1_i32)).bind(dtype)?, &SESSION)? + .vortex_expect("comparison supports file pruning"); + drop(opened); + assert!(!reader_open(path, Some(&retain))?.is_pruned()); + + fs::remove_file(path)?; + let pruned = reader_open(path, Some(&exclude))?; + assert!(pruned.is_pruned()); + assert!(pruned.splits.is_empty()); + assert!(reader_open(path, Some(&retain)).is_err()); + assert!(reader_open(path, None).is_err()); + + let missing = dir.path().join("uncached.vortex"); + let missing = missing.to_str().vortex_expect("temporary path is UTF-8"); + assert!(reader_open(missing, Some(&exclude)).is_err()); + Ok(()) + } +}