From 53879cb4f4f84ba3e076bfe60d01cb88cf282e4b Mon Sep 17 00:00:00 2001 From: Alexander Droste Date: Fri, 13 Nov 2026 12:03:00 +0100 Subject: [PATCH 001/128] feat(cuda-ffi): preserve dictionaries in per-schema device batches (#11421) ## Summary First of two stacked drafts: expose dictionary-preserving GPU batches so consumers can postpone string expansion until after combining batches. This PR adds the export API only; the companion PR #11422 adds an optional cuDF materialization helper and reports the ~20% end-to-end hot-read gain. A fixed-schema Arrow device stream cannot describe batches whose dictionary encodings or index widths differ. The new iterator returns an independently owned schema and device array for each batch, using the existing `DictionaryExport::Preserve` policy. ## Changes - Add `vx_cuda_scan_path_device_batches`, `vx_cuda_device_batches_next`, and `vx_cuda_device_batches_free`. - Reuse the existing scan options, ordered top-level projection, direct I/O, and batch splitting. - Keep the existing fixed-schema Arrow stream API and its decoded output unchanged. - Document ownership, stream synchronization, thread affinity, end-of-stream, and terminal-error behavior; regenerate the C header. - Add 10 regression tests for varying dictionary/index types, plain batches, nulls, empty batches, projection, independent output lifetimes, invalid inputs, and terminal errors. --------- Signed-off-by: Alexander Droste --- Cargo.lock | 1 + vortex-cuda/ffi/Cargo.toml | 1 + vortex-cuda/ffi/README.md | 15 +- vortex-cuda/ffi/cinclude/vortex_cuda.h | 70 ++ vortex-cuda/ffi/src/device_batches/mod.rs | 249 ++++++ vortex-cuda/ffi/src/device_batches/tests.rs | 813 ++++++++++++++++++++ vortex-cuda/ffi/src/lib.rs | 36 +- 7 files changed, 1173 insertions(+), 12 deletions(-) create mode 100644 vortex-cuda/ffi/src/device_batches/mod.rs create mode 100644 vortex-cuda/ffi/src/device_batches/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 265d4b24ebd..576f168b5fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11784,6 +11784,7 @@ dependencies = [ "futures", "tempfile", "vortex", + "vortex-array", "vortex-cuda", "vortex-cuda-driver", "vortex-cuda-macros", diff --git a/vortex-cuda/ffi/Cargo.toml b/vortex-cuda/ffi/Cargo.toml index c21150b9898..88805e23d6f 100644 --- a/vortex-cuda/ffi/Cargo.toml +++ b/vortex-cuda/ffi/Cargo.toml @@ -22,6 +22,7 @@ vortex-ffi = { path = "../../vortex-ffi" } [dev-dependencies] tempfile = { workspace = true } +vortex-array = { workspace = true, features = ["_test-harness"] } vortex-cuda-macros = { workspace = true } [build-dependencies] diff --git a/vortex-cuda/ffi/README.md b/vortex-cuda/ffi/README.md index 854a07b02eb..26fb5252f1b 100644 --- a/vortex-cuda/ffi/README.md +++ b/vortex-cuda/ffi/README.md @@ -4,7 +4,8 @@ CUDA-specific C FFI helpers for cuDF interop. This crate keeps CUDA out of the base `vortex-ffi` crate. Its public C API exports a borrowed `vx_array` as an `ArrowSchema + ArrowDeviceArray` pair. -It does not create cuDF objects itself. The caller passes the exported Arrow Device structs to cuDF and releases them after cuDF is done importing. +The Rust FFI does not create cuDF objects itself. The caller imports the exported Arrow Device +structs into cuDF and retains the device arrays until all GPU work using their buffers completes. Use this crate as the CUDA-enabled FFI artifact. Include both headers: @@ -31,7 +32,15 @@ On Linux, use `vx_cuda_scan_path_arrow_device_stream_with_options` with `vx_cuda_scan_options.flags = VX_CUDA_SCAN_FLAG_DIRECT_IO` to bypass the operating system page cache for pooled data-plane reads. Footer and zone-map reads remain buffered on the host. +## Dictionary-preserving batches + +Use `vx_cuda_scan_path_device_batches` to preserve dictionaries with a schema per batch. +Physical encodings and dictionary index widths may differ between batches; import each batch +with its own schema. The existing fixed-schema stream API continues to decode dictionaries. +See `vortex_cuda.h` for ownership, synchronization, and error contracts. + ## Generated header -`build.rs` generates `cinclude/vortex_cuda.h` with cbindgen. Edit `src/lib.rs` or `cbindgen.toml` -and commit the regenerated header. It skips clang-format; CUDA CI checks for header drift. +`build.rs` generates `cinclude/vortex_cuda.h` with cbindgen. Edit the Rust declarations in `src/` +or `cbindgen.toml` and commit the regenerated header. It skips clang-format; CUDA CI checks for +header drift. diff --git a/vortex-cuda/ffi/cinclude/vortex_cuda.h b/vortex-cuda/ffi/cinclude/vortex_cuda.h index 5d5809d934b..bc4df3cd3ab 100644 --- a/vortex-cuda/ffi/cinclude/vortex_cuda.h +++ b/vortex-cuda/ffi/cinclude/vortex_cuda.h @@ -64,6 +64,16 @@ struct ArrowDeviceArrayStream { */ #define VX_CUDA_SCAN_FLAG_DIRECT_IO (1u << 0) +/** + * Dictionary-preserving CUDA scan with an owned Arrow schema per batch. + * + * Logical dtype and CUDA device are fixed; physical schemas, dictionary values, and index widths + * may vary. Uses `DictionaryExport::Preserve`; plain batches remain plain. + * Retains runtime/session resources. Use and free only on the creating thread, without concurrent + * or reentrant calls. Free with `vx_cuda_device_batches_free`. + */ +typedef struct vx_cuda_device_batches vx_cuda_device_batches; + /** * Options for scanning a CUDA-compatible Vortex file. * @@ -265,6 +275,66 @@ int vx_cuda_partition_scan_arrow_device_stream(const vx_session *session, struct ArrowDeviceArrayStream *out_stream, vx_error **error_out); +/** + * Open a local CUDA scan that preserves per-batch dictionaries. + * + * Returns an owned handle, or null on error. Options, projection, and splitting match + * `vx_cuda_scan_path_arrow_device_stream_projected`: null options use defaults; zero `ncolumns` + * ignores `columns` and selects all. Names must be unique, literal, case-sensitive UTF-8; + * unknown names fail, and nonempty projections require a struct file. + * + * Inputs are borrowed for this call; the handle retains runtime/session resources. + * Non-null `error_out` is cleared on success or receives an error to free with `vx_error_free`. + * + * # Safety + * + * Borrow a live `session` and readable UTF-8 `path`. Non-null `options` must be aligned and + * initialized. For nonzero `ncolumns`, `columns` must reference that many valid, aligned views + * with readable name bytes (null only for zero length). Non-null `error_out` must be writable. + */ +struct vx_cuda_device_batches *vx_cuda_scan_path_device_batches(const vx_session *session, + vx_view path, + const struct vx_cuda_scan_options *options, + const vx_view *columns, + size_t ncolumns, + vx_error **error_out); + +/** + * Return the next owned Arrow schema and CUDA array (`0` on success, `1` on error). + * + * Use each batch's own schema. EOS (including repeated calls) sets both release callbacks to null; + * live zero-row batches are not EOS. Errors leave outputs unchanged. Null/unaligned handle or + * output pointers are rejected before polling; scan/export failures, dtype/device mismatches, + * and panics make the handle terminal (later calls fail). Free it after a terminal error. + * Non-null `error_out` is cleared on success or receives an error to free with `vx_error_free`. + * + * Outputs outlive the handle/session. Release each independently, exactly once, via its Arrow + * callback. Wait on `out_array->sync_event` before consuming buffers; retain the array until GPU + * consumers finish. The event/buffers live until array release; output storage is caller-owned. + * + * # Safety + * + * Use a live handle exclusively on its creating thread, without reentrancy. Non-null, aligned + * output pointers must reference writable storage, disjoint from each other, the handle, and + * `error_out`. Outputs may be uninitialized; release previous contents before overwriting them. + * Non-null `error_out` must be writable for one error pointer. + */ +int vx_cuda_device_batches_next(struct vx_cuda_device_batches *handle, + FFI_ArrowSchema *out_schema, + struct ArrowDeviceArray *out_array, + vx_error **error_out); + +/** + * Free the handle; null is a no-op. + * + * Returned outputs remain caller-owned and must be released via their Arrow callbacks. + * + * # Safety + * + * Free a live, exclusively owned handle exactly once on its creating thread, without reentrancy. + */ +void vx_cuda_device_batches_free(struct vx_cuda_device_batches *handle); + #ifdef __cplusplus } // extern "C" #endif // __cplusplus diff --git a/vortex-cuda/ffi/src/device_batches/mod.rs b/vortex-cuda/ffi/src/device_batches/mod.rs new file mode 100644 index 00000000000..5c5fb96d79a --- /dev/null +++ b/vortex-cuda/ffi/src/device_batches/mod.rs @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::os::raw::c_int; +use std::ptr; + +use arrow_schema::ffi::FFI_ArrowSchema; +use vortex::array::ArrayRef; +use vortex::array::stream::SendableArrayStream; +use vortex::dtype::DType; +use vortex::error::VortexResult; +use vortex::error::vortex_ensure; +use vortex::error::vortex_ensure_eq; +use vortex::io::runtime::BlockingRuntime; +use vortex::io::runtime::current::CurrentThreadRuntime; +use vortex::session::VortexSession; +use vortex_cuda::CudaExecutionCtx; +use vortex_cuda::CudaSession; +use vortex_cuda::DictionaryExport; +use vortex_cuda::arrow::ARROW_DEVICE_CUDA; +use vortex_cuda::arrow::ArrowDeviceArray; +use vortex_cuda::arrow::ArrowDeviceArrayWithSchema; +use vortex_cuda::arrow::DeviceArrayExt; +use vortex_cuda::arrow::release_device_array; +use vortex_ffi::ffi_runtime; +use vortex_ffi::try_or; +use vortex_ffi::vx_error; +use vortex_ffi::vx_session; +use vortex_ffi::vx_session_ref; +use vortex_ffi::vx_view; + +use crate::VX_CUDA_ERR; +use crate::VX_CUDA_OK; +use crate::open_cuda_scan; +use crate::scan_columns; +use crate::scan_options; +use crate::session_with_cuda; +use crate::vx_cuda_scan_options; + +/// Dictionary-preserving CUDA scan with an owned Arrow schema per batch. +/// +/// Logical dtype and CUDA device are fixed; physical schemas, dictionary values, and index widths +/// may vary. Uses `DictionaryExport::Preserve`; plain batches remain plain. +/// Retains runtime/session resources. Use and free only on the creating thread, without concurrent +/// or reentrant calls. Free with `vx_cuda_device_batches_free`. +#[allow(non_camel_case_types)] +pub struct vx_cuda_device_batches { + array_iter: Box>>, + ctx: CudaExecutionCtx, + runtime: CurrentThreadRuntime, + dtype: DType, + state: State, +} + +enum State { + Ready, + End, + Failed, +} + +impl vx_cuda_device_batches { + fn new( + stream: SendableArrayStream, + session: &VortexSession, + runtime: &CurrentThreadRuntime, + ) -> VortexResult { + let dtype = stream.dtype().clone(); + let ctx = CudaSession::create_execution_ctx(session)? + .with_dictionary_export(DictionaryExport::Preserve); + Ok(Self { + array_iter: Box::new(runtime.block_on_stream(stream)), + ctx, + runtime: runtime.clone(), + dtype, + state: State::Ready, + }) + } + + /// Return released outputs carrying this scan's CUDA device metadata. + /// + /// Matches the decoded stream; release callbacks still determine end-of-stream. + fn eos(&self) -> ArrowDeviceArrayWithSchema { + ArrowDeviceArrayWithSchema { + schema: FFI_ArrowSchema::empty(), + array: ArrowDeviceArray { + device_id: self.ctx.stream().context().ordinal() as i64, + device_type: ARROW_DEVICE_CUDA, + ..ArrowDeviceArray::empty() + }, + } + } + + fn next(&mut self) -> VortexResult { + vortex_ensure!( + !matches!(self.state, State::Failed), + "CUDA device batches are terminal after an earlier scan or export error" + ); + if matches!(self.state, State::End) { + return Ok(self.eos()); + } + + // Poison before polling/exporting so a failure or caught panic cannot skip a batch on retry. + self.state = State::Failed; + let Some(array) = self.array_iter.next() else { + self.state = State::End; + return Ok(self.eos()); + }; + let array = array?; + vortex_ensure_eq!( + array.dtype(), + &self.dtype, + "scan batch logical dtype changed" + ); + let mut exported = self + .runtime + .block_on(array.export_device_array_with_schema(&mut self.ctx))?; + if let Err(error) = self.check_device(&exported.array) { + // The schema releases itself on drop; the array needs explicit release. + release_device_array(&mut exported.array); + return Err(error); + } + self.state = State::Ready; + Ok(exported) + } + + /// Require exports to use the handle's CUDA device. + /// + /// Physical schemas may vary between batches, but the execution device must not. + fn check_device(&self, array: &ArrowDeviceArray) -> VortexResult<()> { + vortex_ensure_eq!( + array.device_type, + ARROW_DEVICE_CUDA, + "scan batch exported on non-CUDA device type" + ); + vortex_ensure_eq!( + array.device_id, + self.ctx.stream().context().ordinal() as i64, + "scan batch moved from CUDA device" + ); + Ok(()) + } +} + +/// Open a local CUDA scan that preserves per-batch dictionaries. +/// +/// Returns an owned handle, or null on error. Options, projection, and splitting match +/// `vx_cuda_scan_path_arrow_device_stream_projected`: null options use defaults; zero `ncolumns` +/// ignores `columns` and selects all. Names must be unique, literal, case-sensitive UTF-8; +/// unknown names fail, and nonempty projections require a struct file. +/// +/// Inputs are borrowed for this call; the handle retains runtime/session resources. +/// Non-null `error_out` is cleared on success or receives an error to free with `vx_error_free`. +/// +/// # Safety +/// +/// Borrow a live `session` and readable UTF-8 `path`. Non-null `options` must be aligned and +/// initialized. For nonzero `ncolumns`, `columns` must reference that many valid, aligned views +/// with readable name bytes (null only for zero length). Non-null `error_out` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn vx_cuda_scan_path_device_batches( + session: *const vx_session, + path: vx_view, + options: *const vx_cuda_scan_options, + columns: *const vx_view, + ncolumns: usize, + error_out: *mut *mut vx_error, +) -> *mut vx_cuda_device_batches { + try_or(error_out, ptr::null_mut(), || { + // SAFETY: The caller keeps all borrowed inputs valid for this call. + let (options, columns, path, session) = unsafe { + ( + scan_options(options)?, + scan_columns(columns, ncolumns)?, + path.as_str()?, + vx_session_ref(session)?, + ) + }; + let session = session_with_cuda(session); + let stream = open_cuda_scan(session, path, options, columns)?; + Ok(Box::into_raw(Box::new(vx_cuda_device_batches::new( + stream, + session, + ffi_runtime(), + )?))) + }) +} + +/// Return the next owned Arrow schema and CUDA array (`0` on success, `1` on error). +/// +/// Use each batch's own schema. EOS (including repeated calls) sets both release callbacks to null; +/// live zero-row batches are not EOS. Errors leave outputs unchanged. Null/unaligned handle or +/// output pointers are rejected before polling; scan/export failures, dtype/device mismatches, +/// and panics make the handle terminal (later calls fail). Free it after a terminal error. +/// Non-null `error_out` is cleared on success or receives an error to free with `vx_error_free`. +/// +/// Outputs outlive the handle/session. Release each independently, exactly once, via its Arrow +/// callback. Wait on `out_array->sync_event` before consuming buffers; retain the array until GPU +/// consumers finish. The event/buffers live until array release; output storage is caller-owned. +/// +/// # Safety +/// +/// Use a live handle exclusively on its creating thread, without reentrancy. Non-null, aligned +/// output pointers must reference writable storage, disjoint from each other, the handle, and +/// `error_out`. Outputs may be uninitialized; release previous contents before overwriting them. +/// Non-null `error_out` must be writable for one error pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn vx_cuda_device_batches_next( + handle: *mut vx_cuda_device_batches, + out_schema: *mut FFI_ArrowSchema, + out_array: *mut ArrowDeviceArray, + error_out: *mut *mut vx_error, +) -> c_int { + try_or(error_out, VX_CUDA_ERR, || { + vortex_ensure!(!handle.is_null(), "null vx_cuda_device_batches"); + vortex_ensure!(handle.is_aligned(), "unaligned vx_cuda_device_batches"); + vortex_ensure!(!out_schema.is_null(), "null ArrowSchema output"); + vortex_ensure!(out_schema.is_aligned(), "unaligned ArrowSchema output"); + vortex_ensure!(!out_array.is_null(), "null ArrowDeviceArray output"); + vortex_ensure!(out_array.is_aligned(), "unaligned ArrowDeviceArray output"); + // SAFETY: The pointer checks passed and the caller guarantees exclusive access to a live + // handle on its creating thread. + let exported = unsafe { &mut *handle }.next()?; + // SAFETY: Both outputs passed pointer checks and the caller guarantees separate writable + // storage. Publish only after the entire export succeeds. + unsafe { + ptr::write(out_schema, exported.schema); + ptr::write(out_array, exported.array); + } + Ok(VX_CUDA_OK) + }) +} + +/// Free the handle; null is a no-op. +/// +/// Returned outputs remain caller-owned and must be released via their Arrow callbacks. +/// +/// # Safety +/// +/// Free a live, exclusively owned handle exactly once on its creating thread, without reentrancy. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn vx_cuda_device_batches_free(handle: *mut vx_cuda_device_batches) { + if !handle.is_null() { + // SAFETY: The caller transfers sole ownership of a live handle on its creating thread. + drop(unsafe { Box::from_raw(handle) }); + } +} + +#[cfg(test)] +mod tests; diff --git a/vortex-cuda/ffi/src/device_batches/tests.rs b/vortex-cuda/ffi/src/device_batches/tests.rs new file mode 100644 index 00000000000..549c12982bc --- /dev/null +++ b/vortex-cuda/ffi/src/device_batches/tests.rs @@ -0,0 +1,813 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::io::Write; +use std::mem; +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::Schema; +use futures::stream; +use tempfile::NamedTempFile; +use vortex::VortexSessionDefault; +use vortex::array::IntoArray; +use vortex::array::VortexSessionExecute; +use vortex::array::arrays::DecimalArray; +use vortex::array::arrays::DictArray; +use vortex::array::arrays::PrimitiveArray; +use vortex::array::arrays::StructArray; +use vortex::array::arrays::VarBinViewArray; +use vortex::array::assert_arrays_eq; +use vortex::array::stream::ArrayStreamAdapter; +use vortex::array::stream::ArrayStreamExt; +use vortex::array::validity::Validity; +use vortex::buffer::ByteBufferMut; +use vortex::dtype::DecimalDType; +use vortex::dtype::NativePType; +use vortex::error::VortexError; +use vortex::error::vortex_err; +use vortex::file::WriteOptionsSessionExt; +use vortex::io::session::RuntimeSessionExt; +use vortex::layout::layouts::flat::writer::FlatLayoutStrategy; +use vortex::session::SessionExt; +use vortex_cuda::VarBinExportLayout; +use vortex_cuda::arrow::ARROW_DEVICE_CUDA; +use vortex_cuda::arrow::ArrowArray; +use vortex_cuda::arrow::ArrowDeviceArrayStream; +use vortex_cuda::arrow::release_device_array; +use vortex_cuda_driver::CudaContext; +use vortex_cuda_driver::event; +use vortex_cuda_driver::memory; +use vortex_cuda_driver::sys::CUevent; +use vortex_cuda_macros::test as cuda_test; +use vortex_ffi::vx_error_free; +use vortex_ffi::vx_error_message; +use vortex_ffi::vx_session_free; + +use super::*; +use crate::scan_export_ctx; + +struct Output { + schema: FFI_ArrowSchema, + array: ArrowDeviceArray, +} + +impl Output { + fn empty() -> Self { + Self { + schema: FFI_ArrowSchema::empty(), + array: ArrowDeviceArray::empty(), + } + } + + fn is_eos(&self) -> bool { + assert_eq!( + self.schema.release.is_none(), + self.array.array.release.is_none() + ); + self.schema.release.is_none() + } +} + +impl Drop for Output { + fn drop(&mut self) { + release_device_array(&mut self.array); + } +} + +fn take_error(error: *mut vx_error) -> Option { + if error.is_null() { + return None; + } + // SAFETY: All callers transfer an owned error from these FFI calls. Copy before freeing it. + let message = unsafe { vx_error_message(error).as_str() } + .unwrap() + .to_owned(); + unsafe { vx_error_free(error) }; + Some(message) +} + +fn next(handle: &mut vx_cuda_device_batches) -> VortexResult { + let mut output = Output::empty(); + next_into(handle, &mut output)?; + Ok(output) +} + +/// Advance into existing output storage through the public ABI. +/// +/// Shared by success and error tests so both check status codes and error ownership. +fn next_into(handle: &mut vx_cuda_device_batches, output: &mut Output) -> VortexResult<()> { + let mut error = ptr::null_mut(); + // SAFETY: The handle is exclusively borrowed and outputs are live, disjoint, and writable. + let status = unsafe { + vx_cuda_device_batches_next( + handle, + &raw mut output.schema, + &raw mut output.array, + &raw mut error, + ) + }; + if let Some(error) = take_error(error) { + assert_eq!(status, VX_CUDA_ERR); + return Err(vortex_err!("{error}")); + } + assert_eq!(status, VX_CUDA_OK); + Ok(()) +} + +fn session() -> VortexResult { + // Override Decode per handle, rather than relying on the session default being Preserve. + Ok(VortexSession::default().with_some( + CudaSession::try_default()? + .with_dictionary_export(DictionaryExport::Decode) + .with_varbin_export_layout(VarBinExportLayout::VarBin), + )) +} + +fn batches(session: &VortexSession, arrays: Vec) -> VortexResult { + let dtype = arrays[0].dtype().clone(); + let stream = ArrayStreamAdapter::new(dtype, stream::iter(arrays.into_iter().map(Ok))).boxed(); + vx_cuda_device_batches::new(stream, session, ffi_runtime()) +} + +/// Build a primitive fixture for a mixed-encoding batch stream. +/// +/// Keeps the element type explicit at call sites while returning an erased array. +fn primitive(values: impl IntoIterator) -> ArrayRef { + PrimitiveArray::from_iter(values).into_array() +} + +fn strings(values: &[Option<&str>]) -> ArrayRef { + VarBinViewArray::from_iter_nullable_str(values.iter().copied()).into_array() +} + +fn dictionary(codes: ArrayRef, values: &[Option<&str>]) -> VortexResult { + Ok(DictArray::try_new(codes, strings(values))?.into_array()) +} + +fn table(column: ArrayRef) -> ArrayRef { + let len = column.len(); + StructArray::new(["text"].into(), vec![column], len, Validity::NonNullable).into_array() +} + +fn synchronize(array: &ArrowDeviceArray) -> VortexResult> { + assert_eq!(array.device_type, ARROW_DEVICE_CUDA); + let context = CudaContext::new(usize::try_from(array.device_id)?) + .map_err(|error| vortex_err!("opening device context: {error}"))?; + context + .bind_to_thread() + .map_err(|error| vortex_err!("binding context: {error}"))?; + if !array.sync_event.is_null() { + // SAFETY: The live exported array owns the CUDA event handle. + unsafe { event::synchronize(*array.sync_event.cast::()) } + .map_err(|error| vortex_err!("waiting for device batch: {error}"))?; + } + Ok(context) +} + +/// Read one buffer from a live, synchronized Arrow array with the specified element type/length. +unsafe fn buffer( + array: &ArrowArray, + slot: usize, + len: usize, +) -> VortexResult> { + assert!(slot < usize::try_from(array.n_buffers)?); + let mut values = vec![T::default(); len]; + if len != 0 { + // SAFETY: The caller guarantees the buffer layout, lifetime, and synchronization. + let source = unsafe { *array.buffers.add(slot) }; + unsafe { memory::memcpy_dtoh_sync(&mut values, source as u64) } + .map_err(|error| vortex_err!("copying device buffer: {error}"))?; + } + Ok(values) +} + +/// Read validity from a live, synchronized zero-offset Arrow array. +unsafe fn validity(array: &ArrowArray) -> VortexResult> { + assert_eq!(array.offset, 0); + let len = usize::try_from(array.length)?; + // SAFETY: These exports always have a validity buffer slot. + if unsafe { (*array.buffers).is_null() } { + assert_eq!(array.null_count, 0); + return Ok(vec![true; len]); + } + // SAFETY: The bitmap covers the live array's rows. + let bytes = unsafe { buffer::(array, 0, len.div_ceil(8)) }?; + let bits: Vec<_> = (0..len) + .map(|i| bytes[i / 8] & (1 << (i % 8)) != 0) + .collect(); + assert_eq!( + usize::try_from(array.null_count)?, + bits.iter().filter(|bit| !**bit).count() + ); + Ok(bits) +} + +/// Decode the fixture's synchronized Utf8 or dictionary array through the public ABI. +unsafe fn read_strings(array: &ArrowArray, dtype: &DataType) -> VortexResult>> { + let len = usize::try_from(array.length)?; + // SAFETY: The fixture supplies a live synchronized array and its matching physical schema. + let valid = unsafe { validity(array) }?; + if let DataType::Dictionary(codes_type, values_type) = dtype { + // SAFETY: A dictionary schema requires a live dictionary child in the matching array. + let dictionary = unsafe { array.dictionary.as_ref() }.expect("missing dictionary"); + let values = unsafe { read_strings(dictionary, values_type) }?; + // SAFETY: The matching schema determines the signed codes buffer's element width. + let codes: Vec = unsafe { + match codes_type.as_ref() { + DataType::Int16 => buffer::(array, 1, len)? + .into_iter() + .map(i64::from) + .collect(), + DataType::Int32 => buffer::(array, 1, len)? + .into_iter() + .map(i64::from) + .collect(), + DataType::Int64 => buffer::(array, 1, len)?, + other => panic!("unexpected dictionary index type: {other}"), + } + }; + return codes + .into_iter() + .zip(valid) + .map(|(code, valid)| { + if valid { + Ok(values[usize::try_from(code)?].clone()) + } else { + Ok(None) + } + }) + .collect(); + } + assert_eq!(dtype, &DataType::Utf8); + assert!( + array.dictionary.is_null(), + "plain batches must not acquire identity dictionaries" + ); + // SAFETY: A zero-offset Utf8 array has len + 1 i32 offsets and that many bytes of data. + let offsets = unsafe { buffer::(array, 1, len + 1) }?; + let bytes = unsafe { buffer::(array, 2, usize::try_from(offsets[len])?) }?; + offsets + .windows(2) + .zip(valid) + .map(|(offsets, valid)| { + if valid { + Ok(Some( + std::str::from_utf8( + &bytes[usize::try_from(offsets[0])?..usize::try_from(offsets[1])?], + ) + .map_err(VortexError::external)? + .to_owned(), + )) + } else { + Ok(None) + } + }) + .collect() +} + +#[cuda_test] +fn test_per_batch_dictionaries_widths_plain_and_owned_lifetimes() -> VortexResult<()> { + let session = session()?; + let first = dictionary(primitive([1u8, 0, 1]), &[Some("red"), Some("blue")])?; + let second = dictionary( + primitive([0u8, 1, 0]), + &[Some("green"), Some("a longer dictionary value")], + )?; + let third = strings(&[Some("plain"), None, Some("no identity dictionary")]); + let fourth = dictionary(primitive([1u16, 0, 1]), &[Some("small"), Some("wide")])?; + let fifth = dictionary(primitive([0u32, 1, 0]), &[Some("widest"), Some("last")])?; + let inputs = vec![first, second, third, fourth, fifth]; + let expected = [ + strings(&[Some("blue"), Some("red"), Some("blue")]), + strings(&[ + Some("green"), + Some("a longer dictionary value"), + Some("green"), + ]), + inputs[2].clone(), + strings(&[Some("wide"), Some("small"), Some("wide")]), + strings(&[Some("widest"), Some("last"), Some("widest")]), + ]; + let mut handle = batches(&session, inputs.into_iter().map(table).collect())?; + assert_eq!( + session.get::().dictionary_export(), + DictionaryExport::Decode + ); + let mut outputs = Vec::new(); + for _ in 0..expected.len() { + outputs.push(next(&mut handle)?); + } + assert!(next(&mut handle)?.is_eos()); + // SAFETY: Transfer the exclusively owned handle to its matching destructor on this thread. + unsafe { vx_cuda_device_batches_free(Box::into_raw(Box::new(handle))) }; + drop(session); + + let index_types = [ + Some(DataType::Int16), + Some(DataType::Int16), + None, + Some(DataType::Int32), + Some(DataType::Int64), + ]; + let mut ctx = VortexSession::default().create_execution_ctx(); + for ((output, expected), index_type) in outputs.iter().zip(expected).zip(index_types) { + let schema = Schema::try_from(&output.schema)?; + assert_eq!(schema.fields().len(), 1); + let dtype = schema.field(0).data_type(); + let expected_dtype = index_type.map_or(DataType::Utf8, |index| { + DataType::Dictionary(Box::new(index), Box::new(DataType::Utf8)) + }); + assert_eq!(dtype, &expected_dtype); + let _context = synchronize(&output.array)?; + assert_eq!(output.array.array.n_children, 1); + // SAFETY: This live table batch has one child, described by the checked schema. + let actual = unsafe { read_strings(&**output.array.array.children, dtype) }?; + assert_arrays_eq!( + VarBinViewArray::from_iter_nullable_str(actual).into_array(), + expected, + &mut ctx + ); + } + // Schema and array ownership are independent, even after freeing the producer. + let mut output = outputs.pop().unwrap(); + drop(mem::replace(&mut output.schema, FFI_ArrowSchema::empty())); + let _context = synchronize(&output.array)?; + Ok(()) +} + +/// Upload fixture buffers without decoding to exercise device-resident dictionary export. +fn upload(array: ArrayRef, ctx: &mut CudaExecutionCtx) -> VortexResult { + let mut slots = Vec::new(); + for slot in array.slots().iter() { + slots.push(match slot { + Some(child) => Some(upload(child.clone(), ctx)?), + None => None, + }); + } + let mut buffers = Vec::new(); + for buffer in array.buffer_handles() { + buffers.push(ctx.ensure_on_device_sync(buffer)?); + } + // SAFETY: The fixture's slots and buffers are unchanged except for their memory placement. + unsafe { array.with_slots(slots.into())?.with_buffers(buffers) } +} + +#[cuda_test] +fn test_numeric_dictionary_preserved_alongside_strings() -> VortexResult<()> { + let session = session()?; + let mut ctx = CudaSession::create_execution_ctx(&session)?; + let codes = primitive([1u8, 0, 1]); + let numbers = DictArray::try_new(codes.clone(), primitive([10i32, 30]))?.into_array(); + let text = dictionary(codes, &[Some("red"), Some("blue")])?; + let input = StructArray::new( + ["number", "text"].into(), + vec![numbers, text], + 3, + Validity::NonNullable, + ) + .into_array(); + let input = upload(input, &mut ctx)?; + assert!(!input.is_host()); + ctx.synchronize_stream()?; + let mut handle = batches(&session, vec![input])?; + let output = next(&mut handle)?; + let schema = Schema::try_from(&output.schema)?; + assert_eq!(schema.fields().len(), 2); + for (field, value_type) in schema + .fields() + .iter() + .zip([DataType::Int32, DataType::Utf8]) + { + assert_eq!( + field.data_type(), + &DataType::Dictionary(Box::new(DataType::Int16), Box::new(value_type)) + ); + } + let _context = synchronize(&output.array)?; + assert_eq!(output.array.array.length, 3); + assert_eq!(output.array.array.n_children, 2); + // SAFETY: The checked schema describes the live, synchronized dictionary children. + let numbers = unsafe { &**output.array.array.children }; + let text = unsafe { &**output.array.array.children.add(1) }; + let values = unsafe { numbers.dictionary.as_ref() }.expect("missing numeric dictionary"); + assert_eq!(numbers.length, 3); + assert_eq!(values.length, 2); + // SAFETY: The numeric dictionary has three i16 indices and two i32 dictionary values. + unsafe { + assert_eq!(validity(numbers)?, vec![true; 3]); + assert_eq!(validity(values)?, vec![true; 2]); + assert_eq!(buffer::(numbers, 1, 3)?, vec![1, 0, 1]); + assert_eq!(buffer::(values, 1, 2)?, vec![10, 30]); + } + // SAFETY: The second field describes the live, synchronized string dictionary. + let actual = unsafe { read_strings(text, schema.field(1).data_type()) }?; + assert_arrays_eq!( + VarBinViewArray::from_iter_nullable_str(actual).into_array(), + strings(&[Some("blue"), Some("red"), Some("blue")]), + ctx.execution_ctx() + ); + assert!(next(&mut handle)?.is_eos()); + Ok(()) +} + +#[cuda_test] +fn test_null_dictionary_values_and_codes() -> VortexResult<()> { + let session = session()?; + let input = dictionary( + PrimitiveArray::from_option_iter([Some(0u8), Some(1), None, Some(2), Some(1)]).into_array(), + &[Some("valid"), None, Some("also valid")], + )?; + let mut handle = batches(&session, vec![input])?; + let output = next(&mut handle)?; + let field = Field::try_from(&output.schema)?; + assert!(field.is_nullable()); + let _context = synchronize(&output.array)?; + // SAFETY: The schema describes this live, synchronized dictionary array. + let actual = unsafe { read_strings(&output.array.array, field.data_type()) }?; + assert_arrays_eq!( + VarBinViewArray::from_iter_nullable_str(actual).into_array(), + strings(&[Some("valid"), None, None, Some("also valid"), None]), + handle.ctx.execution_ctx() + ); + // Both the dictionary child bitmap and the logical row bitmap must survive Preserve export. + assert_eq!(output.array.array.null_count, 3); + // SAFETY: Both bitmaps belong to the live, synchronized dictionary export. + unsafe { + assert_eq!( + validity(&*output.array.array.dictionary)?, + vec![true, false, true] + ); + assert_eq!( + validity(&output.array.array)?, + vec![true, false, false, true, false] + ); + } + Ok(()) +} + +#[cuda_test] +fn test_zero_row_batch_and_fused_eos() -> VortexResult<()> { + let session = session()?; + let empty = primitive::([]); + let mut handle = batches(&session, vec![empty, primitive([7i32])])?; + let output = next(&mut handle)?; + assert!(!output.is_eos()); + assert_eq!(output.array.array.length, 0); + assert_eq!(next(&mut handle)?.array.array.length, 1); + let device_id = handle.ctx.stream().context().ordinal() as i64; + let first_eos = next(&mut handle)?; + assert_eos(&first_eos, device_id); + let repeated_eos = next(&mut handle)?; + assert_eos(&repeated_eos, device_id); + Ok(()) +} + +#[cuda_test] +fn test_empty_stream_and_fused_eos() -> VortexResult<()> { + let session = session()?; + let empty = primitive::([]); + let stream = ArrayStreamAdapter::new(empty.dtype().clone(), stream::empty()).boxed(); + let mut handle = vx_cuda_device_batches::new(stream, &session, ffi_runtime())?; + let device_id = handle.ctx.stream().context().ordinal() as i64; + let first_eos = next(&mut handle)?; + assert_eos(&first_eos, device_id); + let repeated_eos = next(&mut handle)?; + assert_eos(&repeated_eos, device_id); + Ok(()) +} + +/// Assert released outputs with the expected CUDA device metadata. +/// +/// Device fields remain populated even though end-of-stream carries no data. +fn assert_eos(output: &Output, device_id: i64) { + assert!(output.is_eos()); + assert_eq!(output.array.device_type, ARROW_DEVICE_CUDA); + assert_eq!(output.array.device_id, device_id); +} + +fn assert_terminal( + handle: &mut vx_cuda_device_batches, + expected_error: &str, + polls: &AtomicUsize, +) -> VortexResult<()> { + let mut output = next(handle)?; + let schema = Field::try_from(&output.schema)?; + let private_data = output.array.array.private_data; + for expected in [expected_error, "terminal", "terminal"] { + let error = next_into(handle, &mut output).expect_err("failed batch must return an error"); + assert!(error.to_string().contains(expected), "{error}"); + assert_eq!(Field::try_from(&output.schema)?, schema); + assert_eq!(output.array.array.private_data, private_data); + assert_eq!( + polls.load(Ordering::Relaxed), + 2, + "retry consumed more input" + ); + } + Ok(()) +} + +#[cuda_test] +fn test_scan_dtype_export_errors_and_panics_are_terminal() -> VortexResult<()> { + let session = session()?; + for failure in ["scan", "dtype", "export", "panic"] { + let seed = if failure == "export" { + DecimalArray::from_iter([1i64], DecimalDType::new(10, 2)).into_array() + } else { + primitive([1i32]) + }; + let mut handle = batches(&session, vec![seed.clone()])?; + let bad = match failure { + "scan" | "panic" => Err(vortex_err!("injected scan failure")), + "dtype" => Ok(primitive([1i64])), + // Same logical decimal dtype, but its physical storage requires unsupported narrowing. + "export" => Ok(DecimalArray::from_iter([1i128], DecimalDType::new(10, 2)).into_array()), + _ => unreachable!(), + }; + let polls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&polls); + // Deliberately bypass ArrayStreamAdapter's debug dtype assertion to reach the handle's + // own guard in both debug and release builds. The trailing batch must never be consumed. + handle.array_iter = Box::new(vec![Ok(seed.clone()), bad, Ok(seed)].into_iter().inspect( + move |_| { + let index = counter.fetch_add(1, Ordering::Relaxed); + assert!( + !(failure == "panic" && index == 1), + "injected polling panic" + ); + }, + )); + let message = match failure { + "scan" => "injected scan failure", + "dtype" => "logical dtype changed", + "export" => "narrowing would require", + "panic" => "injected polling panic", + _ => unreachable!(), + }; + assert_terminal(&mut handle, message, &polls)?; + } + Ok(()) +} + +#[cuda_test] +fn test_device_check_rejects_non_cuda_export() -> VortexResult<()> { + let session = session()?; + let mut handle = batches(&session, vec![primitive([42i32])])?; + let mut output = next(&mut handle)?; + handle.check_device(&output.array)?; + output.array.device_type = 0; + let error = handle + .check_device(&output.array) + .expect_err("non-CUDA export must be rejected"); + assert!(error.to_string().contains("non-CUDA device type")); + Ok(()) +} + +#[cuda_test] +fn test_device_check_rejects_different_cuda_device() -> VortexResult<()> { + let session = session()?; + let mut handle = batches(&session, vec![primitive([42i32])])?; + let mut output = next(&mut handle)?; + handle.check_device(&output.array)?; + output.array.device_id += 1; + let error = handle + .check_device(&output.array) + .expect_err("export from a different CUDA device must be rejected"); + assert!(error.to_string().contains("moved from CUDA device")); + Ok(()) +} + +#[cuda_test] +fn test_invalid_output_pointers_do_not_consume_or_poison() -> VortexResult<()> { + let session = session()?; + let mut handle = batches(&session, vec![primitive([42i32])])?; + let mut output = Output::empty(); + output.array.array.length = 123; + let schema = &raw mut output.schema; + let array = &raw mut output.array; + for (schema, array) in [ + (ptr::null_mut(), array), + (schema, ptr::null_mut()), + (ptr::without_provenance_mut::(1), array), + (schema, ptr::without_provenance_mut::(1)), + ] { + let mut error = ptr::null_mut(); + // SAFETY: Deliberately rejected null/unaligned pointers are never dereferenced; the other + // output and the handle are valid. These failures must not poll or poison the handle. + let status = + unsafe { vx_cuda_device_batches_next(&raw mut handle, schema, array, &raw mut error) }; + assert_eq!(status, VX_CUDA_ERR); + assert!(take_error(error).is_some()); + assert!(output.schema.release.is_none()); + assert_eq!(output.array.array.length, 123); + } + assert_eq!(next(&mut handle)?.array.array.length, 1); + assert!(next(&mut handle)?.is_eos()); + Ok(()) +} + +#[test] +fn test_null_and_unaligned_handles_without_cuda() { + for handle in [ + ptr::null_mut(), + ptr::without_provenance_mut::(1), + ] { + let mut output = Output::empty(); + output.array.array.length = 123; + let mut error = ptr::null_mut(); + // SAFETY: Deliberately rejected handle pointers are never dereferenced; outputs are valid. + let status = unsafe { + vx_cuda_device_batches_next( + handle, + &raw mut output.schema, + &raw mut output.array, + &raw mut error, + ) + }; + assert_eq!(status, VX_CUDA_ERR); + assert!(take_error(error).is_some()); + assert!(output.schema.release.is_none()); + assert_eq!(output.array.array.length, 123); + } + // SAFETY: Null is explicitly supported, including when error details are discarded. + unsafe { + vx_cuda_device_batches_free(ptr::null_mut()); + assert_eq!( + vx_cuda_device_batches_next( + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut() + ), + VX_CUDA_ERR + ); + } +} + +fn view(value: &str) -> vx_view { + vx_view { + ptr: value.as_ptr().cast(), + len: value.len(), + } +} + +#[test] +fn test_open_rejects_invalid_inputs_before_cuda() { + let invalid_options = vx_cuda_scan_options { + flags: u32::MAX, + batch_rows: 0, + }; + let duplicate_names = [view("text"), view("text")]; + let cases = [ + ( + &raw const invalid_options, + ptr::null(), + 0, + "unsupported CUDA scan option flags", + ), + (ptr::null(), ptr::null(), 1, "null CUDA scan columns"), + ( + ptr::null(), + duplicate_names.as_ptr(), + 2, + "duplicate CUDA scan column", + ), + (ptr::null(), ptr::null(), 0, "null vx_session"), + ]; + for (options, columns, ncolumns, message) in cases { + let mut error = ptr::null_mut(); + // SAFETY: All borrowed inputs are live; null inputs are rejected before opening a file + // or initializing CUDA. Only the nonzero column count intentionally lacks its array. + let handle = unsafe { + vx_cuda_scan_path_device_batches( + ptr::null(), + view("unused.vortex"), + options, + columns, + ncolumns, + &raw mut error, + ) + }; + assert!(handle.is_null()); + let error = take_error(error).expect("missing error"); + assert!(error.contains(message), "{error}"); + } +} + +#[cuda_test] +fn test_path_projection_batch_rows_and_session_lifetime() -> VortexResult<()> { + let session = session()?.with_handle(ffi_runtime().handle()); + let input = StructArray::new( + ["unused", "ids"].into(), + vec![ + primitive([90i32, 91, 92, 93, 94]), + primitive([0i32, 1, 2, 3, 4]), + ], + 5, + Validity::NonNullable, + ); + let mut bytes = ByteBufferMut::empty(); + ffi_runtime().block_on( + session + .write_options() + .with_strategy(Arc::new(FlatLayoutStrategy::default())) + .write(&mut bytes, input.into_array().to_array_stream()), + )?; + let mut file = NamedTempFile::new()?; + file.write_all(&bytes)?; + let path = file + .path() + .to_str() + .ok_or_else(|| vortex_err!("non-UTF-8 test path"))?; + let columns = [view("ids")]; + let options = vx_cuda_scan_options { + batch_rows: 2, + ..Default::default() + }; + let session_handle = Box::into_raw(Box::new(session)).cast::(); + let mut error = ptr::null_mut(); + // SAFETY: The session handle and all borrowed views/options are valid for this call. + let handle = unsafe { + vx_cuda_scan_path_device_batches( + session_handle, + view(path), + &raw const options, + columns.as_ptr(), + columns.len(), + &raw mut error, + ) + }; + // SAFETY: The scan must retain its own session resources, independent of this owned handle. + unsafe { vx_session_free(session_handle) }; + assert!(take_error(error).is_none()); + assert!(!handle.is_null()); + // SAFETY: Take ownership of the returned handle on its creating thread. + let mut handle = unsafe { Box::from_raw(handle) }; + let mut ids = Vec::new(); + for rows in [2, 2, 1] { + let output = next(&mut handle)?; + assert_eq!(output.array.array.length, rows); + let schema = Schema::try_from(&output.schema)?; + assert_eq!( + schema, + Schema::new(vec![Field::new("ids", DataType::Int32, false)]) + ); + let _context = synchronize(&output.array)?; + // SAFETY: The checked schema describes the live synchronized table's sole i32 child. + unsafe { + ids.extend(buffer::( + &**output.array.array.children, + 1, + usize::try_from(rows)?, + )?); + } + } + assert_eq!(ids, vec![0, 1, 2, 3, 4]); + assert!(next(&mut handle)?.is_eos()); + Ok(()) +} + +#[cuda_test] +fn test_existing_device_stream_still_decodes_mixed_batches() -> VortexResult<()> { + let session = VortexSession::default().with_some( + CudaSession::try_default()?.with_varbin_export_layout(VarBinExportLayout::VarBin), + ); + assert_eq!( + session.get::().dictionary_export(), + DictionaryExport::Preserve + ); + let arrays = vec![ + dictionary(primitive([0u8]), &[Some("dictionary")])?, + strings(&[Some("plain")]), + dictionary(primitive([0u16]), &[Some("wide")])?, + ]; + let stream = ArrayStreamAdapter::new( + arrays[0].dtype().clone(), + stream::iter(arrays.into_iter().map(Ok)), + ) + .boxed(); + let mut stream = ArrowDeviceArrayStream::new(stream, scan_export_ctx(&session)?, ffi_runtime()); + let mut schema = FFI_ArrowSchema::empty(); + // SAFETY: The stream owns its callbacks and all outputs are writable and released below. + unsafe { + assert_eq!( + stream.get_schema.unwrap()(&raw mut stream, (&raw mut schema).cast()), + 0 + ); + assert_eq!(Field::try_from(&schema)?.data_type(), &DataType::Utf8); + for expected in ["dictionary", "plain", "wide"] { + let mut array = ArrowDeviceArray::empty(); + assert_eq!(stream.get_next.unwrap()(&raw mut stream, &raw mut array), 0); + let _context = synchronize(&array)?; + let values = read_strings(&array.array, &DataType::Utf8)?; + release_device_array(&mut array); + assert_eq!(values, vec![Some(expected.to_owned())]); + } + stream.release.unwrap()(&raw mut stream); + } + Ok(()) +} diff --git a/vortex-cuda/ffi/src/lib.rs b/vortex-cuda/ffi/src/lib.rs index aaec7799d0f..bb28594b414 100644 --- a/vortex-cuda/ffi/src/lib.rs +++ b/vortex-cuda/ffi/src/lib.rs @@ -15,6 +15,7 @@ use std::ptr; use arrow_schema::ffi::FFI_ArrowSchema; use vortex::array::ArrayRef; use vortex::array::stream::ArrayStreamExt; +use vortex::array::stream::SendableArrayStream; use vortex::dtype::FieldName; use vortex::dtype::FieldNames; use vortex::error::VortexResult; @@ -55,6 +56,13 @@ use vortex_ffi::vx_session_new_with; use vortex_ffi::vx_session_ref; use vortex_ffi::vx_view; +mod device_batches; + +pub use device_batches::vx_cuda_device_batches; +pub use device_batches::vx_cuda_device_batches_free; +pub use device_batches::vx_cuda_device_batches_next; +pub use device_batches::vx_cuda_scan_path_device_batches; + const VX_CUDA_OK: c_int = 0; const VX_CUDA_ERR: c_int = 1; @@ -321,15 +329,7 @@ pub unsafe extern "C-unwind" fn vx_cuda_scan_path_arrow_device_stream_projected( ) }; let session = session_with_cuda(session); - let file = ffi_runtime().block_on( - session - .open_options() - .with_cuda() - .with_read_at_options(options.read_at_options) - .open_path(path), - )?; - let scan = projected_scan(&file, columns, options.batch_rows)?; - let array_stream = scan.into_array_stream()?.boxed(); + let array_stream = open_cuda_scan(session, path, options, columns)?; let ctx = scan_export_ctx(session)?; let device_stream = ArrowDeviceArrayStream::new(array_stream, ctx, ffi_runtime()); @@ -339,6 +339,24 @@ pub unsafe extern "C-unwind" fn vx_cuda_scan_path_arrow_device_stream_projected( }) } +fn open_cuda_scan( + session: &VortexSession, + path: &str, + options: CudaScanOptions, + columns: FieldNames, +) -> VortexResult { + let file = ffi_runtime().block_on( + session + .open_options() + .with_cuda() + .with_read_at_options(options.read_at_options) + .open_path(path), + )?; + Ok(projected_scan(&file, columns, options.batch_rows)? + .into_array_stream()? + .boxed()) +} + /// Copy ordered, literal field names, rejecting invalid views and duplicates. Zero selects all. /// /// # Safety From 25f4349aad7fd5557cd7415c9df50e22f7339388 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Fri, 13 Nov 2026 11:28:31 +0000 Subject: [PATCH 002/128] Add Delta decode, probe, filter and take benchmarks (#11429) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR adds benchmarks for the Delta encoding. They are split out of #11428 so that its changes can be measured against `develop`, and #11428 stacks on this PR. ## Changes `encodings/fastlanes/benches/delta_decode.rs` adds 15 benchmarks. **Walltime (9 benchmarks).** `decode_bitpacked_deltas` decodes a 512 KiB Delta array whose deltas are bit-packed, for u16, u32 and u64. It carries `#[cpu_features]`, so it runs on each walltime CPU-feature leg, where the build selects the transpose and decode kernels. **Simulation (6 benchmarks).** These run once each, on 32 KiB arrays so they stay under 1 ms in CodSpeed's simulation, which runs roughly 13× slower than native: - `decode_primitive_deltas` decodes a u32 Delta array whose deltas are a primitive array. - `probe_once` and `probe_repeated` read 8 rows from 2 chunks of a 2048-row array. `probe_once` uses a one-off probe per row; `probe_repeated` reuses one probe for all 8. - `filter` selects one row in every 64, or one in every 4096. - `take` takes 128 scattered rows. --------- Signed-off-by: Robert Kruszewski --- encodings/fastlanes/Cargo.toml | 4 + encodings/fastlanes/benches/delta_decode.rs | 208 ++++++++++++++++++++ scripts/codspeed_bench_counts.json | 1 + 3 files changed, 213 insertions(+) create mode 100644 encodings/fastlanes/benches/delta_decode.rs diff --git a/encodings/fastlanes/Cargo.toml b/encodings/fastlanes/Cargo.toml index c1261092b61..1c4a6d78b02 100644 --- a/encodings/fastlanes/Cargo.toml +++ b/encodings/fastlanes/Cargo.toml @@ -90,6 +90,10 @@ required-features = ["_test-harness"] name = "for_encode" harness = false +[[bench]] +name = "delta_decode" +harness = false + [[bench]] name = "for_decode" harness = false diff --git a/encodings/fastlanes/benches/delta_decode.rs b/encodings/fastlanes/benches/delta_decode.rs new file mode 100644 index 00000000000..095f945ac1a --- /dev/null +++ b/encodings/fastlanes/benches/delta_decode.rs @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Benchmarks decoding and reading a Delta array. +//! +//! - `decode_bitpacked_deltas` decodes a Delta array whose deltas are bit-packed, and +//! `decode_primitive_deltas` one whose deltas are a primitive array. +//! - The probe benchmarks read 8 single rows from two chunks, through a one-off probe for each +//! row or through one repeated probe. +//! - `filter` selects one row in `stride`, and `take` takes scattered rows. +//! +//! Only `decode_bitpacked_deltas` carries `#[cpu_features]`, so it is measured on each walltime +//! CPU-feature leg: the build decides which transpose and decode kernels it runs. The others are +//! measured once, in simulation, on smaller arrays. +//! +//! Run with `cargo bench -p vortex-fastlanes --bench delta_decode`. + +#![expect(clippy::unwrap_used)] + +use std::sync::LazyLock; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::memory::MemorySession; +use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::session::ArraySession; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_fastlanes::BitPacked; +use vortex_fastlanes::Delta; +use vortex_fastlanes::DeltaArray; +use vortex_fastlanes::DeltaArraySlotsExt; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + LazyLock::force(&SESSION); + divan::main(); +} + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty() + .with::() + .with::() + .with::() + .with::(); + vortex_fastlanes::initialize(&session); + session +}); + +/// Bytes of values per input array of the walltime decode benchmark. +const INPUT_BYTES: &[usize] = &[512 * 1024]; + +/// Bytes of values per input array of the simulation benchmarks: eight chunks of `u32`, which +/// keeps each under a millisecond in simulation. +const SIMULATION_BYTES: usize = 32 * 1024; + +/// Enough bits for the deltas between consecutive values. +const BIT_WIDTH: u8 = 4; + +/// Increasing values whose consecutive deltas are below 16, wrapping around at the width of `T`. +fn values>(len: usize) -> Buffer { + let mask = usize::MAX >> (usize::BITS as usize - 8 * size_of::()); + (0..len) + .scan(0usize, |acc, i| { + *acc = acc.wrapping_add((i * 7919) % 16); + Some(T::try_from(*acc & mask).ok().unwrap()) + }) + .collect() +} + +fn delta_bitpacked>(len: usize) -> DeltaArray { + let mut ctx = SESSION.create_execution_ctx(); + let array = PrimitiveArray::new(values::(len), Validity::NonNullable); + let delta = Delta::try_from_primitive_array(&array, &mut ctx).unwrap(); + let packed = BitPacked::encode(delta.deltas(), BIT_WIDTH, &mut ctx).unwrap(); + Delta::try_new( + delta.bases().clone(), + packed.into_array(), + Validity::NonNullable, + 0, + len, + ) + .unwrap() +} + +#[vortex_bench_support::cpu_features] +#[divan::bench(types = [u16, u32, u64], args = INPUT_BYTES)] +fn decode_bitpacked_deltas>(bencher: Bencher, bytes: usize) { + let len = bytes / size_of::(); + let array = delta_bitpacked::(len).into_array(); + bencher + .counter(ItemsCount::new(len)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +#[divan::bench] +fn decode_primitive_deltas(bencher: Bencher) { + let len = SIMULATION_BYTES / size_of::(); + let mut ctx = SESSION.create_execution_ctx(); + let array = PrimitiveArray::new(values::(len), Validity::NonNullable); + let array = Delta::try_from_primitive_array(&array, &mut ctx) + .unwrap() + .into_array(); + bencher + .counter(ItemsCount::new(len)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| (*array).clone().execute::(ctx).unwrap()); +} + +/// Rows in the arrays the probe benchmarks read: two chunks. +const PROBE_LEN: usize = 2048; + +/// Rows the probe benchmarks read, in order: every 256th row, four in each chunk. +fn probe_rows() -> impl Iterator { + (0..PROBE_LEN).step_by(256) +} + +/// Reads each row with a one-off probe. +#[divan::bench] +fn probe_once(bencher: Bencher) { + let array = delta_bitpacked::(PROBE_LEN).into_array(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + for index in probe_rows() { + divan::black_box(array.probe().execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// Reads each row through one repeated probe. +#[divan::bench] +fn probe_repeated(bencher: Bencher) { + let array = delta_bitpacked::(PROBE_LEN).into_array(); + bencher + .counter(ItemsCount::new(probe_rows().count())) + .with_inputs(|| (array.repeated_probe(), SESSION.create_execution_ctx())) + .bench_refs(|(probe, ctx)| { + for index in probe_rows() { + divan::black_box(probe.execute_scalar(index, ctx).unwrap()); + } + }); +} + +/// A u32 Delta array of `SIMULATION_BYTES` over bit-packed deltas. +fn delta_bitpacked_u32() -> ArrayRef { + delta_bitpacked::(SIMULATION_BYTES / size_of::()).into_array() +} + +/// A mask that selects one row in `stride`. +fn strided_mask(len: usize, stride: usize) -> Mask { + Mask::from_indices(len, (0..len).step_by(stride)) +} + +/// Filters the Delta array. +#[divan::bench(args = [64, 4096])] +fn filter(bencher: Bencher, stride: usize) { + let array = delta_bitpacked_u32(); + let mask = strided_mask(array.len(), stride); + bencher + .counter(ItemsCount::new(array.len())) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + (*array) + .clone() + .filter(mask.clone()) + .unwrap() + .execute::(ctx) + .unwrap() + }); +} + +/// `count` indices scattered over `len` rows, in no particular order. +fn scattered_indices(len: usize, count: usize) -> ArrayRef { + PrimitiveArray::from_iter((0..count).map(|i| u32::try_from((i * 7919 + 13) % len).unwrap())) + .into_array() +} + +/// Takes from the Delta array. +#[divan::bench(args = [128])] +fn take(bencher: Bencher, count: usize) { + let array = delta_bitpacked_u32(); + let indices = scattered_indices(array.len(), count); + bencher + .counter(ItemsCount::new(count)) + .with_inputs(|| (&array, SESSION.create_execution_ctx())) + .bench_refs(|(array, ctx)| { + (*array) + .clone() + .take(indices.clone()) + .unwrap() + .execute::(ctx) + .unwrap() + }); +} diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index 8b7757be5ea..1b11f4e872e 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -121,6 +121,7 @@ "canonicalize_bench": 14, "cast_bitpacked": 6, "compute_between": 11, + "delta_decode": 6, "for_decode": 0, "for_encode": 0 }, From a41881952477b6867b0326d67fa65bde0fbfd89c Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 13:12:29 +0000 Subject: [PATCH 003/128] Add changelog/edition label for edition changes (#11440) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Each change to an edition (adding, moving, or removing a member, or freezing an edition) should go in its own PR and show up separately in the release notes. This adds a dedicated `changelog/edition` label. The label check already requires exactly one `changelog/*` label, so an edition PR can't also be labelled as a feature or fix. ## Changes - `.github/workflows/labels.yml`: accept `changelog/edition` as a changelog label. - `.github/release-drafter.yml`: add a "📜 Editions" release-notes section after "Breaks", and make `changelog/edition` trigger a minor version bump, the same as `changelog/feature` and `changelog/break`. - `docs/specs/versioning/editions.md`: under "Maintaining edition records", say that each edition change goes in its own PR labelled `changelog/edition`. - `.github/pull_request_template.md`: add a matching reminder next to the `changelog/break` note. The `changelog/edition` label still needs to be created in the repository's label settings before it can be applied. --------- Signed-off-by: Joe Isaacs --- .github/pull_request_template.md | 2 ++ .github/release-drafter.yml | 4 ++++ .github/workflows/labels.yml | 1 + docs/specs/versioning/editions.md | 4 ++++ 4 files changed, 11 insertions(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8c6f83c93ed..a5f3726098c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -18,4 +18,6 @@ Summarize what changed and why, calling out the important parts when the PR span ## API Changes Uncomment this section if there are user-facing changes, such as a broken public API or a change in the behavior of an engine integration. A breaking change also needs the `changelog/break` label. + +A change to an edition's membership or freeze belongs in its own PR with the `changelog/edition` label. --> diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 6c8589e3fef..89ca41e2e33 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -1,6 +1,9 @@ name-template: "$RESOLVED_VERSION" tag-template: "$RESOLVED_VERSION" categories: + - title: "📜 Editions" + labels: + - "changelog/edition" - title: "⚠️ Breaks" labels: - "changelog/break" @@ -36,6 +39,7 @@ version-resolver: # Any features or breaks will trigger a minor version bump (while we are 0.x) - "changelog/feature" - "changelog/break" + - "changelog/edition" default: patch exclude-labels: diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml index 776a0912a9e..ce477667625 100644 --- a/.github/workflows/labels.yml +++ b/.github/workflows/labels.yml @@ -35,6 +35,7 @@ jobs: run: | REQUIRED_LABELS=( "changelog/break" + "changelog/edition" "changelog/deprecation" "changelog/feature" "changelog/performance" diff --git a/docs/specs/versioning/editions.md b/docs/specs/versioning/editions.md index 010d11e5421..860e800a4fc 100644 --- a/docs/specs/versioning/editions.md +++ b/docs/specs/versioning/editions.md @@ -154,6 +154,10 @@ writers from choosing it, but readers must retain support because existing files ## Maintaining edition records +Each change to an edition, such as adding, moving, or removing a member or freezing an edition, goes +in its own pull request labeled `changelog/edition`, so it appears under its own heading in the +release notes. + Default declarations live in `vortex-edition/src/declarations/`. Optional modules keep declarations with their implementation code. The exported TOML records are under `vortex/editions/`, grouped by family. From 6480845399230f96159cf53d721d041f4dab9352 Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 13:12:39 +0000 Subject: [PATCH 004/128] fix(array): treat bool nulls as sorting first in non-strict is_sorted (#11437) ## Summary `IsSorted` orders nulls first. The non-strict branch of the bool kernel (`check_bool_sorted`) broke that rule: it walked only the indices of valid values, so it dropped nulls instead of ordering them first. The strict branch already handled nulls correctly. It maps each element to `Option`, where `None < Some(_)`, which is what the primitive kernel does in both modes. Two counterexamples showed the bug before this fix: 1. `BoolArray [false, null, true]` reported sorted, but the equivalent `PrimitiveArray [0, null, 1]` reported not sorted. 2. `BoolArray [true, null]` reported sorted, but the same values split into the `ChunkedArray` chunks `[true]` and `[null]` reported not sorted. The accumulator's check at the chunk boundary already sees a valid value followed by a null. --- .../src/aggregate_fn/fns/is_sorted/bool.rs | 29 +++++--------- .../src/aggregate_fn/fns/is_sorted/mod.rs | 40 +++++++++++++++++++ 2 files changed, 51 insertions(+), 18 deletions(-) diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs b/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs index 69c0aaf6692..27a67c400d1 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs @@ -29,25 +29,18 @@ pub(super) fn check_bool_sorted( }) } Mask::Values(mask_values) => { - if strict { - let validity_buffer = mask_values.bit_buffer(); - let values = array.bit_buffer_view(); - Ok(validity_buffer - .iter() - .zip(values.iter()) - .map(|(is_valid, value)| is_valid.then_some(value)) - .is_strict_sorted()) + // Nulls sort first, so map each element to `Option` where `None < Some(_)`. + let values = array.bit_buffer_view(); + let iter = mask_values + .bit_buffer() + .iter() + .zip(values.iter()) + .map(|(is_valid, value)| is_valid.then_some(value)); + Ok(if strict { + iter.is_strict_sorted() } else { - let set_indices = mask_values.bit_buffer().set_indices(); - let values = array.bit_buffer_view(); - let values_iter = set_indices.map(|idx| - // Safety: - // All idxs are in-bounds for the array. - unsafe { - values.value_unchecked(idx) - }); - Ok(values_iter.is_sorted()) - } + iter.is_sorted() + }) } } } diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs index f1f951c08ba..cce3f7fc982 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs @@ -977,4 +977,44 @@ mod tests { assert_arrays_eq!(acc.finish()?, BoolArray::from_iter(expected), &mut ctx); Ok(()) } + + /// A bool array must agree with the equivalent integer array: nulls sort first, so a null + /// after a valid value is unsorted. + #[rstest] + #[case::null_between_values([Some(false), None, Some(true)])] + #[case::null_first([None, Some(false), Some(true)])] + #[case::null_last([Some(false), Some(true), None])] + fn bool_nulls_sort_first_like_primitive(#[case] values: [Option; 3]) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let bools = BoolArray::from_iter(values).into_array(); + let ints = PrimitiveArray::from_option_iter(values.map(|v| v.map(i32::from))).into_array(); + + let expected = values[1..].iter().all(|v| v.is_some()); + assert_eq!(is_sorted(&ints, &mut ctx)?, expected); + assert_eq!(is_sorted(&bools, &mut ctx)?, expected); + assert_eq!( + is_strict_sorted(&bools, &mut ctx)?, + is_strict_sorted(&ints, &mut ctx)? + ); + Ok(()) + } + + /// Splitting a bool array into chunks must not change the non-strict verdict. + #[test] + fn bool_valid_then_null_matches_chunked() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let flat = BoolArray::from_iter([Some(true), None]).into_array(); + let chunked = ChunkedArray::try_new( + vec![ + BoolArray::from_iter([Some(true)]).into_array(), + BoolArray::from_iter([None::]).into_array(), + ], + flat.dtype().clone(), + )? + .into_array(); + + assert!(!is_sorted(&flat, &mut ctx)?); + assert!(!is_sorted(&chunked, &mut ctx)?); + Ok(()) + } } From 7f07d78ffe9240702374ca09ce4fd20f6471b3dc Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 14:02:03 +0000 Subject: [PATCH 005/128] ci: upload sampled vx file trees from SQL benchmarks (#11444) ## Summary The SQL benchmarks write Vortex files that we never look inside. This PR adds one artifact per run containing `vx` file stats and layout trees for a sample of each dataset's files, so you can see which encodings and layouts a PR produced on real data. The full trees are too large for logs: hundreds of thousands of lines for ClickBench and the SF100 datasets. So every file is dumped on the runner, but only a sample within a line budget is kept, and the kept dumps from all jobs are merged into one zip retained for 5 days. --- .github/workflows/ci.yml | 3 +- .github/workflows/sql-bench-matrix.yml | 53 ++++++- scripts/sample-file-trees.py | 181 ++++++++++++++++++++++++ scripts/tests/test_sample_file_trees.py | 107 ++++++++++++++ 4 files changed, 342 insertions(+), 2 deletions(-) create mode 100755 scripts/sample-file-trees.py create mode 100644 scripts/tests/test_sample_file_trees.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f6588178bd..f06b66ed11c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -107,7 +107,8 @@ jobs: pytest scripts/tests/test_measurement_id.py \ scripts/tests/test_benchmark_reporting.py scripts/tests/test_post_ingest.py \ scripts/tests/test_refresh_bench_site.py \ - scripts/tests/test_codspeed_shards.py + scripts/tests/test_codspeed_shards.py \ + scripts/tests/test_sample_file_trees.py python-test: name: "Python (test)" diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index c5eaeff4c26..97148cce449 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -70,7 +70,7 @@ jobs: env: RUSTFLAGS: "-C target-cpu=native -C force-frame-pointers=yes" run: | - packages=(--bin data-gen --bin datafusion-bench --bin duckdb-bench) + packages=(--bin data-gen --bin datafusion-bench --bin duckdb-bench --bin vx) if [ "${{ inputs.mode }}" != "pr" ]; then packages+=(--bin lance-bench) fi @@ -85,6 +85,7 @@ jobs: target/release_debug/datafusion-bench target/release_debug/duckdb-bench target/release_debug/lance-bench + target/release_debug/vx target/release_debug/build/vortex-duckdb-cache/duckdb-lib-*-prebuilt/libduckdb.so - name: Pre-upload SQL benchmark debuginfo to Polar Signals if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false @@ -247,6 +248,31 @@ jobs: -o sizes.json cat sizes.json >> results.json + # Footer stats and layout trees of a sample of the dataset's Vortex files: every file is + # dumped, then one file of every table is kept, plus more partitions weighted by size up to a + # line budget. Observability only, so it never fails the benchmark or holds up its job. + - name: Dump sampled file trees + if: ${{ !cancelled() && matrix.remote_key == null }} + continue-on-error: true + timeout-minutes: 20 + shell: bash + run: | + uv run --no-project scripts/sample-file-trees.py \ + vortex-bench/data/${{ matrix.dataset_dir }} \ + --vx target/release_debug/vx \ + --seed ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ + -o file-trees + + - name: Upload sampled file trees + if: ${{ !cancelled() && matrix.remote_key == null }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: file-trees-${{ inputs.matrix_preset }}-${{ matrix.id }} + path: file-trees/ + retention-days: 5 + if-no-files-found: ignore + - name: Fetch baseline from the benchmarks database if: inputs.mode == 'pr' uses: ./.github/actions/fetch-bench-baseline @@ -327,3 +353,28 @@ jobs: api-key: ${{ secrets.INCIDENT_IO_ALERT_TOKEN }} alert-title: "${{ matrix.name }} SQL benchmark failed on develop" deduplication-key: ci-sql-bench-${{ matrix.id }}-failure + + # Merge every bench job's sampled file trees into one artifact, one directory per job, so a run + # has a single zip to download. + merge-file-trees: + needs: bench + if: ${{ !cancelled() }} + timeout-minutes: 10 + runs-on: >- + ${{ github.repository == 'vortex-data/vortex' + && format('runs-on={0}/region=us-east-1/runner=amd64-ci-small/image=ubuntu26-full-x64-pre-v2/tag=merge-file-trees{1}', github.run_id, (inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false) && '/extras=s3-cache' || '') + || 'ubuntu-latest' }} + steps: + # `extras=s3-cache` points the artifact API at the RunsOn proxy, which only this action wires + # up; without it the merge cannot list the bench jobs' artifacts. + - uses: runs-on/action@v2 + if: inputs.mode != 'pr' || github.event.pull_request.head.repo.fork == false + - name: Merge sampled file trees + continue-on-error: true + uses: actions/upload-artifact/merge@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: file-trees-${{ inputs.matrix_preset }} + pattern: file-trees-${{ inputs.matrix_preset }}-* + separate-directories: true + delete-merged: true + retention-days: 5 diff --git a/scripts/sample-file-trees.py b/scripts/sample-file-trees.py new file mode 100755 index 00000000000..1f00fe46f26 --- /dev/null +++ b/scripts/sample-file-trees.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = [] +# /// + +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +"""Dump `vx` file stats and layout trees for a sample of a benchmark's Vortex files. + +A benchmark dataset can hold hundreds of files, and the full tree of every one is far too large +to keep. Every file is dumped first, so the sample is chosen from the real line counts rather than +an estimate. Per Vortex format directory, the files kept are: + +1. One file of every table. Partitions of a table (`lineitem_0001.vortex`, `lineitem_0002.vortex`, + `hits_17.vortex`) share a table name; one partition per table is drawn at random, weighted by + file size in bytes. These are always kept, even past the line budget. +2. Further partitions in a random order weighted by file size in bytes, each kept if its dump + still fits in the remaining line budget, so the larger partitions that dominate the dataset are + more likely to be inspected. + +The default budget of 200,000 lines is about 2 MB zipped (a line costs ~11 bytes). It keeps every +file of the SF1 and SF10 datasets and samples the larger ones, such as ClickBench's 100 files +(~225,000 lines) and the SF100 datasets. + +The draw is seeded (by default with the commit), so reruns of a commit keep the same files. +`manifest.json` lists every file with its line count and whether its dump was kept. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import random +import re +import shutil +import subprocess +import sys +import tempfile +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from pathlib import Path + +FORMAT_DIRS = ("vortex-file-compressed", "vortex-compact") + +# Trailing partition index: `lineitem_0001`, `hits_17`, `part-3`. +PARTITION_SUFFIX = re.compile(r"[_-]\d+$") + + +@dataclass(frozen=True) +class VortexFile: + path: Path + size: int + lines: int = 0 + + @property + def table(self) -> str: + return table_name(self.path) + + +def table_name(path: Path) -> str: + """The table a file belongs to: its stem without a trailing partition index.""" + return PARTITION_SUFFIX.sub("", path.stem) + + +def weighted_order(files: list[VortexFile], rng: random.Random) -> list[VortexFile]: + """A random order of `files` in which each next file is drawn with probability proportional + to its size, i.e. a weighted sample without replacement of all of them. + + Uses Efraimidis-Spirakis keys `u ** (1 / w)`, compared as `log(u) / w` so that weights of + many gigabytes keep their precision. Zero-byte files get a minimal weight so they still come + last rather than never. + """ + keyed = [(math.log(1.0 - rng.random()) / max(f.size, 1), f) for f in files] + keyed.sort(key=lambda kf: kf[0], reverse=True) + return [f for _, f in keyed] + + +def sample_files(files: list[VortexFile], max_lines: int, rng: random.Random) -> list[VortexFile]: + """One file per table, then size-weighted further files while they fit in `max_lines`.""" + by_table: dict[str, list[VortexFile]] = {} + for f in sorted(files, key=lambda f: f.path): + by_table.setdefault(f.table, []).append(f) + + chosen = [weighted_order(by_table[table], rng)[0] for table in sorted(by_table)] + budget = max_lines - sum(f.lines for f in chosen) + + chosen_paths = {f.path for f in chosen} + remaining = [f for f in sorted(files, key=lambda f: f.path) if f.path not in chosen_paths] + for f in weighted_order(remaining, rng): + if f.lines <= budget: + chosen.append(f) + budget -= f.lines + return sorted(chosen, key=lambda f: f.path) + + +def run_vx(vx: str, args: list[str]) -> str: + result = subprocess.run([vx, *args], capture_output=True, text=True) + if result.returncode != 0: + return f"`vx {' '.join(args)}` failed with exit code {result.returncode}:\n{result.stderr}" + return result.stdout + + +def dump_file(vx: str, file: Path, output: Path) -> int: + """Write the stats and trees of one file to `output`, returning the number of lines.""" + sections = [ + ("vx inspect", ["inspect", str(file)]), + ("vx tree layout --verbose", ["tree", "layout", "--verbose", str(file)]), + ] + text = "".join(f"===== {title} {file} =====\n{run_vx(vx, args)}\n" for title, args in sections) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(text) + return text.count("\n") + + +def find_format_dirs(dataset_dir: Path) -> list[Path]: + return sorted(d for d in dataset_dir.rglob("*") if d.is_dir() and d.name in FORMAT_DIRS) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("dataset_dir", type=Path, help="Benchmark data directory, e.g. vortex-bench/data/tpch") + parser.add_argument("-o", "--output", type=Path, required=True, help="Directory to write the kept dumps to") + parser.add_argument("--vx", default="vx", help="Path to the vx binary") + parser.add_argument( + "--max-lines", + type=int, + default=200_000, + help="Line budget per format directory; one file per table is kept even past it (default: 200000)", + ) + parser.add_argument("--jobs", type=int, default=os.cpu_count() or 1, help="Files to dump in parallel") + parser.add_argument("--seed", default="0", help="Seed for the draw, e.g. the commit SHA") + args = parser.parse_args() + + if not args.dataset_dir.is_dir(): + print(f"Dataset directory not found: {args.dataset_dir}", file=sys.stderr) + sys.exit(1) + + manifest = [] + with tempfile.TemporaryDirectory() as staging_dir: + staging = Path(staging_dir) + for format_dir in find_format_dirs(args.dataset_dir): + paths = sorted(p for p in format_dir.rglob("*.vortex") if p.is_file()) + if not paths: + continue + + def dump(path: Path) -> VortexFile: + rel = path.relative_to(args.dataset_dir) + lines = dump_file(args.vx, path, staging / rel.with_suffix(".txt")) + return VortexFile(path, path.stat().st_size, lines) + + with ThreadPoolExecutor(max_workers=args.jobs) as pool: + files = list(pool.map(dump, paths)) + + rng = random.Random(f"{args.seed}:{format_dir.relative_to(args.dataset_dir)}") + kept = {f.path for f in sample_files(files, args.max_lines, rng)} + print( + f"{format_dir}: kept {len(kept)} of {len(files)} files " + f"({len({f.table for f in files})} tables, {sum(f.size for f in files):,} bytes), " + f"{sum(f.lines for f in files if f.path in kept):,} of {sum(f.lines for f in files):,} lines" + ) + for f in files: + rel = f.path.relative_to(args.dataset_dir) + if f.path in kept: + dest = args.output / rel.with_suffix(".txt") + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.move(staging / rel.with_suffix(".txt"), dest) + print(f" {rel} {f.size:>15,} bytes {f.lines:>8,} lines") + manifest.append( + {"file": str(rel), "table": f.table, "bytes": f.size, "lines": f.lines, "kept": f.path in kept} + ) + + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_sample_file_trees.py b/scripts/tests/test_sample_file_trees.py new file mode 100644 index 00000000000..01df25f0009 --- /dev/null +++ b/scripts/tests/test_sample_file_trees.py @@ -0,0 +1,107 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright the Vortex contributors + +import importlib.util +import random +import sys +from collections import Counter +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "scripts" / "sample-file-trees.py" + + +def load_module() -> ModuleType: + spec = importlib.util.spec_from_file_location("sample_file_trees", SCRIPT) + assert spec is not None + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + # `dataclass` resolves annotations through `sys.modules`. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +sft = load_module() + + +def files(*specs: tuple[str, int, int]) -> list[Any]: + """`(name, bytes, lines)` triples as `VortexFile`s.""" + return [sft.VortexFile(Path(name), size, lines) for name, size, lines in specs] + + +# File names as the vortex-bench data generators write them; Vortex files keep the Parquet stem. +@pytest.mark.parametrize( + ("file_name", "table"), + [ + # TPC-H, TPC-DS and nested TPC-H: `split::part_file_name`, `{table}_{part:04}`. + ("lineitem_0001.vortex", "lineitem"), + ("lineitem_0012.vortex", "lineitem"), + ("customer_0001.vortex", "customer"), + ("customer_address_0001.vortex", "customer_address"), + ("store_sales_0042.vortex", "store_sales"), + # ClickBench: one file, partitioned `hits_{idx}`, or sorted shards `hits_{idx:03}`. + ("hits.vortex", "hits"), + ("hits_17.vortex", "hits"), + ("hits_017.vortex", "hits"), + # Single-file datasets and unsplit tables: the whole stem. + ("sample.vortex", "sample"), + ("stacktraces.vortex", "stacktraces"), + ("gnomad.genomes.v3.1.2.hgdp_tgp.chr21.vortex", "gnomad.genomes.v3.1.2.hgdp_tgp.chr21"), + ("movie_info_idx.vortex", "movie_info_idx"), + ("orderitemnovelty_update.vortex", "orderitemnovelty_update"), + ("test.vortex", "test"), + ], +) +def test_table_name_matches_generated_files(file_name: str, table: str): + assert sft.table_name(Path(file_name)) == table + + +def test_sample_keeps_one_file_per_table_then_fills_the_line_budget(): + dataset = files( + ("nation.vortex", 10, 50), + ("region.vortex", 10, 40), + *((f"lineitem_{i:04}.vortex", 1000, 1700) for i in range(1, 11)), + *((f"orders_{i:04}.vortex", 500, 1500) for i in range(1, 5)), + ) + # The four per-table files take 3,290 lines; 3,500 more fit two further partitions. + sample = sft.sample_files(dataset, 3290 + 3500, random.Random(0)) + + tables = Counter(f.table for f in sample) + assert set(tables) == {"nation", "region", "lineitem", "orders"} + assert sum(tables.values()) == 4 + 2 + assert sum(f.lines for f in sample) <= 3290 + 3500 + assert len({f.path for f in sample}) == len(sample) + + +def test_sample_keeps_every_table_past_the_budget(): + dataset = files(("a_1.vortex", 10, 500), ("a_2.vortex", 10, 500), ("b.vortex", 10, 500)) + assert {f.table for f in sft.sample_files(dataset, 100, random.Random(0))} == {"a", "b"} + + +def test_sample_skips_a_file_too_large_for_the_budget_and_takes_smaller_ones(): + # `t_1` dwarfs the others, so it is drawn as the table's file; `t_2` then exceeds the budget. + dataset = files(("t_1.vortex", 10**12, 1), ("t_2.vortex", 10**9, 1000), ("t_3.vortex", 1, 10)) + sample = sft.sample_files(dataset, 20, random.Random(0)) + assert [f.path.name for f in sample] == ["t_1.vortex", "t_3.vortex"] + + +def test_sample_takes_everything_within_budget(): + dataset = files(("a_1.vortex", 1, 5), ("a_2.vortex", 2, 5), ("b.vortex", 0, 5)) + assert len(sft.sample_files(dataset, 100, random.Random(0))) == 3 + + +def test_sample_is_deterministic_for_a_seed(): + dataset = files(*((f"hits_{i}.vortex", i + 1, 100) for i in range(100))) + assert sft.sample_files(dataset, 900, random.Random("abc")) == sft.sample_files(dataset, 900, random.Random("abc")) + + +def test_weighted_order_puts_large_files_first(): + dataset = files(("big.vortex", 1_000_000_000, 1), ("small.vortex", 1_000, 1)) + rng = random.Random(0) + picks = Counter(sft.weighted_order(dataset, rng)[0].path.name for _ in range(1000)) + assert picks["big.vortex"] > 990 From e780b531765fd9648769e284fccace9309431f9d Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 14:04:53 +0000 Subject: [PATCH 006/128] feat: harden `delta` serde ahead of format stabilization (#11441) ## Summary `fastlanes.delta` is still only in the unstable edition. This PR fixes its serialized contract before it is frozen. A review of Delta's serde found two problems: - **Validity is inferred from the child count.** A third child is always read as validity, so the format can't add a child later without it being mistaken for validity. - **The reader is not robust to corrupt input.** - A float dtype panics in `lane_count` before `validate_parts` runs. - `deltas_len` is not tied to `len`, so a tiny array with constant children can claim an unbounded physical length and force a huge allocation on decode. --------- Signed-off-by: Joe Isaacs --- .../fastlanes/goldenfiles/delta.metadata | 2 +- .../src/delta/array/delta_decompress.rs | 2 +- encodings/fastlanes/src/delta/tests.rs | 158 ++++++++++++++++-- encodings/fastlanes/src/delta/vtable/mod.rs | 22 ++- .../fastlanes/src/delta/vtable/plugin.rs | 59 +++++-- 5 files changed, 210 insertions(+), 33 deletions(-) diff --git a/encodings/fastlanes/goldenfiles/delta.metadata b/encodings/fastlanes/goldenfiles/delta.metadata index be82cf2c4ca..8e6816cd2af 100644 --- a/encodings/fastlanes/goldenfiles/delta.metadata +++ b/encodings/fastlanes/goldenfiles/delta.metadata @@ -1 +1 @@ -ÿÿÿÿÿÿÿÿÿÿÿÿÿ \ No newline at end of file +ÿÿÿÿÿÿÿÿÿÿÿÿÿ \ No newline at end of file diff --git a/encodings/fastlanes/src/delta/array/delta_decompress.rs b/encodings/fastlanes/src/delta/array/delta_decompress.rs index 4bddbff66d1..44d166dd39f 100644 --- a/encodings/fastlanes/src/delta/array/delta_decompress.rs +++ b/encodings/fastlanes/src/delta/array/delta_decompress.rs @@ -59,7 +59,7 @@ where T: NativePType + Delta + Transpose, { let (chunks, remainder) = deltas.as_chunks::<1024>(); - debug_assert!( + assert!( remainder.is_empty(), "deltas must be padded to a multiple of 1024" ); diff --git a/encodings/fastlanes/src/delta/tests.rs b/encodings/fastlanes/src/delta/tests.rs index 37bc80e8e00..09a2a6bfaad 100644 --- a/encodings/fastlanes/src/delta/tests.rs +++ b/encodings/fastlanes/src/delta/tests.rs @@ -3,11 +3,15 @@ //! Delta roundtrips and compute operations against primitive arrays. +use prost::Message; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; use rstest::rstest; use vortex_array::ArrayContext; +use vortex_array::ArrayDeserialization; +use vortex_array::ArrayPlugin; +use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -15,7 +19,9 @@ use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::match_each_integer_ptype; use vortex_array::serde::SerializeOptions; @@ -31,9 +37,11 @@ use vortex_session::registry::ReadContext; use crate::Delta; use crate::DeltaArray; +use crate::DeltaArrayExt; use crate::DeltaArraySlotsExt; use crate::FL_CHUNK_SIZE; use crate::bitpack_compress::bitpack_encode; +use crate::delta::vtable::DeltaMetadata; fn session() -> VortexSession { let session = VortexSession::empty(); @@ -41,6 +49,20 @@ fn session() -> VortexSession { session } +fn serde_roundtrip(array: &ArrayRef, session: &VortexSession) -> VortexResult { + let write_ctx = ArrayContext::empty(); + let mut bytes = ByteBufferMut::empty(); + for buffer in array.serialize(&write_ctx, session, &SerializeOptions::default())? { + bytes.extend_from_slice(&buffer); + } + SerializedArray::try_from(bytes.freeze())?.decode( + array.dtype(), + array.len(), + &ReadContext::new(write_ctx.to_ids()), + session, + ) +} + fn check_roundtrip(source: &PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult { let delta = Delta::try_from_primitive_array(source, ctx)?; assert!(matches!(delta.bases().validity()?, Validity::NonNullable)); @@ -122,17 +144,7 @@ fn delta_null_patterns(#[case] pattern: usize) -> VortexResult<()> { assert_arrays_eq!(packed, source, &mut ctx); for array in [delta.into_array(), packed.into_array()] { - let write_ctx = ArrayContext::empty(); - let mut bytes = ByteBufferMut::empty(); - for buffer in array.serialize(&write_ctx, &session, &SerializeOptions::default())? { - bytes.extend_from_slice(&buffer); - } - let restored = SerializedArray::try_from(bytes.freeze())?.decode( - array.dtype(), - array.len(), - &ReadContext::new(write_ctx.to_ids()), - &session, - )?; + let restored = serde_roundtrip(&array, &session)?; let restored_delta = restored .as_opt::() .ok_or_else(|| vortex_err!("expected deserialized Delta"))?; @@ -257,3 +269,127 @@ fn delta_rejects_invalid_top_validity() -> VortexResult<()> { } Ok(()) } + +/// A nullable signed array sliced to a non-zero offset round-trips through serde. +#[test] +fn delta_serde_sliced_signed() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let len = 3000; + let source = PrimitiveArray::from_option_iter( + (0..len).map(|index| (index % 7 != 0).then_some(index as i64 * -3 + 500)), + ); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let (offset, sliced_len) = (1000, 2000); + let sliced = Delta::try_new( + delta.bases().clone(), + delta.deltas().clone(), + Validity::from_iter((offset..offset + sliced_len).map(|index| index % 7 != 0)), + offset, + sliced_len, + )? + .into_array(); + + let restored = serde_roundtrip(&sliced, &session)?; + let restored_delta = restored + .as_opt::() + .ok_or_else(|| vortex_err!("expected deserialized Delta"))?; + assert_eq!(restored_delta.offset(), offset); + assert_arrays_eq!( + restored, + source.slice(offset..offset + sliced_len)?, + &mut ctx + ); + Ok(()) +} + +/// Serializing rejects an array whose deltas extend past the chunk holding its last value. +#[test] +fn delta_serialize_rejects_trailing_chunks() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let source = PrimitiveArray::from_iter(0..2048u32); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let truncated = Delta::try_new( + delta.bases().clone(), + delta.deltas().clone(), + Validity::NonNullable, + 0, + 10, + )? + .into_array(); + assert!(serde_roundtrip(&truncated, &session).is_err()); + Ok(()) +} + +#[test] +fn delta_deserialize_rejects_malformed_parts() -> VortexResult<()> { + let session = session(); + let mut ctx = session.create_execution_ctx(); + let len = 1500; + let source = PrimitiveArray::from_option_iter( + (0..len).map(|index| (index % 3 != 0).then_some(index as u32)), + ); + let delta = Delta::try_from_primitive_array(&source, &mut ctx)?; + let bases = delta.bases().clone(); + let deltas = delta.deltas().clone(); + let validity = delta + .validity_child() + .ok_or_else(|| vortex_err!("expected a validity child"))? + .clone(); + let metadata = DeltaMetadata { + deltas_len: 2048, + offset: 0, + has_validity: true, + }; + let dtype = source.dtype().clone(); + let deserialize = |dtype: &DType, metadata: &DeltaMetadata, children: &[ArrayRef]| { + Delta.deserialize( + ArrayDeserialization::new( + ArrayPlugin::id(&Delta), + dtype, + len, + &metadata.encode_to_vec(), + &[], + &children, + ), + &session, + ) + }; + let all = [bases.clone(), deltas.clone(), validity.clone()]; + + let restored = deserialize(&dtype, &metadata, &all)?; + assert_arrays_eq!(restored, source, &mut ctx); + + // Readers ignore children that follow the ones the metadata declares. + let with_trailing = [bases.clone(), deltas.clone(), validity, bases.clone()]; + let restored = deserialize(&dtype, &metadata, &with_trailing)?; + assert_arrays_eq!(restored, source, &mut ctx); + + // The metadata declares a validity child that is missing. + assert!(deserialize(&dtype, &metadata, &[bases, deltas]).is_err()); + + // A validity child on a non-nullable dtype. + assert!(deserialize(&dtype.as_nonnullable(), &metadata, &all).is_err()); + + // A non-integer dtype. + let float = DType::Primitive(PType::F32, Nullability::Nullable); + assert!(deserialize(&float, &metadata, &all).is_err()); + + // The offset must lie in the first chunk. + let offset_past_chunk = DeltaMetadata { + offset: 1024, + ..metadata + }; + assert!(deserialize(&dtype, &offset_past_chunk, &all).is_err()); + + // The deltas length must be exactly (offset + len) rounded up to a whole chunk. + for deltas_len in [0, 1024, 2000, 3072, u64::MAX] { + let wrong_len = DeltaMetadata { + deltas_len, + ..metadata + }; + assert!(deserialize(&dtype, &wrong_len, &all).is_err()); + } + Ok(()) +} diff --git a/encodings/fastlanes/src/delta/vtable/mod.rs b/encodings/fastlanes/src/delta/vtable/mod.rs index 28c78653646..8d2d546ce14 100644 --- a/encodings/fastlanes/src/delta/vtable/mod.rs +++ b/encodings/fastlanes/src/delta/vtable/mod.rs @@ -52,13 +52,26 @@ mod validity; /// A [`Delta`]-encoded Vortex array. pub type DeltaArray = Array; +/// Serialized metadata for `fastlanes.delta`. +/// +/// The children are `[bases, deltas]`, followed by the validity child when `has_validity` is set. +/// A nullable array without a validity child is all valid. +/// +/// Readers require at least that many children and ignore any that follow. A later writer may +/// append a child under this ID only if decoding without it still yields the same values, such as +/// a statistic or an index. A child or metadata field that changes the decoded values needs a new +/// encoding ID. #[derive(Clone, prost::Message)] -#[repr(C)] pub struct DeltaMetadata { + /// The physical length of `deltas`: `(offset + len).next_multiple_of(1024)`. #[prost(uint64, tag = "1")] - deltas_len: u64, + pub(super) deltas_len: u64, + /// The offset of the first logical value in the first chunk, less than 1024. #[prost(uint32, tag = "2")] - offset: u32, // must be <1024 + pub(super) offset: u32, + /// Whether the children include a validity child after `bases` and `deltas`. + #[prost(bool, tag = "3")] + pub(super) has_validity: bool, } impl ArrayHash for DeltaData { @@ -227,7 +240,7 @@ fn validate_parts( let lanes = lane_count(bases.dtype().as_ptype()); vortex_ensure!( - deltas.len().is_multiple_of(1024), + deltas.len().is_multiple_of(FL_CHUNK_SIZE), "deltas length ({}) must be a multiple of 1024", deltas.len(), ); @@ -254,6 +267,7 @@ mod tests { &DeltaMetadata { offset: u32::MAX, deltas_len: u64::MAX, + has_validity: true, } .encode_to_vec(), ); diff --git a/encodings/fastlanes/src/delta/vtable/plugin.rs b/encodings/fastlanes/src/delta/vtable/plugin.rs index 8f1cbabc988..564db4fe2f5 100644 --- a/encodings/fastlanes/src/delta/vtable/plugin.rs +++ b/encodings/fastlanes/src/delta/vtable/plugin.rs @@ -46,9 +46,18 @@ impl ArrayPlugin for Delta { "Delta plugin cannot serialize an array of another encoding", ); let array = array.as_::(); + let deltas_len = array.deltas().len(); + let canonical_deltas_len = (array.offset() + array.len()).next_multiple_of(FL_CHUNK_SIZE); + vortex_ensure_eq!( + deltas_len, + canonical_deltas_len, + "DeltaArray deltas length must be (offset + len) rounded up to a multiple of \ + {FL_CHUNK_SIZE}", + ); let metadata = DeltaMetadata { - deltas_len: array.deltas().len() as u64, - offset: array.offset() as u32, + deltas_len: deltas_len as u64, + offset: u32::try_from(array.offset())?, + has_validity: array.validity_child().is_some(), } .encode_to_vec(); Ok(Some(ArraySerialization::from_array( @@ -81,32 +90,50 @@ impl ArrayPlugin for Delta { "DeltaArray expects 0 buffers, got {}", buffers.len() ); + let metadata = DeltaMetadata::decode(metadata)?; + let required_children = 2 + usize::from(metadata.has_validity); vortex_ensure!( - children.len() == 2 || children.len() == 3, - "DeltaArray expects 2 or 3 children, got {}", + children.len() >= required_children, + "DeltaArray expects at least {required_children} children, got {}", children.len() ); - let metadata = DeltaMetadata::decode(metadata)?; - let ptype = PType::try_from(dtype)?; - let lanes = lane_count(ptype); + vortex_ensure!( + dtype.is_int(), + "DeltaArray dtype must be an integer, got {dtype}" + ); + vortex_ensure!( + !metadata.has_validity || dtype.is_nullable(), + "DeltaArray validity child requires a nullable dtype, got {dtype}" + ); + let offset = metadata.offset as usize; + vortex_ensure!( + offset < FL_CHUNK_SIZE, + "DeltaArray offset must be less than {FL_CHUNK_SIZE}, got {offset}" + ); + let lanes = lane_count(PType::try_from(dtype)?); let deltas_len = usize::try_from(metadata.deltas_len) .map_err(|_| vortex_err!("deltas_len {} overflowed usize", metadata.deltas_len))?; - vortex_ensure!( - deltas_len.is_multiple_of(FL_CHUNK_SIZE), - "deltas length must be a multiple of {FL_CHUNK_SIZE}" + let canonical_deltas_len = offset + .checked_add(len) + .and_then(|end| end.checked_next_multiple_of(FL_CHUNK_SIZE)) + .ok_or_else(|| vortex_err!("DeltaArray offset + len overflowed usize"))?; + vortex_ensure_eq!( + deltas_len, + canonical_deltas_len, + "DeltaArray deltas length must be (offset + len) rounded up to a multiple of \ + {FL_CHUNK_SIZE}", ); let bases_len = deltas_len / FL_CHUNK_SIZE * lanes; let bases = children.get(0, &dtype.as_nonnullable(), bases_len)?; let deltas = children.get(1, &dtype.as_nonnullable(), deltas_len)?; - let validity_child = if children.len() == 3 { - Some(children.get(2, &Validity::DTYPE, len)?) - } else { - None - }; + let validity_child = metadata + .has_validity + .then(|| children.get(2, &Validity::DTYPE, len)) + .transpose()?; - let data = DeltaData::try_new(metadata.offset as usize)?; + let data = DeltaData::try_new(offset)?; let slots = DeltaSlots { bases, deltas, From eacb35380c0c7183355840a12a714975189bfc18 Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 14:16:20 +0000 Subject: [PATCH 007/128] Store SQL benchmark file sizes in the benchmarks database (#11443) ## Summary The file-size section disappeared from SQL benchmark PR comments in #10987, which moved the baseline from S3 to the benchmarks Postgres. File sizes were never stored there, so `compare-benchmark-jsons.py` found no baseline rows and dropped the section without a message. This PR stores the sizes on develop runs and reads them back on PR runs. --- .github/workflows/sql-bench-matrix.yml | 6 +- scripts/_measurement_id.py | 21 +++++++ scripts/capture-file-sizes.py | 19 +++++++ scripts/compare-benchmark-jsons.py | 27 +++++++-- scripts/fetch-benchmark-baseline.py | 42 ++++++++++++-- scripts/measurement_id_golden.json | 35 +++++++++++- scripts/post-ingest.py | 51 +++++++++++++++++ scripts/tests/test_benchmark_reporting.py | 68 ++++++++++++++++++++++- scripts/tests/test_post_ingest.py | 18 +++++- 9 files changed, 273 insertions(+), 14 deletions(-) diff --git a/.github/workflows/sql-bench-matrix.yml b/.github/workflows/sql-bench-matrix.yml index 97148cce449..582ec00442d 100644 --- a/.github/workflows/sql-bench-matrix.yml +++ b/.github/workflows/sql-bench-matrix.yml @@ -236,6 +236,8 @@ jobs: --opt remote-data-dir="$REMOTE_STORAGE" \ ${{ matrix.scale_factor && format('--opt scale-factor={0}', matrix.scale_factor) || '' }} + # The `file_size` records join the run's ingest records: develop runs store them in the + # benchmarks database (the `file_sizes` table), and PR runs fetch them back as the baseline. - name: Capture file sizes if: matrix.remote_key == null shell: bash @@ -245,8 +247,10 @@ jobs: --benchmark ${{ matrix.subcommand }} \ --dataset-dir ${{ matrix.dataset_dir }} \ --commit ${{ inputs.mode == 'pr' && github.event.pull_request.head.sha || github.sha }} \ - -o sizes.json + -o sizes.json \ + --ingest-jsonl sizes.ingest.jsonl cat sizes.json >> results.json + cat sizes.ingest.jsonl >> results.ingest.jsonl # Footer stats and layout trees of a sample of the dataset's Vortex files: every file is # dumped, then one file of every table is kept, plus more partitions weighted by size up to a diff --git a/scripts/_measurement_id.py b/scripts/_measurement_id.py index 10118f9f973..9eed66b0329 100644 --- a/scripts/_measurement_id.py +++ b/scripts/_measurement_id.py @@ -61,6 +61,7 @@ _TAG_COMPRESSION_SIZES = "compression_sizes" _TAG_RANDOM_ACCESS_TIMES = "random_access_times" _TAG_VECTOR_SEARCH_RUNS = "vector_search_runs" +_TAG_FILE_SIZES = "file_sizes" def _hasher_buf(tag: str) -> bytearray: @@ -212,6 +213,25 @@ def measurement_id_vector_search( return _finish(buf) +def measurement_id_file_size( + *, + commit_sha: str, + benchmark: str, + scale_factor: str, + format: str, + file: str, +) -> int: + """`measurement_id` for a `file_sizes` row. Postdates the Rust implementation, so its golden + vectors were generated by this function.""" + buf = _hasher_buf(_TAG_FILE_SIZES) + _write_str(buf, commit_sha) + _write_str(buf, benchmark) + _write_str(buf, scale_factor) + _write_str(buf, format) + _write_str(buf, file) + return _finish(buf) + + # Dispatch table keyed by the fact-table name, used by the golden-vector test to # map a vector's `table` field to the matching port function. Keeping it here (vs. # in the test) means a new fact table is wired in one place alongside the port. @@ -221,4 +241,5 @@ def measurement_id_vector_search( _TAG_COMPRESSION_SIZES: measurement_id_compression_size, _TAG_RANDOM_ACCESS_TIMES: measurement_id_random_access, _TAG_VECTOR_SEARCH_RUNS: measurement_id_vector_search, + _TAG_FILE_SIZES: measurement_id_file_size, } diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 6a72fcb10ca..9db05517419 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -24,6 +24,10 @@ def main() -> None: ) parser.add_argument("--commit", required=True, help="Commit SHA") parser.add_argument("-o", "--output", required=True, help="Output JSONL file path") + parser.add_argument( + "--ingest-jsonl", + help="Also write the sizes as `file_size` records for `post-ingest.py` to this JSONL file", + ) args = parser.parse_args() data_dir = Path(args.data_dir) @@ -96,6 +100,21 @@ def main() -> None: for record in records: f.write(json.dumps(record) + "\n") + if args.ingest_jsonl: + with open(args.ingest_jsonl, "w") as f: + for record in records: + f.write( + json.dumps( + { + "kind": "file_size", + "commit_sha": record["commit_id"], + **record["file_size"], + "value_bytes": record["value"], + } + ) + + "\n" + ) + print(f"Captured {len(records)} file sizes to {args.output}", file=sys.stderr) diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index a519be616f5..20be9fb9869 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -57,6 +57,8 @@ Z_SCORE_99 = 2.5758293035489004 CONTROL_FORMAT = "parquet" FILE_SIZE_METRIC = "file_size" +# The columns of a JSONL file with no benchmark rows. +EMPTY_ROW_COLUMNS = ["commit_id", "name", "storage", "unit", "value", "all_runtimes", "target"] QUERY_TARGET_PATTERN = re.compile(r"_q(\d+)/([^:]+):(.+)$") FORMAT_DISPLAY_NAMES = { "vortex": "vortex-file-compressed", @@ -93,7 +95,9 @@ def split_file_size_rows(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: metric = df["metric"] if "metric" in df.columns else pd.Series(pd.NA, index=df.index) file_size = df["file_size"] if "file_size" in df.columns else pd.Series(pd.NA, index=df.index) mask = metric.eq(FILE_SIZE_METRIC) | file_size.notna() - return df[mask].copy(), df[~mask].copy() + rest = df[~mask].copy() + # A file of only file sizes leaves no benchmark rows; give them the columns of an empty file. + return df[mask].copy(), rest if not rest.empty else pd.DataFrame(columns=EMPTY_ROW_COLUMNS) def identity_value(value: object) -> object: @@ -208,6 +212,15 @@ def ingest_record_row(record: dict[str, Any]) -> dict[str, Any] | None: row["unit"] = "bytes" row["value"] = record["value_bytes"] return row + elif kind == "file_size": + dims = ("benchmark", "scale_factor", "format", "file") + return { + "commit_id": record.get("commit_sha"), + "metric": FILE_SIZE_METRIC, + "unit": "bytes", + "value": record["value_bytes"], + "file_size": {dim: record[dim] for dim in dims}, + } else: return None row["value"] = record["value_ns"] @@ -233,7 +246,7 @@ def read_benchmark_rows(path: str) -> pd.DataFrame: if row is not None: rows.append(row) if not rows: - return pd.DataFrame(columns=["commit_id", "name", "storage", "unit", "value", "all_runtimes", "target"]) + return pd.DataFrame(columns=EMPTY_ROW_COLUMNS) return pd.DataFrame(rows) @@ -711,7 +724,7 @@ def format_size(size_bytes: int) -> str: def format_size_change(change_bytes: int) -> str: """Format a byte change with a sign.""" - sign = "+" if change_bytes > 0 else "" + sign = "+" if change_bytes > 0 else "-" if change_bytes < 0 else "" return f"{sign}{format_size(abs(change_bytes))}" @@ -1081,9 +1094,11 @@ def main() -> None: title = format_title(benchmark_name, pr_results) pr_file_sizes, pr = split_file_size_rows(pr_results) if args.pr_records: - pr_records = read_benchmark_rows(args.pr_records) + record_file_sizes, pr_records = split_file_size_rows(read_benchmark_rows(args.pr_records)) if not pr_records.empty: pr = pr_records + if not record_file_sizes.empty: + pr_file_sizes = record_file_sizes base_fetched = os.path.exists(args.base_records) base_file_sizes, base = split_file_size_rows(read_benchmark_rows(args.base_records)) @@ -1245,8 +1260,8 @@ def delta_cell( print("") print("") - # File sizes are not stored in the benchmarks database, so they have no baseline to compare. - file_size_report = "" if base_file_sizes.empty else format_file_size_report(base_file_sizes, pr_file_sizes) + # Says so when the PR measured file sizes and the baseline has none, rather than dropping the section. + file_size_report = format_file_size_report(base_file_sizes, pr_file_sizes) if file_size_report: print("") print("---") diff --git a/scripts/fetch-benchmark-baseline.py b/scripts/fetch-benchmark-baseline.py index 613a80459f0..56318c36348 100644 --- a/scripts/fetch-benchmark-baseline.py +++ b/scripts/fetch-benchmark-baseline.py @@ -32,9 +32,11 @@ if TYPE_CHECKING: from psycopg import Connection -# Per record kind: the fact table and the natural-key columns other than -# `commit_sha`. Rows from different commits match when these columns are equal. -# `None` compares equal to `None`, as the ingest path stores absent dims as NULL. +# Per record kind: the fact table, the columns rows from different commits match +# on, and the columns read back. `None` compares equal to `None`, as the ingest path +# stores absent dims as NULL. File sizes match on their (benchmark, scale factor, +# format) scope rather than per file, so a scope is one lookup and the baseline also +# holds the files the PR no longer writes. _KINDS: dict[str, tuple[str, tuple[str, ...], tuple[str, ...]]] = { "query_measurement": ( "query_measurements", @@ -56,6 +58,11 @@ ("dataset", "format", "open_mode"), ("value_ns", "all_runtimes_ns"), ), + "file_size": ( + "file_sizes", + ("benchmark", "scale_factor", "format"), + ("file", "value_bytes"), + ), } # Rows read per query while looking for an identity's newest reachable commit. @@ -131,6 +138,32 @@ def identity_condition(kind: str, identity: tuple) -> tuple[str, list]: return " AND ".join(conditions), params +def commit_selection_identities(identities: dict[str, list[tuple]]) -> dict[str, list[tuple]]: + """Return the identities that choose the baseline commit. + + File sizes are written by the same job as the measurements beside them, so the commit + those measurements pick has them too. Leaving them out keeps the commit search off the + file-size scopes, whose rows (one per file per commit) make paging back through history slow. + """ + + others = {kind: keys for kind, keys in identities.items() if kind != "file_size"} + return others or identities + + +def existing_kinds(conn: Connection, identities: dict[str, list[tuple]]) -> dict[str, list[tuple]]: + """Drop the kinds whose table the database does not have yet, so a new kind's table + being missing loses that kind alone and not the whole baseline.""" + + kept = {} + for kind, keys in identities.items(): + table = _KINDS[kind][0] + if conn.execute("SELECT to_regclass(%s)", [f"public.{table}"]).fetchone()[0] is not None: + kept[kind] = keys + else: + print(f"The benchmarks database has no {table} table; reporting {kind} rows without a baseline.") + return kept + + def newest_baseline_commit( conn: Connection, identities: dict[str, list[tuple]], reachable: set[str] ) -> tuple[str, object] | None: @@ -229,7 +262,8 @@ def main() -> None: if identities: commits = reachable_commits() with connect_postgres(args.postgres, args.region) as conn: - newest = newest_baseline_commit(conn, identities, set(commits)) + identities = existing_kinds(conn, identities) + newest = newest_baseline_commit(conn, commit_selection_identities(identities), set(commits)) if newest is not None: commit_sha, commit_timestamp = newest records = baseline_records(conn, identities, commit_sha, commit_timestamp) diff --git a/scripts/measurement_id_golden.json b/scripts/measurement_id_golden.json index 5df8fe9775d..74c7cbbcd87 100644 --- a/scripts/measurement_id_golden.json +++ b/scripts/measurement_id_golden.json @@ -1,5 +1,5 @@ { - "note": "Frozen golden vectors for the measurement_id_* hash, generated by the original Rust implementation (server/src/db.rs in the retired vortex-data/benchmarks-website server crate) that wrote the production rows. NEVER regenerate this file: the ids it pins are the primary keys already stored in the benchmarks RDS Postgres, and any drift would break ON CONFLICT (measurement_id) idempotency. scripts/tests/test_measurement_id.py asserts the Python port in scripts/_measurement_id.py reproduces every measurement_id here.", + "note": "Frozen golden vectors for the measurement_id_* hash, generated by the original Rust implementation (server/src/db.rs in the retired vortex-data/benchmarks-website server crate) that wrote the production rows. NEVER regenerate this file: the ids it pins are the primary keys already stored in the benchmarks RDS Postgres, and any drift would break ON CONFLICT (measurement_id) idempotency. scripts/tests/test_measurement_id.py asserts the Python port in scripts/_measurement_id.py reproduces every measurement_id here. The file_sizes vectors postdate that server: scripts/_measurement_id.py generated them when the table was added, and they are frozen the same way.", "seed": 0, "vectors": [ { @@ -820,6 +820,39 @@ }, "measurement_id": 3687626387279485390, "table": "vector_search_runs" + }, + { + "fields": { + "benchmark": "tpch", + "commit_sha": "0123456789abcdef0123456789abcdef01234567", + "file": "lineitem.vortex", + "format": "vortex-file-compressed", + "scale_factor": "1.0" + }, + "measurement_id": 7596070563235302041, + "table": "file_sizes" + }, + { + "fields": { + "benchmark": "clickbench", + "commit_sha": "0123456789abcdef0123456789abcdef01234567", + "file": "hits/hits_0.vortex", + "format": "vortex-compact", + "scale_factor": "1.0" + }, + "measurement_id": 4890035495638497478, + "table": "file_sizes" + }, + { + "fields": { + "benchmark": "", + "commit_sha": "", + "file": "donn\u00e9es/\u00e9.vortex", + "format": "", + "scale_factor": "" + }, + "measurement_id": 6489263215362153183, + "table": "file_sizes" } ] } diff --git a/scripts/post-ingest.py b/scripts/post-ingest.py index d314dd45a1a..9c98668ec01 100755 --- a/scripts/post-ingest.py +++ b/scripts/post-ingest.py @@ -218,6 +218,10 @@ def build_commit(sha: str, branch: str, repo_url: str, git_dir: Path | None) -> ), frozenset({"env_triple"}), ), + "file_size": ( + frozenset({"commit_sha", "benchmark", "scale_factor", "format", "file", "value_bytes"}), + frozenset(), + ), } _MEASUREMENT_ID_MODULE: ModuleType | None = None @@ -419,6 +423,14 @@ def _memory_quartet_consistent(r: dict) -> bool: ("iterations", "i32"), ("env_triple", "opt_str"), ), + "file_size": ( + ("commit_sha", "str"), + ("benchmark", "str"), + ("scale_factor", "str"), + ("format", "str"), + ("file", "str"), + ("value_bytes", "i64"), + ), } @@ -719,6 +731,43 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: ) +def _file_size_id(mid_mod, r: dict) -> int: + """Compute the `file_sizes` primary key.""" + return mid_mod.measurement_id_file_size( + commit_sha=r["commit_sha"], + benchmark=r["benchmark"], + scale_factor=r["scale_factor"], + format=r["format"], + file=r["file"], + ) + + +def _insert_file_size(conn, mid: int, r: dict) -> bool: + """Upsert a `file_sizes` row.""" + return _upsert_returning_was_update( + conn, + """ + INSERT INTO file_sizes ( + measurement_id, commit_sha, benchmark, scale_factor, + format, file, value_bytes + ) VALUES (%s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (measurement_id) DO UPDATE SET + commit_sha = excluded.commit_sha, + value_bytes = excluded.value_bytes + RETURNING (xmax = 0) AS inserted + """, + ( + mid, + r["commit_sha"], + r["benchmark"], + r["scale_factor"], + r["format"], + r["file"], + r["value_bytes"], + ), + ) + + # Dispatch from a record's `kind` to its per-table primary key and upsert. Keyed identically to # `_RECORD_FIELDS`; the three maps are wired together when adding a fact table. _MEASUREMENT_ID = { @@ -727,6 +776,7 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: "compression_size": _compression_size_id, "random_access_time": _random_access_time_id, "vector_search_run": _vector_search_run_id, + "file_size": _file_size_id, } _APPLY_RECORD = { @@ -735,6 +785,7 @@ def _insert_vector_search(conn, mid: int, r: dict) -> bool: "compression_size": _insert_compression_size, "random_access_time": _insert_random_access, "vector_search_run": _insert_vector_search, + "file_size": _insert_file_size, } diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index 0b55fe1e3ca..dc275d8702d 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -582,12 +582,25 @@ def test_file_size_report_omits_formats_the_pr_run_skipped() -> None: assert "-100.0%" not in report +def file_size_ingest_record(commit: str, size: int, file: str) -> dict[str, object]: + return { + "kind": "file_size", + "commit_sha": commit, + "benchmark": "tpch", + "scale_factor": "10", + "format": "vortex-file-compressed", + "file": file, + "value_bytes": size, + } + + def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: data_dir = tmp_path / "data" format_dir = data_dir / "tpch" / "10" / "vortex-file-compressed" format_dir.mkdir(parents=True) (format_dir / "part-0.vortex").write_bytes(b"x" * 42) output_path = tmp_path / "sizes.jsonl" + ingest_path = tmp_path / "sizes.ingest.jsonl" result = subprocess.run( [ @@ -602,6 +615,8 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: "deadbeef", "-o", str(output_path), + "--ingest-jsonl", + str(ingest_path), ], check=False, capture_output=True, @@ -609,6 +624,8 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: ) assert result.returncode == 0, result.stderr + ingest_records = [json.loads(line) for line in ingest_path.read_text(encoding="utf-8").splitlines()] + assert ingest_records == [file_size_ingest_record("deadbeef", 42, "part-0.vortex")] records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] assert records == [ { @@ -664,11 +681,15 @@ def test_baseline_fetch_groups_distinct_pr_identities_by_kind() -> None: query_record("pr", 1, "datafusion", "parquet", 100), random_access_record("pr", "parquet", "cached", 100), {"kind": "vector_search_run", "dataset": "cohere"}, + file_size_ingest_record("pr", 100, "part-0.vortex"), + file_size_ingest_record("pr", 100, "part-1.vortex"), ] assert fetch.identities_by_kind(records) == { "query_measurement": [("tpch", None, "1", 1, "nvme", "datafusion", "parquet")], "random_access_time": [("taxi/uniform", "parquet", "cached")], + # One lookup per scope, so the baseline also returns files the PR no longer writes. + "file_size": [("tpch", "10", "vortex-file-compressed")], } @@ -708,7 +729,52 @@ def test_report_compares_ingest_records(tmp_path: Path) -> None: assert markdown_row(report, "random-access/taxi/uniform/parquet-cached")[1] == "105 / 100 / +5.0%" assert markdown_row(report, "random-access/taxi/uniform/lance-cached")[1] == "300 / — / no baseline" assert "random-access / lance / ns " in report - assert "File Size" not in report + assert "File Size Changes" not in report + assert "_No baseline file sizes found for base commit._" in report + + +def test_report_compares_file_size_records_from_the_database(tmp_path: Path) -> None: + base_records = [ + query_record("base-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("base-sha", 100, "part-0.vortex"), + file_size_ingest_record("base-sha", 50, "part-1.vortex"), + ] + pr_records = [ + query_record("pr-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("pr-sha", 125, "part-0.vortex"), + ] + pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1) | {"doc": "benchmarks/tpch.md"}] + + report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) + + assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / 80 / +0.0%" + assert "File Size Changes (2 files changed, -16.7% overall, 1↑ 1↓)" in report + assert "| part-1.vortex | 10 | vortex-file-compressed | 50 B | 0 B | -50 B | -100.0% |" in report + + +def test_report_handles_a_baseline_of_only_file_sizes(tmp_path: Path) -> None: + base_records = [file_size_ingest_record("base-sha", 100, "part-0.vortex")] + pr_records = [ + query_record("pr-sha", 1, "datafusion", "vortex-file-compressed", 80), + file_size_ingest_record("pr-sha", 125, "part-0.vortex"), + ] + pr_results = [stored_timing_row("pr-sha", "ignored when records exist", 1) | {"doc": "benchmarks/tpch.md"}] + + report = render_report(tmp_path, base_records, pr_results, "TPC-H", pr_records) + + assert markdown_row(report, "tpch_q01/datafusion:vortex-file-compressed")[1] == "80 / — / no baseline" + assert "File Size Changes (1 files changed, +25.0% overall, 1↑ 0↓)" in report + + +def test_baseline_commit_is_chosen_without_file_sizes() -> None: + fetch = load_module("fetch_benchmark_baseline", FETCH_BASELINE_SCRIPT) + query = ("tpch", None, "1", 1, "nvme", "datafusion", "parquet") + scope = ("tpch", "10", "vortex-file-compressed") + + assert fetch.commit_selection_identities({"query_measurement": [query], "file_size": [scope]}) == { + "query_measurement": [query] + } + assert fetch.commit_selection_identities({"file_size": [scope]}) == {"file_size": [scope]} def test_report_says_when_the_baseline_could_not_be_read(tmp_path: Path) -> None: diff --git a/scripts/tests/test_post_ingest.py b/scripts/tests/test_post_ingest.py index 4d4bd0be64e..c2c5c830c4c 100644 --- a/scripts/tests/test_post_ingest.py +++ b/scripts/tests/test_post_ingest.py @@ -49,6 +49,15 @@ def records(commit) -> list[dict[str, object]]: {**common, **timing, "kind": "compression_time", "op": "encode"}, {**common, "kind": "compression_size", "value_bytes": 10, "uncompressed_bytes": 100}, {**common, **timing, "kind": "random_access_time", "open_mode": "cached"}, + { + "kind": "file_size", + "commit_sha": commit["sha"], + "benchmark": "tpch", + "scale_factor": "1.0", + "format": "vortex-file-compressed", + "file": "lineitem.vortex", + "value_bytes": 1024, + }, { "kind": "vector_search_run", "commit_sha": commit["sha"], @@ -71,7 +80,14 @@ def records(commit) -> list[dict[str, object]]: def test_late_invalid_record_never_starts_transaction(writer, commit, records, invalid): records[-1] = None if invalid is None else {**records[-1], **invalid} # A connection with no methods proves validation precedes even BEGIN, including the commit upsert. - with pytest.raises(SystemExit, match="record 4"): + with pytest.raises(SystemExit, match="record 5"): + writer.ingest_postgres(object(), commit, records) + + +@pytest.mark.parametrize("invalid", [{"scale_factor": None}, {"value_bytes": 1.5}, {"file": 3}]) +def test_invalid_file_size_never_starts_transaction(writer, commit, records, invalid): + records[4] = {**records[4], **invalid} + with pytest.raises(SystemExit, match=r"record 4 \(file_size\)"): writer.ingest_postgres(object(), commit, records) From bcbe4c232d478d96ea77b803e50b12f338fc85a9 Mon Sep 17 00:00:00 2001 From: Joe Isaacs Date: Fri, 13 Nov 2026 14:53:13 +0000 Subject: [PATCH 008/128] Store every format's SQL benchmark file sizes (#11447) ## Summary #11443 started storing SQL benchmark file sizes in the benchmarks database, but only for `vortex-file-compressed` and `vortex-compact`. This PR stores every on-disk format, so bench can chart Parquet, DuckDB, Lance and the rest beside Vortex (vortex-data/vortex.dev#222). PR comments still compare only the Vortex formats. ## Changes - `scripts/capture-file-sizes.py` records every format directory that `Format::name()` in `vortex-bench/src/lib.rs` names: `arrow-ipc`, `csv`, `duckdb`, `lance`, `litdata`, `parquet`, `vortex-compact`, `vortex-file-compressed` and `vortex-spatial-native`. Each develop commit adds roughly one row per Parquet file; ClickBench has about 100. - **DuckDB catalogs:** DuckDB keeps a catalog of views (`duckdb.db`, and `duckdb.db.wal` while open) in every format directory it queries (`duckdb-bench/src/lib.rs`). That isn't the format's data, so it's now skipped everywhere except the `duckdb` directory, where the database is the data. This also takes the catalog out of the Vortex totals. Rows recorded today include it, so PR comments based on today's develop commits list `duckdb.db` as a removed file, once. - `scripts/compare-benchmark-jsons.py`: the "File Size Changes" section compares only formats starting with `vortex`. The other formats' files come from the data generators and don't change with a Vortex PR. New tests check that capture records every format, skips the DuckDB catalogs outside `duckdb`, and ignores unknown directories. Another checks that the report leaves out non-Vortex formats. ### Checks - `uv run --no-project --with pytest --with pandas --with numpy --with orjson --with tabulate --with xxhash pytest scripts/tests/test_measurement_id.py scripts/tests/test_benchmark_reporting.py scripts/tests/test_post_ingest.py`: 49 passed. - `uvx ruff format --check` and `uvx ruff check` on the changed files pass, as does `git diff --check`. - Not run: a CI benchmark run. `action/bench-sql` on this PR would exercise capture and the comment. The new formats only reach the database from develop runs. --- _Generated by [Claude Code](https://claude.ai/code/session_01UeniB9quRiv5fCx8AhzH9s)_ Signed-off-by: Joe Isaacs Co-authored-by: Claude Opus 5.5 --- scripts/capture-file-sizes.py | 25 +++++++-- scripts/compare-benchmark-jsons.py | 6 +- scripts/tests/test_benchmark_reporting.py | 68 +++++++++++++++++++++++ 3 files changed, 94 insertions(+), 5 deletions(-) diff --git a/scripts/capture-file-sizes.py b/scripts/capture-file-sizes.py index 9db05517419..f987cbc28f9 100644 --- a/scripts/capture-file-sizes.py +++ b/scripts/capture-file-sizes.py @@ -14,6 +14,8 @@ import sys from pathlib import Path +DUCKDB_CATALOG_FILES = {"duckdb.db", "duckdb.db.wal"} + def main() -> None: parser = argparse.ArgumentParser(description="Capture file sizes from benchmark data directories") @@ -40,9 +42,19 @@ def main() -> None: print(f"Benchmark directory not found: {benchmark_dir}", file=sys.stderr) sys.exit(1) - # Formats to capture (vortex formats only, not parquet/duckdb) - # Note: "vortex" CLI arg maps to "vortex-file-compressed" directory name - formats_to_capture = {"vortex-file-compressed", "vortex-compact"} + # Every on-disk format, named as `Format::name()` in `vortex-bench/src/lib.rs` names its + # directory. The "vortex" CLI argument maps to the "vortex-file-compressed" directory. + formats_to_capture = { + "arrow-ipc", + "csv", + "duckdb", + "lance", + "litdata", + "parquet", + "vortex-compact", + "vortex-file-compressed", + "vortex-spatial-native", + } records = [] @@ -67,8 +79,13 @@ def main() -> None: if not file_path.is_file(): continue - size_bytes = file_path.stat().st_size relative_path = file_path.relative_to(format_dir) + # DuckDB keeps a catalog of views over the files in each format directory it queries + # (`duckdb.db`, and its WAL while open). Only the `duckdb` format's database is data. + if format_name != "duckdb" and relative_path.name in DUCKDB_CATALOG_FILES: + continue + + size_bytes = file_path.stat().st_size records.append( { diff --git a/scripts/compare-benchmark-jsons.py b/scripts/compare-benchmark-jsons.py index 20be9fb9869..77d9ae9bddd 100644 --- a/scripts/compare-benchmark-jsons.py +++ b/scripts/compare-benchmark-jsons.py @@ -57,6 +57,8 @@ Z_SCORE_99 = 2.5758293035489004 CONTROL_FORMAT = "parquet" FILE_SIZE_METRIC = "file_size" +# Every format's file sizes are stored; the PR comment compares only the Vortex formats. +FILE_SIZE_REPORT_FORMAT_PREFIX = "vortex" # The columns of a JSONL file with no benchmark rows. EMPTY_ROW_COLUMNS = ["commit_id", "name", "storage", "unit", "value", "all_runtimes", "target"] QUERY_TARGET_PATTERN = re.compile(r"_q(\d+)/([^:]+):(.+)$") @@ -738,7 +740,7 @@ def format_pct_change(pct: float) -> str: def extract_file_size_data( df: pd.DataFrame, ) -> tuple[dict[tuple[str, str, str, str], int], set[tuple[str, str, str, str]]]: - """Extract file-size rows and the identities explicitly ignored for being empty.""" + """Extract the Vortex formats' file-size rows and the identities ignored for being empty.""" data = {} ignored = set() @@ -756,6 +758,8 @@ def extract_file_size_data( str(metadata.get("format", "")), str(metadata.get("file", "")), ) + if not key[2].startswith(FILE_SIZE_REPORT_FORMAT_PREFIX): + continue value = row.get("value") if pd.isna(value): continue diff --git a/scripts/tests/test_benchmark_reporting.py b/scripts/tests/test_benchmark_reporting.py index dc275d8702d..49712ef9991 100644 --- a/scripts/tests/test_benchmark_reporting.py +++ b/scripts/tests/test_benchmark_reporting.py @@ -643,6 +643,74 @@ def test_capture_file_sizes_emits_shared_benchmark_rows(tmp_path: Path) -> None: ] +def test_capture_file_sizes_records_every_format_but_duckdb_catalogs(tmp_path: Path) -> None: + data_dir = tmp_path / "data" + scale_dir = data_dir / "tpch" / "1.0" + for format_name, file_name, size in [ + ("vortex-file-compressed", "lineitem.vortex", 40), + ("vortex-file-compressed", "duckdb.db", 7), + ("parquet", "lineitem.parquet", 60), + ("parquet", "duckdb.db.wal", 3), + ("duckdb", "duckdb.db", 90), + ("lance", "lineitem.lance/data/0.lance", 70), + ("not-a-format", "notes.txt", 1), + ]: + path = scale_dir / format_name / file_name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x" * size) + output_path = tmp_path / "sizes.jsonl" + + result = subprocess.run( + [ + sys.executable, + str(CAPTURE_SCRIPT), + str(data_dir), + "--benchmark", + "tpch", + "--dataset-dir", + "tpch", + "--commit", + "deadbeef", + "-o", + str(output_path), + ], + check=False, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, result.stderr + records = [json.loads(line) for line in output_path.read_text(encoding="utf-8").splitlines()] + assert [(r["file_size"]["format"], r["file_size"]["file"], r["value"]) for r in records] == [ + ("duckdb", "duckdb.db", 90), + ("lance", "lineitem.lance/data/0.lance", 70), + ("parquet", "lineitem.parquet", 60), + ("vortex-file-compressed", "lineitem.vortex", 40), + ] + + +def test_file_size_report_compares_only_vortex_formats() -> None: + compare = load_module("compare_benchmark_jsons", COMPARE_SCRIPT) + + report = compare.format_file_size_report( + pd.DataFrame( + [ + file_size_record_for("base-sha", 100, "tpch", "10", "vortex-file-compressed", "a"), + file_size_record_for("base-sha", 100, "tpch", "10", "parquet", "a"), + ] + ), + pd.DataFrame( + [ + file_size_record_for("pr-sha", 125, "tpch", "10", "vortex-file-compressed", "a"), + file_size_record_for("pr-sha", 50, "tpch", "10", "parquet", "a"), + ] + ), + ) + + assert "File Size Changes (1 files changed, +25.0% overall, 1↑ 0↓)" in report + assert "parquet" not in report + + def test_baseline_fetch_refuses_a_shallow_checkout(tmp_path: Path) -> None: """A shallow clone must fail loudly, not render a baseline-free report. From a1a21438662a77787e3e443e73096bb47d3414d5 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Fri, 13 Nov 2026 15:27:14 +0000 Subject: [PATCH 009/128] Upgrade Rust to 1.100.0 and nightly to 2026-11-13 (#11446) ## Summary - Set the stable toolchain in `rust-toolchain.toml` to `1.100.0`. - Set `NIGHTLY_TOOLCHAIN` to `nightly-2026-11-13` in all 12 workflows that pin it. The new rustfmt makes no changes to the code. ### Clippy 1.100 (`redundant_clone`) - Remove redundant clones in `vortex-array`, `vortex-fastlanes`, `vortex-fuzz`, `vortex-cuda`, `vortex-sqllogictest` and `xtask`. - `vortex-duckdb`: `test_clone_logical_type` tests the FFI `Clone`. Keep the clone and keep the original value alive, and check the type of both values. ### Cargo 1.100 lints - `unused_workspace_dependencies`: - Remove `arrow-arith`. - Add `vortex-elias-fano` to `vortex`, re-export it as `vortex::encodings::elias_fano` and register it in `VortexSession::default()`. It is not in any file edition yet. - `unused_dependencies`: - `datafusion-bench/build.rs` checks `CARGO_CFG_TARGET_OS` and not `#[cfg(target_os)]`, which reads the host OS. The link argument is for the target. - `vortex-web-wasm` puts all its dependencies under `cfg(target_arch = "wasm32")`, because the library is empty on other targets. --------- Signed-off-by: Robert Kruszewski --- .github/workflows/build-fuzzers.yml | 2 +- .github/workflows/ci.yml | 7 ++++++- .github/workflows/close-fixed-fuzzer-issues.yml | 2 +- .github/workflows/codspeed.yml | 2 +- .github/workflows/fuzz-coverage.yml | 2 +- .github/workflows/fuzzer-fix-automation.yml | 2 +- .github/workflows/minimize_fuzz_corpus_workflow.yml | 2 +- .github/workflows/package.yml | 6 ++++++ .github/workflows/publish-dry-runs.yml | 2 +- .github/workflows/publish.yml | 2 +- .github/workflows/run-fuzzer.yml | 2 +- .github/workflows/rust-instrumented.yml | 2 +- .github/workflows/wasm-fuzz.yml | 2 +- Cargo.lock | 1 + Cargo.toml | 1 - benchmarks/datafusion-bench/build.rs | 6 ++++-- encodings/fastlanes/src/bitpacking/compute/cast.rs | 4 ++-- fuzz/src/array/mod.rs | 2 +- rust-toolchain.toml | 2 +- vortex-array/src/arrays/listview/rebuild.rs | 6 +----- vortex-array/src/arrays/variant/vtable/kernel.rs | 2 +- vortex-array/src/compute/conformance/cast.rs | 2 +- vortex-array/src/scalar_fn/fns/binary/mod.rs | 4 ++-- vortex-cuda/benches/dynamic_dispatch_cuda.rs | 2 +- vortex-duckdb/src/duckdb/logical_type.rs | 6 +++++- vortex-ffi/cmake/tests/test_compiler_commands.py | 4 +++- vortex-sqllogictest/bin/sqllogictests-runner.rs | 1 - vortex-web/crate/Cargo.toml | 11 +++++------ vortex/Cargo.toml | 1 + vortex/src/lib.rs | 6 ++++++ xtask/src/check_editions.rs | 2 +- 31 files changed, 59 insertions(+), 39 deletions(-) diff --git a/.github/workflows/build-fuzzers.yml b/.github/workflows/build-fuzzers.yml index 2eeb4a52180..fd9002062cd 100644 --- a/.github/workflows/build-fuzzers.yml +++ b/.github/workflows/build-fuzzers.yml @@ -14,7 +14,7 @@ on: value: ${{ jobs.build.outputs.artifact_name }} env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: build: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f06b66ed11c..94f2cd7efde 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 TY_VERSION: 0.0.98 jobs: @@ -418,6 +418,11 @@ jobs: && format('runs-on={0}/region=us-east-1/pool=windows-x64-pre/extras=s3-cache', github.run_id) || 'windows-latest' }} env: + # Cargo 1.100 passes rustc one `-L dependency=` per crate in its new build-dir layout, so + # large crates exceed the Windows command line limit. Cargo falls back to an argfile, but + # sccache expands it and fails with os error 206 (mozilla/sccache#2397). Keep the old layout + # until sccache passes an argfile to rustc on Windows. + __CARGO_TEMPORARY_BUILD_DIR_NEW_LAYOUT_OPT_OUT: "1" NEXTEST_WINDOWS_ARGS: >- --cargo-profile ci --locked --workspace --all-features --exclude vortex-bench diff --git a/.github/workflows/close-fixed-fuzzer-issues.yml b/.github/workflows/close-fixed-fuzzer-issues.yml index ec0182fdc8f..99fff128ea9 100644 --- a/.github/workflows/close-fixed-fuzzer-issues.yml +++ b/.github/workflows/close-fixed-fuzzer-issues.yml @@ -16,7 +16,7 @@ permissions: actions: read env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: close-fixed: diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 160902458f3..465e0f33a0b 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -23,7 +23,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: changes: diff --git a/.github/workflows/fuzz-coverage.yml b/.github/workflows/fuzz-coverage.yml index 7dd08670944..cae234239f2 100644 --- a/.github/workflows/fuzz-coverage.yml +++ b/.github/workflows/fuzz-coverage.yml @@ -6,7 +6,7 @@ on: workflow_dispatch: { } env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: coverage: diff --git a/.github/workflows/fuzzer-fix-automation.yml b/.github/workflows/fuzzer-fix-automation.yml index 5fe3ee77b7a..7d1bd0aa978 100644 --- a/.github/workflows/fuzzer-fix-automation.yml +++ b/.github/workflows/fuzzer-fix-automation.yml @@ -26,7 +26,7 @@ on: type: string env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: attempt-fix: diff --git a/.github/workflows/minimize_fuzz_corpus_workflow.yml b/.github/workflows/minimize_fuzz_corpus_workflow.yml index 322ec47b114..e8828e2cc5a 100644 --- a/.github/workflows/minimize_fuzz_corpus_workflow.yml +++ b/.github/workflows/minimize_fuzz_corpus_workflow.yml @@ -44,7 +44,7 @@ on: required: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: minimize: diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 4e78d444822..6551597023f 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -143,6 +143,12 @@ jobs: && format('runs-on={0}/region=us-east-1/pool=windows-x64-pre/extras=s3-cache', github.run_id) || 'windows-latest' }} timeout-minutes: 90 + env: + # Cargo 1.100 passes rustc one `-L dependency=` per crate in its new build-dir layout, so + # large crates exceed the Windows command line limit. Cargo falls back to an argfile, but + # sccache expands it and fails with os error 206 (mozilla/sccache#2397). Keep the old layout + # until sccache passes an argfile to rustc on Windows. + __CARGO_TEMPORARY_BUILD_DIR_NEW_LAYOUT_OPT_OUT: "1" steps: - uses: runs-on/action@v2 if: github.repository == 'vortex-data/vortex' diff --git a/.github/workflows/publish-dry-runs.yml b/.github/workflows/publish-dry-runs.yml index 4bed4af7c6c..4682407ecda 100644 --- a/.github/workflows/publish-dry-runs.yml +++ b/.github/workflows/publish-dry-runs.yml @@ -20,7 +20,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: python-wheel-build: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b5b26592e64..c341a1c7b91 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -5,7 +5,7 @@ concurrency: cancel-in-progress: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 on: release: diff --git a/.github/workflows/run-fuzzer.yml b/.github/workflows/run-fuzzer.yml index 8fa6150835f..c4fa7d54207 100644 --- a/.github/workflows/run-fuzzer.yml +++ b/.github/workflows/run-fuzzer.yml @@ -59,7 +59,7 @@ on: required: true env: - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: fuzz: diff --git a/.github/workflows/rust-instrumented.yml b/.github/workflows/rust-instrumented.yml index db04cd4ca5d..43b5eb4263d 100644 --- a/.github/workflows/rust-instrumented.yml +++ b/.github/workflows/rust-instrumented.yml @@ -20,7 +20,7 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: rust-coverage: diff --git a/.github/workflows/wasm-fuzz.yml b/.github/workflows/wasm-fuzz.yml index 78fea89b740..5a9a599d9fc 100644 --- a/.github/workflows/wasm-fuzz.yml +++ b/.github/workflows/wasm-fuzz.yml @@ -17,7 +17,7 @@ permissions: env: CARGO_TERM_COLOR: always - NIGHTLY_TOOLCHAIN: nightly-2026-09-10 + NIGHTLY_TOOLCHAIN: nightly-2026-11-13 jobs: wasm-fuzz: diff --git a/Cargo.lock b/Cargo.lock index 576f168b5fd..a9f55d9d5a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11341,6 +11341,7 @@ dependencies = [ "vortex-datetime-parts", "vortex-decimal-byte-parts", "vortex-edition", + "vortex-elias-fano", "vortex-error", "vortex-expr", "vortex-fastlanes", diff --git a/Cargo.toml b/Cargo.toml index 658785c90f6..2e2b856e958 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,7 +103,6 @@ anyhow = "1.0.100" arbitrary = "1.3.2" arc-swap = "1.9" arcref = "0.2.0" -arrow-arith = "59.2" arrow-array = "59.2" arrow-buffer = "59.2" arrow-cast = "59.2" diff --git a/benchmarks/datafusion-bench/build.rs b/benchmarks/datafusion-bench/build.rs index de0d0d5a6d9..5f70f6c92f5 100644 --- a/benchmarks/datafusion-bench/build.rs +++ b/benchmarks/datafusion-bench/build.rs @@ -2,6 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors fn main() { - #[cfg(not(target_os = "macos"))] - custom_labels::build::emit_build_instructions(); + // The linker flag is for the target, so check the target OS and not the host OS. + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") { + custom_labels::build::emit_build_instructions(); + } } diff --git a/encodings/fastlanes/src/bitpacking/compute/cast.rs b/encodings/fastlanes/src/bitpacking/compute/cast.rs index c0c1a95b5a8..3cb9aa79ef4 100644 --- a/encodings/fastlanes/src/bitpacking/compute/cast.rs +++ b/encodings/fastlanes/src/bitpacking/compute/cast.rs @@ -292,7 +292,7 @@ mod tests { let mut ctx = SESSION.create_execution_ctx(); // Reference: plain primitive cast of the same values. - let reference = source_ref.clone().cast(target.clone())?; + let reference = source_ref.cast(target.clone())?; // Candidate: bit-pack, then cast through the real engine. This dispatches to // `BitPacked`'s `CastKernel` widening pushdown. @@ -306,7 +306,7 @@ mod tests { let hi = len - len / 4; let sliced = bp(&source_ref, 3).into_array().slice(lo..hi)?; let casted = sliced.cast(target.clone())?; - let reference = source_ref.clone().slice(lo..hi)?.cast(target.clone())?; + let reference = source_ref.slice(lo..hi)?.cast(target)?; assert_arrays_eq!(casted, reference, &mut ctx); } } diff --git a/fuzz/src/array/mod.rs b/fuzz/src/array/mod.rs index bc30d32e49b..6a0b6eb02f3 100644 --- a/fuzz/src/array/mod.rs +++ b/fuzz/src/array/mod.rs @@ -687,7 +687,7 @@ pub fn run_fuzz_action(fuzz_action: FuzzArrayAction) -> VortexFuzzResult { } Action::FillNull(fill_value) => { current_array = current_array - .fill_null(fill_value.clone()) + .fill_null(fill_value) .and_then(|array| array.optimize_ctx(&ctx)) .vortex_expect("fill_null operation should succeed in fuzz test"); assert_array_eq(&expected.array(), ¤t_array, i, &mut ctx)?; diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 051b8fa5930..c3579bf1ee5 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.99.1" +channel = "1.100.0" components = ["rust-src", "rustfmt", "clippy", "rust-analyzer"] profile = "minimal" diff --git a/vortex-array/src/arrays/listview/rebuild.rs b/vortex-array/src/arrays/listview/rebuild.rs index c3e9e15d10f..bf9d48eb39c 100644 --- a/vortex-array/src/arrays/listview/rebuild.rs +++ b/vortex-array/src/arrays/listview/rebuild.rs @@ -789,11 +789,7 @@ mod tests { &mut ctx, )?; let rebuilt = list.compact(&mut ctx)?; - assert_arrays_eq!( - rebuilt.elements().clone(), - expected_elements.clone(), - &mut ctx - ); + assert_arrays_eq!(rebuilt.elements().clone(), expected_elements, &mut ctx); assert_eq!(rebuilt.offsets().dtype(), list.offsets().dtype()); assert_arrays_eq!( rebuilt.offsets().cast(u32_dtype.clone())?, diff --git a/vortex-array/src/arrays/variant/vtable/kernel.rs b/vortex-array/src/arrays/variant/vtable/kernel.rs index 267e67dbcea..35f9b02f6c4 100644 --- a/vortex-array/src/arrays/variant/vtable/kernel.rs +++ b/vortex-array/src/arrays/variant/vtable/kernel.rs @@ -165,7 +165,7 @@ fn typed_shredded_path( let len = current_struct.len(); let current_validity = current_struct.validity()?.to_array(len); - current = field.clone().mask(current_validity.clone())?; + current = field.clone().mask(current_validity)?; } Ok(Some(current)) diff --git a/vortex-array/src/compute/conformance/cast.rs b/vortex-array/src/compute/conformance/cast.rs index af406d138ae..8e4d846d9bd 100644 --- a/vortex-array/src/compute/conformance/cast.rs +++ b/vortex-array/src/compute/conformance/cast.rs @@ -126,7 +126,7 @@ fn test_cast_from_null(array: &ArrayRef, ctx: &mut ExecutionCtx) { ]; for dtype in non_nullable_types { - assert!(cast_and_execute(&array.clone(), dtype.clone(), ctx).is_err()); + assert!(cast_and_execute(&array.clone(), dtype, ctx).is_err()); } } diff --git a/vortex-array/src/scalar_fn/fns/binary/mod.rs b/vortex-array/src/scalar_fn/fns/binary/mod.rs index 83fe3e02c5c..8e7848e21a5 100644 --- a/vortex-array/src/scalar_fn/fns/binary/mod.rs +++ b/vortex-array/src/scalar_fn/fns/binary/mod.rs @@ -748,7 +748,7 @@ mod tests { // ^ nullable for (lhs, rhs) in [(left.clone(), right.clone()), (right.clone(), left)] { let array = lhs - .binary(rhs.clone(), Operator::And)? + .binary(rhs, Operator::And)? .is_null()? .optimize_ctx(&SESSION)?; assert_eq!(*array.as_::>().options, Operator::And); @@ -773,7 +773,7 @@ mod tests { // ^ nullable for (lhs, rhs) in [(left.clone(), right.clone()), (right.clone(), left)] { let array = lhs - .binary(rhs.clone(), Operator::Or)? + .binary(rhs, Operator::Or)? .is_not_null()? .optimize_ctx(&SESSION)?; assert_eq!(*array.as_::>().options, Operator::Or); diff --git a/vortex-cuda/benches/dynamic_dispatch_cuda.rs b/vortex-cuda/benches/dynamic_dispatch_cuda.rs index 9b4df35002c..6d676b51fb8 100644 --- a/vortex-cuda/benches/dynamic_dispatch_cuda.rs +++ b/vortex-cuda/benches/dynamic_dispatch_cuda.rs @@ -688,7 +688,7 @@ fn bench_dict_bp_codes_alp_for_bp_values_composed_standalone(c: &mut Criterion) .clone() .execute::(&mut ctx) .vortex_expect("to primitive"); - let for_arr = FoRData::encode(alp_encoded.clone(), &mut ctx).vortex_expect("for encode"); + let for_arr = FoRData::encode(alp_encoded, &mut ctx).vortex_expect("for encode"); let bp = BitPackedData::encode(for_arr.encoded(), values_bit_width, &mut ctx) .vortex_expect("bitpack values"); let values_bp = bp; diff --git a/vortex-duckdb/src/duckdb/logical_type.rs b/vortex-duckdb/src/duckdb/logical_type.rs index ea1443db50a..fa2b41c714b 100644 --- a/vortex-duckdb/src/duckdb/logical_type.rs +++ b/vortex-duckdb/src/duckdb/logical_type.rs @@ -500,7 +500,11 @@ mod tests { !excluded_types.contains(&variant) }) { - assert_eq!(LogicalType::new(variant).clone().as_type_id(), variant); + let original = LogicalType::new(variant); + let copy = original.clone(); + + assert_eq!(copy.as_type_id(), variant); + assert_eq!(original.as_type_id(), variant); } } diff --git a/vortex-ffi/cmake/tests/test_compiler_commands.py b/vortex-ffi/cmake/tests/test_compiler_commands.py index d5e04f430f1..4abba182609 100644 --- a/vortex-ffi/cmake/tests/test_compiler_commands.py +++ b/vortex-ffi/cmake/tests/test_compiler_commands.py @@ -101,7 +101,9 @@ def test_compiler_arguments_warning_policy_and_freshness(self) -> None: self.build() original = self.archives() for archive in original: - self.assertIn("warning: unused variable 'vendored_unused'", (archive.parent.parent / "output").read_text()) + # The archive is in the build unit's `out` directory, and `run/stdout` holds the script output. + stdout = archive.parent.parent / "run" / "stdout" + self.assertIn("warning: unused variable 'vendored_unused'", stdout.read_text()) self.build() self.assertEqual(self.archives(), original, "An unchanged build must remain fresh") self.configure(policy=False) diff --git a/vortex-sqllogictest/bin/sqllogictests-runner.rs b/vortex-sqllogictest/bin/sqllogictests-runner.rs index 5bb9ea1247e..419d487a62f 100644 --- a/vortex-sqllogictest/bin/sqllogictests-runner.rs +++ b/vortex-sqllogictest/bin/sqllogictests-runner.rs @@ -272,7 +272,6 @@ fn main() -> anyhow::Result { } if run_duckdb { - let path = path.clone(); let test_name = format!("slt::duckdb::{name}"); let work_dir = work_dir_for(&test_name); trials.push( diff --git a/vortex-web/crate/Cargo.toml b/vortex-web/crate/Cargo.toml index 41a7cf05e5f..5df60e02724 100644 --- a/vortex-web/crate/Cargo.toml +++ b/vortex-web/crate/Cargo.toml @@ -10,10 +10,14 @@ publish = false [lib] crate-type = ["cdylib", "rlib"] -[dependencies] +# The library is empty on other targets, so every dependency is wasm-only. +[target.'cfg(target_arch = "wasm32")'.dependencies] arrow-array = { workspace = true } arrow-ipc = { workspace = true } arrow-schema = { workspace = true } +console_error_panic_hook = "0.1.7" +futures = { workspace = true } +js-sys = "0.3.85" serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } vortex = { path = "../../vortex", default-features = false, features = [ @@ -22,13 +26,8 @@ vortex = { path = "../../vortex", default-features = false, features = [ "wasm-bindgen", ] } vortex-arrow = { workspace = true } - -[target.'cfg(target_arch = "wasm32")'.dependencies] -futures = { workspace = true } wasm-bindgen = "0.2.108" wasm-bindgen-futures = { workspace = true } -console_error_panic_hook = "0.1.7" -js-sys = "0.3.85" web-sys = { version = "0.3.85", features = [ "Blob", "console", diff --git a/vortex/Cargo.toml b/vortex/Cargo.toml index 9a7b53aa004..dc5d380f7c5 100644 --- a/vortex/Cargo.toml +++ b/vortex/Cargo.toml @@ -29,6 +29,7 @@ vortex-cloud = { workspace = true, optional = true } vortex-datetime-parts = { workspace = true } vortex-decimal-byte-parts = { workspace = true } vortex-edition = { workspace = true } +vortex-elias-fano = { workspace = true } vortex-error = { workspace = true } vortex-expr = { workspace = true } vortex-fastlanes = { workspace = true } diff --git a/vortex/src/lib.rs b/vortex/src/lib.rs index dc47180cfa1..a5e45c7c7ab 100644 --- a/vortex/src/lib.rs +++ b/vortex/src/lib.rs @@ -272,6 +272,11 @@ pub mod encodings { pub use vortex_decimal_byte_parts::*; } + /// Elias-Fano and unary integer encodings. + pub mod elias_fano { + pub use vortex_elias_fano::*; + } + /// FastLanes integer encodings: bit-packing, delta, frame-of-reference, and RLE. pub mod fastlanes { pub use vortex_fastlanes::*; @@ -349,6 +354,7 @@ impl VortexSessionDefault for VortexSession { #[cfg(feature = "parquet-variant")] vortex_parquet_variant::initialize(&session); vortex_uuid::initialize(&session); + vortex_elias_fano::initialize(&session); editions::register_default_editions(&session); editions::enable_default_editions(&session); diff --git a/xtask/src/check_editions.rs b/xtask/src/check_editions.rs index 4b0b266ef1c..83cf3324627 100644 --- a/xtask/src/check_editions.rs +++ b/xtask/src/check_editions.rs @@ -323,7 +323,7 @@ pub fn check_editions(base: &str) -> anyhow::Result<()> { _ => "changes", }; let moved = if old == new { - old.clone() + old } else { format!("{old} -> {new}") }; From fd987279639a81713e800a5a6d84d51e2efdee57 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Fri, 13 Nov 2026 10:32:14 -0500 Subject: [PATCH 010/128] Declare extension storage dtypes instead of validating them (#11184) ## Summary - Tracking Issue: #11114 Right now, an extension type validates whatever storage dtype the caller hands it, so one type can have several storage forms, and its metadata doesn't say which one a dtype uses. Each `ExtVTable` now declares its storage from its metadata, so the metadata **deterministically fixes / decides** the whole storage dtype except the top-level nullability. Reads then require the stored storage to equal that declaration exactly, **including nested nullability**. This has to be strict, since arrays decode their storage child with the declared dtype, so a stored form that differs would be misread instead of rejected. Every built-in type accepts the same stored forms as before, so existing files still read. _NB on nested nullability: this means that if we potentially need nulls in the storage, an extension type MUST require its storage type to be nullable, even if in some cases it might not be. I think this is a worthwhile tradeoff for clarity of implementation._ ## Changes Some facts lived only in the storage dtype, like the element type of `Vector` and `FixedShapeTensor` and the dimension of the native spatial types, so they move into the in-memory `Metadata`. `deserialize_metadata` decodes `StoredMetadata` (which is the old `Metadata`, and `metadata_from_storage` combines it with storage to rebuild complete metadata. The serialized bytes don't change. Some other things: - File reads and storage-based dtype, array, and scalar constructors share the same checked path. - `ForeignExtDType` can't derive its storage, since it doesn't know its type, so it keeps the stored storage in its metadata and declares that. - The nested-nullability checks that #11183 added to the spatial helpers go away, since the read check now covers them. Follow-up: a read error in a struct field still panics on first access (SF in #11114). ## API Changes - `ExtVTable::validate_dtype` becomes `storage_dtype` (plus an optional `validate_metadata`), `deserialize_metadata` returns `StoredMetadata`, and `metadata_from_storage` reconstructs complete metadata from stored metadata and storage. - `ExtDType::try_new` and `try_with_vtable` take a nullability in place of the storage dtype. - Reading an extension dtype whose stored storage differs from its declaration fails, and so does building a scalar or array over the wrong storage. - `FixedShapeTensorMetadata::new` takes the element type, `Vector`'s metadata is `VectorMetadata`, metadata-first construction of native spatial dtypes needs `SpatialMetadata::with_dimension`, and `SpatialMetadata` no longer implements `prost::Message`. - `ExtDType` and `ExtensionArray` gain `try_from_storage` constructors, and `Scalar` gains `try_extension_from_storage`, with explicit-vtable variants. Existing metadata-first constructors remain available. - `FixedShapeTensorStoredMetadata` supplies shape and layout, and `SpatialStoredMetadata` supplies CRS when constructing from storage. - Fallible constructors reject non-nullable null storage, including extensions over null storage, with an error. --------- Signed-off-by: Connor Tsui --- docs/developer-guide/internals/vtables.md | 94 +++-- encodings/parquet-variant/src/kernel.rs | 8 +- encodings/uuid/src/arrow.rs | 27 +- encodings/uuid/src/lib.rs | 7 +- encodings/uuid/src/vtable.rs | 120 +++---- .../vortex/api/ExpressionTagParityTest.java | 2 +- .../java/dev/vortex/api/ExpressionTest.java | 2 +- .../src/aggregate_fn/fns/min_max/mod.rs | 22 +- vortex-array/src/arrays/extension/array.rs | 49 ++- .../src/arrays/extension/compute/rules.rs | 33 +- vortex-array/src/arrays/extension/tests.rs | 93 ++++- vortex-array/src/dtype/extension/foreign.rs | 40 ++- vortex-array/src/dtype/extension/mod.rs | 25 +- vortex-array/src/dtype/extension/plugin.rs | 19 +- vortex-array/src/dtype/extension/tests.rs | 243 ++++++++++++- vortex-array/src/dtype/extension/typed.rs | 134 ++++++- vortex-array/src/dtype/extension/vtable.rs | 85 +++-- vortex-array/src/dtype/serde/proto.rs | 4 + vortex-array/src/extension/datetime/date.rs | 47 ++- vortex-array/src/extension/datetime/time.rs | 47 ++- .../src/extension/datetime/timestamp.rs | 29 +- .../src/extension/tests/divisible_int.rs | 65 ++-- vortex-array/src/scalar/constructor.rs | 49 ++- vortex-array/src/scalar/proto.rs | 21 +- vortex-array/src/scalar/tests/casting.rs | 40 ++- .../src/scalar/typed_view/extension/tests.rs | 51 ++- vortex-arrow/src/ext_metadata.rs | 5 +- vortex-arrow/src/extension/adapter.rs | 3 +- vortex-arrow/src/extension/mod.rs | 3 +- vortex-arrow/src/extension/tests.rs | 46 ++- vortex-arrow/src/scalar.rs | 17 +- vortex-arrow/tests/vortex_id.rs | 48 ++- vortex-bench/src/conversions.rs | 11 +- vortex-bench/src/vector_dataset/convert.rs | 14 +- .../src/compressor/constant/tests.rs | 23 +- vortex-compressor/src/compressor/tests.rs | 25 +- vortex-datafusion/src/convert/scalars.rs | 2 +- vortex-datafusion/src/convert/schema.rs | 27 +- vortex-datafusion/src/convert/stats/tests.rs | 2 +- vortex-datafusion/src/persistent/tests.rs | 5 +- vortex-duckdb/src/convert/dtype.rs | 56 ++- vortex-duckdb/src/convert/scalar.rs | 2 +- vortex-duckdb/src/convert/vector.rs | 4 +- .../src/e2e_test/spatial_pushdown_test.rs | 8 +- .../src/e2e_test/vortex_scan_test.rs | 2 +- vortex-duckdb/src/exporter/uuid.rs | 2 +- vortex-jni/src/expression.rs | 14 +- vortex-json/src/arrow.rs | 9 +- vortex-json/src/dtype.rs | 22 +- vortex-python/src/scalar/factory.rs | 12 +- vortex-spatial/src/aggregate_fn/aabb.rs | 28 +- vortex-spatial/src/extension/coordinate.rs | 21 +- vortex-spatial/src/extension/linestring.rs | 83 +++-- vortex-spatial/src/extension/mod.rs | 340 +++++++++++++++--- .../src/extension/multilinestring.rs | 92 +++-- vortex-spatial/src/extension/multipoint.rs | 85 +++-- vortex-spatial/src/extension/multipolygon.rs | 94 +++-- vortex-spatial/src/extension/point.rs | 89 +++-- vortex-spatial/src/extension/polygon.rs | 91 +++-- vortex-spatial/src/extension/rect.rs | 92 ++--- vortex-spatial/src/extension/wkb.rs | 42 ++- vortex-spatial/src/prune/test_harness.rs | 8 +- vortex-spatial/src/scalar_fn/collect.rs | 15 +- vortex-spatial/src/scalar_fn/convex_hull.rs | 8 +- vortex-spatial/src/scalar_fn/envelope.rs | 14 +- vortex-spatial/src/scalar_fn/make_line.rs | 19 +- vortex-spatial/src/test_harness.rs | 65 +--- vortex-spatial/src/tests/wkb.rs | 25 +- vortex-tensor/benches/cosine_similarity.rs | 3 +- vortex-tensor/src/matcher.rs | 5 +- vortex-tensor/src/scalar_fns/l2_norm.rs | 10 +- .../src/types/fixed_shape_tensor/matcher.rs | 63 +--- .../src/types/fixed_shape_tensor/metadata.rs | 190 ++++++++-- .../src/types/fixed_shape_tensor/mod.rs | 1 + .../src/types/fixed_shape_tensor/proto.rs | 12 +- .../src/types/fixed_shape_tensor/vtable.rs | 200 +++++++++-- vortex-tensor/src/types/vector/arrow.rs | 27 +- vortex-tensor/src/types/vector/matcher.rs | 104 +----- vortex-tensor/src/types/vector/metadata.rs | 58 +++ vortex-tensor/src/types/vector/mod.rs | 61 ++-- vortex-tensor/src/types/vector/vtable.rs | 114 +++--- vortex-tensor/src/utils.rs | 25 +- 82 files changed, 2504 insertions(+), 1298 deletions(-) create mode 100644 vortex-tensor/src/types/vector/metadata.rs diff --git a/docs/developer-guide/internals/vtables.md b/docs/developer-guide/internals/vtables.md index 39bcd292b66..adbfcec1efd 100644 --- a/docs/developer-guide/internals/vtables.md +++ b/docs/developer-guide/internals/vtables.md @@ -31,7 +31,7 @@ FooRef thin Arc wrapper, delegates to DynFoo **Data struct** `Foo` is generic over the vtable type `V`. It holds the vtable instance (which may be zero-sized for native implementations or non-zero-sized for language bindings), common fields, and a VTable-specific associated type for concept-specific data (e.g. -`V::Metadata` for ExtDType, `V::Array` for Array). `Foo` is not Arc-wrapped — it lives +`V::Metadata` for ExtDType, `V::Array` for Array). `Foo` is not Arc-wrapped, it lives behind `Arc` inside `FooRef`. `Foo` has inherent methods for all operations, with pre/post-condition enforcement. These delegate to `FooVTable` methods. @@ -41,7 +41,7 @@ the result of downcasting from `&FooRef`), while common methods on `Foo` rema via normal method resolution. **Sealed trait** `DynFoo` is object-safe and has a blanket `impl DynFoo for Foo`. -This blanket impl is a thin forwarder to `Foo` inherent methods — no logic of its own. +This blanket impl is a thin forwarder to `Foo` inherent methods, no logic of its own. Its purpose is to enable dynamic dispatch from `FooRef` through to the typed `Foo`. `DynFoo` must stay private (`pub(super)`) because it exposes internal plumbing (`as_any`, `metadata_any`) that should not be part of the public API. @@ -57,6 +57,9 @@ FooRef::as_::(&self) -> &Foo borrow, free after type check FooRef::downcast::(self) -> Arc> owned, free after type check ``` +Extension dtypes provide borrowed metadata access through `metadata::()` and owned typed access +through `downcast::()`, as shown in the extension dtype example below. + **Plugin** `FooPlugin` is a separate trait for registry-based deserialization. It knows how to reconstruct a `FooRef` from serialized bytes without knowing `V` at compile time. Plugins are registered in the session by their ID. @@ -86,16 +89,25 @@ For Array encodings, each encoding has its own module (e.g. `arrays/primitive/`) Extension dtypes follow this pattern: ```rust -trait ExtDTypeVTable: Sized + Send + Sync + Clone + Debug { +trait ExtVTable: Sized + Send + Sync + Clone + Debug { type Metadata: Send + Sync + Clone + Debug + Display + Eq + Hash; + type StoredMetadata; fn id(&self) -> ExtId; - fn serialize(&self, metadata: &Self::Metadata) -> VortexResult>; - fn deserialize(&self, metadata: &[u8]) -> VortexResult; - fn validate(&self, metadata: &Self::Metadata, storage_dtype: &DType) -> VortexResult<()>; + fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult>; + fn deserialize_metadata(&self, bytes: &[u8]) -> VortexResult; + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult; + fn storage_dtype(metadata: &Self::Metadata) -> DType; + fn validate_metadata(_metadata: &Self::Metadata) -> VortexResult<()> { + Ok(()) + } } -struct ExtDType { +struct ExtDType { vtable: V, metadata: V::Metadata, storage_dtype: DType, @@ -107,11 +119,47 @@ struct ExtDTypeRef(Arc); Downcasting from the erased form recovers the typed data struct: ```rust -let ext: & ExtDTypeRef = dtype.ext(); -let ts: & ExtDType = ext.as_::(); -let unit: & TimeUnit = & ts.metadata; // V::Metadata is concrete +let ext: &ExtDTypeRef = dtype.as_extension(); +let metadata = ext.metadata::(); +let unit: &TimeUnit = &metadata.unit; // V::Metadata is concrete. +let ts: Arc> = ext.clone().downcast::(); ``` +## Storage and nullability + +`ExtDType::try_new(metadata, nullability)` uses a default vtable. `try_with_vtable` accepts an +explicit vtable instance. Both validate metadata before deriving storage through +`ExtVTable::storage_dtype`. + +The in-memory metadata determines the storage structure, element types, and nested nullability. +`ExtDType` applies the requested top-level nullability. For example, a vector's metadata holds its +float element type and dimension, and its storage is a fixed-size list of non-nullable elements. +The outer list can be nullable independently of its elements. + +`with_nullability` keeps the metadata and rebuilds storage from the declaration with the requested +outer nullability. It does not validate metadata again. Storage of `DType::Null`, including an +extension over it, is always nullable. `with_nullability` panics if asked to make that storage +non-nullable, while fallible constructors return an error. + +`StoredMetadata` is the in-memory form of the metadata stored alongside the storage dtype. +Callers can also construct it directly. Complete `Metadata` adds facts inferred from storage. +For a vector, stored metadata is `()`, and storage supplies the element type and dimension. +Stored tensor metadata supplies shape, dimension names, and permutation, while storage supplies +the element type. A timestamp uses the same type for both, because storage cannot determine its +unit or time zone. + +`ExtDType::try_from_storage(stored_metadata, storage_dtype)` reconstructs metadata through +`metadata_from_storage`. It passes a nullable outer storage level, validates the metadata, and +requires its declaration to match the supplied storage exactly, including nested nullability. +The resulting dtype keeps the supplied outer nullability. `try_from_storage_with_vtable` accepts +an explicit vtable. `ExtensionArray::try_from_storage` and +`Scalar::try_extension_from_storage` use the actual storage array or scalar's dtype. The scalar +constructor also validates the value. + +On read, `deserialize_metadata` decodes bytes into `StoredMetadata`. The dtype plugin then uses the +same checked storage constructor. Serialized bytes can omit facts represented by storage, and a +storage mismatch returns an error naming both dtypes. + ## Why Not `dyn Trait` Rust's `dyn Trait` vtables have several limitations that make them unsuitable for Vortex's @@ -147,7 +195,7 @@ on the same type triggers `clippy::same_name_method`. The correct handling is: delegation to `FooVTable` all happen here. 2. **`DynFoo` blanket impl is a thin forwarder.** Each method body is just `self.method()`. Rust's method resolution picks inherent methods over trait methods, so this calls the - inherent impl — no infinite recursion. + inherent impl, no infinite recursion. 3. **`#[allow(clippy::same_name_method)]`** on the `Foo` inherent impl block acknowledges the intentional shadowing. @@ -169,7 +217,7 @@ impl DynFoo for Foo { `DynFoo` must stay **private** (`pub(super)`) because it exposes internal plumbing (`as_any`, `metadata_any`) that external callers should never reach. Making it public or implementing it for `FooRef` would leak these internals. Instead, `FooRef` has its -own inherent methods that delegate to `DynFoo` — providing a clean public API without +own inherent methods that delegate to `DynFoo`, providing a clean public API without exposing the dispatch machinery. Methods that exist only for erased dispatch (e.g. `as_any`, `metadata_any`, @@ -189,19 +237,19 @@ consistent across all vtable-backed types in Vortex. ## Migration Status -All four vtable-backed types are converging on the pattern described above. +All four vtable-backed types are converging on the pattern described above. The extension dtype +status reflects the API above. The remaining subsections retain the broader migration plan. -### ExtDType -- Partially done +### ExtDType -- Done -File split already matches conventions: `vtable.rs`, `typed.rs`, `erased.rs`, -`plugin.rs`, `matcher.rs`. Remaining: +The file split matches the conventions: `vtable.rs`, `typed.rs`, `erased.rs`, `plugin.rs`, and +`matcher.rs`. -- **Drop internal Arc from `ExtDType`.** Currently wraps - `Arc>`. Should become the data struct itself, with - `ExtDTypeRef(Arc)` holding the Arc. Remove `ExtDTypeAdapter`. -- **Rename** `ExtDTypeImpl` → `DynExtDType`, `DynExtVTable` → `ExtDTypePlugin`. -- **Remove `ExtDTypeMetadata`** erased wrapper. Its methods (`serialize`, `Display`, - `Debug`, `PartialEq`, `Hash`) should move to `ExtDTypeRef`. +- `ExtDType` is the data struct. `ExtDTypeRef(Arc)` owns the shared allocation. +- `ExtVTable` is the public implementation trait, `DynExtDType` provides private erased dispatch, + and `ExtDTypePlugin` provides registry-based deserialization. +- Metadata stays typed inside `ExtDType`. `ExtDTypeRef` exposes serialization, `Display`, + `Debug`, equality, and hashing through the private dispatch layer. ### Expr -- Not started @@ -254,7 +302,7 @@ with pre/post-condition enforcement. These delegate to `ArrayVTable` methods. the associated type are callable directly on `&Array`. Common methods (`dtype()`, `len()`) are inherent on `Array` and resolve first. -Children live in `V::Array` — each encoding owns its child representation. +Children live in `V::Array`, each encoding owns its child representation. The VTable provides `nchildren()` / `child(i)` for generic traversal. Constructors live on the vtable ZST: `Primitive::new(...) -> ArrayRef`. diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index d28bd43a45d..6290b04bca4 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -362,13 +362,9 @@ mod tests { use vortex_uuid::Uuid; use vortex_uuid::UuidMetadata; - let storage = VortexDType::FixedSizeList( - Arc::new(VortexDType::Primitive(PType::U8, Nullability::NonNullable)), - 16, - Nullability::NonNullable, - ); let uuid = VortexDType::Extension( - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage)?.erased(), + ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), Nullability::NonNullable)? + .erased(), ); let arrow = SESSION.arrow(); diff --git a/encodings/uuid/src/arrow.rs b/encodings/uuid/src/arrow.rs index 4a4011c5859..7cc58d2263f 100644 --- a/encodings/uuid/src/arrow.rs +++ b/encodings/uuid/src/arrow.rs @@ -26,8 +26,6 @@ use vortex_array::arrays::FixedSizeListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_array::buffer::BufferHandle; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_array::validity::Validity; @@ -100,16 +98,10 @@ impl ArrowExtVTable for Uuid { return Ok(None); } - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - UUID_BYTE_LEN as u32, - field.is_nullable().into(), - ); - Ok(Some(ExtDType::try_with_vtable( Uuid, UuidMetadata::default(), - storage_dtype, + field.is_nullable().into(), )?)) } @@ -209,8 +201,10 @@ mod tests { use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldNames; + use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; use vortex_array::iter::ArrayIterator; use vortex_arrow::ArrowArrayStreamAdapter; @@ -261,13 +255,8 @@ mod tests { } fn uuid_dtype(nullable: bool) -> DType { - let storage = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - 16, - nullable.into(), - ); DType::Extension( - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage) + ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), nullable.into()) .expect("uuid ext dtype") .erased(), ) @@ -807,12 +796,8 @@ mod tests { /// Builds three UUIDs with valid version bits, with a null middle row when nullable. fn versioned_uuid_array(version: Option, nullable: bool) -> VortexResult { - let dtype = ExtDType::try_with_vtable( - Uuid, - UuidMetadata { version }, - uuid_dtype(nullable).as_extension().storage_dtype().clone(), - )? - .erased(); + let dtype = + ExtDType::try_with_vtable(Uuid, UuidMetadata { version }, nullable.into())?.erased(); let bytes = match version { Some(Version::Max) => [u8::MAX; 16], diff --git a/encodings/uuid/src/lib.rs b/encodings/uuid/src/lib.rs index 7db124c50a4..d1773741c7b 100644 --- a/encodings/uuid/src/lib.rs +++ b/encodings/uuid/src/lib.rs @@ -99,8 +99,11 @@ mod tests { leading_bytes.len(), ) .into_array(); - let ext_dtype = - ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage.dtype().clone())?; + let ext_dtype = ExtDType::try_with_vtable( + Uuid, + UuidMetadata::default(), + storage.dtype().nullability(), + )?; Ok(ExtensionArray::new(ext_dtype.erased(), storage).into_array()) } diff --git a/encodings/uuid/src/vtable.rs b/encodings/uuid/src/vtable.rs index 03b7400347f..5746fb2f43e 100644 --- a/encodings/uuid/src/vtable.rs +++ b/encodings/uuid/src/vtable.rs @@ -3,7 +3,10 @@ //! The extension dtype vtable for UUIDs. +use std::sync::Arc; + use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; @@ -12,7 +15,6 @@ use vortex_array::scalar::PValue; use vortex_array::scalar::ScalarValue; use vortex_error::VortexResult; use vortex_error::vortex_bail; -use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; use vortex_error::vortex_err; use vortex_session::registry::CachedId; @@ -26,6 +28,7 @@ pub(crate) const UUID_BYTE_LEN: usize = 16; impl ExtVTable for Uuid { type Metadata = UuidMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = uuid::Uuid; fn id(&self) -> ExtId { @@ -40,7 +43,7 @@ impl ExtVTable for Uuid { } } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { let version = match metadata.len() { 0 => None, 1 => Some(u8_to_version(metadata[0])?), @@ -52,29 +55,24 @@ impl ExtVTable for Uuid { Ok(UuidMetadata { version }) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { - let storage_dtype = ext_dtype.storage_dtype(); - let DType::FixedSizeList(element_dtype, list_size, _nullability) = storage_dtype else { - vortex_bail!("UUID storage dtype must be a FixedSizeList, got {storage_dtype}"); - }; - - vortex_ensure_eq!( - *list_size as usize, - UUID_BYTE_LEN, - "UUID storage FixedSizeList size mismatch" - ); - - let DType::Primitive(ptype, elem_nullability) = element_dtype.as_ref() else { - vortex_bail!("UUID element dtype must be Primitive(U8), got {element_dtype}"); - }; - - vortex_ensure_eq!(*ptype, PType::U8, "UUID element dtype must be U8"); - vortex_ensure!( - !elem_nullability.is_nullable(), - "UUID element dtype must be non-nullable" - ); + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } - Ok(()) + #[expect( + clippy::cast_possible_truncation, + reason = "UUID_BYTE_LEN always fits u32" + )] + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ) } fn unpack_native<'a>( @@ -130,6 +128,7 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtDTypePlugin; use vortex_array::dtype::extension::ExtVTable; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; @@ -179,47 +178,35 @@ mod tests { #[rstest] #[case::non_nullable(Nullability::NonNullable)] #[case::nullable(Nullability::Nullable)] - fn validate_correct_storage_dtype(#[case] nullability: Nullability) -> VortexResult<()> { - let metadata = UuidMetadata::default(); - let storage_dtype = uuid_storage_dtype(nullability); - ExtDType::try_with_vtable(Uuid, metadata, storage_dtype)?; + fn read_accepts_declared_storage_dtype(#[case] nullability: Nullability) -> VortexResult<()> { + Uuid.deserialize(&[], uuid_storage_dtype(nullability))?; Ok(()) } - #[test] - fn validate_rejects_wrong_list_size() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), - 8, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_wrong_element_type() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U64, Nullability::NonNullable)), - UUID_BYTE_LEN as u32, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_nullable_elements() { - let storage_dtype = DType::FixedSizeList( - Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), - UUID_BYTE_LEN as u32, - Nullability::NonNullable, - ); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); - } - - #[test] - fn validate_rejects_non_fsl() { - let storage_dtype = DType::Primitive(PType::U8, Nullability::NonNullable); - assert!(ExtDType::try_with_vtable(Uuid, UuidMetadata::default(), storage_dtype).is_err()); + /// A read fails unless the stored storage dtype is the declared one, including the + /// nullability of the bytes, and the error names both dtypes. + #[rstest] + #[case::wrong_list_size(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::NonNullable)), + 8, + Nullability::NonNullable, + ))] + #[case::wrong_element_type(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U64, Nullability::NonNullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ))] + #[case::nullable_elements(DType::FixedSizeList( + Arc::new(DType::Primitive(PType::U8, Nullability::Nullable)), + UUID_BYTE_LEN as u32, + Nullability::NonNullable, + ))] + #[case::non_fsl(DType::Primitive(PType::U8, Nullability::NonNullable))] + fn read_rejects_other_storage_dtype(#[case] storage_dtype: DType) { + let expected = + format!("vortex.uuid storage must be fixed_size_list(u8)[16], got {storage_dtype}"); + let result = Uuid.deserialize(&[], storage_dtype); + assert!(result.is_err_and(|error| error.to_string().contains(&expected))); } #[test] @@ -227,10 +214,7 @@ mod tests { let expected = uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000") .map_err(|e| vortex_error::vortex_err!("{e}"))?; - let ext_dtype = ExtDType::try_new( - UuidMetadata::default(), - uuid_storage_dtype(Nullability::NonNullable), - )?; + let ext_dtype = ExtDType::try_new(UuidMetadata::default(), Nullability::NonNullable)?; let children: Vec = expected .as_bytes() .iter() @@ -264,7 +248,7 @@ mod tests { UuidMetadata { version: Some(Version::SortRand), }, - uuid_storage_dtype(Nullability::NonNullable), + Nullability::NonNullable, )?; let children: Vec = v4_uuid .as_bytes() @@ -309,7 +293,7 @@ mod tests { UuidMetadata { version: Some(Version::Random), }, - uuid_storage_dtype(Nullability::NonNullable), + Nullability::NonNullable, )?; let storage_value = uuid_storage_scalar(&v4_uuid); diff --git a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java index 5790979286a..95c0e5cb1d2 100644 --- a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java +++ b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTagParityTest.java @@ -233,7 +233,7 @@ public void theTagTablesAreReadIndependently() { private static void assertDateRejects(TimeUnit unit) { RuntimeException exception = assertThrows(RuntimeException.class, () -> Expression.literalDate(0L, unit)); assertTrue( - exception.getMessage().contains("Date type does not support time unit"), + exception.getMessage().contains("Date time unit must be days or milliseconds"), () -> "unexpected message for " + unit + ": " + exception.getMessage()); } } diff --git a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java index 5ba86dfac12..5a0fd712aeb 100644 --- a/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java +++ b/java/vortex-jni/src/test/java/dev/vortex/api/ExpressionTest.java @@ -98,7 +98,7 @@ public void literalTimeAcceptsEveryUnitExceptDays() { RuntimeException exception = assertThrows(RuntimeException.class, () -> Expression.literalTime(0L, Expression.TimeUnit.DAYS)); assertTrue( - exception.getMessage().contains("Time type does not support time unit"), + exception.getMessage().contains("Time time unit must be finer than days"), () -> "unexpected message: " + exception.getMessage()); } diff --git a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs index 303ca9c5d07..9b0dfa81b63 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -1360,6 +1360,7 @@ mod tests { impl ExtVTable for F64Ext { type Metadata = EmptyMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a ScalarValue; #[expect(clippy::disallowed_methods, reason = "test-only id")] @@ -1371,12 +1372,20 @@ mod tests { Ok(vec![]) } - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { Ok(EmptyMetadata) } - fn validate_dtype(_extension_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::F64, Nullability::NonNullable) } fn unpack_native<'a>( @@ -1388,11 +1397,8 @@ mod tests { } fn f64_ext_array(values: Buffer) -> VortexResult { - let ext_dtype = ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::F64, Nullability::NonNullable), - )? - .erased(); + let ext_dtype = + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable)?.erased(); Ok(ExtensionArray::new(ext_dtype, values.into_array()).into_array()) } diff --git a/vortex-array/src/arrays/extension/array.rs b/vortex-array/src/arrays/extension/array.rs index 80858d33cb4..411f28f7460 100644 --- a/vortex-array/src/arrays/extension/array.rs +++ b/vortex-array/src/arrays/extension/array.rs @@ -39,6 +39,36 @@ pub trait ExtensionArrayExt: TypedArrayRef { impl> ExtensionArrayExt for T {} impl Array { + /// Reconstructs an extension array from stored metadata and its storage array. + /// + /// See [`try_from_storage_with_vtable`](Self::try_from_storage_with_vtable) for the checks. + pub fn try_from_storage( + stored_metadata: V::StoredMetadata, + storage: ArrayRef, + ) -> VortexResult { + Self::try_from_storage_with_vtable(V::default(), stored_metadata, storage) + } + + /// Reconstructs metadata and checks its declaration against the storage array's dtype. + /// + /// # Errors + /// + /// Returns an error if metadata reconstruction or validation fails, or storage differs from + /// the declaration, including nested nullability. + pub fn try_from_storage_with_vtable( + vtable: V, + stored_metadata: V::StoredMetadata, + storage: ArrayRef, + ) -> VortexResult { + let dtype = ExtDType::try_from_storage_with_vtable( + vtable, + stored_metadata, + storage.dtype().clone(), + )?; + + Self::try_new(dtype.erased(), storage) + } + /// Constructs a new `ExtensionArray`. /// /// # Panics @@ -48,12 +78,17 @@ impl Array { Self::try_new(ext_dtype, storage_array).vortex_expect("Unable to create `ExtensionArray`") } - /// Tries to construct a new `ExtensionArray`. + /// Constructs an extension array whose storage dtype exactly matches `ext_dtype`. + /// + /// # Errors + /// + /// Returns an error if the storage dtypes differ, including top-level or nested nullability. pub fn try_new(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> VortexResult { vortex_ensure_eq!( ext_dtype.storage_dtype(), storage_array.dtype(), - "Tried to create an `ExtensionArray` with an incompatible storage array" + "{} storage must match its declaration", + ext_dtype.id() ); let dtype = DType::Extension(ext_dtype); @@ -75,13 +110,21 @@ impl Array { /// Creates a new [`ExtensionArray`](crate::arrays::ExtensionArray) from a vtable, metadata, and /// a storage array. + /// + /// Uses the storage array's top-level nullability when constructing the dtype. The complete + /// storage dtype must match the metadata's declaration. + /// + /// # Errors + /// + /// Returns an error if metadata validation fails or the storage dtype differs from the + /// declaration, including nested nullability. pub fn try_new_from_vtable( vtable: V, metadata: V::Metadata, storage_array: ArrayRef, ) -> VortexResult { let ext_dtype = - ExtDType::::try_with_vtable(vtable, metadata, storage_array.dtype().clone())? + ExtDType::::try_with_vtable(vtable, metadata, storage_array.dtype().nullability())? .erased(); Self::try_new(ext_dtype, storage_array) diff --git a/vortex-array/src/arrays/extension/compute/rules.rs b/vortex-array/src/arrays/extension/compute/rules.rs index 28c63ee791b..623f151c9a1 100644 --- a/vortex-array/src/arrays/extension/compute/rules.rs +++ b/vortex-array/src/arrays/extension/compute/rules.rs @@ -132,6 +132,7 @@ mod tests { struct TestExt; impl ExtVTable for TestExt { type Metadata = EmptyMetadata; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a str; #[expect(clippy::disallowed_methods, reason = "test-only id")] @@ -143,12 +144,20 @@ mod tests { Ok(vec![]) } - fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, _data: &[u8]) -> VortexResult { Ok(EmptyMetadata) } - fn validate_dtype(_extension_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Primitive(PType::I64, Nullability::NonNullable) } fn unpack_native<'a>( @@ -160,12 +169,9 @@ mod tests { } fn test_ext_dtype() -> ExtDTypeRef { - ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::I64, Nullability::NonNullable), - ) - .unwrap() - .erased() + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable) + .unwrap() + .erased() } #[test] @@ -204,12 +210,9 @@ mod tests { #[test] fn test_filter_pushdown_nullable() { - let ext_dtype = ExtDType::::try_new( - EmptyMetadata, - DType::Primitive(PType::I64, Nullability::Nullable), - ) - .unwrap() - .erased(); + let ext_dtype = ExtDType::::try_new(EmptyMetadata, Nullability::Nullable) + .unwrap() + .erased(); let storage = PrimitiveArray::from_option_iter([Some(1i64), None, Some(3), Some(4), None]) .into_array(); let ext_array = ExtensionArray::new(ext_dtype, storage).into_array(); diff --git a/vortex-array/src/arrays/extension/tests.rs b/vortex-array/src/arrays/extension/tests.rs index 2769a52edba..e50f3e327e6 100644 --- a/vortex-array/src/arrays/extension/tests.rs +++ b/vortex-array/src/arrays/extension/tests.rs @@ -16,7 +16,6 @@ use vortex_session::registry::CachedId; use crate::ArrayParts; use crate::ArrayRef; use crate::EmptyArrayData; -use crate::EmptyMetadata; use crate::IntoArray; use crate::VortexSessionExecute; use crate::aggregate_fn::AggregateFn; @@ -31,6 +30,7 @@ use crate::arrays::ConstantArray; use crate::arrays::Extension; use crate::arrays::ExtensionArray; use crate::arrays::PrimitiveArray; +use crate::arrays::extension::ExtensionArrayExt; use crate::arrays::extension::ExtensionSlots; use crate::assert_arrays_eq; use crate::dtype::DType; @@ -62,10 +62,7 @@ struct NonZero; impl NonZero { fn dtype(ptype: PType, nullability: Nullability) -> VortexResult { - Ok( - ExtDType::::try_new(EmptyMetadata, DType::Primitive(ptype, nullability))? - .erased(), - ) + Ok(ExtDType::::try_new(ptype, nullability)?.erased()) } fn array(storage: ArrayRef) -> VortexResult { @@ -76,7 +73,8 @@ impl NonZero { } impl ExtVTable for NonZero { - type Metadata = EmptyMetadata; + type Metadata = PType; + type StoredMetadata = (); type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -88,18 +86,26 @@ impl ExtVTable for NonZero { Ok(vec![]) } - fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { - Ok(EmptyMetadata) + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(()) + } + + fn metadata_from_storage( + &self, + _stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + PType::try_from(storage_dtype) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + DType::Primitive(*metadata, Nullability::NonNullable) } - fn validate_dtype(ext_dtype: &ExtDType) -> VortexResult<()> { + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { vortex_ensure!( - matches!( - ext_dtype.storage_dtype(), - DType::Primitive(PType::I64 | PType::F64, _) - ), - "NonZero requires i64 or f64 storage, got {}", - ext_dtype.storage_dtype() + matches!(metadata, PType::I64 | PType::F64), + "NonZero requires i64 or f64 storage, got {metadata}" ); Ok(()) @@ -170,16 +176,36 @@ fn test_scalar_values_require_the_storage_dtype(#[case] value: ScalarValue) -> V } #[rstest] -#[case::wrong_dtype(Scalar::from(1.0f64))] -#[case::invalid_value(Scalar::from(0i64))] -fn test_extension_constructor_rejects_invalid_storage(#[case] storage: Scalar) -> VortexResult<()> { +#[case::wrong_dtype( + Scalar::from(1.0f64), + "test.non_zero storage must match its declaration\n left: i64\n right: f64" +)] +#[case::invalid_value(Scalar::from(0i64), "NonZero requires a finite nonzero value, got 0")] +fn test_extension_constructor_rejects_invalid_storage( + #[case] storage: Scalar, + #[case] expected: &str, +) -> VortexResult<()> { let dtype = NonZero::dtype(PType::I64, Nullability::NonNullable)?; - assert!(Scalar::try_extension_ref(dtype, storage).is_err()); + let result = Scalar::try_extension_ref(dtype, storage); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); Ok(()) } +/// Building an extension array over storage of another dtype fails with an error that names the +/// type and both storage dtypes. +#[test] +fn test_array_constructor_rejects_other_storage_dtype() { + let result = + ExtensionArray::try_new_from_vtable(NonZero, PType::I64, buffer![1f64].into_array()); + assert!(result.is_err_and(|error| { + error + .to_string() + .contains("test.non_zero storage must match its declaration\n left: i64\n right: f64") + })); +} + #[rstest] #[case::wrong_kind(ConstantArray::new("value", 1).into_array())] #[case::wrong_primitive(buffer![1f64].into_array())] @@ -256,3 +282,32 @@ fn test_rejected_extension_zero_cannot_construct_a_scalar( Scalar::zero_value(&dtype); } + +/// Storage-based construction preserves outer nullability and scalar validation. +#[rstest] +#[case::non_nullable(Nullability::NonNullable)] +#[case::nullable(Nullability::Nullable)] +fn storage_constructors(#[case] nullability: Nullability) -> VortexResult<()> { + let storage = Scalar::primitive(1i64, nullability); + let scalar = Scalar::try_extension_from_storage::((), storage.clone())?; + assert_eq!(scalar.dtype().nullability(), nullability); + + let array = ConstantArray::new(storage, 2).into_array(); + let result = ExtensionArray::try_from_storage::((), array.clone())?; + assert_eq!(result.ext_dtype().storage_dtype(), array.dtype()); + + assert!( + Scalar::try_extension_from_storage::((), Scalar::primitive(0i64, nullability)) + .is_err() + ); + + Ok(()) +} + +#[test] +fn storage_constructor_accepts_null_scalar() -> VortexResult<()> { + let null = Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)); + assert!(Scalar::try_extension_from_storage::((), null)?.is_null()); + + Ok(()) +} diff --git a/vortex-array/src/dtype/extension/foreign.rs b/vortex-array/src/dtype/extension/foreign.rs index b7636225ff9..9efa0f3af3e 100644 --- a/vortex-array/src/dtype/extension/foreign.rs +++ b/vortex-array/src/dtype/extension/foreign.rs @@ -14,12 +14,27 @@ use crate::dtype::extension::ExtId; use crate::dtype::extension::ExtVTable; use crate::scalar::ScalarValue; +/// Opaque metadata bytes and storage dtype preserved for an unregistered extension type. #[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct ForeignExtMetadata(pub Vec); +pub struct ForeignExtMetadata { + bytes: Vec, + /// The stored storage dtype with a nullable top level. Normalizing that level keeps metadata + /// equality and hashing independent of the extension dtype's top-level nullability. + storage_dtype: DType, +} + +impl ForeignExtMetadata { + fn new(bytes: Vec, storage_dtype: &DType) -> Self { + Self { + bytes, + storage_dtype: storage_dtype.as_nullable(), + } + } +} impl Display for ForeignExtMetadata { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "{}B", self.0.len()) + write!(f, "{}B", self.bytes.len()) } } @@ -40,7 +55,7 @@ impl ForeignExtDType { storage_dtype: DType, ) -> VortexResult { Ok( - ExtDType::try_with_vtable(Self::new(id), ForeignExtMetadata(metadata), storage_dtype)? + ExtDType::try_from_storage_with_vtable(Self::new(id), metadata, storage_dtype)? .erased(), ) } @@ -48,6 +63,7 @@ impl ForeignExtDType { impl ExtVTable for ForeignExtDType { type Metadata = ForeignExtMetadata; + type StoredMetadata = Vec; type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -55,15 +71,23 @@ impl ExtVTable for ForeignExtDType { } fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult> { - Ok(metadata.0.clone()) + Ok(metadata.bytes.clone()) + } + + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + Ok(metadata.to_vec()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { - Ok(ForeignExtMetadata(metadata.to_vec())) + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + Ok(ForeignExtMetadata::new(stored_metadata, storage_dtype)) } - fn validate_dtype(_ext_dtype: &ExtDType) -> VortexResult<()> { - Ok(()) + fn storage_dtype(metadata: &Self::Metadata) -> DType { + metadata.storage_dtype.clone() } fn unpack_native<'a>( diff --git a/vortex-array/src/dtype/extension/mod.rs b/vortex-array/src/dtype/extension/mod.rs index e2808e79ed8..9d5975f66e2 100644 --- a/vortex-array/src/dtype/extension/mod.rs +++ b/vortex-array/src/dtype/extension/mod.rs @@ -1,26 +1,31 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Extension DTypes, and interfaces for working with extension types. +//! Extension dtypes and their typed, erased, and registered interfaces. //! //! An extension dtype gives semantic meaning to values stored in an ordinary Vortex storage dtype. //! For example, a timestamp extension can store an integer while carrying unit/time-zone metadata. //! Arrays with [`DType::Extension`](crate::dtype::DType::Extension) use //! [`crate::arrays::ExtensionArray`] to pair the extension dtype with the storage array. //! -//! Extension dtype implementations provide an [`ExtVTable`] for identity, metadata -//! serialization, storage dtype validation, scalar validation, and typed scalar unpacking. Register -//! extension plugins in a session before deserializing data that may reference them. +//! Extension dtype implementations provide an [`ExtVTable`] for identity, metadata serialization, +//! the storage dtype declaration, scalar validation, and typed scalar unpacking. Register extension +//! plugins in a session before deserializing data that may reference them. +//! +//! [`ExtDType`] provides typed access to a concrete [`ExtVTable`]. Its erased handle, +//! [`ExtDTypeRef`], stores different extension types behind one interface. [`Matcher`] retrieves +//! metadata for a known type, and [`ExtDTypePlugin`] reconstructs dtypes through the session +//! registry. //! //! ## File layout convention //! -//! Each vtable-backed concept `Foo` follows this module structure: +//! Each vtable-backed concept `Foo` separates these responsibilities: //! -//! - `vtable.rs` — `FooVTable` (the non-object-safe trait users implement) -//! - `plugin.rs` — `FooPlugin` (registry trait for deserialization + blanket impl) -//! - `typed.rs` — `Foo` (typed wrapper) + `FooInner` + `DynFoo` (private) -//! - `erased.rs` — `FooRef` (erased ref + Display/Debug/PartialEq/Hash impls) -//! - `matcher.rs` — `Matcher` trait + blanket impl for `V: FooVTable` +//! - `vtable.rs`: `FooVTable`, the non-object-safe trait users implement. +//! - `plugin.rs`: `FooPlugin`, the registry trait and its blanket implementation. +//! - `typed.rs`: `Foo`, the typed wrapper, and the private `DynFoo` dispatch trait. +//! - `erased.rs`: `FooRef`, including display, debug, equality, and hashing. +//! - `matcher.rs`: `Matcher` and its implementation for `V: FooVTable`. mod vtable; pub use vtable::*; diff --git a/vortex-array/src/dtype/extension/plugin.rs b/vortex-array/src/dtype/extension/plugin.rs index 7d242d85274..eddf6b0bc4d 100644 --- a/vortex-array/src/dtype/extension/plugin.rs +++ b/vortex-array/src/dtype/extension/plugin.rs @@ -26,7 +26,16 @@ pub trait ExtDTypePlugin: 'static + Send + Sync + Debug { /// Returns the ID for this extension type. fn id(&self) -> ExtId; - /// Deserialize an extension type from serialized metadata. + /// Reconstructs an extension dtype from serialized metadata and its stored storage dtype. + /// + /// The blanket implementation for [`ExtVTable`] reconstructs and validates the metadata, then + /// checks the declared storage against `storage_dtype`. The returned dtype has exactly that + /// storage dtype, including top-level and nested nullability. + /// + /// # Errors + /// + /// Returns an error if metadata reconstruction or validation fails, or if the declaration with + /// the stored top-level nullability differs from `storage_dtype`. fn deserialize(&self, data: &[u8], storage_dtype: DType) -> VortexResult; } @@ -36,7 +45,11 @@ impl ExtDTypePlugin for V { } fn deserialize(&self, data: &[u8], storage_dtype: DType) -> VortexResult { - let metadata = ExtVTable::deserialize_metadata(self, data)?; - Ok(ExtDType::try_with_vtable(self.clone(), metadata, storage_dtype)?.erased()) + let stored_metadata = ExtVTable::deserialize_metadata(self, data)?; + + Ok( + ExtDType::try_from_storage_with_vtable(self.clone(), stored_metadata, storage_dtype)? + .erased(), + ) } } diff --git a/vortex-array/src/dtype/extension/tests.rs b/vortex-array/src/dtype/extension/tests.rs index 5fee4a2375e..2aa5c9350f8 100644 --- a/vortex-array/src/dtype/extension/tests.rs +++ b/vortex-array/src/dtype/extension/tests.rs @@ -1,36 +1,54 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Regression tests for extension dtype nullability changes and debug output. +//! Regression tests for extension dtype construction, reads, nullability changes, and debug +//! output. +use std::hash::DefaultHasher; +use std::hash::Hasher; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use rstest::rstest; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_session::registry::CachedId; use super::ExtDType; +use super::ExtDTypePlugin; +use super::ExtDTypeRef; use super::ExtId; use super::ExtVTable; +use super::ForeignExtDType; +use crate::IntoArray; +use crate::arrays::ConstantArray; +use crate::arrays::ExtensionArray; use crate::dtype::DType; +use crate::dtype::Nullability; use crate::dtype::Nullability::NonNullable; use crate::dtype::Nullability::Nullable; use crate::dtype::PType; +use crate::extension::datetime::Date; +use crate::extension::datetime::Time; use crate::extension::datetime::TimeUnit; use crate::extension::datetime::Timestamp; +use crate::scalar::Scalar; use crate::scalar::ScalarValue; -/// The number of times [`CountingValidator::validate_dtype`] ran. +/// The number of times [`CountingValidator::validate_metadata`] ran. static VALIDATIONS: AtomicUsize = AtomicUsize::new(0); -/// An extension type that counts how often its dtype is validated. +/// The number of times [`CountingValidator::storage_dtype`] ran. +static DECLARATIONS: AtomicUsize = AtomicUsize::new(0); + +/// An extension type over `i64` storage that counts how often its metadata is validated. #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] struct CountingValidator; impl ExtVTable for CountingValidator { type Metadata = u32; + type StoredMetadata = Self::Metadata; type NativeValue<'a> = &'a ScalarValue; fn id(&self) -> ExtId { @@ -42,7 +60,7 @@ impl ExtVTable for CountingValidator { Ok(metadata.to_le_bytes().to_vec()) } - fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { + fn deserialize_metadata(&self, metadata: &[u8]) -> VortexResult { let bytes = metadata .try_into() .map_err(|_| vortex_err!("Expected four metadata bytes, got {}", metadata.len()))?; @@ -50,7 +68,22 @@ impl ExtVTable for CountingValidator { Ok(u32::from_le_bytes(bytes)) } - fn validate_dtype(_ext_dtype: &ExtDType) -> VortexResult<()> { + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + assert!(storage_dtype.is_nullable()); + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DECLARATIONS.fetch_add(1, Ordering::Relaxed); + + DType::Primitive(PType::I64, NonNullable) + } + + fn validate_metadata(_metadata: &Self::Metadata) -> VortexResult<()> { VALIDATIONS.fetch_add(1, Ordering::Relaxed); Ok(()) @@ -64,13 +97,13 @@ impl ExtVTable for CountingValidator { } } -// One test owns `VALIDATIONS`, so test threads cannot race on the counter. +// One test owns both counters, so test threads cannot race on them. #[test] fn test_nullability_changes_do_not_validate_again() -> VortexResult<()> { for initial in [NonNullable, Nullable] { VALIDATIONS.store(0, Ordering::Relaxed); - let dtype = - ExtDType::::try_new(42, DType::Primitive(PType::I64, initial))?; + DECLARATIONS.store(0, Ordering::Relaxed); + let dtype = ExtDType::::try_new(42, initial)?; assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); for target in [Nullable, NonNullable] { @@ -85,6 +118,148 @@ fn test_nullability_changes_do_not_validate_again() -> VortexResult<()> { } assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 3); + + VALIDATIONS.store(0, Ordering::Relaxed); + DECLARATIONS.store(0, Ordering::Relaxed); + let storage = DType::Primitive(PType::I64, initial); + let reconstructed = ExtDType::::try_from_storage(42, storage.clone())?; + assert_eq!(reconstructed.metadata(), &42); + assert_eq!(reconstructed.storage_dtype(), &storage); + assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 1); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 1); + let restored = CountingValidator.deserialize(&42u32.to_le_bytes(), storage)?; + assert_eq!(restored, reconstructed.erased()); + assert_eq!(VALIDATIONS.load(Ordering::Relaxed), 2); + assert_eq!(DECLARATIONS.load(Ordering::Relaxed), 2); + } + + Ok(()) +} + +/// An extension type that declares the storage dtype that its vtable holds. A read keeps that +/// declaration whatever the stored storage dtype is. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct DeclaredStorage(DType); + +impl ExtVTable for DeclaredStorage { + type Metadata = DType; + type StoredMetadata = Self::Metadata; + type NativeValue<'a> = &'a ScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.declared_storage"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(vec![]) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(self.0.clone()) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + metadata.clone() + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } +} + +/// A [`DeclaredStorage`] dtype over [`DType::Null`] storage, which is always nullable. +fn null_extension() -> DType { + let ext_dtype = ExtDType::try_with_vtable(DeclaredStorage(DType::Null), DType::Null, Nullable) + .vortex_expect("DeclaredStorage accepts every storage dtype"); + DType::Extension(ext_dtype.erased()) +} + +/// A read of a declared storage dtype without a non-nullable form, from a non-nullable stored +/// storage dtype, returns the storage mismatch error instead of panicking. +#[rstest] +#[case::null(DType::Null, "test.declared_storage storage must be null, got i32")] +#[case::extension_over_null( + null_extension(), + "test.declared_storage storage must be test.declared_storage[null](null), got i32" +)] +fn test_read_of_storage_without_non_nullable_form(#[case] declared: DType, #[case] expected: &str) { + let stored = DType::Primitive(PType::I32, NonNullable); + let result = ExtDType::try_from_storage_with_vtable( + DeclaredStorage(declared.clone()), + declared.clone(), + stored.clone(), + ); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); + let result = DeclaredStorage(declared).deserialize(&[], stored); + assert!(result.is_err_and(|error| error.to_string().contains(expected))); +} + +/// [`ExtDType::try_with_vtable`] validates the metadata before it asks for the storage +/// declaration, so a time unit that [`Date`] or [`Time`] does not support returns an error +/// instead of a panic. +#[rstest] +#[case::date_seconds( + Date::try_new(TimeUnit::Seconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got s" +)] +#[case::date_microseconds( + Date::try_new(TimeUnit::Microseconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got µs" +)] +#[case::date_nanoseconds( + Date::try_new(TimeUnit::Nanoseconds, NonNullable).map(ExtDType::erased), + "Date time unit must be days or milliseconds, got ns" +)] +#[case::time_days( + Time::try_new(TimeUnit::Days, NonNullable).map(ExtDType::erased), + "Time time unit must be finer than days, got days" +)] +fn test_unsupported_time_unit_returns_error( + #[case] result: VortexResult, + #[case] expected: &str, +) { + assert!(result.is_err_and(|error| error.to_string().contains(expected))); +} + +/// Foreign metadata normalizes outer nullability and preserves nested nullability, so equality +/// and hashing that ignore nullability still distinguish different nested storage declarations. +#[rstest] +#[case::top_level(NonNullable, Nullable, true)] +#[case::nested(Nullable, NonNullable, false)] +fn test_foreign_dtype_ignores_only_top_level_nullability( + #[case] element: Nullability, + #[case] list: Nullability, + #[case] expected: bool, +) -> VortexResult<()> { + static ID: CachedId = CachedId::new("test.foreign"); + let i32_list = |element, list| DType::list(DType::Primitive(PType::I32, element), list); + let dtype = ForeignExtDType::from_parts(*ID, vec![], i32_list(NonNullable, NonNullable))?; + let other = ForeignExtDType::from_parts(*ID, vec![], i32_list(element, list))?; + let (dtype, other) = (DType::Extension(dtype), DType::Extension(other)); + + assert_eq!(dtype.eq_ignore_nullability(&other), expected); + + // Dtypes that are equal ignoring nullability must also hash equally ignoring nullability. + if expected { + let hash = |dtype: &DType| { + let mut hasher = DefaultHasher::new(); + dtype.hash_ignore_nullability(&mut hasher); + hasher.finish() + }; + assert_eq!(hash(&dtype), hash(&other)); } Ok(()) @@ -114,3 +289,55 @@ fn test_debug_preserves_metadata(#[case] pretty: bool) -> VortexResult<()> { Ok(()) } + +#[test] +fn storage_construction_validates_before_declaration() { + let storage = DType::Primitive(PType::I32, NonNullable); + let error = ExtDType::::try_from_storage(TimeUnit::Seconds, storage) + .expect_err("Date rejects seconds before requesting its storage declaration"); + assert!( + error + .to_string() + .contains("Date time unit must be days or milliseconds") + ); +} + +/// Null storage supports nullable construction and rejects non-nullable requests without panicking. +#[rstest] +#[case::null(DType::Null)] +#[case::extension_over_null(null_extension())] +fn metadata_first_null_storage(#[case] declared: DType) -> VortexResult<()> { + let vtable = DeclaredStorage(declared.clone()); + let dtype = ExtDType::try_with_vtable(vtable.clone(), declared.clone(), Nullable)?; + assert_eq!(dtype.storage_dtype(), &declared); + + let expected = + format!("test.declared_storage storage must have a non-nullable form, got {declared}"); + let error = ExtDType::try_with_vtable(vtable.clone(), declared.clone(), NonNullable) + .expect_err("null storage has no non-nullable form"); + assert!(error.to_string().contains(&expected), "{error}"); + + let storage = ConstantArray::new(Scalar::null(declared.clone()), 1).into_array(); + ExtensionArray::try_new_from_vtable(vtable.clone(), declared.clone(), storage)?; + + let storage = ConstantArray::new(1i32, 1).into_array(); + let error = ExtensionArray::try_new_from_vtable(vtable, declared, storage) + .expect_err("null storage cannot match non-nullable i32 storage"); + assert!(error.to_string().contains(&expected), "{error}"); + + Ok(()) +} + +#[test] +fn null_elements_allow_non_nullable_list_storage() -> VortexResult<()> { + let declared = DType::list(DType::Null, Nullable); + let dtype = + ExtDType::try_with_vtable(DeclaredStorage(declared.clone()), declared, NonNullable)?; + + assert_eq!( + dtype.storage_dtype(), + &DType::list(DType::Null, NonNullable) + ); + + Ok(()) +} diff --git a/vortex-array/src/dtype/extension/typed.rs b/vortex-array/src/dtype/extension/typed.rs index 18387482a33..6f7f5b710c6 100644 --- a/vortex-array/src/dtype/extension/typed.rs +++ b/vortex-array/src/dtype/extension/typed.rs @@ -13,6 +13,7 @@ use std::hash::Hasher; use std::sync::Arc; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use crate::dtype::DType; use crate::dtype::Nullability; @@ -23,8 +24,9 @@ use crate::scalar::ScalarValue; /// A typed extension data type, parameterized by a concrete [`ExtVTable`]. /// -/// You can construct one of these via [`try_new()`] (for zero-sized vtables) or -/// [`try_with_vtable()`], and erase the type with [`erased()`] to obtain an [`ExtDTypeRef`]. +/// [`try_new()`] and [`try_with_vtable()`] construct a dtype from complete metadata. +/// [`try_from_storage`](Self::try_from_storage) reconstructs metadata from its stored metadata and storage. +/// [`erased()`] returns an [`ExtDTypeRef`] for type-erased dispatch. /// /// [`try_new()`]: ExtDType::try_new /// [`try_with_vtable()`]: ExtDType::try_with_vtable @@ -35,35 +37,118 @@ pub struct ExtDType { vtable: V, /// The extension dtype metadata. metadata: V::Metadata, - /// The underlying storage dtype. + /// The declared storage dtype with this dtype's top-level nullability. + /// + /// Cached so that [`storage_dtype`](Self::storage_dtype) can return a reference. storage_dtype: DType, } /// Convenience implementation for zero-sized VTables (or VTables that implement `Default`). impl ExtDType { - /// Creates a new extension dtype with the given metadata and storage dtype. - pub fn try_new(metadata: V::Metadata, storage_dtype: DType) -> VortexResult { - Self::try_with_vtable(V::default(), metadata, storage_dtype) + /// Reconstructs a dtype from stored metadata and its complete storage dtype. + /// + /// See [`try_from_storage_with_vtable`](Self::try_from_storage_with_vtable) for the checks. + /// + /// ``` + /// use vortex_array::dtype::{DType, Nullability, PType}; + /// use vortex_array::dtype::extension::ExtDType; + /// use vortex_array::extension::datetime::{Time, TimeUnit}; + /// + /// let storage = DType::Primitive(PType::I32, Nullability::Nullable); + /// let dtype = ExtDType::