From 70c9cebe67e9d8e148811234da7a268bb7af0060 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 05:52:21 +0000 Subject: [PATCH 01/13] Add an experimental extension layout that decomposes struct storage An extension column was always written by the leaf strategy, so a column whose storage is a struct became one segment per block and reading one field read every field. The new `vortex.ext` layout wraps a layout of the storage, so the table strategy splits an opted-in extension type's storage into per-field columns. Readers and the planner rewrite `ext_storage(root)` to the storage root, so projections, filters and pruning reach the storage columns, and they wrap whole values back into the extension type themselves. Decomposition is opt-in per extension type through the layout session and the unstable edition, so existing types such as the spatial types keep their leaf layout and statistics. Signed-off-by: Connor Tsui --- .../src/declarations/unstable/mod.rs | 5 +- vortex-file/src/strategy.rs | 27 +- vortex-file/src/tests.rs | 137 ++++++ vortex-layout/src/layouts/extension/expr.rs | 120 +++++ vortex-layout/src/layouts/extension/mod.rs | 181 ++++++++ vortex-layout/src/layouts/extension/plan.rs | 243 ++++++++++ vortex-layout/src/layouts/extension/reader.rs | 229 ++++++++++ vortex-layout/src/layouts/extension/tests.rs | 429 ++++++++++++++++++ vortex-layout/src/layouts/extension/writer.rs | 99 ++++ vortex-layout/src/layouts/mod.rs | 1 + vortex-layout/src/layouts/table.rs | 65 ++- vortex-layout/src/plan/physical/mod.rs | 3 + vortex-layout/src/scan/v2/tests.rs | 249 +++++++++- vortex-layout/src/session.rs | 26 ++ vortex-layout/src/test.rs | 73 ++- .../editions/unstable/unstable2026.10.0.toml | 8 +- 16 files changed, 1875 insertions(+), 20 deletions(-) create mode 100644 vortex-layout/src/layouts/extension/expr.rs create mode 100644 vortex-layout/src/layouts/extension/mod.rs create mode 100644 vortex-layout/src/layouts/extension/plan.rs create mode 100644 vortex-layout/src/layouts/extension/reader.rs create mode 100644 vortex-layout/src/layouts/extension/tests.rs create mode 100644 vortex-layout/src/layouts/extension/writer.rs diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index 5af80759731..73400e7f45b 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -31,5 +31,8 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { immutable: false, min_library_version: None, }, - added: &[EditionMember::array(&"fastlanes.delta")], + added: &[ + EditionMember::array(&"fastlanes.delta"), + EditionMember::layout(&"vortex.ext"), + ], }; diff --git a/vortex-file/src/strategy.rs b/vortex-file/src/strategy.rs index 1c15a1a0ba7..fe6cca1c84f 100644 --- a/vortex-file/src/strategy.rs +++ b/vortex-file/src/strategy.rs @@ -7,6 +7,7 @@ use std::num::NonZeroUsize; use std::sync::Arc; use vortex_array::dtype::FieldPath; +use vortex_array::dtype::extension::ExtId; use vortex_btrblocks::BtrBlocksCompressorBuilder; use vortex_btrblocks::SchemeExt; use vortex_btrblocks::schemes::integer::IntDictScheme; @@ -22,6 +23,7 @@ use vortex_layout::layouts::compressed::CompressingStrategy; use vortex_layout::layouts::compressed::CompressorPlugin; use vortex_layout::layouts::dict::writer::DictLayoutOptions; use vortex_layout::layouts::dict::writer::DictStrategy; +use vortex_layout::layouts::extension::Extension; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; use vortex_layout::layouts::list::List; use vortex_layout::layouts::list::writer::ListLayoutStrategy; @@ -30,6 +32,7 @@ use vortex_layout::layouts::repartition::RepartitionWriterOptions; use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::writer::ZonedLayoutOptions; use vortex_layout::layouts::zoned::writer::ZonedStrategy; +use vortex_layout::session::LayoutSessionExt; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -128,12 +131,28 @@ pub struct WriteStrategyBuilder { /// /// [`ListLayoutStrategy`]: vortex_layout::layouts::list::writer::ListLayoutStrategy use_list_layout: bool, + /// The extension types whose columns are written using [`ExtensionStrategy`]. + /// + /// [`ExtensionStrategy`]: vortex_layout::layouts::extension::ExtensionStrategy + extension_layouts: Vec, } impl WriteStrategyBuilder { /// Create a new builder that compresses with the schemes registered on `session`. It can be /// further configured, and then finally built yielding the [`LayoutStrategy`]. + /// + /// The strategy uses the list layout and the extension layout when the session's enabled + /// editions include them. The extension layout only applies to the extension types that the + /// session opts in with [`LayoutSession::decompose_extension`]. + /// + /// [`LayoutSession::decompose_extension`]: vortex_layout::session::LayoutSession::decompose_extension pub fn from_session(session: &VortexSession) -> Self { + let enabled_layouts = session.enabled_component_ids(ComponentKind::Layout); + let extension_layouts = if enabled_layouts.contains(&Extension.id()) { + session.layouts().decomposed_extensions() + } else { + Vec::new() + }; Self { compressor: CompressorConfig::BtrBlocks(BtrBlocksCompressorBuilder::from_session( session, @@ -143,9 +162,8 @@ impl WriteStrategyBuilder { field_writers: HashMap::new(), flat_strategy: None, probe_compressor: None, - use_list_layout: session - .enabled_component_ids(ComponentKind::Layout) - .contains(&List.id()), + use_list_layout: enabled_layouts.contains(&List.id()), + extension_layouts, } } @@ -296,7 +314,8 @@ impl WriteStrategyBuilder { // Take any field overrides from the builder and apply them to the final strategy. let mut table_strategy = TableStrategy::new(Arc::new(validity_strategy), Arc::new(repartition)) - .with_field_writers(self.field_writers); + .with_field_writers(self.field_writers) + .with_extension_layout(self.extension_layouts); if self.use_list_layout { // We need a closure here to enable recursive application of list layout. diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index f4b848f0f95..7cadcaed61d 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -21,6 +21,7 @@ use rand::rngs::StdRng; use rstest::rstest; use tempfile::tempdir; use vortex_array::ArrayRef; +use vortex_array::EmptyMetadata; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; @@ -32,6 +33,7 @@ use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DecimalArray; use vortex_array::arrays::Dict; +use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; @@ -53,13 +55,18 @@ use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::PType::I32; use vortex_array::dtype::StructFields; +use vortex_array::dtype::extension::ExtDType; +use vortex_array::dtype::extension::ExtId; +use vortex_array::dtype::extension::ExtVTable; use vortex_array::dtype::i256; +use vortex_array::dtype::session::DTypeSessionExt; use vortex_array::expr::BoundExpression; use vortex_array::expr::Expression; use vortex_array::expr::and; use vortex_array::expr::cast; use vortex_array::expr::col; use vortex_array::expr::eq; +use vortex_array::expr::ext_storage; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::gt_eq; @@ -96,6 +103,7 @@ use vortex_decimal_byte_parts::DecimalByteParts; use vortex_decimal_byte_parts::DecimalBytePartsArraySlotsExt; use vortex_edition::ComponentKind; use vortex_edition::EDITION_DECLARATIONS; +use vortex_edition::EditionInclusion; use vortex_edition::EditionSession; use vortex_edition::EditionSessionExt; use vortex_edition::declarations::core::CORE_2026_08_3; @@ -109,8 +117,10 @@ use vortex_io::session::RuntimeSession; use vortex_io::std_file::FileWrite; use vortex_layout::DynLayout; use vortex_layout::LayoutStrategy; +use vortex_layout::VTable; use vortex_layout::layouts::buffered::BufferedStrategy; use vortex_layout::layouts::chunked::writer::ChunkedLayoutStrategy; +use vortex_layout::layouts::extension::Extension; use vortex_layout::layouts::file_stats::AggregateStats; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; use vortex_layout::layouts::struct_::StructStrategy; @@ -121,8 +131,10 @@ use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; use vortex_layout::session::LayoutSession; +use vortex_layout::session::LayoutSessionExt; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use vortex_session::registry::Id; use vortex_zigzag::ZigZag; @@ -3667,3 +3679,128 @@ async fn null_dominated_clustered_f32_writes() -> VortexResult<()> { .await?; Ok(()) } + +/// A test extension type stored as `{a: i32, b: i64}`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct Point; + +impl ExtVTable for Point { + type Metadata = EmptyMetadata; + type StoredMetadata = EmptyMetadata; + type NativeValue<'a> = &'a ScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.point"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(Vec::new()) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(EmptyMetadata) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Struct( + StructFields::from_iter([ + ("a", DType::Primitive(I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I64, Nullability::NonNullable)), + ]), + Nullability::NonNullable, + ) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } +} + +/// The default writer splits the struct storage of an extension column into one column per field +/// exactly when the enabled editions include the extension layout and the session opts the +/// extension type into it. Enabling the unstable edition alone keeps the column a leaf, so the +/// statistics computed over its values do not change. Either way the file reads back the same +/// values and storage fields. +#[rstest] +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn extension_layout_follows_enabled_editions( + #[values(false, true)] unstable: bool, + #[values(false, true)] opted_in: bool, +) -> VortexResult<()> { + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + session.dtypes().register(Point); + for declaration in EDITION_DECLARATIONS { + session.register_edition(declaration)?; + } + session.editions().declare_inclusion(EditionInclusion::new( + ComponentKind::DType, + &Point.id(), + CORE_2026_08_3, + ))?; + session.enable_edition(CORE_2026_08_3)?; + if unstable { + session.enable_edition(UNSTABLE)?; + } + if opted_in { + session.layouts().decompose_extension(Point.id()); + } + + let a = PrimitiveArray::from_iter(0..1000i32).into_array(); + let storage = StructArray::from_fields(&[ + ("a", a.clone()), + ( + "b", + PrimitiveArray::from_iter((0..1000i64).map(|i| 10 * i)).into_array(), + ), + ])?; + let points = ExtensionArray::try_new( + ExtDType::::try_new(EmptyMetadata, Nullability::NonNullable)?.erased(), + storage.into_array(), + )?; + let array = StructArray::from_fields(&[("point", points.into_array())])?.into_array(); + + let mut buffer = ByteBufferMut::empty(); + session + .write_options() + .write(&mut buffer, array.clone().to_array_stream()) + .await?; + let file = session.open_options().open_buffer(buffer)?; + let uses_extension_layout = file + .footer() + .layout() + .depth_first_traversal() + .map(|layout| Ok(layout?.encoding_id())) + .collect::>>()? + .contains(&Extension.id()); + assert_eq!(uses_extension_layout, unstable && opted_in); + + let mut ctx = session.create_execution_ctx(); + let values = file.scan()?.into_array_stream()?.read_all().await?; + assert_arrays_eq!(values, array, &mut ctx); + let projection = get_item("a", ext_storage(get_item("point", root()))).bind(file.dtype())?; + let field = file + .scan()? + .with_projection(projection) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(field, a, &mut ctx); + Ok(()) +} diff --git a/vortex-layout/src/layouts/extension/expr.rs b/vortex-layout/src/layouts/extension/expr.rs new file mode 100644 index 00000000000..7e773900f24 --- /dev/null +++ b/vortex-layout/src/layouts/extension/expr.rs @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Rebinding expressions over extension values to their storage. + +use vortex_array::dtype::DType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::scalar_fn::fns::ext_storage::ExtStorage; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_error::VortexResult; + +/// Rebinds `expr`, bound to an extension scope, to the extension's storage. +/// +/// Every `ext_storage(root)` becomes the storage root. `is_null(root)` and `is_not_null(root)` read +/// the storage validity, because an extension value is null exactly when its storage value is null. +/// Returns `None` when `expr` uses the root in any other way, which needs the extension values +/// themselves. +pub(super) fn rebind_to_storage( + expr: &BoundExpression, + storage_dtype: &DType, +) -> VortexResult> { + let storage_root = BoundExpression::new_root(storage_dtype.clone()); + let mut reads_values = false; + let rebound = expr + .clone() + .transform_down(|node| { + if node.is_root() { + reads_values = true; + return Ok(Transformed::no(node)); + } + if !node + .children() + .first() + .is_some_and(BoundExpression::is_root) + { + return Ok(Transformed::no(node)); + } + let value = if node.is::() { + storage_root.clone() + } else if node.is::() || node.is::() { + node.with_children([storage_root.clone()])? + } else { + return Ok(Transformed::no(node)); + }; + Ok(Transformed { + value, + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner(); + Ok((!reads_values).then_some(rebound)) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::expr::Expression; + use vortex_array::expr::and; + use vortex_array::expr::ext_storage; + use vortex_array::expr::get_item; + use vortex_array::expr::gt; + use vortex_array::expr::is_not_null; + use vortex_array::expr::is_null; + use vortex_array::expr::lit; + use vortex_array::expr::pack; + use vortex_array::expr::root; + use vortex_error::VortexResult; + + use super::rebind_to_storage; + use crate::test::TestPoint; + + fn extension_dtype() -> DType { + DType::Extension(TestPoint::dtype(Nullability::Nullable)) + } + + fn storage_dtype() -> DType { + TestPoint::dtype(Nullability::Nullable) + .storage_dtype() + .clone() + } + + #[rstest] + #[case::storage(ext_storage(root()), "$")] + #[case::field(get_item("a", ext_storage(root())), "$.a")] + #[case::predicate( + and( + gt(get_item("a", ext_storage(root())), lit(1i32)), + gt(get_item("b", ext_storage(root())), lit(2i64)), + ), + "(($.a > 1i32) and ($.b > 2i64))" + )] + #[case::is_null(is_null(root()), "vortex.is_null($)")] + #[case::is_not_null(is_not_null(root()), "is_not_null($)")] + fn rebinds_storage_reads(#[case] expr: Expression, #[case] expected: &str) -> VortexResult<()> { + let rebound = rebind_to_storage(&expr.bind(&extension_dtype())?, &storage_dtype())? + .expect("reads only the storage"); + assert_eq!(rebound.to_string(), expected); + assert!(rebound.is_root_bound_to(&storage_dtype())); + Ok(()) + } + + #[rstest] + #[case::root(root())] + #[case::mixed(pack( + [("a", get_item("a", ext_storage(root()))), ("value", root())], + Nullability::NonNullable, + ))] + fn keeps_value_reads(#[case] expr: Expression) -> VortexResult<()> { + let bound = expr.bind(&extension_dtype())?; + assert!(rebind_to_storage(&bound, &storage_dtype())?.is_none()); + Ok(()) + } +} diff --git a/vortex-layout/src/layouts/extension/mod.rs b/vortex-layout/src/layouts/extension/mod.rs new file mode 100644 index 00000000000..e8ad1b0d155 --- /dev/null +++ b/vortex-layout/src/layouts/extension/mod.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! An experimental structural layout for extension-typed columns. +//! +//! An [`ExtensionLayout`] stores extension values as a layout of their storage, so a column of +//! extension values with struct storage is split into one column per storage field. Its single +//! child holds the storage, and the extension dtype is the layout dtype. +//! +//! Extension types are opaque: readers reach the storage only through the explicit +//! [`ext_storage`](vortex_array::expr::ext_storage) expression. An expression that reads the +//! extension root only inside `ext_storage(root)` is rebound to the storage and pushed down to the +//! child, so reading one storage field reads only that field, and the storage validity when the +//! extension is nullable. The planner-driven scan does not push expressions through a nullable +//! struct yet, so there it reads every column of a nullable struct storage. Any other use of the +//! root reads the whole storage and wraps it back into extension values. +//! +//! The writer decomposes only the extension types that opt in, see +//! [`TableStrategy::with_extension_layout`](crate::layouts::table::TableStrategy::with_extension_layout). + +mod expr; +mod plan; +mod reader; +#[cfg(test)] +mod tests; +pub mod writer; + +use std::sync::Arc; + +pub use plan::ExtPack; +pub use plan::ExtPackData; +pub use plan::ExtPackPlan; +use reader::ExtensionReader; +use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_error::vortex_panic; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; +pub use writer::ExtensionStrategy; + +use crate::Layout; +use crate::LayoutChildType; +use crate::LayoutDeserializeArgs; +use crate::LayoutId; +use crate::LayoutParts; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::LayoutRef; +use crate::VTable; +use crate::children::OwnedLayoutChildren; +use crate::lowering::slots_from_layout; +use crate::plan::physical::PlanRef; +use crate::segments::SegmentSource; + +/// Slot of the storage child. +pub const STORAGE_SLOT: usize = 0; + +/// Extension layout vtable. +#[derive(Clone, Debug)] +pub struct Extension; + +/// An extension-typed layout whose only child holds the extension storage. +pub type ExtensionLayout = Layout; + +impl VTable for Extension { + type LayoutData = (); + type Metadata = EmptyMetadata; + + fn id(&self) -> LayoutId { + static ID: CachedId = CachedId::new("vortex.ext"); + *ID + } + + fn metadata(_layout: &Layout) -> Self::Metadata { + // The extension dtype, and with it the storage dtype, is the layout dtype. + EmptyMetadata + } + + fn deserialize( + &self, + args: &LayoutDeserializeArgs<'_>, + _metadata: &EmptyMetadata, + ) -> VortexResult { + let ext_dtype = args + .dtype + .as_extension_opt() + .ok_or_else(|| vortex_err!("ExtensionLayout requires an extension dtype"))?; + vortex_ensure_eq!(args.children.nchildren(), 1); + let storage = args + .children + .child(STORAGE_SLOT, ext_dtype.storage_dtype())?; + vortex_ensure_eq!( + storage.row_count(), + args.row_count, + "ExtensionLayout storage row count does not match parent" + ); + Ok(()) + } + + fn child_dtype(layout: &Layout, slot: usize) -> VortexResult { + match slot { + STORAGE_SLOT => Ok(layout.ext_dtype().storage_dtype().clone()), + _ => vortex_bail!("Invalid child index {slot} for ExtensionLayout"), + } + } + + fn child_type(_layout: &Layout, slot: usize) -> LayoutChildType { + match slot { + STORAGE_SLOT => LayoutChildType::Transparent("storage".into()), + _ => vortex_panic!("Invalid child index {slot} for ExtensionLayout"), + } + } + + fn new_reader( + layout: &Layout, + name: Arc, + segment_source: Arc, + session: &VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + Ok(Arc::new(ExtensionReader::try_new( + layout.clone(), + name, + segment_source, + session, + ctx, + )?)) + } + + fn new_plan(layout: &Layout) -> VortexResult { + // SAFETY: Extension layout construction validates that the only slot holds the storage + // dtype of the layout's extension dtype, over the layout's rows. + let plan = unsafe { + ExtPack::from_slots_unchecked( + layout.ext_dtype().clone(), + layout.row_count(), + slots_from_layout(&layout.to_layout()), + ) + }; + Ok(plan.into_plan()) + } +} + +impl Layout { + /// Construct an extension layout over a layout of its storage. + /// + /// # Errors + /// + /// Returns an error if `storage` does not have the storage dtype of `ext_dtype`. + pub fn try_new(ext_dtype: ExtDTypeRef, storage: LayoutRef) -> VortexResult { + vortex_ensure_eq!(storage.dtype(), ext_dtype.storage_dtype()); + Ok(LayoutParts::new( + Extension, + DType::Extension(ext_dtype), + storage.row_count(), + Vec::new(), + OwnedLayoutChildren::layout_children(vec![storage]), + (), + ) + .into_typed()) + } + + /// Returns the extension dtype of this layout. + pub fn ext_dtype(&self) -> &ExtDTypeRef { + self.dtype() + .as_extension_opt() + .vortex_expect("ExtensionLayout dtype must be an extension") + } + + /// Returns the layout of the extension storage. + pub fn storage(&self) -> VortexResult { + self.slot(STORAGE_SLOT)? + .ok_or_else(|| vortex_err!("ExtensionLayout storage slot is absent")) + } +} diff --git a/vortex-layout/src/layouts/extension/plan.rs b/vortex-layout/src/layouts/extension/plan.rs new file mode 100644 index 00000000000..4d87b659484 --- /dev/null +++ b/vortex-layout/src/layouts/extension/plan.rs @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The scan plan of an extension layout. + +use std::borrow::Cow; +use std::ops::Range; + +use vortex_array::EmptyMetadata; +use vortex_array::IntoArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure_eq; +use vortex_mask::Mask; +use vortex_scan::execution::operator::Cx; +use vortex_scan::execution::operator::Input; +use vortex_scan::execution::operator::Operator; +use vortex_scan::execution::operator::Step; +use vortex_scan::execution::pipeline::Chain; +use vortex_scan::execution::pipeline::Compiler; +use vortex_scan::plan::Eval; +use vortex_scan::plan::EvalPlan; +use vortex_scan::plan::Plan; +use vortex_scan::plan::PlanId; +use vortex_scan::plan::PlanParts; +use vortex_scan::plan::PlanRef; +use vortex_scan::plan::PlanSlots; +use vortex_scan::plan::PlanVTable; +use vortex_scan::plan::optimizer::PlanParentReduceRule; +use vortex_scan::plan::optimizer::PlanParentReduceRuleAdapter; +use vortex_scan::plan::optimizer::PlanParentRuleSet; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::layouts::extension::expr::rebind_to_storage; + +const STORAGE: usize = 0; + +/// Assembles extension values from the storage in its only slot. +/// +/// An [`Eval`] above it whose expression reads the extension only through `ext_storage(root)`, +/// `is_null(root)` or `is_not_null(root)` is rewritten to evaluate over the storage instead, so the +/// storage plan can push the expression further down. Compiled, it wraps each storage batch into +/// extension values. +#[derive(Clone, Debug)] +pub struct ExtPack; + +/// Operator-specific extension assembly data. +#[derive(Clone, Debug)] +pub struct ExtPackData; + +/// A plan that assembles extension values from their storage. +pub type ExtPackPlan = Plan; + +impl ExtPack { + /// Creates an extension assembly from potentially unbuilt slots without validation. + /// + /// # Safety + /// + /// `slots` must hold exactly one present slot producing the storage dtype of `ext_dtype` over + /// `row_count` rows. + pub(crate) unsafe fn from_slots_unchecked( + ext_dtype: ExtDTypeRef, + row_count: u64, + slots: PlanSlots, + ) -> ExtPackPlan { + PlanParts { + vtable: ExtPack, + dtype: DType::Extension(ext_dtype), + row_count, + slots, + data: ExtPackData, + } + .into_typed() + } + + /// Creates an assembly of `ext_dtype` values from a plan producing their storage. + /// + /// # Errors + /// + /// Returns an error if `storage` does not produce the storage dtype of `ext_dtype`. + pub fn try_new_plan(ext_dtype: ExtDTypeRef, storage: PlanRef) -> VortexResult { + let row_count = storage.row_count(); + let slots = [storage].into(); + validate_slots(&ext_dtype, row_count, &slots)?; + + // SAFETY: The slot shape was validated above. + Ok(unsafe { Self::from_slots_unchecked(ext_dtype, row_count, slots) }) + } + + /// Returns the extension dtype `plan` assembles. + pub fn ext_dtype(plan: &ExtPackPlan) -> &ExtDTypeRef { + plan.dtype() + .as_extension_opt() + .vortex_expect("ExtPack dtype must be an extension") + } + + /// Returns the plan producing the storage of `plan`. + pub fn storage(plan: &ExtPackPlan) -> VortexResult { + plan.slot_required(STORAGE) + } +} + +impl PlanVTable for ExtPack { + type PlanData = ExtPackData; + type Metadata = EmptyMetadata; + + fn id(&self) -> PlanId { + static ID: CachedId = CachedId::new("vortex.plan.ext_pack"); + *ID + } + + fn metadata(_plan: &Plan) -> Option { + // The extension dtype is the plan dtype. + Some(EmptyMetadata) + } + + fn with_slots( + plan: &Plan, + slots: &PlanSlots, + _data: &mut Self::PlanData, + ) -> VortexResult<()> { + validate_slots(ExtPack::ext_dtype(plan), plan.row_count(), slots) + } + + fn slot_name(_plan: &Plan, slot: usize) -> Cow<'_, str> { + match slot { + STORAGE => Cow::Borrowed("storage"), + _ => Cow::Owned(format!("slot[{slot}]")), + } + } + + fn reduce_parent( + plan: &Plan, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult> { + static RULES: PlanParentRuleSet = + PlanParentRuleSet::new(&[&PlanParentReduceRuleAdapter::new(ExpressionExtPackRule)]); + RULES.evaluate(&plan.to_plan(), parent, slot, session) + } + + fn compile( + plan: &Plan, + rows: Range, + mask: &Mask, + compiler: &mut Compiler<'_>, + ) -> VortexResult> { + let chain = compiler.compile(&ExtPack::storage(plan)?, rows, mask)?; + let ext_dtype = ExtPack::ext_dtype(plan).clone(); + Ok(chain.map(|chain| chain.with(ExtWrapStage::new(ext_dtype)))) + } +} + +fn validate_slots(ext_dtype: &ExtDTypeRef, row_count: u64, slots: &PlanSlots) -> VortexResult<()> { + slots.check_len("ExtPack", STORAGE + 1)?; + let storage = slots.required(STORAGE)?; + vortex_ensure_eq!(storage.dtype(), ext_dtype.storage_dtype()); + vortex_ensure_eq!(storage.row_count(), row_count); + Ok(()) +} + +/// Rewrites an [`Eval`] over an [`ExtPack`] into an [`Eval`] over its storage, when the expression +/// reads only the storage. +#[derive(Debug)] +struct ExpressionExtPackRule; + +impl PlanParentReduceRule for ExpressionExtPackRule { + type Parent = Eval; + + fn reduce_parent( + &self, + child: &ExtPackPlan, + parent: &Plan, + _child_idx: usize, + _session: &VortexSession, + ) -> VortexResult> { + let storage = ExtPack::storage(child)?; + let Some(expr) = rebind_to_storage(parent.expression(), storage.dtype())? else { + return Ok(None); + }; + Ok(Some(EvalPlan::try_new(expr, storage)?.into_plan())) + } +} + +/// Wraps each storage batch into extension values. +struct ExtWrapStage { + ext_dtype: ExtDTypeRef, +} + +impl ExtWrapStage { + fn new(ext_dtype: ExtDTypeRef) -> Self { + Self { ext_dtype } + } +} + +impl Operator for ExtWrapStage { + fn compute(&mut self, input: Input, _cx: &mut Cx<'_>) -> VortexResult { + let Input::Batch(batch) = input else { + return Ok(Step::End); + }; + Ok(Step::Final( + ExtensionArray::try_new(self.ext_dtype.clone(), batch)?.into_array(), + )) + } +} + +#[cfg(test)] +mod tests { + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_error::VortexResult; + use vortex_scan::plan::PlanRef; + use vortex_session::registry::ReadContext; + + use super::ExtPack; + use crate::layouts::flat::FlatLayout; + use crate::segments::SegmentId; + use crate::test::TestPoint; + + fn scan(dtype: DType) -> VortexResult { + FlatLayout::new(4, dtype, SegmentId::from(0), ReadContext::new([])).new_plan() + } + + #[test] + fn try_new_plan_requires_the_storage_dtype() -> VortexResult<()> { + let ext_dtype = TestPoint::dtype(Nullability::Nullable); + + let plan = + ExtPack::try_new_plan(ext_dtype.clone(), scan(ext_dtype.storage_dtype().clone())?)?; + assert_eq!(plan.dtype(), &DType::Extension(ext_dtype.clone())); + assert_eq!(plan.row_count(), 4); + + let storage = DType::Primitive(PType::I32, Nullability::Nullable); + assert!(ExtPack::try_new_plan(ext_dtype, scan(storage)?).is_err()); + Ok(()) + } +} diff --git a/vortex-layout/src/layouts/extension/reader.rs b/vortex-layout/src/layouts/extension/reader.rs new file mode 100644 index 00000000000..1df3fbde6f8 --- /dev/null +++ b/vortex-layout/src/layouts/extension/reader.rs @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::any::Any; +use std::ops::Range; +use std::sync::Arc; +use std::sync::OnceLock; + +use futures::FutureExt; +use futures::try_join; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::ExactBoundExpr; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_utils::aliases::dash_map::DashMap; + +use crate::ArrayFuture; +use crate::LayoutReader; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::RowSplits; +use crate::SplitRange; +use crate::layouts::extension::ExtensionLayout; +use crate::layouts::extension::expr::rebind_to_storage; +use crate::segments::SegmentSource; + +/// Reader for [`ExtensionLayout`]. +/// +/// An expression that reads the extension root only through `ext_storage(root)`, `is_null(root)` +/// or `is_not_null(root)` is rebound to the storage and delegated to the storage reader. Any other +/// expression is evaluated over extension values rebuilt from the whole storage, and pruning +/// leaves its rows unpruned. +pub(super) struct ExtensionReader { + layout: ExtensionLayout, + name: Arc, + session: VortexSession, + storage: LayoutReaderRef, + storage_root: BoundExpression, + /// Storage expressions keyed by the identity of the expression they were rebound from. Cached + /// so the storage reader sees the same tree on every split, keeping its own identity-keyed + /// caches warm. + rebound: DashMap>>>, +} + +impl ExtensionReader { + pub(super) fn try_new( + layout: ExtensionLayout, + name: Arc, + segment_source: Arc, + session: &VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + let storage = layout.storage()?.new_reader( + format!("{name}.storage").into(), + segment_source, + session, + ctx, + )?; + let storage_root = BoundExpression::new_root(layout.ext_dtype().storage_dtype().clone()); + Ok(Self { + layout, + name, + session: session.clone(), + storage, + storage_root, + rebound: DashMap::with_hasher_and_shard_amount(Default::default(), 8), + }) + } + + /// Returns `expr` rebound to the storage, or `None` when it reads the extension values. + fn storage_expr(&self, expr: &BoundExpression) -> VortexResult> { + let key = ExactBoundExpr(expr.clone()); + let cell = match self.rebound.get(&key) { + Some(entry) => Arc::clone(entry.value()), + None => Arc::clone( + self.rebound + .entry(key) + .or_insert_with(|| Arc::new(OnceLock::new())) + .value(), + ), + }; + if let Some(rebound) = cell.get() { + return Ok(rebound.clone()); + } + let rebound = rebind_to_storage(expr, self.storage_root.dtype())?; + Ok(cell.get_or_init(|| rebound).clone()) + } + + /// Reads the storage of the rows `mask` selects and wraps it back into extension values. + fn project_values( + &self, + row_range: &Range, + mask: MaskFuture, + ) -> VortexResult { + let storage = self + .storage + .projection_evaluation(row_range, &self.storage_root, mask)?; + let ext_dtype = self.layout.ext_dtype().clone(); + Ok( + async move { Ok(ExtensionArray::try_new(ext_dtype, storage.await?)?.into_array()) } + .boxed(), + ) + } +} + +impl LayoutReader for ExtensionReader { + fn name(&self) -> &Arc { + &self.name + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn dtype(&self) -> &DType { + self.layout.dtype() + } + + fn row_count(&self) -> u64 { + self.layout.row_count() + } + + fn can_prune_file(&self, expr: &BoundExpression) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self.storage.can_prune_file(&storage_expr), + None => Ok(false), + } + } + + fn split_pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => { + self.storage + .split_pruning_evaluation(row_range, &storage_expr, mask) + } + None => Ok(MaskFuture::ready(mask)), + } + } + + fn split_pruning_is_statistics(&self, expr: &BoundExpression) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self.storage.split_pruning_is_statistics(&storage_expr), + None => Ok(true), + } + } + + fn register_splits( + &self, + field_mask: &[FieldMask], + split_range: &SplitRange, + splits: &mut RowSplits, + ) -> VortexResult<()> { + // A field path cannot step into an opaque extension value, so the mask relative to the + // extension root applies unchanged to the storage root. + self.storage + .register_splits(field_mask, split_range, splits) + } + + fn pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self + .storage + .pruning_evaluation(row_range, &storage_expr, mask), + None => Ok(MaskFuture::ready(mask)), + } + } + + fn filter_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + if let Some(storage_expr) = self.storage_expr(expr)? { + return self + .storage + .filter_evaluation(row_range, &storage_expr, mask); + } + + let len = mask.len(); + let input = mask.clone(); + let values = self.project_values(row_range, mask)?; + let expr = expr.clone(); + let session = self.session.clone(); + Ok(MaskFuture::new(len, async move { + let (input, values) = try_join!(input, values)?; + let predicate = values + .apply_bound(&expr)? + .fill_null(false)? + .execute::(&mut session.create_execution_ctx())?; + Ok(input.intersect_by_rank(&predicate)) + })) + } + + fn projection_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + if let Some(storage_expr) = self.storage_expr(expr)? { + return self + .storage + .projection_evaluation(row_range, &storage_expr, mask); + } + + let values = self.project_values(row_range, mask)?; + let expr = expr.clone(); + Ok(async move { values.await?.apply_bound(&expr) }.boxed()) + } +} diff --git a/vortex-layout/src/layouts/extension/tests.rs b/vortex-layout/src/layouts/extension/tests.rs new file mode 100644 index 00000000000..38a520ed9d6 --- /dev/null +++ b/vortex-layout/src/layouts/extension/tests.rs @@ -0,0 +1,429 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::num::NonZeroUsize; +use std::sync::Arc; + +use futures::stream; +use rstest::rstest; +use vortex_array::ArrayContext; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::extension::ExtVTable; +use vortex_array::expr::Expression; +use vortex_array::expr::and; +use vortex_array::expr::ext_storage; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::lit; +use vortex_array::expr::lt; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::extension::datetime::TimeUnit; +use vortex_array::extension::datetime::Timestamp; +use vortex_array::scalar::Scalar; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::stats::rewrite::BoundExpressionPruneExt; +use vortex_mask::Mask; + +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::extension::Extension; +use crate::layouts::flat::Flat; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::table::TableStrategy; +use crate::layouts::zoned::writer::ZonedLayoutOptions; +use crate::layouts::zoned::writer::ZonedStrategy; +use crate::plan::physical::EvalPlan; +use crate::plan::physical::Zoned as ZonedPlanVTable; +use crate::plan::physical::optimize; +use crate::scan::scan_builder::ScanBuilder; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSource; +use crate::segments::TestSegments; +use crate::sequence::SequenceId; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; +use crate::test::SESSION; +use crate::test::TestPoint; + +const LEN: usize = 6; + +/// Points `{a: i, b: 10 * i}` for `i` in `0..LEN`, null at every third row when nullable. +fn points(nullability: Nullability) -> VortexResult { + let validity = match nullability { + Nullability::NonNullable => Validity::NonNullable, + Nullability::Nullable => Validity::from_iter((0..LEN).map(|row| row % 3 != 0)), + }; + let storage = StructArray::try_new( + FieldNames::from(["a", "b"]), + [ + buffer![0i32, 1, 2, 3, 4, 5].into_array(), + buffer![0i64, 10, 20, 30, 40, 50].into_array(), + ], + LEN, + validity, + )?; + Ok(ExtensionArray::try_new(TestPoint::dtype(nullability), storage.into_array())?.into_array()) +} + +/// A table `{id: i32, point: test.point}`. +fn table(nullability: Nullability) -> VortexResult { + Ok(StructArray::from_fields(&[ + ("id", buffer![0i32, 1, 2, 3, 4, 5].into_array()), + ("point", points(nullability)?), + ])? + .into_array()) +} + +fn flat_table() -> TableStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + TableStrategy::new(Arc::clone(&flat), flat) +} + +/// [`flat_table`] with [`TestPoint`] columns opted into the extension layout. +fn point_table() -> TableStrategy { + flat_table().with_extension_layout([TestPoint.id()]) +} + +async fn write( + strategy: &dyn LayoutStrategy, + chunks: Vec, +) -> VortexResult<(Arc, LayoutRef)> { + let segments = Arc::new(TestSegments::default()); + let (mut sequence_id, eof) = SequenceId::root().split(); + let dtype = chunks[0].dtype().clone(); + let chunks = chunks + .into_iter() + .map(|chunk| Ok((sequence_id.advance(), chunk))) + .collect::>(); + let layout = strategy + .write_stream( + ArrayContext::empty().into(), + Arc::::clone(&segments), + SequentialStreamAdapter::new(dtype, stream::iter(chunks)).sendable(), + eof, + &SESSION, + ) + .await?; + Ok((segments, layout)) +} + +/// Scans `layout` through its reader, the path of the classic scan. +async fn scan( + segments: Arc, + layout: &LayoutRef, + projection: &Expression, + filter: Option<&Expression>, +) -> VortexResult { + let reader = layout.new_reader("".into(), segments, &SESSION, &Default::default())?; + ScanBuilder::new(SESSION.clone(), reader) + .with_projection(projection.bind(layout.dtype())?) + .with_some_filter( + filter + .map(|filter| filter.bind(layout.dtype())) + .transpose()?, + ) + .into_array_stream()? + .read_all() + .await +} + +/// The rows of `array` where `filter` holds, projected by `projection`, evaluated in memory. +fn reference( + array: &ArrayRef, + projection: &Expression, + filter: Option<&Expression>, +) -> VortexResult { + let array = match filter { + Some(filter) => { + let mask = array + .clone() + .apply(filter)? + .fill_null(false)? + .execute::(&mut SESSION.create_execution_ctx())?; + array.filter(mask)? + } + None => array.clone(), + }; + array.apply(projection) +} + +fn point_storage(field: &str) -> Expression { + get_item(field, ext_storage(get_item("point", root()))) +} + +/// The storage struct of an extension column is split into one column per field. +#[tokio::test] +async fn writes_storage_fields_as_columns() -> VortexResult<()> { + let (_, layout) = write(&point_table(), vec![table(Nullability::Nullable)?]).await?; + insta::assert_snapshot!(layout.display_tree(), @r" + vortex.struct, dtype: {id=i32, point=test.point({a=i32, b=i64}?)}, children: 2 + ├── id: vortex.flat, dtype: i32, segment: 0 + └── point: vortex.ext, dtype: test.point({a=i32, b=i64}?), children: 1 + └── storage: vortex.struct, dtype: {a=i32, b=i64}?, children: 3 + ├── validity: vortex.flat, dtype: bool, segment: 1 + ├── a: vortex.flat, dtype: i32, segment: 2 + └── b: vortex.flat, dtype: i64, segment: 3 + "); + Ok(()) +} + +/// Extension columns keep their leaf layout unless their type is opted into the extension layout +/// and their storage is a struct. +#[rstest] +#[case::disabled(flat_table(), points(Nullability::NonNullable))] +#[case::other_type( + flat_table().with_extension_layout([Timestamp.id()]), + points(Nullability::NonNullable), +)] +#[case::primitive_storage( + flat_table().with_extension_layout([Timestamp.id()]), + ExtensionArray::try_new( + Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(), + buffer![1i64, 2, 3].into_array(), + ) + .map(IntoArray::into_array), +)] +#[tokio::test] +async fn keeps_other_extensions_as_leaves( + #[case] strategy: TableStrategy, + #[case] array: VortexResult, +) -> VortexResult<()> { + let (_, layout) = write(&strategy, vec![array?]).await?; + assert!(layout.is::(), "{}", layout.display_tree()); + Ok(()) +} + +/// Chunks of any encoding are written through their storage. +#[tokio::test] +async fn writes_extension_chunks_of_any_encoding() -> VortexResult<()> { + let points = points(Nullability::Nullable)?; + let dtype = points.dtype().clone(); + let ext_dtype = TestPoint::dtype(Nullability::Nullable); + let storage = Scalar::struct_( + ext_dtype.storage_dtype().clone(), + vec![Scalar::from(7i32), Scalar::from(70i64)], + ); + let chunks = vec![ + points.clone(), + ConstantArray::new(Scalar::extension_ref(ext_dtype.clone(), storage), 2).into_array(), + ConstantArray::new(Scalar::null(dtype.clone()), 2).into_array(), + ChunkedArray::try_new( + vec![points.slice(0..2)?, points.slice(4..LEN)?], + dtype.clone(), + )? + .into_array(), + ]; + let expected = ChunkedArray::try_new(chunks.clone(), dtype)?.into_array(); + + let chunked: Arc = + Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())); + let strategy = + TableStrategy::new(Arc::clone(&chunked), chunked).with_extension_layout([TestPoint.id()]); + let (segments, layout) = write(&strategy, chunks).await?; + assert!(layout.is::(), "{}", layout.display_tree()); + let actual = scan(segments, &layout, &root(), None).await?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + Ok(()) +} + +/// An extension column nested in a list is decomposed under the list elements. +#[tokio::test] +async fn decomposes_extension_list_elements() -> VortexResult<()> { + let points = points(Nullability::NonNullable)?; + let list = ListArray::try_new( + points, + buffer![0u32, 2, 2, 6].into_array(), + Validity::NonNullable, + &mut SESSION.create_execution_ctx(), + )? + .into_array(); + let strategy = point_table().with_list_layout(); + let (segments, layout) = write(&strategy, vec![list.clone()]).await?; + insta::assert_snapshot!(layout.display_tree(), @r" + vortex.list, dtype: list(test.point({a=i32, b=i64})), children: 2 + ├── elements: vortex.ext, dtype: test.point({a=i32, b=i64}), children: 1 + │ └── storage: vortex.struct, dtype: {a=i32, b=i64}, children: 2 + │ ├── a: vortex.flat, dtype: i32, segment: 1 + │ └── b: vortex.flat, dtype: i64, segment: 2 + └── offsets: vortex.flat, dtype: u64, segment: 0 + "); + + let actual = scan(segments, &layout, &root(), None).await?; + assert_arrays_eq!(actual, list, &mut SESSION.create_execution_ctx()); + Ok(()) +} + +/// Reading through the classic scan returns what the expression returns over the input. +#[rstest] +#[case::field(point_storage("a"), None)] +#[case::storage(ext_storage(get_item("point", root())), None)] +#[case::values(get_item("point", root()), None)] +#[case::table(root(), None)] +#[case::is_null(is_null(get_item("point", root())), None)] +#[case::mixed( + pack( + [("a", point_storage("a")), ("point", get_item("point", root()))], + Nullability::NonNullable, + ), + None, +)] +#[case::filter_field(get_item("id", root()), Some(gt(point_storage("a"), lit(2i32))))] +#[case::filter_values( + get_item("point", root()), + Some(and(gt(point_storage("a"), lit(1i32)), lt(point_storage("b"), lit(50i64)))) +)] +#[case::filter_is_not_null(point_storage("b"), Some(is_not_null(get_item("point", root()))))] +#[tokio::test] +async fn scan_matches_reference( + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, + #[case] projection: Expression, + #[case] filter: Option, +) -> VortexResult<()> { + let table = table(nullability)?; + let (segments, layout) = write(&point_table(), vec![table.clone()]).await?; + let actual = scan(segments, &layout, &projection, filter.as_ref()).await?; + let expected = reference(&table, &projection, filter.as_ref())?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + Ok(()) +} + +/// A filter that reads the extension values is evaluated over values rebuilt from the storage. +#[rstest] +#[tokio::test] +async fn filter_over_values_reads_storage( + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, +) -> VortexResult<()> { + let points = points(nullability)?; + let (segments, layout) = write(&point_table(), vec![points.clone()]).await?; + let reader = layout.new_reader("".into(), segments, &SESSION, &Default::default())?; + // `get_item` over `pack` uses the extension root outside `ext_storage`. + let filter = is_not_null(get_item( + "value", + pack([("value", root())], Nullability::NonNullable), + )); + let input = Mask::from_iter([true, true, false, true, true, true]); + + let actual = reader + .filter_evaluation( + &(0..LEN as u64), + &filter.bind(reader.dtype())?, + MaskFuture::ready(input.clone()), + )? + .await?; + + let valid = points + .validity()? + .execute_mask(LEN, &mut SESSION.create_execution_ctx())?; + assert_eq!(actual, &input & &valid); + Ok(()) +} + +/// Projecting storage fields reads only their segments, plus the storage validity when the +/// extension is nullable. +#[rstest] +#[case::field(Nullability::NonNullable, point_storage("a"), 1)] +#[case::nullable_field(Nullability::Nullable, point_storage("a"), 2)] +#[case::is_null(Nullability::Nullable, is_null(get_item("point", root())), 1)] +#[case::values(Nullability::NonNullable, get_item("point", root()), 2)] +#[case::nullable_values(Nullability::Nullable, get_item("point", root()), 3)] +#[tokio::test] +async fn projection_reads_only_needed_fields( + #[case] nullability: Nullability, + #[case] projection: Expression, + #[case] expected_requests: usize, +) -> VortexResult<()> { + let (segments, layout) = write(&point_table(), vec![table(nullability)?]).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &SESSION, + &Default::default(), + )?; + reader + .projection_evaluation( + &(0..LEN as u64), + &projection.bind(reader.dtype())?, + MaskFuture::new_true(LEN), + )? + .await?; + assert_eq!(source.requests(), expected_requests); + Ok(()) +} + +/// The plan of a storage field projection reads only that field, while a projection of the +/// extension values keeps the assembly of the whole storage. +#[tokio::test] +async fn plan_pushes_storage_reads_down() -> VortexResult<()> { + let (_, layout) = write(&point_table(), vec![table(Nullability::NonNullable)?]).await?; + let optimized = |projection: Expression| -> VortexResult<_> { + let plan = EvalPlan::try_new(projection.bind(layout.dtype())?, layout.new_plan()?)?; + optimize(plan.into_plan(), &SESSION) + }; + + insta::assert_snapshot!(optimized(point_storage("a"))?.display_tree(), @" + root: vortex.plan.filter(i32, rows=6) + child: vortex.plan.segment_scan(i32, rows=6) + "); + insta::assert_snapshot!(optimized(get_item("point", root()))?.display_tree(), @" + root: vortex.plan.ext_pack(test.point({a=i32, b=i64}), rows=6) + storage: vortex.plan.pack({a=i32, b=i64}, rows=6) + a: vortex.plan.filter(i32, rows=6) + child: vortex.plan.segment_scan(i32, rows=6) + b: vortex.plan.filter(i64, rows=6) + child: vortex.plan.segment_scan(i64, rows=6) + "); + Ok(()) +} + +/// A filter on a storage field plans zone pruning over the zone map of that field, reading only +/// metadata. +#[tokio::test] +async fn pruning_plan_reaches_storage_zones() -> VortexResult<()> { + let zoned = ZonedStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + FlatLayoutStrategy::default(), + ZonedLayoutOptions { + block_size: NonZeroUsize::new(2).ok_or_else(|| vortex_err!("zero block size"))?, + ..Default::default() + }, + ); + let strategy = TableStrategy::new(Arc::new(FlatLayoutStrategy::default()), Arc::new(zoned)) + .with_extension_layout([TestPoint.id()]); + let (_, layout) = write(&strategy, vec![table(Nullability::NonNullable)?]).await?; + + let falsifier = gt(point_storage("a"), lit(2i32)) + .bind(layout.dtype())? + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + let pruning = optimize( + EvalPlan::try_new(falsifier, layout.new_plan()?)?.into_plan(), + &SESSION, + )?; + let zoned = pruning + .as_opt::() + .ok_or_else(|| vortex_err!("not a zone pruning plan: {}", pruning.display_tree()))?; + assert!(zoned.is_pruning()); + assert_eq!(zoned.zone_len(), 2); + Ok(()) +} diff --git a/vortex-layout/src/layouts/extension/writer.rs b/vortex-layout/src/layouts/extension/writer.rs new file mode 100644 index 00000000000..8955ce49a55 --- /dev/null +++ b/vortex-layout/src/layouts/extension/writer.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! A writer strategy for extension-typed arrays. + +use std::sync::Arc; + +use async_trait::async_trait; +use futures::StreamExt; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::extension::ExtensionArrayExt; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_session::VortexSession; + +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::LayoutWriterContext; +use crate::layouts::extension::ExtensionLayout; +use crate::segments::SegmentSinkRef; +use crate::sequence::SendableSequentialStream; +use crate::sequence::SequencePointer; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; + +/// Writes extension-typed arrays into an [`ExtensionLayout`] over a layout of their storage. +/// +/// Every chunk is replaced by its storage, and the storage stream is written through `storage`. +/// Like [`StructStrategy`](crate::layouts::struct_::StructStrategy), it is a structural writer +/// that does not decide which extension columns to decompose. That is the job of +/// [`TableStrategy`](crate::layouts::table::TableStrategy). +pub struct ExtensionStrategy { + storage: Arc, +} + +impl ExtensionStrategy { + /// Create a writer that writes the extension storage through `storage`. + pub fn new(storage: Arc) -> Self { + Self { storage } + } +} + +#[async_trait] +impl LayoutStrategy for ExtensionStrategy { + async fn write_stream( + &self, + ctx: LayoutWriterContext, + segment_sink: SegmentSinkRef, + stream: SendableSequentialStream, + eof: SequencePointer, + session: &VortexSession, + ) -> VortexResult { + let ext_dtype = stream + .dtype() + .as_extension_opt() + .ok_or_else(|| { + vortex_err!( + "ExtensionStrategy can only write extension-typed streams, got {}", + stream.dtype() + ) + })? + .clone(); + let storage_dtype = ext_dtype.storage_dtype().clone(); + + let storage_session = session.clone(); + let storage_stream = stream.map(move |chunk| { + let (sequence_id, chunk) = chunk?; + Ok((sequence_id, extension_storage(chunk, &storage_session)?)) + }); + let storage = self + .storage + .write_stream( + ctx, + segment_sink, + SequentialStreamAdapter::new(storage_dtype, storage_stream).sendable(), + eof, + session, + ) + .await?; + Ok(ExtensionLayout::try_new(ext_dtype, storage)?.into_layout()) + } +} + +/// Returns the storage of an extension-typed `chunk`, whatever its encoding. +/// +/// A constant chunk keeps a constant storage. Any other chunk that is not already an extension +/// array is executed into one. +fn extension_storage(chunk: ArrayRef, session: &VortexSession) -> VortexResult { + if let Some(scalar) = chunk.as_constant() { + let storage = scalar.as_extension().to_storage_scalar(); + return Ok(ConstantArray::new(storage, chunk.len()).into_array()); + } + let extension = chunk.execute::(&mut session.create_execution_ctx())?; + Ok(extension.storage_array().clone()) +} diff --git a/vortex-layout/src/layouts/mod.rs b/vortex-layout/src/layouts/mod.rs index d2a8dd71ca9..0ff756be445 100644 --- a/vortex-layout/src/layouts/mod.rs +++ b/vortex-layout/src/layouts/mod.rs @@ -13,6 +13,7 @@ pub mod chunked; pub mod collect; pub mod compressed; pub mod dict; +pub mod extension; pub mod file_stats; pub mod flat; pub(crate) mod foreign; diff --git a/vortex-layout/src/layouts/table.rs b/vortex-layout/src/layouts/table.rs index 08575a80515..0fcf1d30fc5 100644 --- a/vortex-layout/src/layouts/table.rs +++ b/vortex-layout/src/layouts/table.rs @@ -4,10 +4,11 @@ //! A configurable writer strategy for tabular data. //! //! [`TableStrategy`] is a *dispatcher*: it inspects the dtype of the stream it is handed and -//! routes struct columns to [`StructStrategy`], list columns to [`ListLayoutStrategy`], and -//! everything else to the configured leaf strategy. Because it hands *itself* (suitably descended) -//! to those structural writers as the strategy for their children, arbitrarily nested struct/list -//! trees are written with no manual wiring. +//! routes struct columns to [`StructStrategy`], list columns to [`ListLayoutStrategy`], columns of +//! opted-in extension types to [`ExtensionStrategy`], and everything else to the configured leaf +//! strategy. Because it hands *itself* (suitably descended) to those structural +//! writers as the strategy for their children, arbitrarily nested struct/list trees are written +//! with no manual wiring. //! //! The dispatcher also owns field-path overrides, letting callers force a specific leaf field — //! at any depth — onto a custom strategy. @@ -15,9 +16,11 @@ use std::sync::Arc; use async_trait::async_trait; +use vortex_array::dtype::DType; use vortex_array::dtype::Field; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldPath; +use vortex_array::dtype::extension::ExtId; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -26,6 +29,7 @@ use vortex_utils::aliases::hash_set::HashSet; use crate::LayoutRef; use crate::LayoutStrategy; use crate::LayoutWriterContext; +use crate::layouts::extension::writer::ExtensionStrategy; use crate::layouts::list::writer::ListLayoutStrategy; use crate::layouts::struct_::StructStrategy; use crate::segments::SegmentSinkRef; @@ -45,9 +49,16 @@ type ListLayoutFactory = Arc Arc, + /// The extension types whose columns are written with [`ExtensionStrategy`] when their storage + /// decomposes. + extension_layouts: Arc>, } impl TableStrategy { @@ -88,6 +102,7 @@ impl TableStrategy { validity, leaf: fallback, list_layout_factory: None, + extension_layouts: Default::default(), } } @@ -175,6 +190,23 @@ impl TableStrategy { self.list_layout_factory = Some(Arc::new(factory)); self } + + /// Enable writing columns of the extension types `ext_ids` with [`ExtensionStrategy`], when + /// their storage is a struct (or a list, with list decomposition enabled), so their storage is + /// decomposed like any other struct or list column. + /// + /// Decomposition is opt-in per type: the leaf strategy of a decomposed column only sees the + /// storage fields, so it no longer computes statistics over the extension values, such as the + /// zone maps of aggregates registered for the type. + /// + /// **Note**: this is an unstable and experimental layout that is expected to change. + /// Using it may lead to unreadable files in the future. + pub fn with_extension_layout(mut self, ext_ids: impl IntoIterator) -> Self { + let mut extension_layouts = (*self.extension_layouts).clone(); + extension_layouts.extend(ext_ids); + self.extension_layouts = Arc::new(extension_layouts); + self + } } impl TableStrategy { @@ -225,6 +257,23 @@ impl TableStrategy { Some(factory(list_layout)) } + /// Build the [`ExtensionStrategy`] used to write an extension-typed stream at this level, if + /// its type is opted into the extension layout and this dispatcher decomposes its storage + /// dtype. + /// + /// The storage is written by a copy of this dispatcher: an extension column has no fields of + /// its own, so overrides beneath it address the fields of its storage. + fn extension_strategy(&self, dtype: &DType) -> Option { + let ext_dtype = dtype.as_extension_opt()?; + if !self.extension_layouts.contains(&ext_dtype.id()) { + return None; + } + let storage_dtype = ext_dtype.storage_dtype(); + let decomposes = storage_dtype.is_struct() + || (storage_dtype.is_list() && self.list_layout_factory.is_some()); + decomposes.then(|| ExtensionStrategy::new(Arc::new(self.clone()))) + } + /// Descend into a subfield, retaining only the overrides that apply beneath it (rebased to be /// relative to the child). fn descend(&self, field: &Field) -> Self { @@ -244,6 +293,7 @@ impl TableStrategy { validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + extension_layouts: Arc::clone(&self.extension_layouts), } } @@ -255,6 +305,7 @@ impl TableStrategy { validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + extension_layouts: Arc::clone(&self.extension_layouts), } } @@ -305,6 +356,12 @@ impl LayoutStrategy for TableStrategy { .await; } + if let Some(extension_strategy) = self.extension_strategy(&dtype) { + return extension_strategy + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + } + // Leaf: hand off to the leaf strategy. self.leaf .write_stream(ctx, segment_sink, stream, eof, session) diff --git a/vortex-layout/src/plan/physical/mod.rs b/vortex-layout/src/plan/physical/mod.rs index aeb31bfee02..ef4a9a82c82 100644 --- a/vortex-layout/src/plan/physical/mod.rs +++ b/vortex-layout/src/plan/physical/mod.rs @@ -5,6 +5,9 @@ pub use vortex_scan::plan::*; +pub use crate::layouts::extension::ExtPack; +pub use crate::layouts::extension::ExtPackData; +pub use crate::layouts::extension::ExtPackPlan; pub use crate::lowering::LegacyStats; pub use crate::lowering::LegacyStatsData; pub use crate::lowering::LegacyStatsPlan; diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests.rs index 289bbbd56ab..5f3e3c71068 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests.rs @@ -19,15 +19,21 @@ use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinArray; use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::extension::ExtVTable; use vortex_array::expr::Expression; use vortex_array::expr::and; use vortex_array::expr::eq; +use vortex_array::expr::ext_storage; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::is_null; @@ -67,11 +73,13 @@ use crate::layouts::zoned::writer::ZonedLayoutOptions; use crate::layouts::zoned::writer::ZonedStrategy; use crate::scan::arrow::to_record_batch; use crate::scan::scan_builder::ScanBuilder as V1ScanBuilder; +use crate::segments::CountingSegmentSource; use crate::segments::SegmentSource; use crate::segments::TestSegments; use crate::sequence::SequenceId; use crate::sequence::SequentialStreamAdapter; use crate::sequence::SequentialStreamExt as _; +use crate::test::TestPoint; use crate::test::new_session; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -108,26 +116,71 @@ fn table_chunk(start: usize) -> VortexResult { .into_array()) } +/// A chunk of `CHUNK_ROWS` rows starting at row `start`: an integer column and a nullable +/// extension column whose struct storage holds the row and ten times the row. +fn point_chunk(start: usize) -> VortexResult { + points_chunk(start, true, Nullability::Nullable) +} + +/// [`point_chunk`] with a non-nullable extension column. +fn non_nullable_point_chunk(start: usize) -> VortexResult { + points_chunk(start, true, Nullability::NonNullable) +} + +/// [`point_chunk`] with the storage struct in place of the extension column. +fn plain_point_chunk(start: usize) -> VortexResult { + points_chunk(start, false, Nullability::Nullable) +} + +fn points_chunk(start: usize, extension: bool, nullability: Nullability) -> VortexResult { + let rows = start..start + CHUNK_ROWS; + let ids = Buffer::from_iter( + rows.clone() + .map(|row| i32::try_from(row).unwrap_or(i32::MAX)), + ); + let tens = Buffer::from_iter( + rows.clone() + .map(|row| i64::try_from(10 * row).unwrap_or(i64::MAX)), + ); + let validity = match nullability { + Nullability::NonNullable => Validity::NonNullable, + Nullability::Nullable => Validity::from_iter(rows.map(|row| row % 5 != 0)), + }; + let storage = StructArray::try_new( + FieldNames::from(["a", "b"]), + [ids.clone().into_array(), tens.into_array()], + CHUNK_ROWS, + validity, + )?; + let points = if extension { + ExtensionArray::try_new(TestPoint::dtype(nullability), storage.into_array())?.into_array() + } else { + storage.into_array() + }; + Ok(StructArray::from_fields(&[("id", ids.into_array()), ("point", points)])?.into_array()) +} + /// Writes `CHUNKS` table chunks with `strategy`. async fn write( session: &VortexSession, strategy: &dyn LayoutStrategy, ) -> VortexResult<(Arc, LayoutRef)> { - write_chunks(session, strategy, CHUNKS).await + write_chunks(session, strategy, table_chunk, CHUNKS).await } -/// Writes `count` table chunks with `strategy`. +/// Writes `count` chunks made by `chunk`, called with each chunk's first row, with `strategy`. async fn write_chunks( session: &VortexSession, strategy: &dyn LayoutStrategy, + chunk: fn(usize) -> VortexResult, count: usize, ) -> VortexResult<(Arc, LayoutRef)> { let segments = Arc::new(TestSegments::default()); let (mut sequence_id, eof) = SequenceId::root().split(); let chunks = (0..count) - .map(|chunk| Ok((sequence_id.advance(), table_chunk(chunk * CHUNK_ROWS)?))) + .map(|index| Ok((sequence_id.advance(), chunk(index * CHUNK_ROWS)?))) .collect::>(); - let dtype = table_chunk(0)?.dtype().clone(); + let dtype = chunk(0)?.dtype().clone(); let layout = strategy .write_stream( ArrayContext::empty().into(), @@ -145,12 +198,12 @@ fn chunked_flat() -> Arc { } /// Every column is shredded into its own chunked leaves. -fn table() -> Arc { - Arc::new(TableStrategy::new(chunked_flat(), chunked_flat())) +fn table_strategy() -> TableStrategy { + TableStrategy::new(chunked_flat(), chunked_flat()) } /// Every column is shredded into chunked leaves with zone statistics. -fn zoned_table() -> Arc { +fn zoned_table_strategy() -> TableStrategy { let zoned = ZonedStrategy::new( ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), FlatLayoutStrategy::default(), @@ -159,7 +212,15 @@ fn zoned_table() -> Arc { ..Default::default() }, ); - Arc::new(TableStrategy::new(chunked_flat(), Arc::new(zoned))) + TableStrategy::new(chunked_flat(), Arc::new(zoned)) +} + +fn table() -> Arc { + Arc::new(table_strategy()) +} + +fn zoned_table() -> Arc { + Arc::new(zoned_table_strategy()) } /// A [`ScanFile`] over test segments. They have no byte offsets, and the scan fetches them by id, @@ -494,6 +555,178 @@ async fn projection_skips_unsupported_unselected_layouts() -> VortexResult<()> { .await } +fn point_storage(field: &str) -> Expression { + get_item(field, ext_storage(get_item("point", root()))) +} + +/// Extension columns written with the extension layout scan the same on both executors, and as +/// the expressions evaluate over the input. +#[rstest] +#[case::field(point_storage("a"), None)] +#[case::values(get_item("point", root()), None)] +#[case::is_null(is_null(get_item("point", root())), None)] +#[case::mixed( + pack( + [("a", point_storage("a")), ("point", get_item("point", root()))], + Nullability::NonNullable, + ), + None, +)] +#[case::filter_field(get_item("id", root()), Some(gt(point_storage("a"), lit(2500i32))))] +#[case::filter_values( + get_item("point", root()), + Some(and( + gt(point_storage("a"), lit(995i32)), + lt(point_storage("b"), lit(20_500i64)), + )) +)] +#[case::filter_is_null(point_storage("b"), Some(is_null(get_item("point", root()))))] +#[tokio::test] +async fn extension_layout_matches_v1( + #[values(false, true)] zoned: bool, + #[case] projection: Expression, + #[case] filter: Option, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let strategy = if zoned { + zoned_table_strategy() + } else { + table_strategy() + } + .with_extension_layout([TestPoint.id()]); + let (segments, layout) = write_chunks(&session, &strategy, point_chunk, CHUNKS).await?; + let dtype = layout.dtype().clone(); + let make = || -> VortexResult { + Ok(builder(&session, &segments, &layout)? + .with_projection(projection.bind(&dtype)?) + .with_some_filter( + filter + .as_ref() + .map(|filter| filter.bind(&dtype)) + .transpose()?, + )) + }; + assert_same_as_v1(&session, make).await?; + + let input = ChunkedArray::try_new( + (0..CHUNKS) + .map(|chunk| point_chunk(chunk * CHUNK_ROWS)) + .collect::>>()?, + layout.dtype().clone(), + )? + .into_array(); + let mut ctx = session.create_execution_ctx(); + let input = match &filter { + Some(filter) => { + let mask = input + .clone() + .apply(filter)? + .fill_null(false)? + .execute::(&mut ctx)?; + input.filter(mask)? + } + None => input, + }; + let expected = input.apply(&projection)?; + let scan = make()?; + let actual = collect_scan(scan.dtype().clone(), scan).await?; + assert_arrays_eq!(actual, expected, &mut ctx); + Ok(()) +} + +/// Filtering a storage field through `ext_storage` returns the same rows and reads the same +/// segments as filtering the same field of a plain struct column. +#[rstest] +#[tokio::test] +async fn extension_filter_prunes_like_struct(#[values(false, true)] v2: bool) -> VortexResult<()> { + let session = new_session().with_tokio(); + let strategy = zoned_table_strategy().with_extension_layout([TestPoint.id()]); + let mut scans = Vec::new(); + for (chunk, point) in [ + ( + point_chunk as fn(usize) -> VortexResult, + ext_storage(get_item("point", root())), + ), + (plain_point_chunk, get_item("point", root())), + ] { + let (segments, layout) = write_chunks(&session, &strategy, chunk, CHUNKS).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let projection = get_item("id", root()).bind(layout.dtype())?; + let filter = gt(get_item("a", point), lit(3500i32)).bind(layout.dtype())?; + let dtype = projection.dtype().clone(); + let rows = if v2 { + let segments: Arc = Arc::::clone(&source); + let scan = builder(&session, &segments, &layout)? + .with_projection(projection) + .with_some_filter(Some(filter)); + collect_scan(dtype, scan).await? + } else { + let reader = layout.new_reader( + "".into(), + Arc::::clone(&source), + &session, + &Default::default(), + )?; + let scan = V1ScanBuilder::new(session.clone(), reader) + .with_projection(projection) + .with_filter(filter); + collect(dtype, scan.into_stream()?).await? + }; + scans.push((rows, source.requests())); + } + + let mut ctx = session.create_execution_ctx(); + assert_arrays_eq!(scans[0].0, scans[1].0, &mut ctx); + assert_eq!(scans[0].1, scans[1].1); + Ok(()) +} + +/// Projecting one storage field of an extension column reads the segments of that field, plus +/// those of the storage validity when the extension is nullable. +/// +/// The planner does not push an expression through the assembly of a nullable struct yet, so with +/// a nullable extension it reads every storage column. A plain nullable struct column reads the +/// same segments, so the extension layout adds no reads of its own. +#[rstest] +#[case::v1(false, non_nullable_point_chunk, point_storage("a"), 1)] +#[case::v1_nullable(false, point_chunk, point_storage("a"), 2)] +#[case::v1_nullable_struct(false, plain_point_chunk, get_item("a", get_item("point", root())), 2)] +#[case::v2(true, non_nullable_point_chunk, point_storage("a"), 1)] +#[case::v2_nullable(true, point_chunk, point_storage("a"), 3)] +#[case::v2_nullable_struct(true, plain_point_chunk, get_item("a", get_item("point", root())), 3)] +#[tokio::test] +async fn extension_field_projection_reads( + #[case] v2: bool, + #[case] chunk: fn(usize) -> VortexResult, + #[case] projection: Expression, + #[case] columns_read: usize, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let strategy = table_strategy().with_extension_layout([TestPoint.id()]); + let (segments, layout) = write_chunks(&session, &strategy, chunk, CHUNKS).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let projection = projection.bind(layout.dtype())?; + let dtype = projection.dtype().clone(); + let actual = if v2 { + let segments: Arc = Arc::::clone(&source); + let scan = builder(&session, &segments, &layout)?.with_projection(projection); + collect_scan(dtype, scan).await? + } else { + let reader = layout.new_reader( + "".into(), + Arc::::clone(&source), + &session, + &Default::default(), + )?; + let scan = V1ScanBuilder::new(session.clone(), reader).with_projection(projection); + collect(dtype, scan.into_stream()?).await? + }; + + assert_eq!(actual.len(), CHUNKS * CHUNK_ROWS); + assert_eq!(source.requests(), columns_read * CHUNKS); + Ok(()) +} + #[test] fn partition_rows_tile_the_file_on_row_blocks() { let (file_size, row_count) = (1_000u64, 100_000u64); diff --git a/vortex-layout/src/session.rs b/vortex-layout/src/session.rs index bb8afedeb19..e04ce709e3f 100644 --- a/vortex-layout/src/session.rs +++ b/vortex-layout/src/session.rs @@ -3,6 +3,7 @@ use std::any::Any; +use vortex_array::dtype::extension::ExtId; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_session::ArcSwapMap; @@ -18,6 +19,7 @@ use crate::LayoutPluginRef; use crate::LayoutSerialization; use crate::layouts::chunked::Chunked; use crate::layouts::dict::Dict; +use crate::layouts::extension::Extension; use crate::layouts::flat::Flat; use crate::layouts::indexed::Indexed; use crate::layouts::list::List; @@ -35,6 +37,9 @@ pub struct LayoutSession { registry: LayoutRegistry, /// Serializers keyed by the in-memory layout ID. serializers: LayoutRegistry, + /// The extension types opted into the extension layout, see + /// [`decompose_extension`](Self::decompose_extension). + decomposed_extensions: ArcSwapMap, } impl LayoutSession { @@ -65,6 +70,25 @@ impl LayoutSession { fn serializer(&self, id: &LayoutId) -> Option { self.serializers.get(id) } + + /// Opts the extension type `id` into the experimental + /// [extension layout](crate::layouts::extension). + /// + /// The default write strategy of `vortex-file` writes a column of an opted-in type as an + /// extension layout over its decomposed storage, when the enabled editions include that layout. + /// It writes columns of every other extension type as leaves, so their statistics are computed + /// over the extension values. A type opts in when readers query its storage fields, rather + /// than its values. + pub fn decompose_extension(&self, id: ExtId) { + self.decomposed_extensions.insert(id, ()); + } + + /// Returns the extension types opted into the extension layout with + /// [`decompose_extension`](Self::decompose_extension). + pub fn decomposed_extensions(&self) -> Vec { + self.decomposed_extensions + .read(|extensions| extensions.keys().copied().collect()) + } } impl Default for LayoutSession { @@ -72,6 +96,7 @@ impl Default for LayoutSession { let this = Self { registry: LayoutRegistry::default(), serializers: LayoutRegistry::default(), + decomposed_extensions: ArcSwapMap::default(), }; // Register the built-in layout encodings. @@ -83,6 +108,7 @@ impl Default for LayoutSession { this.register(&Dict as &dyn LayoutPlugin); this.register(&List as &dyn LayoutPlugin); this.register(&Indexed as &dyn LayoutPlugin); + this.register(&Extension as &dyn LayoutPlugin); this } } diff --git a/vortex-layout/src/test.rs b/vortex-layout/src/test.rs index 29eeb8c3eba..855385f8e53 100644 --- a/vortex-layout/src/test.rs +++ b/vortex-layout/src/test.rs @@ -3,9 +3,22 @@ use std::sync::LazyLock; +use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::dtype::extension::ExtDType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_array::dtype::extension::ExtId; +use vortex_array::dtype::extension::ExtVTable; +use vortex_array::scalar::ScalarValue; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; use vortex_io::session::RuntimeSession; use vortex_io::session::RuntimeSessionExt; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::session::LayoutSession; @@ -34,7 +47,65 @@ impl crate::LayoutStrategy for FailingStrategy { _stream: crate::sequence::SendableSequentialStream, _eof: crate::sequence::SequencePointer, _session: &VortexSession, - ) -> vortex_error::VortexResult { + ) -> VortexResult { vortex_error::vortex_bail!("{}", Self::MESSAGE) } } + +/// A test extension type stored as `{a: i32, b: i64}`. It makes no claims about its storage, so +/// only structural operations and `ext_storage` apply to its values. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct TestPoint; + +impl TestPoint { + /// The point dtype with the given top-level nullability. + pub fn dtype(nullability: Nullability) -> ExtDTypeRef { + ExtDType::::try_new(EmptyMetadata, nullability) + .vortex_expect("TestPoint accepts every nullability") + .erased() + } +} + +impl ExtVTable for TestPoint { + type Metadata = EmptyMetadata; + type StoredMetadata = EmptyMetadata; + type NativeValue<'a> = &'a ScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.point"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(Vec::new()) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(EmptyMetadata) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Struct( + StructFields::from_iter([ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I64, Nullability::NonNullable)), + ]), + Nullability::NonNullable, + ) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } +} diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index edb21f0d1dc..e5cdc90a3bc 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -15,7 +15,9 @@ immutable = false arrays = [ "fastlanes.delta", ] -layouts = [] +layouts = [ + "vortex.ext", +] dtypes = [] aggregates = [] @@ -25,6 +27,8 @@ aggregates = [] arrays = [ "fastlanes.delta", ] -layouts = [] +layouts = [ + "vortex.ext", +] dtypes = [] aggregates = [] From d65ce3b60dd6f438e3ab54447d0842268845323b Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Fri, 20 Nov 2026 16:07:41 -0500 Subject: [PATCH 02/13] Push down DataFusion field access on extension types Field access on an extension column converts to a Vortex field read on its storage, so the Vortex scan evaluates it instead of DataFusion. Taken from the extension field access changes of the protobuf prototype (ba36f9042), without the protobuf crate. Signed-off-by: Connor Tsui --- vortex-datafusion/src/convert/exprs/mod.rs | 58 +++++- vortex-datafusion/src/convert/exprs/tests.rs | 194 ++++++++++++++++++- 2 files changed, 246 insertions(+), 6 deletions(-) diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 5e5602e32e6..61bd7330468 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -47,10 +47,12 @@ use vortex::dtype::DType; use vortex::dtype::Nullability; use vortex::dtype::PType; use vortex::dtype::StructFields; +use vortex::dtype::extension::ExtDTypeRef; use vortex::expr::Expression; use vortex::expr::Lambda; use vortex::expr::byte_length; use vortex::expr::cast; +use vortex::expr::ext_storage; use vortex::expr::get_item; use vortex::expr::in_list_of; use vortex::expr::is_not_null; @@ -265,7 +267,10 @@ type Conversion = Result; /// integer arithmetic. Matching DataFusion's overflow behavior is deferred to a future patch. /// Nested struct field access also uses Vortex semantics: a null parent produces a null child, /// whereas DataFusion extracts the child without applying parent validity. These differences -/// are accepted for both filters and projections. +/// are accepted for both filters and projections. DataFusion sees an extension type that Arrow +/// exports as its struct storage as that struct, so field access on it reads the storage through +/// `ext_storage`. Field access on an extension type that the session does not know stays in +/// DataFusion. /// Searched `CASE WHEN` expressions preserve short-circuit evaluation: conditions and /// branch values only execute on the rows that reach them, including fallible branches. /// Other expressions require compatible SQL semantics or remain in DataFusion. @@ -618,6 +623,46 @@ impl DefaultExpressionConverter { Ok(converted) } + /// Returns the struct whose fields DataFusion reads when it reads a field of `expr`. + /// + /// DataFusion sees an extension value through its Arrow type. When the session exports an + /// extension type as its struct storage, as it does for every type without an Arrow plugin, + /// DataFusion reads the fields of the storage. Vortex extension types are opaque and expose + /// their storage only through `ext_storage`, so the field access reads the storage + /// explicitly. Field access on any other extension type stays in DataFusion. + fn struct_source(&self, expr: Expression, input_dtype: &DType) -> Conversion { + let DType::Extension(ext_dtype) = converted_dtype(&expr, input_dtype)? else { + return Ok(expr); + }; + if !ext_dtype.storage_dtype().is_struct() || !self.exports_storage(&ext_dtype) { + return Err(Unconverted::Unsupported); + } + Ok(ext_storage(expr)) + } + + /// Whether `field` is an Arrow extension type that the session imports as a plain type. + /// + /// The session does not know the type, so a Vortex file stores the column as an extension + /// type that the converted expression cannot see. Reading its fields needs `ext_storage`, so + /// field access on it stays in DataFusion. + fn is_unknown_extension(&self, field: &Field) -> Conversion { + if field.extension_type_name().is_none() { + return Ok(false); + } + Ok(!self.arrow_dtype(field)?.is_extension()) + } + + /// Whether the session exports `ext_dtype` with the same Arrow type as its storage. + fn exports_storage(&self, ext_dtype: &ExtDTypeRef) -> bool { + let arrow = self.session.arrow(); + let exported = arrow.to_arrow_field("", &DType::Extension(ext_dtype.clone())); + let storage = arrow.to_arrow_field("", ext_dtype.storage_dtype()); + matches!( + (exported, storage), + (Ok(exported), Ok(storage)) if exported.data_type() == storage.data_type() + ) + } + fn convert_in_list( &self, in_list: &df_expr::InListExpr, @@ -745,7 +790,7 @@ impl DefaultExpressionConverter { if paths.is_empty() { return Err(exec_datafusion_err!("get_field requires a field path").into()); } - let mut source_type = source.data_type(schema)?; + let mut source_field = source.return_field(schema)?; let mut names = Vec::with_capacity(paths.len()); for path in paths { let name = path @@ -754,18 +799,21 @@ impl DefaultExpressionConverter { .ok_or_else(|| { exec_datafusion_err!("get_field path must be a non-null string literal") })?; - let DataType::Struct(fields) = &source_type else { + if self.is_unknown_extension(&source_field)? { + return Err(Unconverted::Unsupported); + } + let DataType::Struct(fields) = source_field.data_type() else { return Err(Unconverted::Unsupported); }; let (_, field) = fields.find(name).ok_or_else(|| { exec_datafusion_err!("get_field references missing field {name}") })?; - source_type = field.data_type().clone(); + source_field = Arc::clone(field); names.push(name); } let mut result = self.convert_expr(source, schema, input_dtype)?; for name in names { - result = get_item(name, result); + result = get_item(name, self.struct_source(result, input_dtype)?); } return Ok(result); } diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index cc093437f05..fd926aead4a 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -55,17 +55,23 @@ use datafusion_physical_plan::expressions as df_expr; use insta::assert_snapshot; use rstest::rstest; use vortex::array::Canonical; +use vortex::array::EmptyMetadata; use vortex::array::IntoArray; use vortex::array::arrays::ConstantArray; use vortex::array::arrays::PrimitiveArray; use vortex::array::builtins::ArrayBuiltins; use vortex::dtype::PType; +use vortex::dtype::extension::ExtDType; +use vortex::dtype::extension::ExtId; +use vortex::dtype::extension::ExtVTable; +use vortex::dtype::session::DTypeSessionExt; use vortex::encodings::uuid::Uuid; use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::expr::between; use vortex::expr::proto::ExprSerializeProtoExt; use vortex::scalar::Scalar; +use vortex::scalar::ScalarValue as VortexScalarValue; use vortex::scalar_fn::fns::between::BetweenOptions; use vortex::scalar_fn::fns::between::StrictComparison; use vortex::scalar_fn::fns::cast::Cast; @@ -1600,7 +1606,15 @@ fn test_case_when_datafusion_vortex_equivalence() -> anyhow::Result<()> { } fn assert_native_matches(expr: Arc, batch: RecordBatch) -> anyhow::Result<()> { - let session = VortexSession::default(); + assert_native_matches_in(&VortexSession::default(), expr, batch) +} + +/// Like [`assert_native_matches`], resolving Arrow extension types through `session`. +fn assert_native_matches_in( + session: &VortexSession, + expr: Arc, + batch: RecordBatch, +) -> anyhow::Result<()> { let converted = DefaultExpressionConverter::new(session.clone()) .try_convert(&expr, &batch.schema())? .ok_or_else(|| anyhow::anyhow!("Expected native conversion for {expr}"))?; @@ -2912,3 +2926,181 @@ fn test_fallible_boolean_rhs_is_residual( assert!(!converts(&expr, &batch.schema())?); Ok(()) } + +/// A test extension type stored as `{x: i32, y: i64}`. It has no Arrow plugin, so Arrow exports it +/// as its storage struct. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct Point; + +impl ExtVTable for Point { + type Metadata = EmptyMetadata; + type StoredMetadata = EmptyMetadata; + type NativeValue<'a> = &'a VortexScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.point"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(Vec::new()) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(EmptyMetadata) + } + + fn metadata_from_storage( + &self, + stored_metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(stored_metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + DType::Struct( + StructFields::from_iter([ + ("x", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("y", DType::Primitive(PType::I64, Nullability::NonNullable)), + ]), + Nullability::NonNullable, + ) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a VortexScalarValue, + ) -> VortexResult> { + Ok(storage_value) + } +} + +/// A session that knows the [`Point`] extension type. +fn point_session() -> VortexSession { + let session = VortexSession::default(); + session.dtypes().register(Point); + session +} + +/// A batch `{point: test.point?, outer: {point: test.point?}}` as the session exports it, with +/// points `{x: i, y: 10 * i}` for `i` in `1..=3`. With `null_point`, the second point is null. +fn point_batch(session: &VortexSession, null_point: bool) -> anyhow::Result { + let point_dtype = DType::Extension( + ExtDType::::try_new(EmptyMetadata, Nullability::Nullable)?.erased(), + ); + let point_field = session.arrow().to_arrow_field("point", &point_dtype)?; + let DataType::Struct(point_fields) = point_field.data_type() else { + anyhow::bail!("Expected the struct storage of a point, got {point_field}"); + }; + let points: ArrowArrayRef = Arc::new(StructArray::try_new( + point_fields.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(Int64Array::from(vec![10, 20, 30])), + ], + null_point.then(|| NullBuffer::from(vec![true, false, true])), + )?); + let outer: ArrowArrayRef = Arc::new(StructArray::try_new( + vec![point_field.clone()].into(), + vec![Arc::clone(&points)], + None, + )?); + let schema = Schema::new(vec![ + point_field, + Field::new("outer", outer.data_type().clone(), false), + ]); + Ok(RecordBatch::try_new(Arc::new(schema), vec![points, outer])?) +} + +/// DataFusion reads the fields of an extension value from the struct storage that Arrow exports. +/// Vortex extension types are opaque, so the converted field access reads the storage explicitly. +#[rstest] +#[case::column(false, false)] +#[case::nested(true, false)] +#[case::nested_flattened(true, true)] +fn test_get_field_reads_extension_storage( + #[case] nested: bool, + #[case] flattened: bool, +) -> anyhow::Result<()> { + let session = point_session(); + let batch = point_batch(&session, true)?; + let schema = batch.schema(); + let (expr, point) = if !nested { + let column = Arc::new(df_expr::Column::new("point", 0)); + ( + get_field_expr(column, &["y"], &schema)?, + get_item("point", root()), + ) + } else { + let column = Arc::new(df_expr::Column::new("outer", 1)); + let expr = if flattened { + get_field_expr(column, &["point", "y"], &schema)? + } else { + get_field_expr( + get_field_expr(column, &["point"], &schema)?, + &["y"], + &schema, + )? + }; + (expr, get_item("point", get_item("outer", root()))) + }; + + let converted = DefaultExpressionConverter::new(session.clone()) + .try_convert(&expr, &schema)? + .ok_or_else(|| anyhow::anyhow!("Expected native conversion for {expr}"))?; + assert_eq!(converted, get_item("y", ext_storage(point))); + + // Unlike DataFusion, Vortex applies the validity of the extension value to its fields. + let input = session.arrow().from_arrow_record_batch(batch, &schema)?; + assert_arrays_eq!( + input.apply(&converted)?, + PrimitiveArray::from_option_iter([Some(10i64), None, Some(30)]), + &mut session.create_execution_ctx() + ); + Ok(()) +} + +/// A filter on a storage field of an extension column converts and matches DataFusion. +#[rstest] +#[case::column(&["point", "x"])] +#[case::nested(&["outer", "point", "x"])] +fn test_extension_storage_field_filter(#[case] path: &[&str]) -> anyhow::Result<()> { + let session = point_session(); + let batch = point_batch(&session, false)?; + let schema = batch.schema(); + let [column, fields @ ..] = path else { + anyhow::bail!("Expected a column and a field path"); + }; + let column = Arc::new(df_expr::Column::new(column, schema.index_of(column)?)); + let predicate: Arc = Arc::new(df_expr::BinaryExpr::new( + get_field_expr(column, fields, &schema)?, + DFOperator::Gt, + Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(1)))), + )); + assert_native_matches_in(&session, predicate, batch) +} + +/// A session that does not know an extension type imports its Arrow field as the storage struct, +/// while a Vortex file stores the column as an extension that only `ext_storage` reads. So field +/// access on it stays in DataFusion, at any depth. +#[rstest] +#[case::column(&["point", "x"])] +#[case::nested(&["outer", "point", "x"])] +fn test_get_field_on_unknown_extension_is_unsupported(#[case] path: &[&str]) -> anyhow::Result<()> { + let batch = point_batch(&point_session(), false)?; + let schema = batch.schema(); + let [column, fields @ ..] = path else { + anyhow::bail!("Expected a column and a field path"); + }; + let column = Arc::new(df_expr::Column::new(column, schema.index_of(column)?)); + let expr = get_field_expr(column, fields, &schema)?; + assert!(!converts(&expr, &schema)?); + // The session that knows the type reads the field through `ext_storage`. + assert!( + DefaultExpressionConverter::new(point_session()) + .try_convert(&expr, &schema)? + .is_some() + ); + Ok(()) +} From 2fc48e8e76722ae5b39885c636072e522fccf8ec Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 08:29:31 +0000 Subject: [PATCH 03/13] Read single fields of nullable structs and prune beneath them Most protobuf message fields are nullable structs, and three gaps made them slow. The planner scan read every field of a nullable struct for a projection of one field, because the Pack rules skipped nullable structs. The same skip made a planner read of any field next to a list-layout child fail with "Plan vortex.plan.list_pack has no pipeline implementation". And the zoned writer wrote no zone map for any field beneath a nullable struct. Projections of a nullable struct field now read that field and the struct validity. Fields beneath a nullable struct now record the zone statistics that stay correct when the struct is null: bounds, and whether a zone holds no NaN in place of the NaN count. Their hidden values can only widen a bound, so pruning stays conservative, and counts, which those values would make wrong, are not recorded. This changes the zone maps that every writer produces for such fields. Signed-off-by: Connor Tsui --- .../src/declarations/unstable/mod.rs | 1 + vortex-layout/src/layouts/extension/tests.rs | 18 + vortex-layout/src/layouts/struct_/mod.rs | 1 + vortex-layout/src/layouts/struct_/reader.rs | 93 +++-- vortex-layout/src/layouts/struct_/unmask.rs | 134 +++++++ vortex-layout/src/layouts/struct_/writer.rs | 52 ++- vortex-layout/src/layouts/zoned/writer.rs | 151 ++++++-- vortex-layout/src/scan/v2/tests.rs | 354 +++++++++++++++++- vortex-layout/src/strategy.rs | 6 +- vortex-scan/src/plan/builtins/pack/mask.rs | 171 +++++++++ vortex-scan/src/plan/builtins/pack/mod.rs | 32 +- vortex-scan/src/plan/builtins/zoned/mod.rs | 24 ++ vortex-scan/src/plan/mod.rs | 1 + vortex-scan/src/plan/tests.rs | 122 +++++- .../editions/unstable/unstable2026.10.0.toml | 8 +- 15 files changed, 1059 insertions(+), 109 deletions(-) create mode 100644 vortex-layout/src/layouts/struct_/unmask.rs create mode 100644 vortex-scan/src/plan/builtins/pack/mask.rs diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index 73400e7f45b..5bf265be04c 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -34,5 +34,6 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { added: &[ EditionMember::array(&"fastlanes.delta"), EditionMember::layout(&"vortex.ext"), + EditionMember::aggregate(&"vortex.all_non_nan"), ], }; diff --git a/vortex-layout/src/layouts/extension/tests.rs b/vortex-layout/src/layouts/extension/tests.rs index 38a520ed9d6..1422508861d 100644 --- a/vortex-layout/src/layouts/extension/tests.rs +++ b/vortex-layout/src/layouts/extension/tests.rs @@ -396,6 +396,24 @@ async fn plan_pushes_storage_reads_down() -> VortexResult<()> { Ok(()) } +/// Over nullable storage, the plan of a storage field projection reads that field and the storage +/// validity, which nulls the field where the extension value is null. +#[tokio::test] +async fn plan_pushes_nullable_storage_reads_down() -> VortexResult<()> { + let (_, layout) = write(&point_table(), vec![table(Nullability::Nullable)?]).await?; + let plan = EvalPlan::try_new(point_storage("a").bind(layout.dtype())?, layout.new_plan()?)?; + + insta::assert_snapshot!(optimize(plan.into_plan(), &SESSION)?.display_tree(), @" + root: vortex.plan.eval(i32?, rows=6) expr=vortex.mask($.0, $.1) + child: vortex.plan.pack({0=i32, 1=bool}, rows=6) + 0: vortex.plan.filter(i32, rows=6) + child: vortex.plan.segment_scan(i32, rows=6) + 1: vortex.plan.filter(bool, rows=6) + child: vortex.plan.segment_scan(bool, rows=6) + "); + Ok(()) +} + /// A filter on a storage field plans zone pruning over the zone map of that field, reading only /// metadata. #[tokio::test] diff --git a/vortex-layout/src/layouts/struct_/mod.rs b/vortex-layout/src/layouts/struct_/mod.rs index 389d04f9423..a6b920ded8c 100644 --- a/vortex-layout/src/layouts/struct_/mod.rs +++ b/vortex-layout/src/layouts/struct_/mod.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod reader; +mod unmask; pub mod writer; use std::sync::Arc; diff --git a/vortex-layout/src/layouts/struct_/reader.rs b/vortex-layout/src/layouts/struct_/reader.rs index 06b3a722bae..a3535bf8f37 100644 --- a/vortex-layout/src/layouts/struct_/reader.rs +++ b/vortex-layout/src/layouts/struct_/reader.rs @@ -52,6 +52,7 @@ use crate::RowSplits; use crate::SplitRange; use crate::layouts::partitioned::PartitionedEval; use crate::layouts::struct_::StructLayout; +use crate::layouts::struct_::unmask::unmask_fields; use crate::segments::SegmentSource; #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -90,9 +91,14 @@ pub struct StructReader { expanded_root_expr: BoundExpression, field_lookup: Option>, - partitioned_expr_cache: DashMap>>, + partitioned_expr_cache: PartitionCache, + /// Partitions of pruning predicates, which read the fields of a nullable struct past its + /// validity where they can. + pruning_partition_cache: PartitionCache, } +type PartitionCache = DashMap>>; + impl StructReader { pub(super) fn try_new( layout: StructLayout, @@ -147,6 +153,7 @@ impl StructReader { lazy_children, field_lookup, partitioned_expr_cache: DashMap::with_hasher_and_shard_amount(Default::default(), 8), + pruning_partition_cache: DashMap::with_hasher_and_shard_amount(Default::default(), 8), }) } @@ -195,36 +202,36 @@ impl StructReader { /// Utility for partitioning an expression over the fields of a struct. fn partition_expr(&self, expr: &BoundExpression) -> VortexResult { - let key = ExactBoundExpr(expr.clone()); - - // Look up the cell under a shared shard lock; only a miss takes the write lock, and - // only for as long as it takes to insert an empty cell. - let cell = match self.partitioned_expr_cache.get(&key) { - Some(entry) => Arc::clone(entry.value()), - None => Arc::clone( - self.partitioned_expr_cache - .entry(key) - .or_insert_with(|| Arc::new(OnceLock::new())) - .value(), - ), - }; - // All map guards are dropped here, so partitioning runs outside any shard lock. - // Concurrent misses may compute redundantly; `get_or_init` keeps a single winner. + cached_partition(&self.partitioned_expr_cache, expr, |expr| { + self.compute_partitioned_expr(expr, false) + }) + } - if let Some(value) = cell.get() { - return Ok(value.clone()); + /// Partitions a pruning predicate over the fields of a struct. + /// + /// Over a nullable struct, the predicate reads its fields past the struct validity wherever + /// it cannot hold in a row where the struct is null, so it reaches the fields' zone maps. + fn partition_pruning_expr(&self, expr: &BoundExpression) -> VortexResult { + if !self.dtype().is_nullable() { + return self.partition_expr(expr); } - // Cache the bound trees themselves: rebinding would create fresh child identity and defeat - // downstream `ExactBoundExpr` caches on every split. - let result = self.compute_partitioned_expr(expr)?; - Ok(cell.get_or_init(|| result).clone()) + cached_partition(&self.pruning_partition_cache, expr, |expr| { + self.compute_partitioned_expr(expr, true) + }) } - fn compute_partitioned_expr(&self, expr: &BoundExpression) -> VortexResult { + fn compute_partitioned_expr( + &self, + expr: &BoundExpression, + pruning: bool, + ) -> VortexResult { // First, we expand the root scope into the fields of the struct to ensure // that partitioning works correctly. - let expr = + let mut expr = expand_struct_root(expr.clone(), &self.expanded_root_expr, self.struct_fields())?; + if pruning && let Some(validity) = expanded_validity(&self.expanded_root_expr) { + expr = unmask_fields(expr, validity)?; + } // Partition the expression into expressions that can be evaluated // over individual coordinates. @@ -263,6 +270,42 @@ impl StructReader { } } +/// Returns the cached partition of `expr`, computing it with `compute` on a miss. +fn cached_partition( + cache: &PartitionCache, + expr: &BoundExpression, + compute: impl FnOnce(&BoundExpression) -> VortexResult, +) -> VortexResult { + let key = ExactBoundExpr(expr.clone()); + + // Look up the cell under a shared shard lock; only a miss takes the write lock, and + // only for as long as it takes to insert an empty cell. + let cell = match cache.get(&key) { + Some(entry) => Arc::clone(entry.value()), + None => Arc::clone( + cache + .entry(key) + .or_insert_with(|| Arc::new(OnceLock::new())) + .value(), + ), + }; + // All map guards are dropped here, so partitioning runs outside any shard lock. + // Concurrent misses may compute redundantly; `get_or_init` keeps a single winner. + + if let Some(value) = cell.get() { + return Ok(value.clone()); + } + // Cache the bound trees themselves: rebinding would create fresh child identity and defeat + // downstream `ExactBoundExpr` caches on every split. + let result = compute(expr)?; + Ok(cell.get_or_init(|| result).clone()) +} + +/// The validity that the expanded root of a nullable struct masks its fields with. +fn expanded_validity(expanded_root: &BoundExpression) -> Option<&BoundExpression> { + expanded_root.is::().then(|| expanded_root.child(1)) +} + fn expanded_struct_root( root_dtype: &DType, fields: &StructFields, @@ -551,7 +594,7 @@ impl LayoutReader for StructReader { mask: Mask, ) -> VortexResult { // Partition the expression into expressions that can be evaluated over individual fields - match &self.partition_expr(expr)? { + match &self.partition_pruning_expr(expr)? { Partitioned::Single(name, partition) => { let reader = self.field_reader(name)?; reader diff --git a/vortex-layout/src/layouts/struct_/unmask.rs b/vortex-layout/src/layouts/struct_/unmask.rs new file mode 100644 index 00000000000..b6fdf21a181 --- /dev/null +++ b/vortex-layout/src/layouts/struct_/unmask.rs @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Pruning predicates over the fields of a nullable struct, read past the struct's validity. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::traversal::Transformed; +use vortex_array::scalar_fn::fns::binary::Binary; +use vortex_array::scalar_fn::fns::mask::Mask; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_error::VortexResult; + +/// Reads the fields of `predicate` past the struct `validity` wherever the predicate cannot hold +/// in a row where the struct is null. +/// +/// A struct reader reads a field of a nullable struct as `mask($.field, validity)`, which is null +/// wherever the struct is. A predicate that reaches the mask only through strict functions is null +/// there too, and AND and OR above it hold only where such an operand holds. Where the struct is +/// valid, the mask returns the field itself. So the predicate over the unmasked field holds in +/// every row where the predicate over the masked field holds, and pruning with it keeps every row +/// the predicate keeps. Reading the field alone, it reaches the field's reader and its zone map. +/// +/// A predicate that can hold where the struct is null, such as `is_null($.field)`, keeps the mask. +pub(super) fn unmask_fields( + predicate: BoundExpression, + validity: &BoundExpression, +) -> VortexResult { + Ok(unmask(predicate, validity, true)?.into_inner()) +} + +/// `connective` holds while every function from the predicate root down to `expr` is AND or OR. +fn unmask( + expr: BoundExpression, + validity: &BoundExpression, + connective: bool, +) -> VortexResult> { + if expr.is::() && expr.child(1) == validity { + return Ok(Transformed::yes(expr.child(0).clone())); + } + let Some(scalar_fn) = expr.as_scalar() else { + return Ok(Transformed::no(expr)); + }; + let connective = connective + && expr + .as_opt::() + .is_some_and(|operator| matches!(operator, Operator::And | Operator::Or)); + if !connective && !scalar_fn.signature().is_strict() { + return Ok(Transformed::no(expr)); + } + + let mut changed = false; + let children = expr + .children() + .iter() + .map(|child| { + let child = unmask(child.clone(), validity, connective)?; + changed |= child.changed; + Ok(child.into_inner()) + }) + .collect::>>()?; + if !changed { + return Ok(Transformed::no(expr)); + } + Ok(Transformed::yes(expr.with_children(children)?)) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::and; + use vortex_array::expr::get_item; + use vortex_array::expr::gt; + use vortex_array::expr::is_not_null; + use vortex_array::expr::is_null; + use vortex_array::expr::lit; + use vortex_array::expr::lt; + use vortex_array::expr::mask; + use vortex_array::expr::not; + use vortex_array::expr::or; + use vortex_array::expr::root; + use vortex_error::VortexResult; + + use super::unmask_fields; + + /// `$.name` as a struct reader reads it from a nullable struct. + fn field(name: &str) -> Expression { + mask(get_item(name, root()), is_not_null(root())) + } + + /// Unmasks `predicate` over a nullable `{a: i32, b: i32}`, returning both in display form. + fn unmasked(predicate: Expression) -> VortexResult { + let dtype = DType::Struct( + StructFields::from_iter([ + ("a", DType::Primitive(PType::I32, Nullability::NonNullable)), + ("b", DType::Primitive(PType::I32, Nullability::NonNullable)), + ]), + Nullability::Nullable, + ); + let validity = is_not_null(root()).bind(&dtype)?; + Ok(unmask_fields(predicate.bind(&dtype)?, &validity)?.to_string()) + } + + #[rstest] + #[case::comparison(gt(field("a"), lit(5i32)), "($.a > 5i32)")] + #[case::not(not(gt(field("a"), lit(5i32))), "vortex.not(($.a > 5i32))")] + #[case::connectives( + or( + gt(field("a"), lit(5i32)), + and(lt(field("b"), lit(1i32)), is_not_null(root())) + ), + "(($.a > 5i32) or (($.b < 1i32) and is_not_null($)))" + )] + #[case::is_null( + is_null(field("a")), + "vortex.is_null(vortex.mask($.a, is_not_null($)))" + )] + #[case::not_and( + not(and(gt(field("a"), lit(5i32)), lt(field("b"), lit(1i32)))), + "vortex.not(((vortex.mask($.a, is_not_null($)) > 5i32) and \ + (vortex.mask($.b, is_not_null($)) < 1i32)))" + )] + fn unmasks_only_where_struct_nulls_cannot_hold( + #[case] predicate: Expression, + #[case] expected: &str, + ) -> VortexResult<()> { + assert_eq!(unmasked(predicate)?, expected); + Ok(()) + } +} diff --git a/vortex-layout/src/layouts/struct_/writer.rs b/vortex-layout/src/layouts/struct_/writer.rs index b842c121168..45aadabefe0 100644 --- a/vortex-layout/src/layouts/struct_/writer.rs +++ b/vortex-layout/src/layouts/struct_/writer.rs @@ -274,6 +274,7 @@ mod tests { use std::num::NonZeroUsize; use vortex_array::ArrayContext; + use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::validity::Validity; @@ -295,8 +296,21 @@ mod tests { use crate::test::SESSION; use crate::test::new_session; - /// Write a single-field struct with zoned fields, returning whether the field got a zone map. - fn field_has_zone_map(validity: Validity) -> VortexResult { + /// Whether `layout` is a zone map that records null counts. + /// + /// A field beneath a nullable struct records no counts, which the rows where only the struct + /// is null make wrong, so this tells the leaves below a nullable struct from the others. + fn counts_nulls(layout: &LayoutRef) -> bool { + layout.as_opt::().is_some_and(|zoned| { + zoned + .aggregate_fns() + .iter() + .any(|aggregate_fn| aggregate_fn.is::()) + }) + } + + /// Write a single-field struct with zoned fields, returning the layout of the field. + fn write_field(validity: Validity) -> VortexResult { let strategy = StructStrategy::new( Arc::new(FlatLayoutStrategy::default()), Arc::new(ZonedStrategy::new( @@ -332,7 +346,7 @@ mod tests { })?; // The validity child, when present, precedes the fields. - Ok(layout.children()?[usize::from(is_nullable)].is::()) + Ok(Arc::clone(&layout.children()?[usize::from(is_nullable)])) } /// Write `array` through a [`TableStrategy`] with zoned leaves, returning the layout. @@ -366,17 +380,19 @@ mod tests { #[test] fn non_nullable_struct_fields_get_a_zone_map() -> VortexResult<()> { - assert!(field_has_zone_map(Validity::NonNullable)?); + assert!(counts_nulls(&write_field(Validity::NonNullable)?)); Ok(()) } - /// The field holds values in rows the struct nulls out, so no aggregate over it is exact for - /// the logical column and no zone map is written. + /// The field holds values in rows the struct nulls out, which keep its bounds valid but make + /// its counts wrong, so its zone map records only bounds. #[test] - fn nullable_struct_fields_get_no_zone_map() -> VortexResult<()> { - assert!(!field_has_zone_map(Validity::Array( + fn nullable_struct_fields_get_a_zone_map_of_bounds() -> VortexResult<()> { + let field = write_field(Validity::Array( BoolArray::from_iter([false, true, true]).into_array(), - ))?); + ))?; + assert!(field.is::()); + assert!(!counts_nulls(&field)); Ok(()) } @@ -396,10 +412,10 @@ mod tests { )?; let layout = write_table(outer_nullable)?; let inner = &layout.children()?[1]; - assert!(!inner.children()?[0].is::()); + assert!(!counts_nulls(&inner.children()?[0])); - // Non-nullable outer struct: a leaf beside the nullable inner struct keeps its zone map, - // the leaf below it loses it. + // Non-nullable outer struct: a leaf beside the nullable inner struct keeps its counts, the + // leaf below it loses them. let inner_nullable = StructArray::try_from_iter([ ("sibling", buffer![1, 2, 3].into_array()), ( @@ -413,8 +429,8 @@ mod tests { ])?; let layout = write_table(inner_nullable)?; let children = layout.children()?; - assert!(children[0].is::()); - assert!(!children[1].children()?[1].is::()); + assert!(counts_nulls(&children[0])); + assert!(!counts_nulls(&children[1].children()?[1])); Ok(()) } @@ -447,10 +463,10 @@ mod tests { let layout = write_table(root)?; // Skip the root's validity child, then walk every non-nullable level to the leaf. let leaf = descend(&layout.children()?[1], DEPTH)?; - assert!(!leaf.is::()); + assert!(!counts_nulls(&leaf)); // Non-nullable levels above, a nullable struct in the middle, non-nullable levels below. - // A leaf above the nullable level keeps its zone map, the leaf below it does not. + // A leaf above the nullable level keeps its counts, the leaf below it does not. let middle = StructArray::try_from_iter_with_validity( [("below", nest(buffer![1, 2, 3].into_array(), DEPTH)?)], some_nulls(), @@ -467,10 +483,10 @@ mod tests { let layout = write_table(root)?; let holder = descend(&layout, DEPTH)?; let holder_children = holder.children()?; - assert!(holder_children[0].is::()); + assert!(counts_nulls(&holder_children[0])); // The nullable middle struct's children are `[validity, below]`. let leaf = descend(&holder_children[1].children()?[1], DEPTH)?; - assert!(!leaf.is::()); + assert!(!counts_nulls(&leaf)); Ok(()) } diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index 8331567b399..8a9ac278a57 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -15,6 +15,7 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; @@ -29,6 +30,7 @@ use vortex_error::VortexError; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::session::RuntimeSessionExt; +use vortex_scan::plan::holds_under_masking; use vortex_session::VortexSession; use vortex_utils::parallelism::get_available_parallelism; @@ -110,31 +112,32 @@ impl LayoutStrategy for ZonedStrategy { mut eof: SequencePointer, session: &VortexSession, ) -> VortexResult { - let aggregate_fns = self + let mut aggregate_fns = self .options .aggregate_fns .clone() .unwrap_or_else(|| default_zoned_aggregate_fns(stream.dtype(), session)); - // Fields of a nullable struct are written unmasked, so every aggregate over them sees - // values the logical column does not contain: counts come out wrong and min/max come out - // wider than the truth. Zone maps hold exact values only, so until the aggregates are - // computed over the masked values no zone map is written for such a field. + // Fields of a nullable struct are written unmasked: a field holds values in rows where the + // struct is null, which reads through the struct return as nulls. A bound over them, such + // as a max, still bounds the field as read, only less tightly, and so does whether no value + // is NaN. A count does not: the null count misses the rows where only the struct is null, + // so a zone it shows without nulls can still hold rows where `is_null(s.a)` is true. Such a + // field records only the statistics that hold under masking, with whether a zone holds no + // NaN in place of its NaN count, and no legacy zone map, whose statistics are fixed. // - // TODO(joe): write zone maps for fields under a nullable struct. The struct validity has - // to travel with each chunk, since repartitioning below the struct writer re-chunks the - // stream, and the aggregates then run over `chunk.mask(validity)` while the data child - // still receives the unmasked chunk. - if ctx.has_nullable_ancestor() { - return self - .child - .write_stream(ctx, segment_sink, stream, eof, session) - .await; + // TODO(joe): record every aggregate for fields under a nullable struct. The struct + // validity has to travel with each chunk, since repartitioning below the struct writer + // re-chunks the stream, and the aggregates then run over `chunk.mask(validity)` while the + // data child still receives the unmasked chunk. + let nullable_ancestor = ctx.has_nullable_ancestor(); + if nullable_ancestor { + aggregate_fns = aggregates_under_masking(&aggregate_fns, &ctx); } // Readers before `vortex.zoned` only know the legacy `vortex.stats` layout. If the write // does not permit either layout, the column gets no zone map. if !ctx.allows_layout(&Zoned.id()) { - if ctx.allows_layout(&LegacyStats.id()) { + if ctx.allows_layout(&LegacyStats.id()) && !nullable_ancestor { return self .write_legacy_stream(ctx, segment_sink, stream, eof, session) .await; @@ -145,6 +148,12 @@ impl LayoutStrategy for ZonedStrategy { .write_stream(ctx, segment_sink, stream, eof, session) .await; } + if aggregate_fns.is_empty() { + return self + .child + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + } let compute_session = session.clone(); @@ -313,6 +322,32 @@ impl ZonedStrategy { } } +/// Returns the aggregates of `aggregate_fns` that a field beneath a nullable struct records: those +/// whose statistics [hold under masking](holds_under_masking), and whether a zone holds no NaN in +/// place of a NaN count, where `ctx` allows it. +/// +/// Float bounds prune only with a proof that the zone holds no NaN, so without it no comparison of +/// a float field beneath a nullable struct would prune. +fn aggregates_under_masking( + aggregate_fns: &[AggregateFnRef], + ctx: &LayoutWriterContext, +) -> Arc<[AggregateFnRef]> { + let all_non_nan = AllNonNan.bind(EmptyOptions); + let replaces_nan_count = ctx.allows_aggregate(&all_non_nan.id()); + let mut kept = Vec::with_capacity(aggregate_fns.len()); + for aggregate_fn in aggregate_fns { + let aggregate_fn = if replaces_nan_count && aggregate_fn.is::() { + &all_non_nan + } else { + aggregate_fn + }; + if holds_under_masking(aggregate_fn) && !kept.contains(aggregate_fn) { + kept.push(aggregate_fn.clone()); + } + } + kept.into() +} + fn default_zoned_aggregate_fns(dtype: &DType, session: &VortexSession) -> Arc<[AggregateFnRef]> { let (max, min) = match dtype { DType::Utf8(_) | DType::Binary(_) => ( @@ -424,6 +459,15 @@ mod tests { ..Default::default() }, ); + write_layout_with(&strategy, ctx) + } + + /// Write three zones of primitives with `strategy` through `ctx`, returning the resulting + /// layout. + fn write_layout_with( + strategy: &ZonedStrategy, + ctx: LayoutWriterContext, + ) -> VortexResult { let (ptr, eof) = SequenceId::root().split(); let stream = ChunkedArray::from_iter([ buffer![1, 2, 3].into_array(), @@ -463,16 +507,81 @@ mod tests { Ok(()) } - /// A field of a nullable struct is written unmasked, so no aggregate over it is exact and no - /// zone map is written. + /// A field of a nullable struct holds values in rows the struct nulls out. They loosen its + /// bounds but falsify its counts, so its zone map records only the bounds. #[test] - fn a_nullable_ancestor_writes_no_zone_map() -> VortexResult<()> { - let layout = - write_layout(LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor())?; - assert!(!layout.is::()); + fn a_nullable_ancestor_records_only_bounds() -> VortexResult<()> { + let written = + write_zones(LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor())?; + assert_eq!(written, [Max.id().to_string(), Min.id().to_string()]); Ok(()) } + /// A legacy zone map records a fixed set of statistics, counts among them, so a field of a + /// nullable struct gets none. + #[test] + fn a_nullable_ancestor_writes_no_legacy_zone_map() -> VortexResult<()> { + let ctx = LayoutWriterContext::new(ArrayContext::empty()) + .with_allowed_layouts(HashSet::from_iter([LegacyStats.id()])); + assert!(write_layout(ctx.clone())?.is::()); + assert!(!write_layout(ctx.with_nullable_ancestor())?.is::()); + Ok(()) + } + + /// Explicitly requested counts are dropped under a nullable ancestor like the default ones, + /// and a field left with no bound gets no zone map. + #[test] + fn a_nullable_ancestor_without_bounds_writes_no_zone_map() -> VortexResult<()> { + let strategy = ZonedStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + FlatLayoutStrategy::default(), + ZonedLayoutOptions { + block_size: NonZeroUsize::new(3).vortex_expect("non zero"), + aggregate_fns: Some([NullCount.bind(EmptyOptions)].into()), + ..Default::default() + }, + ); + let ctx = LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor(); + assert!(!write_layout_with(&strategy, ctx)?.is::()); + Ok(()) + } + + /// Beneath a nullable struct, a float field records whether each zone holds no NaN in place + /// of its NaN count, which float bounds need to prune, where the context permits it. An + /// integer field holds no NaN, so it records only its bounds. + #[rstest] + #[case::float(PType::F64, true, true)] + #[case::float_not_permitted(PType::F64, false, false)] + #[case::integer(PType::I32, true, false)] + fn a_nullable_ancestor_records_whether_floats_hold_no_nan( + #[case] ptype: PType, + #[case] permitted: bool, + #[case] records: bool, + ) { + let dtype = DType::from(ptype); + let mut ctx = LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor(); + if !permitted { + ctx = ctx.with_allowed_aggregates(HashSet::from_iter([ + Min.id(), + Max.id(), + NanCount.id(), + NullCount.id(), + ])); + } + let aggregate_fns = + aggregates_under_masking(&default_zoned_aggregate_fns(&dtype, &SESSION), &ctx); + let recorded = AggregateStatsAccumulator::new(&dtype, &aggregate_fns) + .aggregate_fns() + .iter() + .map(|aggregate_fn| aggregate_fn.id().to_string()) + .collect::>(); + let mut expected = vec![Max.id().to_string(), Min.id().to_string()]; + if records { + expected.push(AllNonNan.id().to_string()); + } + assert_eq!(recorded, expected); + } + #[test] fn a_permitted_set_covering_the_defaults_writes_them() -> VortexResult<()> { let ctx = LayoutWriterContext::new(ArrayContext::empty()).with_allowed_aggregates( diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests.rs index 5f3e3c71068..1ddabcb5a2d 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests.rs @@ -29,16 +29,22 @@ use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtVTable; use vortex_array::expr::Expression; use vortex_array::expr::and; +use vortex_array::expr::cast; +use vortex_array::expr::checked_add; use vortex_array::expr::eq; use vortex_array::expr::ext_storage; use vortex_array::expr::get_item; use vortex_array::expr::gt; +use vortex_array::expr::is_not_null; use vortex_array::expr::is_null; use vortex_array::expr::lit; use vortex_array::expr::lt; +use vortex_array::expr::not; +use vortex_array::expr::or; use vortex_array::expr::pack; use vortex_array::expr::root; use vortex_array::validity::Validity; @@ -67,6 +73,8 @@ use crate::LayoutRef; use crate::LayoutStrategy; use crate::layouts::chunked::writer::ChunkedLayoutStrategy; use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::repartition::RepartitionStrategy; +use crate::layouts::repartition::RepartitionWriterOptions; use crate::layouts::row_idx::row_idx; use crate::layouts::table::TableStrategy; use crate::layouts::zoned::writer::ZonedLayoutOptions; @@ -160,6 +168,131 @@ fn points_chunk(start: usize, extension: bool, nullability: Nullability) -> Vort Ok(StructArray::from_fields(&[("id", ids.into_array()), ("point", points)])?.into_array()) } +/// A chunk of `CHUNK_ROWS` rows starting at row `start`, shaped like a protobuf message column: +/// `{id, msg: {x, inner: {y}?, list}?}`, where `msg` is null at every fifth row and `inner` at +/// every seventh. +/// +/// `x` is the row, `y` ten times the row and `list` holds the row twice. The fields keep their +/// values in rows where a struct above them is null. +fn message_chunk(start: usize) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let rows = start..start + CHUNK_ROWS; + let ids = Buffer::from_iter( + rows.clone() + .map(|row| i32::try_from(row).unwrap_or(i32::MAX)), + ); + let tens = Buffer::from_iter( + rows.clone() + .map(|row| i64::try_from(10 * row).unwrap_or(i64::MAX)), + ); + let inner = StructArray::try_new( + FieldNames::from(["y"]), + [tens.into_array()], + CHUNK_ROWS, + Validity::from_iter(rows.clone().map(|row| row % 7 != 0)), + )?; + let elements = Buffer::from_iter( + rows.clone() + .flat_map(|row| [row, row]) + .map(|row| i64::try_from(row).unwrap_or(i64::MAX)), + ); + let offsets = Buffer::from_iter((0..=CHUNK_ROWS).map(|i| u32::try_from(2 * i).unwrap_or(0))); + let list = ListArray::try_new( + elements.into_array(), + offsets.into_array(), + Validity::NonNullable, + &mut ctx, + )?; + let msg = StructArray::try_new( + FieldNames::from(["x", "inner", "list"]), + [ + ids.clone().into_array(), + inner.into_array(), + list.into_array(), + ], + CHUNK_ROWS, + Validity::from_iter(rows.map(|row| row % 5 != 0)), + )?; + Ok( + StructArray::from_fields(&[("id", ids.into_array()), ("msg", msg.into_array())])? + .into_array(), + ) +} + +/// A chunk of `CHUNK_ROWS` rows starting at row `start`: `{id, s: {a}?}` with a non-nullable `a` +/// that holds values in rows where `s` is null, like a proto3 scalar in an absent message. +/// +/// Chunk `k` is the `k`-th zone of a zoned layout. `a` is the row wherever `s` is valid. `s` is null +/// in all of zone 1 and in the odd rows of zone 2, where `a` holds 1,000,000 plus the row: values +/// that no read through `s` returns but that the zone map of `a` sees. +fn hidden_values_chunk(start: usize) -> VortexResult { + let rows = start..start + CHUNK_ROWS; + let valid = |row: usize| match row / CHUNK_ROWS { + 1 => false, + 2 => row.is_multiple_of(2), + _ => true, + }; + let ids = Buffer::from_iter( + rows.clone() + .map(|row| i32::try_from(row).unwrap_or(i32::MAX)), + ); + let values = Buffer::from_iter(rows.clone().map(|row| { + let value = if valid(row) { row } else { 1_000_000 + row }; + i64::try_from(value).unwrap_or(i64::MAX) + })); + let s = StructArray::try_new( + FieldNames::from(["a"]), + [values.into_array()], + CHUNK_ROWS, + Validity::from_iter(rows.map(valid)), + )?; + Ok(StructArray::from_fields(&[("id", ids.into_array()), ("s", s.into_array())])?.into_array()) +} + +/// A table chunk of `id` and a nullable struct `s` of `{small: i64, x: i64, y: i64, f: f64}`, which +/// is null where it is in [`hidden_values_chunk`]. +/// +/// Where `s` is valid, `small` and `x` hold `row % 100`, `y` holds 50 and `f` holds `row + 0.5`. +/// Where it is null, they hold values that no read through `s` returns: `small` holds `i64::MAX`, +/// which is outside the range of `i8` and overflows when added to, `x` is below every `y`, and `f` +/// is above every visible `f`. +fn masked_fields_chunk(start: usize) -> VortexResult { + let rows = start..start + CHUNK_ROWS; + let valid = |row: usize| match row / CHUNK_ROWS { + 1 => false, + 2 => row.is_multiple_of(2), + _ => true, + }; + let field = |visible: fn(i64) -> i64, hidden: fn(i64) -> i64| { + Buffer::from_iter(rows.clone().map(|row| { + let value = i64::try_from(row).unwrap_or(i64::MAX); + if valid(row) { + visible(value) + } else { + hidden(value) + } + })) + .into_array() + }; + let f = Buffer::from_iter(rows.clone().map(|row| { + let value = f64::from(u32::try_from(row).unwrap_or(u32::MAX)); + if valid(row) { value + 0.5 } else { 1e9 + value } + })); + let s = StructArray::try_new( + FieldNames::from(["small", "x", "y", "f"]), + [ + field(|row| row % 100, |_| i64::MAX), + field(|row| row % 100, |_| -1_000_000), + field(|_| 50, |_| 1_000_000), + f.into_array(), + ], + CHUNK_ROWS, + Validity::from_iter(rows.clone().map(valid)), + )?; + let ids = Buffer::from_iter(rows.map(|row| i32::try_from(row).unwrap_or(i32::MAX))); + Ok(StructArray::from_fields(&[("id", ids.into_array()), ("s", s.into_array())])?.into_array()) +} + /// Writes `CHUNKS` table chunks with `strategy`. async fn write( session: &VortexSession, @@ -203,6 +336,9 @@ fn table_strategy() -> TableStrategy { } /// Every column is shredded into chunked leaves with zone statistics. +/// +/// Leaves are repartitioned into zones of `CHUNK_ROWS` rows first, as the file writer does, since a +/// list layout writes its elements in chunks as long as the lists they hold. fn zoned_table_strategy() -> TableStrategy { let zoned = ZonedStrategy::new( ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), @@ -212,7 +348,16 @@ fn zoned_table_strategy() -> TableStrategy { ..Default::default() }, ); - TableStrategy::new(chunked_flat(), Arc::new(zoned)) + let repartition = RepartitionStrategy::new( + zoned, + RepartitionWriterOptions { + block_size_minimum: 0, + block_len_multiple: CHUNK_ROWS, + block_size_target: None, + canonicalize: false, + }, + ); + TableStrategy::new(chunked_flat(), Arc::new(repartition)) } fn table() -> Arc { @@ -587,36 +732,210 @@ async fn extension_layout_matches_v1( #[case] projection: Expression, #[case] filter: Option, ) -> VortexResult<()> { - let session = new_session().with_tokio(); let strategy = if zoned { zoned_table_strategy() } else { table_strategy() } .with_extension_layout([TestPoint.id()]); - let (segments, layout) = write_chunks(&session, &strategy, point_chunk, CHUNKS).await?; + assert_matches_v1_and_input(&strategy, point_chunk, &projection, filter.as_ref()).await +} + +fn msg(field: &str) -> Expression { + get_item(field, get_item("msg", root())) +} + +/// A nullable struct with a list field, written with the list layout, scans on the planner-driven +/// executor whenever the scan reads no list. Its fields are null wherever a struct above them is. +#[rstest] +#[case::sibling_of_list(msg("x"), None)] +#[case::nested_nullable(get_item("y", msg("inner")), None)] +#[case::struct_validity(is_null(get_item("msg", root())), None)] +#[case::pack( + pack( + [("id", get_item("id", root())), ("x", msg("x"))], + Nullability::NonNullable, + ), + None, +)] +#[case::filter_field(get_item("id", root()), Some(gt(msg("x"), lit(2500i32))))] +#[case::filter_nested(msg("x"), Some(lt(get_item("y", msg("inner")), lit(20_500i64))))] +#[case::filter_nested_null(msg("x"), Some(is_null(get_item("y", msg("inner")))))] +#[tokio::test] +async fn nullable_struct_beside_a_list_matches_v1( + #[values(false, true)] zoned: bool, + #[case] projection: Expression, + #[case] filter: Option, +) -> VortexResult<()> { + let strategy = if zoned { + zoned_table_strategy() + } else { + table_strategy() + } + .with_list_layout(); + assert_matches_v1_and_input(&strategy, message_chunk, &projection, filter.as_ref()).await +} + +fn s_a() -> Expression { + get_item("a", get_item("s", root())) +} + +/// Zone maps beneath a nullable struct prune filters on its fields without losing rows. +/// +/// The zones of `s.a` see the values it holds where `s` is null, which no read through `s` +/// returns. Bounds over them are only looser, so `s.a > 2500` reads zone 1 and finds no row +/// there. A null count over them would be 0 in zones 1 and 2, where `is_null(s.a)` holds, so the +/// zone map records none (#9205). +#[rstest] +#[case::gt(gt(s_a(), lit(2500i64)))] +#[case::lt(lt(s_a(), lit(100i64)))] +#[case::hidden_value(eq(s_a(), lit(1_001_500i64)))] +#[case::not(not(gt(s_a(), lit(500i64))))] +#[case::is_null(is_null(s_a()))] +#[case::is_not_null(is_not_null(s_a()))] +#[case::is_null_or_lt(or(is_null(s_a()), lt(s_a(), lit(10i64))))] +#[tokio::test] +async fn pruning_beneath_a_nullable_struct_keeps_every_row( + #[case] filter: Expression, +) -> VortexResult<()> { + assert_matches_v1_and_input( + &zoned_table_strategy(), + hidden_values_chunk, + &get_item("id", root()), + Some(&filter), + ) + .await +} + +fn s_field(name: &str) -> Expression { + get_item(name, get_item("s", root())) +} + +/// Pruning beneath a nullable struct keeps every row, also where the zone map statistics of a +/// field feed a function that fails on the values the struct hides, where a filter compares two +/// fields of the struct, and for a float field, whose bounds prune only with a proof that the zone +/// holds no NaN. +#[rstest] +#[case::cast(gt( + cast(s_field("small"), DType::Primitive(PType::I8, Nullability::Nullable)), + lit(5i8) +))] +#[case::cast_lt(lt( + cast(s_field("small"), DType::Primitive(PType::I8, Nullability::Nullable)), + lit(5i8) +))] +#[case::overflow(gt(checked_add(s_field("small"), lit(1i64)), lit(95i64)))] +#[case::two_fields(gt(s_field("x"), s_field("y")))] +#[case::float_gt(gt(s_field("f"), lit(1500.0f64)))] +#[case::float_lt(lt(s_field("f"), lit(100.0f64)))] +#[case::float_not(not(gt(s_field("f"), lit(500.0f64))))] +#[tokio::test] +async fn pruning_beneath_a_nullable_struct_keeps_rows_of_any_filter( + #[case] filter: Expression, +) -> VortexResult<()> { + assert_matches_v1_and_input( + &zoned_table_strategy(), + masked_fields_chunk, + &get_item("id", root()), + Some(&filter), + ) + .await +} + +/// A filter on a field beneath a nullable struct reads only the zones its bounds keep. +/// +/// A filter the bounds of the field cannot prune reads its zone map and, in each of the four +/// zones, the field, the validity of `s` and `id`: 13 segments. The pruned filter holds only in +/// zone 0, so it reads the three there alone. The classic scan still reads `id` in every zone. A +/// float field prunes too: its zone map records whether each zone holds no NaN, which the bounds +/// of a float need. +#[rstest] +#[case::v1(false, hidden_values_chunk, s_a(), lit(100i64), lit(10_000_000i64), 7)] +#[case::v2(true, hidden_values_chunk, s_a(), lit(100i64), lit(10_000_000i64), 4)] +#[case::v1_float( + false, + masked_fields_chunk, + s_field("f"), + lit(100.0f64), + lit(1e12f64), + 7 +)] +#[case::v2_float( + true, + masked_fields_chunk, + s_field("f"), + lit(100.0f64), + lit(1e12f64), + 4 +)] +#[tokio::test] +async fn pruning_beneath_a_nullable_struct_skips_zones( + #[case] v2: bool, + #[case] chunk: fn(usize) -> VortexResult, + #[case] field: Expression, + #[case] pruned: Expression, + #[case] unpruned: Expression, + #[case] pruned_requests: usize, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = write_chunks(&session, &zoned_table_strategy(), chunk, CHUNKS).await?; + let mut requests = Vec::new(); + for filter in [lt(field.clone(), pruned), lt(field, unpruned)] { + let source = Arc::new(CountingSegmentSource::new(Arc::clone(&segments))); + let projection = get_item("id", root()).bind(layout.dtype())?; + let filter = filter.bind(layout.dtype())?; + let dtype = projection.dtype().clone(); + if v2 { + let segments: Arc = Arc::::clone(&source); + let scan = builder(&session, &segments, &layout)? + .with_projection(projection) + .with_some_filter(Some(filter)); + collect_scan(dtype, scan).await?; + } else { + let reader = layout.new_reader( + "".into(), + Arc::::clone(&source), + &session, + &Default::default(), + )?; + let scan = V1ScanBuilder::new(session.clone(), reader) + .with_projection(projection) + .with_filter(filter); + collect(dtype, scan.into_stream()?).await?; + } + requests.push(source.requests()); + } + assert_eq!(requests, [pruned_requests, 13]); + Ok(()) +} + +/// Writes `CHUNKS` chunks made by `chunk` with `strategy`, then scans them with `projection` and +/// `filter` on both executors. Checks both return what the expressions return over the input. +async fn assert_matches_v1_and_input( + strategy: &dyn LayoutStrategy, + chunk: fn(usize) -> VortexResult, + projection: &Expression, + filter: Option<&Expression>, +) -> VortexResult<()> { + let session = new_session().with_tokio(); + let (segments, layout) = write_chunks(&session, strategy, chunk, CHUNKS).await?; let dtype = layout.dtype().clone(); let make = || -> VortexResult { Ok(builder(&session, &segments, &layout)? .with_projection(projection.bind(&dtype)?) - .with_some_filter( - filter - .as_ref() - .map(|filter| filter.bind(&dtype)) - .transpose()?, - )) + .with_some_filter(filter.map(|filter| filter.bind(&dtype)).transpose()?)) }; assert_same_as_v1(&session, make).await?; let input = ChunkedArray::try_new( (0..CHUNKS) - .map(|chunk| point_chunk(chunk * CHUNK_ROWS)) + .map(|index| chunk(index * CHUNK_ROWS)) .collect::>>()?, layout.dtype().clone(), )? .into_array(); let mut ctx = session.create_execution_ctx(); - let input = match &filter { + let input = match filter { Some(filter) => { let mask = input .clone() @@ -627,7 +946,7 @@ async fn extension_layout_matches_v1( } None => input, }; - let expected = input.apply(&projection)?; + let expected = input.apply(projection)?; let scan = make()?; let actual = collect_scan(scan.dtype().clone(), scan).await?; assert_arrays_eq!(actual, expected, &mut ctx); @@ -682,18 +1001,15 @@ async fn extension_filter_prunes_like_struct(#[values(false, true)] v2: bool) -> } /// Projecting one storage field of an extension column reads the segments of that field, plus -/// those of the storage validity when the extension is nullable. -/// -/// The planner does not push an expression through the assembly of a nullable struct yet, so with -/// a nullable extension it reads every storage column. A plain nullable struct column reads the -/// same segments, so the extension layout adds no reads of its own. +/// those of the storage validity when the extension is nullable. A plain nullable struct column +/// reads the same segments, so the extension layout adds no reads of its own. #[rstest] #[case::v1(false, non_nullable_point_chunk, point_storage("a"), 1)] #[case::v1_nullable(false, point_chunk, point_storage("a"), 2)] #[case::v1_nullable_struct(false, plain_point_chunk, get_item("a", get_item("point", root())), 2)] #[case::v2(true, non_nullable_point_chunk, point_storage("a"), 1)] -#[case::v2_nullable(true, point_chunk, point_storage("a"), 3)] -#[case::v2_nullable_struct(true, plain_point_chunk, get_item("a", get_item("point", root())), 3)] +#[case::v2_nullable(true, point_chunk, point_storage("a"), 2)] +#[case::v2_nullable_struct(true, plain_point_chunk, get_item("a", get_item("point", root())), 2)] #[tokio::test] async fn extension_field_projection_reads( #[case] v2: bool, diff --git a/vortex-layout/src/strategy.rs b/vortex-layout/src/strategy.rs index 3e5bcedd5ec..e7d2b3153b4 100644 --- a/vortex-layout/src/strategy.rs +++ b/vortex-layout/src/strategy.rs @@ -135,8 +135,10 @@ impl LayoutWriterContext { /// /// Container writers store their children unmasked: a field holds a value even in rows where /// the containing struct is null, and the struct's validity is written separately. Statistics - /// computed over such a child therefore see values the logical column does not contain, so - /// writers that record statistics must omit them rather than record inexact values. + /// computed over such a child therefore see values the logical column does not contain. + /// Writers that record statistics must record only those that stay correct for the logical + /// column, such as bounds on its values, which these values only loosen. Counts do not stay + /// correct: a null count misses the rows where only the container is null. pub fn with_nullable_ancestor(mut self) -> Self { self.nullable_ancestor = true; self diff --git a/vortex-scan/src/plan/builtins/pack/mask.rs b/vortex-scan/src/plan/builtins/pack/mask.rs new file mode 100644 index 00000000000..21042334e8a --- /dev/null +++ b/vortex-scan/src/plan/builtins/pack/mask.rs @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Moving expressions below the validity mask of a nullable struct's fields. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::bound; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::NodeRewriter; +use vortex_array::expr::traversal::Transformed; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_array::scalar_fn::fns::mask::Mask; +use vortex_array::scalar_fn::fns::stat::StatFn; +use vortex_error::VortexResult; + +use crate::plan::builtins::zoned::holds_under_masking; + +/// Moves field reads and statistics of `expr` below the masks over their input. +/// +/// The partition rules read a field of a nullable struct as `mask(field, validity)`. An expression +/// over that mask stays above the struct, so this moves what it can below the mask, where the next +/// partitioning pushes it into the field's plan: +/// +/// - `mask(s, v).name` becomes `mask(s.name, v)`: a field of a masked struct is null wherever the +/// struct is. Reading a nested field then reads only that field. +/// - `stat(mask(x, v), agg)` becomes `stat(x, agg)` when `agg` [holds under +/// masking](holds_under_masking), such as a bound, and every function above the statistic is +/// infallible. Masking only replaces values with nulls, so the statistic of `x` still holds for +/// `mask(x, v)`, if less tightly, and a pruning proof reads it only as such. The statistic of `x` +/// also covers the values that `v` hides, which a fallible function, such as a cast to a +/// narrower type, can fail on, although the rows never reach it. +/// - Any other statistic of a masked input becomes a null, which a pruning proof reads as a +/// statistic the zones do not store. A count over `x`, for one, misses the nulls `v` adds. +pub(super) fn lift_masks(expr: BoundExpression) -> VortexResult { + Ok(expr.rewrite(&mut MaskLifter::default())?.into_inner()) +} + +#[derive(Default)] +struct MaskLifter { + /// For each node on the path from the root to the current node, whether it is a fallible + /// function. + fallible: Vec, +} + +impl NodeRewriter for MaskLifter { + type NodeTy = BoundExpression; + + fn visit_down(&mut self, node: BoundExpression) -> VortexResult> { + let fallible = node + .as_scalar() + .is_some_and(|scalar_fn| !scalar_fn.signature().is_infallible()); + self.fallible.push(fallible); + Ok(Transformed::no(node)) + } + + fn visit_up(&mut self, node: BoundExpression) -> VortexResult> { + self.fallible.pop(); + let Some(masked) = node.children().first().filter(|child| child.is::()) else { + return Ok(Transformed::no(node)); + }; + let (input, validity) = (masked.child(0).clone(), masked.child(1).clone()); + + if let Some(name) = node.as_opt::() { + let field = bound::get_item(name.clone(), input); + return Ok(Transformed::yes(bound::mask(field, validity))); + } + + let Some(options) = node.as_opt::() else { + return Ok(Transformed::no(node)); + }; + if holds_under_masking(options.aggregate_fn()) && !self.fallible.contains(&true) { + let unmasked = node.clone().with_children([input])?; + // A statistic's dtype is nullable, so the unmasked input rarely changes it. Should it, + // the expressions above it would change type, so the statistic is left unknown. + if unmasked.dtype() == node.dtype() { + return Ok(Transformed::yes(unmasked)); + } + } + let unknown = Scalar::null(node.dtype().clone()); + Ok(Transformed::yes(bound::lit(unknown))) + } +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::aggregate_fn::AggregateFnRef; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; + use vortex_array::aggregate_fn::fns::max::Max; + use vortex_array::aggregate_fn::fns::nan_count::NanCount; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::and; + use vortex_array::expr::cast; + use vortex_array::expr::eq; + use vortex_array::expr::get_item; + use vortex_array::expr::is_not_null; + use vortex_array::expr::lit; + use vortex_array::expr::lt_eq; + use vortex_array::expr::mask; + use vortex_array::expr::root; + use vortex_array::scalar_fn::ScalarFnVTableExt; + use vortex_array::scalar_fn::fns::stat::StatFn; + use vortex_array::scalar_fn::fns::stat::StatOptions; + use vortex_error::VortexResult; + + use super::lift_masks; + + fn max() -> AggregateFnRef { + Max.bind(NumericalAggregateOpts::skip_nans()) + } + + /// The statistic `aggregate_fn` of the field `f` of a nullable struct, read through the + /// struct's validity. + fn masked_stat(aggregate_fn: AggregateFnRef) -> Expression { + StatFn.new_expr( + StatOptions::new(aggregate_fn), + [mask(get_item("f", root()), is_not_null(root()))], + ) + } + + /// Lifts the masks of `expr` over a nullable `{f: f64}`, returning the result in display form. + fn lifted(expr: Expression) -> VortexResult { + let dtype = DType::Struct( + StructFields::from_iter([( + "f", + DType::Primitive(PType::F64, Nullability::NonNullable), + )]), + Nullability::Nullable, + ); + Ok(lift_masks(expr.bind(&dtype)?)?.to_string()) + } + + /// A statistic that holds under masking moves below the mask where only infallible functions + /// read it. A fallible function above it, such as a cast to a narrower type, could fail on the + /// values that the mask hides, and a count does not hold under masking, so both see a null. + #[rstest] + #[case::bound( + lt_eq(masked_stat(max()), lit(5.0f64)), + "(stat($.f, vortex.max()) <= 5f64)" + )] + #[case::no_nan( + and( + masked_stat(AllNonNan.bind(EmptyOptions)), + lt_eq(masked_stat(max()), lit(5.0f64)) + ), + "(stat($.f, vortex.all_non_nan()) and (stat($.f, vortex.max()) <= 5f64))" + )] + #[case::fallible( + lt_eq( + cast(masked_stat(max()), DType::Primitive(PType::I8, Nullability::Nullable)), + lit(5i8) + ), + "(cast(null as i8?) <= 5i8)" + )] + #[case::count(eq(masked_stat(NanCount.bind(EmptyOptions)), lit(0u64)), "(null = 0u64)")] + fn lifts_statistics_that_hold_where_they_are_read( + #[case] expr: Expression, + #[case] expected: &str, + ) -> VortexResult<()> { + assert_eq!(lifted(expr)?, expected); + Ok(()) + } +} diff --git a/vortex-scan/src/plan/builtins/pack/mod.rs b/vortex-scan/src/plan/builtins/pack/mod.rs index 11a921e6cb4..8771c178b9a 100644 --- a/vortex-scan/src/plan/builtins/pack/mod.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors pub(crate) mod execute; +mod mask; use std::borrow::Cow; use std::iter; @@ -31,6 +32,7 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; +use self::mask::lift_masks; use crate::execution::operators::OnceSource; use crate::execution::operators::PackSource; use crate::execution::operators::WrapStage; @@ -307,18 +309,16 @@ fn validate_validity_child(expected_row_count: u64, child: &PlanRef) -> VortexRe } impl PackPlan { - /// Rebuilds this plan with only `fields`, which must be a subset of the current fields. + /// Builds a non-nullable struct of `fields`, each a slot of this plan or an expression over + /// one. /// - /// Pruning is only sound for a non-nullable struct: dropping a field of a nullable struct - /// would drop the validity child that the remaining fields depend on. + /// The result drops the validity of a nullable struct. An expression over a nullable struct + /// partitions its validity into a field of its own wherever the struct's nulls are observable, + /// so a pruned struct carries the validity exactly when the expression reads it. pub(crate) fn with_pruned_fields( &self, fields: Vec<(FieldName, PlanRef)>, ) -> VortexResult { - vortex_ensure!( - !self.dtype().is_nullable(), - "Cannot prune fields from a nullable Pack" - ); let struct_fields = StructFields::from_iter( fields .iter() @@ -336,6 +336,11 @@ impl PackPlan { } /// Pushes an expression into the referenced fields of a [`Pack`], pruning the rest. +/// +/// Over a nullable struct, the partition rules read a field as `mask(field, validity)`, so the +/// pruned struct reads the validity alongside the fields and the expression above it still sees +/// a field as null wherever the struct is null. Nested field reads and statistics above such a +/// mask move below it, so a later rewrite pushes them into the field's plan. #[derive(Debug)] pub(crate) struct ExpressionPackRule; @@ -349,10 +354,6 @@ impl PlanParentReduceRule for ExpressionPackRule { _child_idx: usize, session: &VortexSession, ) -> VortexResult> { - if child.dtype().is_nullable() { - return Ok(None); - } - let expression = parent.expression(); let fields = child.fields(); if fields.nfields() == 0 { @@ -373,8 +374,15 @@ impl PlanParentReduceRule for ExpressionPackRule { combiner, partitions, } = partitioned; + let combiner = if child.dtype().is_nullable() { + lift_masks(combiner)? + } else { + combiner + }; - let mut fields_changed = partitions.len() != fields.nfields(); + // The combiner reads a non-nullable struct, which a nullable child never is. + let mut fields_changed = + child.dtype().is_nullable() || partitions.len() != fields.nfields(); let mut pruned_fields = Vec::with_capacity(partitions.len()); for (position, partition) in partitions.into_iter().enumerate() { fields_changed |= partition.slot != Pack::FIELDS_OFFSET + position; diff --git a/vortex-scan/src/plan/builtins/zoned/mod.rs b/vortex-scan/src/plan/builtins/zoned/mod.rs index debce724ae4..770afca26a0 100644 --- a/vortex-scan/src/plan/builtins/zoned/mod.rs +++ b/vortex-scan/src/plan/builtins/zoned/mod.rs @@ -12,6 +12,12 @@ use vortex_array::EmptyMetadata; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; +use vortex_array::aggregate_fn::fns::all_null::AllNull; +use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; +use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::StructArray; @@ -478,6 +484,24 @@ pub fn is_zone_pruning(eval: &Plan) -> VortexResult { Ok(eval.dtype().is_boolean() && contains_stat && !contains_root) } +/// Whether a statistic of `aggregate_fn` over a column also holds, if less tightly, for the column +/// with some of its values replaced by nulls. +/// +/// Min and max bound the non-null values, which such a replacement only removes, and so does +/// whether no value is NaN, or whether every value is null. Pruning proofs read these statistics +/// only in that direction: a zone whose maximum is at most 5 holds no value above 5, and a looser +/// maximum proves less. The fields of a nullable struct hold values in rows where the struct is +/// null, so these statistics of a field also hold for the field as read through the struct. +/// Counts do not: a field's null count misses the rows where only the struct is null. +pub fn holds_under_masking(aggregate_fn: &AggregateFnRef) -> bool { + aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() +} + /// Replaces a zoned data plan by its data: a scan reads the data through it and never its zone /// table. Pruning plans are derived from the filter over the lowered plan before this runs, so /// an optimized plan carries a zone table only where a pruning plan reads it. diff --git a/vortex-scan/src/plan/mod.rs b/vortex-scan/src/plan/mod.rs index c65eab1a482..f7da9063515 100644 --- a/vortex-scan/src/plan/mod.rs +++ b/vortex-scan/src/plan/mod.rs @@ -52,6 +52,7 @@ pub use builtins::Zoned; pub use builtins::ZonedData; pub use builtins::ZonedPlan; pub(crate) use builtins::plan_row_idx_expression; +pub use builtins::zoned::holds_under_masking; #[doc(hidden)] pub use builtins::zoned::is_zone_pruning; pub use display::PlanIndentedFormatter; diff --git a/vortex-scan/src/plan/tests.rs b/vortex-scan/src/plan/tests.rs index 4a161beb0b0..35d7973f219 100644 --- a/vortex-scan/src/plan/tests.rs +++ b/vortex-scan/src/plan/tests.rs @@ -991,27 +991,129 @@ fn non_strict_expression_pushes_into_dictionary_without_null_codes() -> VortexRe Ok(()) } -#[test] -fn nullable_struct_keeps_expression_above_parent_validity() -> VortexResult<()> { +/// A nullable struct `{a: i32, b: i32}?` over three rows, its validity in segment `segment` and +/// its fields in the two segments after it. +fn nullable_struct(segment: u32) -> PlanRef { let field_dtype = primitive(PType::I32, Nullability::NonNullable); - let layout = struct_plan( + struct_plan( 3, DType::Struct( - StructFields::from_iter([("a", field_dtype.clone())]), + StructFields::from_iter([("a", field_dtype.clone()), ("b", field_dtype.clone())]), Nullability::Nullable, ), + vec![ + flat(3, DType::Bool(Nullability::NonNullable), segment), + flat(3, field_dtype.clone(), segment + 1), + flat(3, field_dtype, segment + 2), + ], + ) +} + +/// An expression over one field of a nullable struct reads that field and the struct validity, +/// and stays above the validity, which nulls the field where the struct is null. +#[test] +fn nullable_struct_field_reads_the_field_and_validity() -> VortexResult<()> { + let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), nullable_struct(0))?.into_plan(); + + let optimized = optimize(plan, &SESSION)?; + insta::assert_snapshot!(optimized.display_tree(), @" + root: vortex.plan.eval(bool?, rows=3) expr=(vortex.mask($.0, $.1) > 5i32) + child: vortex.plan.pack({0=i32, 1=bool}, rows=3) + 0: vortex.plan.filter(i32, rows=3) + child: vortex.test.source(i32, rows=3) + 1: vortex.plan.filter(bool, rows=3) + child: vortex.test.source(bool, rows=3) + "); + Ok(()) +} + +/// A field nested in nullable structs reads only that field and the validity of each struct +/// around it. +#[test] +fn nested_nullable_struct_field_reads_the_field_and_validities() -> VortexResult<()> { + let outer_dtype = DType::Struct( + StructFields::from_iter([ + ("s", nullable_struct(1).dtype().clone()), + ("c", primitive(PType::I32, Nullability::NonNullable)), + ]), + Nullability::Nullable, + ); + let outer = struct_plan( + 3, + outer_dtype, vec![ flat(3, DType::Bool(Nullability::NonNullable), 0), - flat(3, field_dtype, 1), + nullable_struct(1), + flat(3, primitive(PType::I32, Nullability::NonNullable), 4), ], ); - let plan = make_eval(gt(get_item("a", root()), lit(5_i32)), layout)?.into_plan(); + let plan = make_eval(get_item("b", get_item("s", root())), outer)?.into_plan(); let optimized = optimize(plan, &SESSION)?; - let eval = optimized - .as_opt::() - .ok_or_else(|| vortex_err!("Nullable struct expression unexpectedly pushed down"))?; - assert!(eval.child_plan()?.is::()); + insta::assert_snapshot!(optimized.display_tree(), @" + root: vortex.plan.eval(i32?, rows=3) expr=vortex.mask($.0, $.1) + child: vortex.plan.pack({0=i32?, 1=bool}, rows=3) + 0: vortex.plan.eval(i32?, rows=3) expr=vortex.mask($.0, $.1) + child: vortex.plan.pack({0=i32, 1=bool}, rows=3) + 0: vortex.plan.filter(i32, rows=3) + child: vortex.test.source(i32, rows=3) + 1: vortex.plan.filter(bool, rows=3) + child: vortex.test.source(bool, rows=3) + 1: vortex.plan.filter(bool, rows=3) + child: vortex.test.source(bool, rows=3) + "); + let reoptimized = optimize(optimized.clone(), &SESSION)?; + assert!(PlanRef::ptr_eq(&optimized, &reoptimized)); + Ok(()) +} + +/// A falsifier over a field of a nullable struct reaches the zones of the field through its +/// bounds, which also bound the field with the struct's nulls in it. A null count of the field +/// would miss the struct's nulls, so a proof needing one has nothing to prune with and reads no +/// data. +#[test] +fn pruning_reaches_zones_beneath_a_nullable_struct() -> VortexResult<()> { + let value_dtype = primitive(PType::I32, Nullability::NonNullable); + let (max, zones_dtype) = max_zones_dtype(&value_dtype)?; + let zone_len = NonZeroUsize::new(3).ok_or_else(|| vortex_err!("zone length is zero"))?; + let struct_dtype = DType::Struct( + StructFields::from_iter([("a", value_dtype.clone())]), + Nullability::Nullable, + ); + let layout = struct_plan( + 5, + struct_dtype.clone(), + vec![ + flat(5, DType::Bool(Nullability::NonNullable), 0), + zoned_plan( + flat(5, value_dtype, 1), + flat(2, zones_dtype, 2), + zone_len, + vec![max].into(), + ), + ], + ); + let session = VortexSession::empty(); + let prune = |filter: Expression| -> VortexResult { + let falsifier = filter + .bind(&struct_dtype)? + .falsify(&session)? + .ok_or_else(|| vortex_err!("filter has no falsifier"))?; + optimize( + EvalPlan::try_new(falsifier, layout.clone())?.into_plan(), + &SESSION, + ) + }; + + insta::assert_snapshot!(prune(gt(get_item("a", root()), lit(5_i32)))?.display_tree(), @" + root: vortex.plan.zoned(bool?, rows=5) prune=(stat($, vortex.max()) <= 5i32) + zones: vortex.plan.filter({vortex.max()=i32?}, rows=2) + child: vortex.test.source({vortex.max()=i32?}, rows=2) + "); + insta::assert_snapshot!(prune(is_null(get_item("a", root())))?.display_tree(), @" + root: vortex.plan.eval(bool?, rows=5) expr=((null = 0u64) or null) + child: vortex.plan.pack({}, rows=5) + "); Ok(()) } diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index e5cdc90a3bc..929a9125600 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -19,7 +19,9 @@ layouts = [ "vortex.ext", ] dtypes = [] -aggregates = [] +aggregates = [ + "vortex.all_non_nan", +] # The edition's full membership: the members above, plus every member of earlier # editions of the family. @@ -31,4 +33,6 @@ layouts = [ "vortex.ext", ] dtypes = [] -aggregates = [] +aggregates = [ + "vortex.all_non_nan", +] From 24fd9daa62fbb5255f68a5ad6869393890d66568 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 11:14:58 -0500 Subject: [PATCH 04/13] Write opt-in extension storage as a structural layout A struct-backed extension written as a leaf makes a field query load every storage field. Let types opt into a structural layout so explicit storage reads can use the existing struct reader and planner without losing the extension dtype. Signed-off-by: Connor Tsui --- docs/developer-guide/benchmarking.md | 4 +- vortex-array/src/dtype/extension/foreign.rs | 5 + vortex-array/src/dtype/extension/mod.rs | 5 + .../src/declarations/unstable/mod.rs | 1 + vortex-file/src/footer/field_sizes.rs | 7 +- vortex-file/src/strategy.rs | 26 +- vortex-file/src/tests/extension_layout.rs | 191 +++++++++++++++ vortex-file/src/{tests.rs => tests/mod.rs} | 6 + vortex-layout/src/layouts/extension/expr.rs | 55 +++++ vortex-layout/src/layouts/extension/mod.rs | 186 ++++++++++++++ vortex-layout/src/layouts/extension/plan.rs | 148 +++++++++++ vortex-layout/src/layouts/extension/reader.rs | 227 +++++++++++++++++ vortex-layout/src/layouts/extension/tests.rs | 230 ++++++++++++++++++ vortex-layout/src/layouts/extension/writer.rs | 81 ++++++ vortex-layout/src/layouts/mod.rs | 1 + vortex-layout/src/layouts/table.rs | 41 +++- vortex-layout/src/session.rs | 25 +- .../editions/unstable/unstable2026.10.0.toml | 8 +- 18 files changed, 1231 insertions(+), 16 deletions(-) create mode 100644 vortex-file/src/tests/extension_layout.rs rename vortex-file/src/{tests.rs => tests/mod.rs} (99%) create mode 100644 vortex-layout/src/layouts/extension/expr.rs create mode 100644 vortex-layout/src/layouts/extension/mod.rs create mode 100644 vortex-layout/src/layouts/extension/plan.rs create mode 100644 vortex-layout/src/layouts/extension/reader.rs create mode 100644 vortex-layout/src/layouts/extension/tests.rs create mode 100644 vortex-layout/src/layouts/extension/writer.rs diff --git a/docs/developer-guide/benchmarking.md b/docs/developer-guide/benchmarking.md index 36899d73249..6a3f3ad7f2e 100644 --- a/docs/developer-guide/benchmarking.md +++ b/docs/developer-guide/benchmarking.md @@ -257,7 +257,9 @@ factors are configurable per suite (e.g. `--opt scale-factor=10.0` for TPC-H SF= Benchmark sessions enable the newest `preview` edition and the `unstable` edition, so every benchmark measures Vortex files whose compressor may also choose their encodings. `preview` currently holds `fastlanes.delta`, and `unstable` holds `vortex.decimal_byte_parts.v2` and -`vortex.widen`. `vortex_bench::enable_unstable_encodings` enables both on a session. +`vortex.widen`. `unstable` also holds the `vortex.extension` layout, which benchmarks do not use +because they opt no extension type into it. `vortex_bench::enable_unstable_encodings` enables +both editions on a session. ### Running SQL Benchmarks diff --git a/vortex-array/src/dtype/extension/foreign.rs b/vortex-array/src/dtype/extension/foreign.rs index 9efa0f3af3e..51dbad1c7d6 100644 --- a/vortex-array/src/dtype/extension/foreign.rs +++ b/vortex-array/src/dtype/extension/foreign.rs @@ -45,10 +45,15 @@ pub struct ForeignExtDType { } impl ForeignExtDType { + /// Creates the placeholder vtable for the extension ID `id`. pub fn new(id: ExtId) -> Self { Self { id } } + /// Builds an extension dtype for `id` from its serialized metadata and storage dtype. + /// + /// No registered vtable checks the metadata, so any metadata bytes and storage dtype are + /// accepted. pub fn from_parts( id: ExtId, metadata: Vec, diff --git a/vortex-array/src/dtype/extension/mod.rs b/vortex-array/src/dtype/extension/mod.rs index 9d5975f66e2..2494114d50c 100644 --- a/vortex-array/src/dtype/extension/mod.rs +++ b/vortex-array/src/dtype/extension/mod.rs @@ -34,6 +34,11 @@ mod plugin; pub use plugin::*; mod foreign; +// Tests in other crates use it to build extension dtypes over arbitrary storage without +// defining a vtable for each storage shape. +#[cfg(feature = "_test-harness")] +pub use foreign::ForeignExtDType; +#[cfg(not(feature = "_test-harness"))] pub(crate) use foreign::*; mod typed; diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index f2a1913ac46..683ba486fec 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -34,5 +34,6 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { added: &[ EditionMember::array(&"vortex.decimal_byte_parts.v2"), EditionMember::array(&"vortex.widen"), + EditionMember::layout(&"vortex.extension"), ], }; diff --git a/vortex-file/src/footer/field_sizes.rs b/vortex-file/src/footer/field_sizes.rs index afd47353d5b..87b9dc89296 100644 --- a/vortex-file/src/footer/field_sizes.rs +++ b/vortex-file/src/footer/field_sizes.rs @@ -24,10 +24,15 @@ use crate::footer::SegmentSpec; /// split). /// /// Fields nested inside non-struct types (e.g. structs within lists) are not split into separate -/// layout subtrees by the writer, so their bytes are attributed to the enclosing field. +/// layout subtrees by the writer, so their bytes are attributed to the enclosing field. The +/// exception is a struct-backed extension written with the [extension layout], whose storage +/// fields get their own paths, such as `point.x`. These paths do not resolve against the file's +/// logical dtype, because [`FieldPath::resolve`] cannot step into an extension. /// /// File-level metadata, alignment padding, and the footer are not part of any segment and are /// never attributed. +/// +/// [extension layout]: vortex_layout::layouts::extension #[derive(Debug, Clone)] pub struct CompressedFieldSizes { sizes: HashMap, diff --git a/vortex-file/src/strategy.rs b/vortex-file/src/strategy.rs index 1c15a1a0ba7..6c388feba09 100644 --- a/vortex-file/src/strategy.rs +++ b/vortex-file/src/strategy.rs @@ -7,6 +7,7 @@ use std::num::NonZeroUsize; use std::sync::Arc; use vortex_array::dtype::FieldPath; +use vortex_array::dtype::extension::ExtId; use vortex_btrblocks::BtrBlocksCompressorBuilder; use vortex_btrblocks::SchemeExt; use vortex_btrblocks::schemes::integer::IntDictScheme; @@ -22,6 +23,7 @@ use vortex_layout::layouts::compressed::CompressingStrategy; use vortex_layout::layouts::compressed::CompressorPlugin; use vortex_layout::layouts::dict::writer::DictLayoutOptions; use vortex_layout::layouts::dict::writer::DictStrategy; +use vortex_layout::layouts::extension::Extension; use vortex_layout::layouts::flat::writer::FlatLayoutStrategy; use vortex_layout::layouts::list::List; use vortex_layout::layouts::list::writer::ListLayoutStrategy; @@ -30,6 +32,7 @@ use vortex_layout::layouts::repartition::RepartitionWriterOptions; use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::writer::ZonedLayoutOptions; use vortex_layout::layouts::zoned::writer::ZonedStrategy; +use vortex_layout::session::LayoutSessionExt; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -128,12 +131,27 @@ pub struct WriteStrategyBuilder { /// /// [`ListLayoutStrategy`]: vortex_layout::layouts::list::writer::ListLayoutStrategy use_list_layout: bool, + /// Extension types selected by the session when the edition allows decomposition. + extension_layouts: Vec, } impl WriteStrategyBuilder { /// Create a new builder that compresses with the schemes registered on `session`. It can be /// further configured, and then finally built yielding the [`LayoutStrategy`]. + /// + /// The builder reads the session's [extension layout policy] when it is created, and only if + /// the enabled editions include the extension layout. An extension type opted in, or an + /// edition enabled, after this call does not change the built strategy. + /// + /// [extension layout policy]: vortex_layout::session::LayoutSession::decompose_extension pub fn from_session(session: &VortexSession) -> Self { + let enabled_layouts = session.enabled_component_ids(ComponentKind::Layout); + let extension_layouts = if enabled_layouts.contains(&Extension.id()) { + session.layouts().decomposed_extensions() + } else { + Vec::new() + }; + Self { compressor: CompressorConfig::BtrBlocks(BtrBlocksCompressorBuilder::from_session( session, @@ -143,9 +161,8 @@ impl WriteStrategyBuilder { field_writers: HashMap::new(), flat_strategy: None, probe_compressor: None, - use_list_layout: session - .enabled_component_ids(ComponentKind::Layout) - .contains(&List.id()), + use_list_layout: enabled_layouts.contains(&List.id()), + extension_layouts, } } @@ -296,7 +313,8 @@ impl WriteStrategyBuilder { // Take any field overrides from the builder and apply them to the final strategy. let mut table_strategy = TableStrategy::new(Arc::new(validity_strategy), Arc::new(repartition)) - .with_field_writers(self.field_writers); + .with_field_writers(self.field_writers) + .with_extension_layout(self.extension_layouts); if self.use_list_layout { // We need a closure here to enable recursive application of list layout. diff --git a/vortex-file/src/tests/extension_layout.rs b/vortex-file/src/tests/extension_layout.rs new file mode 100644 index 00000000000..1bf7ab92613 --- /dev/null +++ b/vortex-file/src/tests/extension_layout.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! File round trips for the experimental extension layout. + +use futures::TryStreamExt; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::extension::ForeignExtDType; +use vortex_array::dtype::session::DTypeSessionExt; +use vortex_array::expr::Expression; +use vortex_array::expr::ext_storage; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::is_not_null; +use vortex_array::expr::lit; +use vortex_array::expr::root; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::validity::Validity; +use vortex_buffer::ByteBufferMut; +use vortex_buffer::buffer; +use vortex_edition::ComponentKind; +use vortex_edition::EDITION_DECLARATIONS; +use vortex_edition::EditionInclusion; +use vortex_edition::EditionSession; +use vortex_edition::EditionSessionExt; +use vortex_edition::declarations::core::CORE_2026_08_3; +use vortex_edition::declarations::unstable::UNSTABLE; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_io::session::RuntimeSessionExt; +use vortex_layout::layouts::extension::Extension; +use vortex_layout::layouts::struct_::Struct; +use vortex_layout::scan::v2; +use vortex_layout::session::LayoutSession; +use vortex_layout::session::LayoutSessionExt; +use vortex_scan::execution::driver::ScanDriver; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::OpenOptionsSessionExt; +use crate::VortexFile; +use crate::WriteOptionsSessionExt; + +static POINT_ID: CachedId = CachedId::new("test.point"); + +fn session(unstable: bool, opted_in: bool) -> VortexResult { + let session = VortexSession::empty() + .with::() + .with::() + .with_tokio(); + crate::register_default_encodings(&session); + session.dtypes().register(ForeignExtDType::new(*POINT_ID)); + for declaration in EDITION_DECLARATIONS { + session.register_edition(declaration)?; + } + session.editions().declare_inclusion(EditionInclusion::new( + ComponentKind::DType, + &*POINT_ID, + CORE_2026_08_3, + ))?; + session.enable_edition(CORE_2026_08_3)?; + if unstable { + session.enable_edition(UNSTABLE)?; + } + if opted_in { + session.layouts().decompose_extension(*POINT_ID); + } + + Ok(session) +} + +fn points(validity: Validity) -> VortexResult { + let storage = StructArray::try_from_iter_with_validity( + [ + ("x", buffer![1i32, 99, 3].into_array()), + ("y", buffer![10i64, 990, 30].into_array()), + ], + validity, + )?; + let dtype = ForeignExtDType::from_parts(*POINT_ID, vec![1], storage.dtype().clone())?; + Ok(ExtensionArray::try_new(dtype, storage.into_array())?.into_array()) +} + +async fn write_points(session: &VortexSession, points: ArrayRef) -> VortexResult { + let input = StructArray::try_from_iter([("point", points)])?.into_array(); + let mut buffer = ByteBufferMut::empty(); + session + .write_options() + .write(&mut buffer, input.to_array_stream()) + .await?; + session.open_options().open_buffer(buffer) +} + +fn point() -> Expression { + get_item("point", root()) +} + +#[rstest] +#[case::core_opted_in(false, true)] +#[case::unstable_default(true, false)] +#[case::unstable_opted_in(true, true)] +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn test_extension_layout_policy( + #[case] unstable: bool, + #[case] opted_in: bool, +) -> VortexResult<()> { + let session = session(unstable, opted_in)?; + let points = points(Validity::NonNullable)?; + let file = write_points(&session, points.clone()).await?; + let layout = file + .footer() + .layout() + .slot(1)? + .ok_or_else(|| vortex_err!("missing point field"))?; + + assert_eq!(layout.is::(), unstable && opted_in); + if let Some(extension) = layout.as_opt::() { + assert!(extension.storage()?.is::()); + } + + let actual = file + .scan()? + .with_projection(point().bind(file.dtype())?) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(actual, points, &mut session.create_execution_ctx()); + + Ok(()) +} + +#[rstest] +#[case::whole_value(point(), None, None)] +#[case::field(get_item("x", ext_storage(point())), None, Some(vec![Some(1), None, Some(3)]))] +#[case::storage_filter( + get_item("x", ext_storage(point())), + Some(gt(get_item("x", ext_storage(point())), lit(2i32))), + Some(vec![Some(3)]), +)] +#[case::null_filter( + get_item("x", ext_storage(point())), + Some(is_not_null(point())), + Some(vec![Some(1), Some(3)]), +)] +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn test_nullable_extension_layout_scans( + #[case] projection: Expression, + #[case] filter: Option, + #[case] expected_field: Option>>, +) -> VortexResult<()> { + let session = session(true, true)?; + let points = points(Validity::from_iter([true, false, true]))?; + let file = write_points(&session, points.clone()).await?; + let projection = projection.bind(file.dtype())?; + let filter = filter.map(|expr| expr.bind(file.dtype())).transpose()?; + let expected = expected_field.map_or(points, |field| { + PrimitiveArray::from_option_iter(field).into_array() + }); + + let classic = file + .scan()? + .with_projection(projection.clone()) + .with_some_filter(filter.clone()) + .into_array_stream()? + .read_all() + .await?; + assert_arrays_eq!(classic, expected, &mut session.create_execution_ctx()); + + let scan = v2::ScanBuilder::new(session.clone(), file.scan_file()) + .with_projection(projection) + .with_some_filter(filter); + let dtype = scan.dtype().clone(); + let chunks: Vec = ScanDriver::new(session.handle(), 1, true) + .run(scan) + .try_collect() + .await?; + let v2 = ChunkedArray::try_new(chunks, dtype)?.into_array(); + assert_arrays_eq!(v2, expected, &mut session.create_execution_ctx()); + + Ok(()) +} diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests/mod.rs similarity index 99% rename from vortex-file/src/tests.rs rename to vortex-file/src/tests/mod.rs index 111abcf6745..fdba49d93f6 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests/mod.rs @@ -1,8 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Tests for the file format and its public read and write APIs. +//! +//! The tests exercise layouts through file round trips so they cover both serialization +//! and the readers that use the decoded layouts. + #![expect(clippy::cast_possible_truncation)] +mod extension_layout; mod scan_metrics; use std::fs; diff --git a/vortex-layout/src/layouts/extension/expr.rs b/vortex-layout/src/layouts/extension/expr.rs new file mode 100644 index 00000000000..82f1c20fe59 --- /dev/null +++ b/vortex-layout/src/layouts/extension/expr.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Rebinding expressions over extension values to their storage. + +use vortex_array::dtype::DType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::scalar_fn::fns::ext_storage::ExtStorage; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_error::VortexResult; + +/// Rebinds `expr`, bound to an extension scope, to the extension's storage. +/// +/// Returns `None` if any use of the root requires whole extension values. A null check can use +/// the storage because the extension and its storage share the same validity. +pub(super) fn rebind_to_storage( + expr: &BoundExpression, + storage_dtype: &DType, +) -> VortexResult> { + let storage_root = BoundExpression::new_root(storage_dtype.clone()); + let mut needs_extension_value = false; + let rebound = expr + .clone() + .transform_down(|node| { + if node.is_root() { + needs_extension_value = true; + return Ok(Transformed::no(node)); + } + + if !matches!(node.children(), [child] if child.is_root()) { + return Ok(Transformed::no(node)); + } + + let value = if node.is::() { + storage_root.clone() + } else if node.is::() || node.is::() { + node.with_children([storage_root.clone()])? + } else { + return Ok(Transformed::no(node)); + }; + + Ok(Transformed { + value, + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner(); + + Ok((!needs_extension_value).then_some(rebound)) +} diff --git a/vortex-layout/src/layouts/extension/mod.rs b/vortex-layout/src/layouts/extension/mod.rs new file mode 100644 index 00000000000..6e647c6edea --- /dev/null +++ b/vortex-layout/src/layouts/extension/mod.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! A layout for struct-backed extension types. +//! +//! [`ExtensionLayout`] preserves the logical dtype around a single storage child. This lets +//! [`ext_storage`](vortex_array::expr::ext_storage) use field projection and pruning while +//! whole-value reads reconstruct the extension from the storage. +//! +//! The default file writer uses this experimental format for opted-in types in the unstable +//! edition. The wire format can change under the same layout ID. + +mod expr; +mod plan; +mod reader; +pub(super) mod writer; + +use std::sync::Arc; + +use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_error::vortex_ensure_eq; +use vortex_error::vortex_err; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::Layout; +use crate::LayoutChildType; +use crate::LayoutDeserializeArgs; +use crate::LayoutId; +use crate::LayoutParts; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::LayoutRef; +use crate::VTable; +use crate::children::OwnedLayoutChildren; +use crate::lowering::slots_from_layout; +use crate::plan::physical::PlanParts; +use crate::plan::physical::PlanRef; +use crate::segments::SegmentSource; + +const STORAGE_SLOT: usize = 0; + +/// Vtable for the experimental `vortex.extension` layout. +#[derive(Clone, Debug)] +pub struct Extension; + +/// An extension-typed layout with one child of its struct storage dtype. +pub type ExtensionLayout = Layout; + +impl ExtensionLayout { + /// Wraps a storage layout, retaining its row count and exposing the extension dtype. + /// + /// # Errors + /// + /// The extension must have struct storage, and the child must have the declared storage + /// dtype and nullability. + pub fn try_new(ext_dtype: ExtDTypeRef, storage: LayoutRef) -> VortexResult { + vortex_ensure_eq!(storage.dtype(), struct_storage_dtype(&ext_dtype)?); + + Ok(LayoutParts::new( + Extension, + DType::Extension(ext_dtype), + storage.row_count(), + Vec::new(), + OwnedLayoutChildren::layout_children(vec![storage]), + (), + ) + .into_typed()) + } + + /// Returns the extension dtype retained by the layout. + pub fn ext_dtype(&self) -> &ExtDTypeRef { + self.dtype() + .as_extension_opt() + .vortex_expect("extension dtype is validated when building the extension layout") + } + + /// Returns the storage child, which has the same row range as this layout. + /// + /// # Errors + /// + /// Returns an error if the storage child cannot be loaded. + pub fn storage(&self) -> VortexResult { + self.slot(STORAGE_SLOT)? + .ok_or_else(|| vortex_err!("extension layout requires a storage child")) + } +} + +impl VTable for Extension { + type LayoutData = (); + type Metadata = EmptyMetadata; + + fn id(&self) -> LayoutId { + static ID: CachedId = CachedId::new("vortex.extension"); + *ID + } + + fn metadata(_layout: &Layout) -> Self::Metadata { + EmptyMetadata + } + + fn deserialize( + &self, + args: &LayoutDeserializeArgs<'_>, + _metadata: &EmptyMetadata, + ) -> VortexResult { + let ext_dtype = args.dtype.as_extension_opt().ok_or_else(|| { + vortex_err!( + "extension layout requires an extension dtype, got {}", + args.dtype + ) + })?; + struct_storage_dtype(ext_dtype)?; + + vortex_ensure_eq!( + args.segment_ids.len(), + 0, + "extension layout must have no direct segments" + ); + vortex_ensure_eq!( + args.children.nchildren(), + 1, + "extension layout must have exactly one storage child" + ); + vortex_ensure_eq!( + args.children.child_row_count(STORAGE_SLOT), + args.row_count, + "extension layout storage row count must match the parent" + ); + + Ok(()) + } + + fn child_dtype(layout: &Layout, slot: usize) -> VortexResult { + vortex_ensure_eq!(slot, STORAGE_SLOT); + Ok(layout.ext_dtype().storage_dtype().clone()) + } + + fn child_type(_layout: &Layout, _slot: usize) -> LayoutChildType { + LayoutChildType::Transparent("storage".into()) + } + + fn new_reader( + layout: &Layout, + name: Arc, + segment_source: Arc, + session: &VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + Ok(Arc::new(reader::ExtensionReader::try_new( + layout.clone(), + name, + segment_source, + session, + ctx, + )?)) + } + + fn new_plan(layout: &Layout) -> VortexResult { + Ok(PlanParts { + vtable: plan::ExtensionPack, + dtype: layout.dtype().clone(), + row_count: layout.row_count(), + slots: slots_from_layout(&layout.to_layout()), + data: (), + } + .into_plan()) + } +} + +fn struct_storage_dtype(ext_dtype: &ExtDTypeRef) -> VortexResult<&DType> { + let storage_dtype = ext_dtype.storage_dtype(); + vortex_ensure!( + storage_dtype.is_struct(), + "extension layout requires struct storage, got {storage_dtype}" + ); + Ok(storage_dtype) +} + +#[cfg(test)] +mod tests; diff --git a/vortex-layout/src/layouts/extension/plan.rs b/vortex-layout/src/layouts/extension/plan.rs new file mode 100644 index 00000000000..a370f778eda --- /dev/null +++ b/vortex-layout/src/layouts/extension/plan.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lowers reconstruction and storage-only reads into the scan plan. + +use std::borrow::Cow; +use std::ops::Range; + +use vortex_array::EmptyMetadata; +use vortex_array::IntoArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure_eq; +use vortex_mask::Mask; +use vortex_scan::execution::operator::Cx; +use vortex_scan::execution::operator::Input; +use vortex_scan::execution::operator::Operator; +use vortex_scan::execution::operator::Step; +use vortex_scan::execution::pipeline::Chain; +use vortex_scan::execution::pipeline::Compiler; +use vortex_scan::plan::Eval; +use vortex_scan::plan::EvalPlan; +use vortex_scan::plan::Plan; +use vortex_scan::plan::PlanId; +use vortex_scan::plan::PlanRef; +use vortex_scan::plan::PlanSlots; +use vortex_scan::plan::PlanVTable; +use vortex_scan::plan::optimizer::PlanParentReduceRule; +use vortex_scan::plan::optimizer::PlanParentReduceRuleAdapter; +use vortex_scan::plan::optimizer::PlanParentRuleSet; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use super::STORAGE_SLOT; +use super::expr::rebind_to_storage; + +/// Reconstructs extension values from batches of storage. +#[derive(Clone, Debug)] +pub(super) struct ExtensionPack; + +impl ExtensionPack { + fn ext_dtype(plan: &Plan) -> &ExtDTypeRef { + plan.dtype() + .as_extension_opt() + .vortex_expect("extension pack inherits the validated extension layout dtype") + } +} + +impl PlanVTable for ExtensionPack { + type PlanData = (); + type Metadata = EmptyMetadata; + + fn id(&self) -> PlanId { + static ID: CachedId = CachedId::new("vortex.plan.ext_pack"); + *ID + } + + fn metadata(_plan: &Plan) -> Option { + Some(EmptyMetadata) + } + + fn with_slots( + plan: &Plan, + slots: &PlanSlots, + _data: &mut Self::PlanData, + ) -> VortexResult<()> { + slots.check_len("ExtensionPack", 1)?; + let storage = slots.required(STORAGE_SLOT)?; + vortex_ensure_eq!(storage.dtype(), Self::ext_dtype(plan).storage_dtype()); + vortex_ensure_eq!(storage.row_count(), plan.row_count()); + + Ok(()) + } + + fn slot_name(_plan: &Plan, _slot: usize) -> Cow<'_, str> { + Cow::Borrowed("storage") + } + + fn reduce_parent( + plan: &Plan, + parent: &PlanRef, + slot: usize, + session: &VortexSession, + ) -> VortexResult> { + static RULES: PlanParentRuleSet = + PlanParentRuleSet::new(&[&PlanParentReduceRuleAdapter::new(StorageEvalRule)]); + RULES.evaluate(&plan.to_plan(), parent, slot, session) + } + + fn compile( + plan: &Plan, + rows: Range, + mask: &Mask, + compiler: &mut Compiler<'_>, + ) -> VortexResult> { + let chain = compiler.compile(&plan.slot_required(STORAGE_SLOT)?, rows, mask)?; + Ok(chain.map(|chain| { + chain.with(ExtensionPackStage { + ext_dtype: Self::ext_dtype(plan).clone(), + }) + })) + } +} + +/// Removes reconstruction when the parent evaluates only the storage or its validity. +#[derive(Debug)] +struct StorageEvalRule; + +impl PlanParentReduceRule for StorageEvalRule { + type Parent = Eval; + + fn reduce_parent( + &self, + child: &Plan, + parent: &EvalPlan, + _child_idx: usize, + _session: &VortexSession, + ) -> VortexResult> { + let Some(expr) = rebind_to_storage( + parent.expression(), + ExtensionPack::ext_dtype(child).storage_dtype(), + )? + else { + return Ok(None); + }; + + let storage = child.slot_required(STORAGE_SLOT)?; + Ok(Some(EvalPlan::try_new(expr, storage)?.into_plan())) + } +} + +struct ExtensionPackStage { + ext_dtype: ExtDTypeRef, +} + +impl Operator for ExtensionPackStage { + fn compute(&mut self, input: Input, _cx: &mut Cx<'_>) -> VortexResult { + let Input::Batch(batch) = input else { + return Ok(Step::End); + }; + + Ok(Step::Final( + ExtensionArray::try_new(self.ext_dtype.clone(), batch)?.into_array(), + )) + } +} diff --git a/vortex-layout/src/layouts/extension/reader.rs b/vortex-layout/src/layouts/extension/reader.rs new file mode 100644 index 00000000000..f4441857879 --- /dev/null +++ b/vortex-layout/src/layouts/extension/reader.rs @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Delegates classic reads to the storage reader and reconstructs extension values on demand. + +use std::any::Any; +use std::ops::Range; +use std::sync::Arc; + +use futures::FutureExt; +use futures::try_join; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::ExactBoundExpr; +use vortex_error::VortexResult; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_utils::aliases::dash_map::DashMap; + +use super::ExtensionLayout; +use super::expr::rebind_to_storage; +use crate::ArrayFuture; +use crate::LayoutReader; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::RowSplits; +use crate::SplitRange; +use crate::segments::SegmentSource; + +/// Reader for [`ExtensionLayout`]. +pub(super) struct ExtensionReader { + layout: ExtensionLayout, + name: Arc, + session: VortexSession, + storage: LayoutReaderRef, + storage_root: BoundExpression, + /// Reuse the rebound tree across splits because the storage reader caches by tree identity. + rebound: DashMap>, +} + +impl ExtensionReader { + pub(super) fn try_new( + layout: ExtensionLayout, + name: Arc, + segment_source: Arc, + session: &VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + let storage = layout.storage()?.new_reader( + format!("{name}.storage").into(), + segment_source, + session, + ctx, + )?; + let storage_root = BoundExpression::new_root(layout.ext_dtype().storage_dtype().clone()); + + Ok(Self { + layout, + name, + session: session.clone(), + storage, + storage_root, + rebound: DashMap::with_hasher_and_shard_amount(Default::default(), 8), + }) + } + + /// Returns `expr` rebound to the storage, or `None` when it reads the extension values. + fn storage_expr(&self, expr: &BoundExpression) -> VortexResult> { + if expr.is_root() { + return Ok(None); + } + + let key = ExactBoundExpr(expr.clone()); + if let Some(rebound) = self.rebound.get(&key) { + return Ok(rebound.value().clone()); + } + + let rebound = rebind_to_storage(expr, self.storage_root.dtype())?; + Ok(self.rebound.entry(key).or_insert(rebound).value().clone()) + } + + /// Reads the storage of the rows `mask` selects and wraps it back into extension values. + fn project_values( + &self, + row_range: &Range, + mask: MaskFuture, + ) -> VortexResult { + let storage = self + .storage + .projection_evaluation(row_range, &self.storage_root, mask)?; + let ext_dtype = self.layout.ext_dtype().clone(); + + Ok(async move { + let storage = storage.await?; + Ok(ExtensionArray::try_new(ext_dtype, storage)?.into_array()) + } + .boxed()) + } +} + +impl LayoutReader for ExtensionReader { + fn name(&self) -> &Arc { + &self.name + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn dtype(&self) -> &DType { + self.layout.dtype() + } + + fn row_count(&self) -> u64 { + self.layout.row_count() + } + + fn can_prune_file(&self, expr: &BoundExpression) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self.storage.can_prune_file(&storage_expr), + None => Ok(false), + } + } + + fn split_pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => { + self.storage + .split_pruning_evaluation(row_range, &storage_expr, mask) + } + None => Ok(MaskFuture::ready(mask)), + } + } + + fn split_pruning_is_statistics(&self, expr: &BoundExpression) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self.storage.split_pruning_is_statistics(&storage_expr), + None => Ok(true), + } + } + + fn register_splits( + &self, + field_mask: &[FieldMask], + split_range: &SplitRange, + splits: &mut RowSplits, + ) -> VortexResult<()> { + // Field paths stop at the extension, so a mask for the extension root also applies + // to the storage root. + self.storage + .register_splits(field_mask, split_range, splits) + } + + fn pruning_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + match self.storage_expr(expr)? { + Some(storage_expr) => self + .storage + .pruning_evaluation(row_range, &storage_expr, mask), + None => Ok(MaskFuture::ready(mask)), + } + } + + fn filter_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + if let Some(storage_expr) = self.storage_expr(expr)? { + return self + .storage + .filter_evaluation(row_range, &storage_expr, mask); + } + + let len = mask.len(); + let input = mask.clone(); + let values = self.project_values(row_range, mask)?; + let expr = expr.clone(); + let session = self.session.clone(); + + Ok(MaskFuture::new(len, async move { + let (input, values) = try_join!(input, values)?; + let predicate = values + .apply_bound(&expr)? + .fill_null(false)? + .execute::(&mut session.create_execution_ctx())?; + Ok(input.intersect_by_rank(&predicate)) + })) + } + + fn projection_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + if let Some(storage_expr) = self.storage_expr(expr)? { + return self + .storage + .projection_evaluation(row_range, &storage_expr, mask); + } + + let values = self.project_values(row_range, mask)?; + if expr.is_root() { + return Ok(values); + } + + let expr = expr.clone(); + Ok(async move { values.await?.apply_bound(&expr) }.boxed()) + } +} diff --git a/vortex-layout/src/layouts/extension/tests.rs b/vortex-layout/src/layouts/extension/tests.rs new file mode 100644 index 00000000000..6b405fa7450 --- /dev/null +++ b/vortex-layout/src/layouts/extension/tests.rs @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::num::NonZeroUsize; +use std::sync::Arc; + +use futures::stream; +use vortex_array::ArrayContext; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_array::dtype::extension::ForeignExtDType; +use vortex_array::expr::ext_storage; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::field_path; +use vortex_buffer::buffer; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_expr::stats::rewrite::BoundExpressionPruneExt; +use vortex_mask::Mask; +use vortex_session::registry::CachedId; +use vortex_session::registry::ReadContext; + +use super::Extension; +use super::ExtensionLayout; +use super::expr::rebind_to_storage; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::flat::Flat; +use crate::layouts::flat::FlatLayout; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::table::TableStrategy; +use crate::layouts::zoned::ZonedLayoutEncoding; +use crate::layouts::zoned::writer::ZonedLayoutOptions; +use crate::layouts::zoned::writer::ZonedStrategy; +use crate::plan::physical::EvalPlan; +use crate::plan::physical::Zoned; +use crate::plan::physical::optimize; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentId; +use crate::segments::TestSegments; +use crate::sequence::SequenceId; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; +use crate::test::SESSION; + +static EXTENSION_ID: CachedId = CachedId::new("test.measurement"); + +/// Writes `chunks` in order with `strategy`, and returns the layout with the segments it wrote. +async fn write( + strategy: &TableStrategy, + chunks: Vec, +) -> VortexResult<(LayoutRef, Arc)> { + let dtype = chunks + .first() + .vortex_expect("a write needs at least one chunk") + .dtype() + .clone(); + let segments = Arc::new(TestSegments::default()); + let (mut ptr, eof) = SequenceId::root().split(); + let chunks: Vec> = chunks + .into_iter() + .map(|chunk| Ok((ptr.advance(), chunk))) + .collect(); + + let layout = strategy + .write_stream( + ArrayContext::empty().into(), + Arc::::clone(&segments), + SequentialStreamAdapter::new(dtype, stream::iter(chunks)).sendable(), + eof, + &SESSION, + ) + .await?; + + Ok((layout, segments)) +} + +fn flat_table() -> TableStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + TableStrategy::new(Arc::clone(&flat), flat) +} + +fn extension_dtype(storage_dtype: &DType) -> VortexResult { + ForeignExtDType::from_parts(*EXTENSION_ID, vec![], storage_dtype.clone()) +} + +#[tokio::test] +async fn test_storage_reads_use_field_layouts() -> VortexResult<()> { + let storage = StructArray::try_from_iter([ + ("value", buffer![1i32, 2, 30, 40].into_array()), + ("other", buffer![10i64, 20, 300, 400].into_array()), + ])?; + let ext_dtype = extension_dtype(storage.dtype())?; + let array = ExtensionArray::try_new(ext_dtype.clone(), storage.into_array())?.into_array(); + let zoned = ZonedStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + FlatLayoutStrategy::default(), + ZonedLayoutOptions { + block_size: NonZeroUsize::new(2).vortex_expect("two rows per zone"), + ..Default::default() + }, + ); + let strategy = TableStrategy::new(Arc::new(FlatLayoutStrategy::default()), Arc::new(zoned)) + .with_extension_layout([ext_dtype.id()]); + let (layout, segments) = write(&strategy, vec![array.slice(0..2)?, array.slice(2..4)?]).await?; + + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "measurement".into(), + Arc::clone(&source) as _, + &SESSION, + &Default::default(), + )?; + let field = get_item("value", ext_storage(root())); + let predicate = gt(field.clone(), lit(20i32)).bind(layout.dtype())?; + + let pruned = reader + .split_pruning_evaluation(&(0..4), &predicate, Mask::new_true(4))? + .await?; + assert_eq!(pruned, Mask::from_iter([false, false, true, true])); + assert_eq!(source.requests(), 1); + + let values = reader + .projection_evaluation( + &(0..4), + &field.bind(layout.dtype())?, + MaskFuture::ready(pruned), + )? + .await?; + assert_arrays_eq!( + values, + buffer![30i32, 40].into_array(), + &mut SESSION.create_execution_ctx() + ); + assert_eq!(source.requests(), 2); + + let falsifier = predicate + .falsify(&SESSION)? + .ok_or_else(|| vortex_err!("storage comparison has no falsifier"))?; + let pruning = EvalPlan::try_new(falsifier, layout.new_plan()?)?; + let pruning = optimize(pruning.into_plan(), &SESSION)?; + let zoned = pruning + .as_opt::() + .ok_or_else(|| vortex_err!("expected field zone map, got {}", pruning.display_tree()))?; + assert!(zoned.is_pruning()); + + Ok(()) +} + +#[tokio::test] +async fn test_opted_in_primitive_storage_uses_the_leaf() -> VortexResult<()> { + let storage = buffer![1i32, 2].into_array(); + let ext_dtype = extension_dtype(storage.dtype())?; + let flat_storage = FlatLayout::new( + 2, + storage.dtype().clone(), + SegmentId::from(0), + ReadContext::new([]), + ) + .into_layout(); + assert!(ExtensionLayout::try_new(ext_dtype.clone(), flat_storage).is_err()); + + let array = ExtensionArray::try_new(ext_dtype.clone(), storage)?.into_array(); + let strategy = flat_table().with_extension_layout([ext_dtype.id()]); + let (layout, _) = write(&strategy, vec![array]).await?; + assert!(layout.is::()); + + Ok(()) +} + +#[tokio::test] +async fn test_field_override_applies_to_storage_field() -> VortexResult<()> { + let storage = StructArray::try_from_iter([ + ("x", buffer![1i32, 2].into_array()), + ("y", buffer![10i64, 20].into_array()), + ])?; + let ext_dtype = extension_dtype(storage.dtype())?; + let point = ExtensionArray::try_new(ext_dtype.clone(), storage.into_array())?.into_array(); + let table = StructArray::try_from_iter([("point", point)])?.into_array(); + let zoned = ZonedStrategy::new( + FlatLayoutStrategy::default(), + FlatLayoutStrategy::default(), + ZonedLayoutOptions::default(), + ); + let strategy = flat_table() + .with_extension_layout([ext_dtype.id()]) + .with_field_writer(field_path!(point.x), Arc::new(zoned)); + let (layout, _) = write(&strategy, vec![table]).await?; + + let point = layout.slot(1)?.vortex_expect("the table has a point field"); + let storage = point.as_::().storage()?; + let x = storage.slot(1)?.vortex_expect("the storage has an x field"); + let y = storage.slot(2)?.vortex_expect("the storage has a y field"); + assert!(x.is::()); + assert!(y.is::()); + + Ok(()) +} + +#[test] +fn test_mixed_projection_keeps_extension_scope() -> VortexResult<()> { + let storage = StructArray::try_from_iter([("value", buffer![1i32].into_array())])?; + let dtype = DType::Extension(extension_dtype(storage.dtype())?); + let projection = pack( + [ + ("point", root()), + ("value", get_item("value", ext_storage(root()))), + ], + Nullability::NonNullable, + ) + .bind(&dtype)?; + + assert!(rebind_to_storage(&projection, storage.dtype())?.is_none()); + + Ok(()) +} diff --git a/vortex-layout/src/layouts/extension/writer.rs b/vortex-layout/src/layouts/extension/writer.rs new file mode 100644 index 00000000000..3b7900e0572 --- /dev/null +++ b/vortex-layout/src/layouts/extension/writer.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Adapts extension streams to the struct writer without changing their row order. + +use async_trait::async_trait; +use futures::StreamExt; +use vortex_array::VortexSessionExecute; +use vortex_array::scalar_fn::EmptyOptions; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::VecExecutionArgs; +use vortex_array::scalar_fn::fns::ext_storage::ExtStorage; +use vortex_error::VortexResult; +use vortex_error::vortex_err; +use vortex_session::VortexSession; + +use super::ExtensionLayout; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::LayoutWriterContext; +use crate::layouts::struct_::StructStrategy; +use crate::segments::SegmentSinkRef; +use crate::sequence::SendableSequentialStream; +use crate::sequence::SequencePointer; +use crate::sequence::SequentialStreamAdapter; +use crate::sequence::SequentialStreamExt; + +/// Sends extension storage through the dispatcher-selected struct writer. +pub(in crate::layouts) struct ExtensionStrategy { + storage: StructStrategy, +} + +impl ExtensionStrategy { + pub(in crate::layouts) fn new(storage: StructStrategy) -> Self { + Self { storage } + } +} + +#[async_trait] +impl LayoutStrategy for ExtensionStrategy { + async fn write_stream( + &self, + ctx: LayoutWriterContext, + segment_sink: SegmentSinkRef, + stream: SendableSequentialStream, + eof: SequencePointer, + session: &VortexSession, + ) -> VortexResult { + let ext_dtype = stream + .dtype() + .as_extension_opt() + .ok_or_else(|| { + vortex_err!( + "extension writer requires an extension dtype, got {}", + stream.dtype() + ) + })? + .clone(); + let storage_dtype = ext_dtype.storage_dtype().clone(); + + let storage_session = session.clone(); + let storage_chunks = stream.map(move |chunk| { + let (sequence_id, chunk) = chunk?; + let len = chunk.len(); + let storage = ExtStorage.execute( + &EmptyOptions, + &VecExecutionArgs::new(vec![chunk], len), + &mut storage_session.create_execution_ctx(), + )?; + Ok((sequence_id, storage)) + }); + let storage_stream = SequentialStreamAdapter::new(storage_dtype, storage_chunks).sendable(); + + let storage = self + .storage + .write_stream(ctx, segment_sink, storage_stream, eof, session) + .await?; + + Ok(ExtensionLayout::try_new(ext_dtype, storage)?.into_layout()) + } +} diff --git a/vortex-layout/src/layouts/mod.rs b/vortex-layout/src/layouts/mod.rs index d2a8dd71ca9..0ff756be445 100644 --- a/vortex-layout/src/layouts/mod.rs +++ b/vortex-layout/src/layouts/mod.rs @@ -13,6 +13,7 @@ pub mod chunked; pub mod collect; pub mod compressed; pub mod dict; +pub mod extension; pub mod file_stats; pub mod flat; pub(crate) mod foreign; diff --git a/vortex-layout/src/layouts/table.rs b/vortex-layout/src/layouts/table.rs index 08575a80515..e28ceae607a 100644 --- a/vortex-layout/src/layouts/table.rs +++ b/vortex-layout/src/layouts/table.rs @@ -3,14 +3,10 @@ //! A configurable writer strategy for tabular data. //! -//! [`TableStrategy`] is a *dispatcher*: it inspects the dtype of the stream it is handed and -//! routes struct columns to [`StructStrategy`], list columns to [`ListLayoutStrategy`], and -//! everything else to the configured leaf strategy. Because it hands *itself* (suitably descended) -//! to those structural writers as the strategy for their children, arbitrarily nested struct/list -//! trees are written with no manual wiring. +//! [`TableStrategy`] selects a writer for each column. Structural writers use the dispatcher +//! for their children so that nested columns follow the same policy. //! -//! The dispatcher also owns field-path overrides, letting callers force a specific leaf field — -//! at any depth — onto a custom strategy. +//! A field-path override selects a custom writer for a column at any depth. use std::sync::Arc; @@ -18,6 +14,7 @@ use async_trait::async_trait; use vortex_array::dtype::Field; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldPath; +use vortex_array::dtype::extension::ExtId; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; @@ -26,6 +23,9 @@ use vortex_utils::aliases::hash_set::HashSet; use crate::LayoutRef; use crate::LayoutStrategy; use crate::LayoutWriterContext; +use crate::VTable; +use crate::layouts::extension::Extension; +use crate::layouts::extension::writer::ExtensionStrategy; use crate::layouts::list::writer::ListLayoutStrategy; use crate::layouts::struct_::StructStrategy; use crate::segments::SegmentSinkRef; @@ -45,6 +45,8 @@ type ListLayoutFactory = Arc Arc, + /// Extension IDs whose struct storage can be split into fields. + extension_layouts: Arc>, } impl TableStrategy { @@ -88,6 +92,7 @@ impl TableStrategy { validity, leaf: fallback, list_layout_factory: None, + extension_layouts: Arc::default(), } } @@ -175,6 +180,16 @@ impl TableStrategy { self.list_layout_factory = Some(Arc::new(factory)); self } + + /// Enable writing the given extension types with the experimental extension layout. + /// + /// Opted-in types with struct storage use the struct writer when the write context allows + /// the layout, and a field override below such an extension applies to its storage field. + /// Any other extension column goes to the leaf writer, so overrides below it have no effect. + pub fn with_extension_layout(mut self, ids: impl IntoIterator) -> Self { + Arc::make_mut(&mut self.extension_layouts).extend(ids); + self + } } impl TableStrategy { @@ -244,6 +259,7 @@ impl TableStrategy { validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + extension_layouts: Arc::clone(&self.extension_layouts), } } @@ -255,6 +271,7 @@ impl TableStrategy { validity: Arc::clone(&self.validity), leaf: Arc::clone(&self.leaf), list_layout_factory: self.list_layout_factory.clone(), + extension_layouts: Arc::clone(&self.extension_layouts), } } @@ -305,6 +322,16 @@ impl LayoutStrategy for TableStrategy { .await; } + if let Some(ext_dtype) = dtype.as_extension_opt() + && self.extension_layouts.contains(&ext_dtype.id()) + && ext_dtype.storage_dtype().is_struct() + && ctx.allows_layout(&Extension.id()) + { + return ExtensionStrategy::new(self.struct_strategy()) + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + } + // Leaf: hand off to the leaf strategy. self.leaf .write_stream(ctx, segment_sink, stream, eof, session) diff --git a/vortex-layout/src/session.rs b/vortex-layout/src/session.rs index bb8afedeb19..e53e9f8833b 100644 --- a/vortex-layout/src/session.rs +++ b/vortex-layout/src/session.rs @@ -3,6 +3,7 @@ use std::any::Any; +use vortex_array::dtype::extension::ExtId; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_session::ArcSwapMap; @@ -18,6 +19,7 @@ use crate::LayoutPluginRef; use crate::LayoutSerialization; use crate::layouts::chunked::Chunked; use crate::layouts::dict::Dict; +use crate::layouts::extension::Extension; use crate::layouts::flat::Flat; use crate::layouts::indexed::Indexed; use crate::layouts::list::List; @@ -28,13 +30,15 @@ use crate::layouts::zoned::Zoned; /// Registry of layout encodings. pub type LayoutRegistry = ArcSwapMap; -/// Session state for layout encodings. +/// Session state for layout encodings and extension layout write policy. #[derive(Clone, Debug)] pub struct LayoutSession { /// Deserializers keyed by the layout ID found on the wire. registry: LayoutRegistry, /// Serializers keyed by the in-memory layout ID. serializers: LayoutRegistry, + /// Extension IDs opted into struct storage decomposition for new files. + decomposed_extensions: ArcSwapMap, } impl LayoutSession { @@ -62,6 +66,23 @@ impl LayoutSession { &self.registry } + /// Opts an extension type with struct storage into the experimental extension layout. + /// + /// The default file writer uses this policy when the enabled editions include the layout. + /// Opt in when queries use storage fields, since each storage field is then written like a + /// field of a plain struct column, with the same zone maps for pruning predicates on it. The + /// decomposed column has no whole-value zone map, so predicates on the whole extension value + /// cannot prune zones. + pub fn decompose_extension(&self, id: ExtId) { + self.decomposed_extensions.insert(id, ()); + } + + /// Returns the extension IDs selected by [`Self::decompose_extension`]. + pub fn decomposed_extensions(&self) -> Vec { + self.decomposed_extensions + .read(|extensions| extensions.keys().copied().collect()) + } + fn serializer(&self, id: &LayoutId) -> Option { self.serializers.get(id) } @@ -72,6 +93,7 @@ impl Default for LayoutSession { let this = Self { registry: LayoutRegistry::default(), serializers: LayoutRegistry::default(), + decomposed_extensions: ArcSwapMap::default(), }; // Register the built-in layout encodings. @@ -81,6 +103,7 @@ impl Default for LayoutSession { this.register(&Zoned as &dyn LayoutPlugin); this.register(&LegacyStats as &dyn LayoutPlugin); this.register(&Dict as &dyn LayoutPlugin); + this.register(&Extension as &dyn LayoutPlugin); this.register(&List as &dyn LayoutPlugin); this.register(&Indexed as &dyn LayoutPlugin); this diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index 03d8b474fa9..af0ed94f7a9 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -16,7 +16,9 @@ arrays = [ "vortex.decimal_byte_parts.v2", "vortex.widen", ] -layouts = [] +layouts = [ + "vortex.extension", +] dtypes = [] aggregates = [] @@ -27,6 +29,8 @@ arrays = [ "vortex.decimal_byte_parts.v2", "vortex.widen", ] -layouts = [] +layouts = [ + "vortex.extension", +] dtypes = [] aggregates = [] From 75d0da7abf53ebb71c5491335f671261f62f43c8 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 08:29:32 +0000 Subject: [PATCH 05/13] Push field reads under unsupported expressions into Vortex scans A projection with any expression that the converter could not convert fell back to reading whole top-level columns. With a wide struct or protobuf column, one unsupported function anywhere in the SELECT list read every field. The scan now evaluates the largest convertible subexpressions that read columns, such as field access, and DataFusion evaluates the rest over the scan output. Identical subexpressions are read once, and residual filters use the same split. The scan evaluates a fallible subexpression only where DataFusion evaluates it on every row. Nested field access under a null parent returns null, as it already does when a whole projection converts. Signed-off-by: Connor Tsui --- Cargo.lock | 1 + vortex-datafusion/Cargo.toml | 1 + vortex-datafusion/src/convert/exprs/mod.rs | 76 ++- .../src/convert/exprs/partial/mod.rs | 328 ++++++++++++ .../src/convert/exprs/partial/tests.rs | 490 ++++++++++++++++++ vortex-datafusion/src/persistent/opener.rs | 112 +++- vortex-datafusion/src/persistent/source.rs | 10 +- vortex-datafusion/src/tests/mod.rs | 55 ++ .../src/tests/nested_projection.rs | 85 ++- vortex-datafusion/src/v2/tests.rs | 76 +++ 10 files changed, 1197 insertions(+), 37 deletions(-) create mode 100644 vortex-datafusion/src/convert/exprs/partial/mod.rs create mode 100644 vortex-datafusion/src/convert/exprs/partial/tests.rs diff --git a/Cargo.lock b/Cargo.lock index ab273f5e43d..ee47754210f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11733,6 +11733,7 @@ dependencies = [ "insta", "itertools 0.14.0", "object_store 0.13.2", + "parking_lot", "rstest", "tempfile", "tokio", diff --git a/vortex-datafusion/Cargo.toml b/vortex-datafusion/Cargo.toml index fa73a69b0e9..7dabc4e39fd 100644 --- a/vortex-datafusion/Cargo.toml +++ b/vortex-datafusion/Cargo.toml @@ -43,6 +43,7 @@ vortex-utils = { workspace = true, features = ["dashmap"] } anyhow = { workspace = true } datafusion = { workspace = true } insta = { workspace = true } +parking_lot = { workspace = true } rstest = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = ["test-util", "rt-multi-thread", "fs"] } diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 61bd7330468..a22316bda41 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -83,6 +83,10 @@ use vortex_arrow::ArrowSessionExt; use crate::row_index::RowIndex; +mod partial; + +pub(crate) use partial::split_filtered_projection; + /// Result of splitting a projection into Vortex expressions and leftover DataFusion projections. pub struct ProcessedProjection { /// Projection evaluated by the Vortex scan. @@ -143,8 +147,17 @@ pub trait ExpressionConverter: Send + Sync { /// Split a projection into Vortex expressions that can be pushed down and leftover /// DataFusion projections that need to be evaluated after the scan. /// - /// If any expression is unsupported, evaluate the complete projection in DataFusion - /// over deduplicated raw inputs. This avoids mixing input names with output aliases. + /// When every expression converts, the scan evaluates the whole projection. Otherwise the + /// scan evaluates each converted expression and the largest convertible subexpressions of the + /// others that read its input, such as field access under an unsupported function, under + /// generated names. DataFusion evaluates the rest over the scan output, so a wide struct column + /// is not read whole for one field. Converting a subexpression applies its conversion's + /// semantics, including [`DefaultExpressionConverter`]'s nested field access. + /// + /// An expression or subexpression whose conversion fails stays in DataFusion, like an + /// unsupported one, and DataFusion reports any error when it evaluates it. Duplicate aliases, + /// and a lambda that would stay in DataFusion, evaluate the complete projection in DataFusion + /// over deduplicated raw inputs. fn split_projection( &self, source_projection: ProjectionExprs, @@ -159,13 +172,26 @@ pub trait ExpressionConverter: Send + Sync { { return self.no_pushdown_projection(source_projection, input_schema); } - let mut scan_projection = Vec::with_capacity(source_projection.as_ref().len()); - for projection in source_projection.as_ref() { - let Some(expr) = self.try_convert(&projection.expr, input_schema)? else { - return self.no_pushdown_projection(source_projection, input_schema); + let converted = source_projection + .iter() + .map(|projection| partial::try_convert_or_keep(self, &projection.expr, input_schema)) + .collect_vec(); + if converted.iter().any(Option::is_none) { + return match partial::split_projection_partially( + self, + &source_projection, + converted, + input_schema, + )? { + Some(processed) => Ok(processed), + None => self.no_pushdown_projection(source_projection, input_schema), }; - scan_projection.push((projection.alias.clone(), expr)); } + let scan_projection = source_projection + .iter() + .zip(converted.into_iter().flatten()) + .map(|(projection, expr)| (projection.alias.clone(), expr)) + .collect_vec(); // The output schema names its fields after the projection aliases. let output_indices = (0..scan_projection.len()).collect_vec(); Ok(ProcessedProjection { @@ -244,6 +270,28 @@ pub(crate) fn raw_projection( }) } +/// Read the raw columns of a projection and of the residual filters that DataFusion evaluates +/// before it, returning the filters unchanged. +pub(crate) fn raw_filtered_projection( + projection: ProjectionExprs, + residual_filters: Vec>, + input_schema: &Schema, +) -> DFResult<(ProcessedProjection, Vec>)> { + let mut indices = projection.column_indices(); + indices.extend( + residual_filters + .iter() + .flat_map(collect_columns) + .map(|column| column.index()), + ); + indices.sort_unstable(); + indices.dedup(); + Ok(( + raw_projection(&indices, input_schema, projection)?, + residual_filters, + )) +} + /// Why an expression was not converted. enum Unconverted { /// A valid expression that Vortex cannot evaluate; it stays in DataFusion. @@ -793,18 +841,20 @@ impl DefaultExpressionConverter { let mut source_field = source.return_field(schema)?; let mut names = Vec::with_capacity(paths.len()); for path in paths { - let name = path - .downcast_ref::() - .and_then(|literal| literal.value().try_as_str().flatten()) - .ok_or_else(|| { - exec_datafusion_err!("get_field path must be a non-null string literal") - })?; if self.is_unknown_extension(&source_field)? { return Err(Unconverted::Unsupported); } + // Access into another type, such as a map, whose keys need not be strings, is + // valid but unsupported, so the path is checked only for a struct. let DataType::Struct(fields) = source_field.data_type() else { return Err(Unconverted::Unsupported); }; + let name = path + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str().flatten()) + .ok_or_else(|| { + exec_datafusion_err!("get_field path must be a non-null string literal") + })?; let (_, field) = fields.find(name).ok_or_else(|| { exec_datafusion_err!("get_field references missing field {name}") })?; diff --git a/vortex-datafusion/src/convert/exprs/partial/mod.rs b/vortex-datafusion/src/convert/exprs/partial/mod.rs new file mode 100644 index 00000000000..30132a61264 --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/partial/mod.rs @@ -0,0 +1,328 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Partial projection pushdown. +//! +//! A projection expression that does not convert as a whole often contains subexpressions that do, +//! such as field access on a wide struct or extension column under an unsupported function. The +//! scan evaluates the largest such subexpressions that read its input, and DataFusion evaluates the +//! rest of the expression over the scan output. The scan then reads only the fields that the +//! projection uses, rather than whole columns. +//! +//! A pushed-down subexpression has the semantics of its conversion, including the exceptions that +//! [`DefaultExpressionConverter`] documents. Nested field access under a null parent returns null, +//! where DataFusion extracts the child without applying parent validity. So a field read under an +//! unsupported function returns the same values as the same field read on its own, which the scan +//! evaluates whole. +//! +//! The scan evaluates every row it returns, so it evaluates a fallible subexpression only where +//! DataFusion evaluates it on every row too: a whole projection expression without a residual +//! filter. Such an expression uses Vortex's checked integer arithmetic, as it does when the whole +//! projection converts. Elsewhere, such as under an unsupported function, after a residual filter +//! or in a `CASE` branch, the scan evaluates only infallible subexpressions, and DataFusion +//! evaluates the rest, including any arithmetic. +//! +//! [`DefaultExpressionConverter`]: super::DefaultExpressionConverter + +use std::sync::Arc; + +use arrow_schema::Field; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use datafusion_common::Result as DFResult; +use datafusion_common::exec_datafusion_err; +use datafusion_common::tree_node::TreeNode; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::projection::ProjectionExpr; +use datafusion_physical_expr::projection::ProjectionExprs; +use datafusion_physical_plan::expressions as df_expr; +use vortex::dtype::Nullability; +use vortex::expr::Expression; +use vortex::expr::get_item; +use vortex::expr::pack; +use vortex::expr::root; +use vortex::layout::layouts::row_idx; +use vortex_utils::aliases::hash_map::Entry; +use vortex_utils::aliases::hash_map::HashMap; + +use super::ExpressionConverter; +use super::ProcessedProjection; +use super::is_infallible; +use super::raw_filtered_projection; +use crate::row_index::RowIndex; + +/// The prefix of the names of scan columns that hold pushed-down subexpressions. +const PUSHED_PREFIX: &str = "__vortex_expr_"; + +/// Splits a projection whose expressions do not all convert. +/// +/// `converted` holds the conversion of each projection expression. DataFusion evaluates a +/// projection on every row that the scan returns, so the scan evaluates each converted expression +/// whole, and the largest convertible subexpressions of the others. +/// +/// Returns `None` when DataFusion would evaluate a lambda over the scan output. DataFusion numbers +/// lambda parameters after the columns of the input schema, so the caller reads the raw input +/// columns instead, which never outnumber them. +pub(super) fn split_projection_partially( + converter: &C, + source_projection: &ProjectionExprs, + converted: Vec>, + input_schema: &Schema, +) -> DFResult> { + let unconverted = source_projection + .iter() + .zip(&converted) + .filter(|(_, converted)| converted.is_none()) + .map(|(projection, _)| &projection.expr); + if contains_lambda(unconverted)? { + return Ok(None); + } + let mut scan = ScanColumns::new(converter, input_schema); + let leftover = source_projection + .iter() + .zip(converted) + .map(|(projection, converted)| { + let expr = scan.rewrite_converted(&projection.expr, converted, Evaluation::EveryRow)?; + Ok(ProjectionExpr::new(expr, projection.alias.clone())) + }) + .collect::>>()?; + Ok(Some(scan.finish(leftover.into()))) +} + +/// Splits a projection and the residual filters that DataFusion evaluates before it. +/// +/// Both read one scan output. The scan evaluates no filter whole, since the caller found that the +/// filters do not convert, and DataFusion evaluates the projection only on the rows that they keep. +/// So the scan evaluates only infallible subexpressions of either. Returns the residual filters +/// rewritten to read the scan output. +/// +/// When an expression contains a lambda, falls back to [`raw_filtered_projection`], for the reason +/// given on [`split_projection_partially`]. +pub(crate) fn split_filtered_projection( + converter: &C, + projection: ProjectionExprs, + residual_filters: Vec>, + input_schema: &Schema, +) -> DFResult<(ProcessedProjection, Vec>)> { + let exprs = residual_filters + .iter() + .chain(projection.iter().map(|projection| &projection.expr)); + if contains_lambda(exprs)? { + return raw_filtered_projection(projection, residual_filters, input_schema); + } + let mut scan = ScanColumns::new(converter, input_schema); + let rewritten_filters = residual_filters + .iter() + .map(|filter| scan.rewrite_converted(filter, None, Evaluation::SomeRows)) + .collect::>>()?; + let leftover = projection + .iter() + .map(|projection| { + let expr = scan.rewrite(&projection.expr)?; + Ok(ProjectionExpr::new(expr, projection.alias.clone())) + }) + .collect::>>()?; + Ok((scan.finish(leftover.into()), rewritten_filters)) +} + +/// Whether DataFusion evaluates an expression on every row that the scan returns. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Evaluation { + /// On every row, so the scan may evaluate a fallible expression, as it does a projection that + /// it evaluates whole. + EveryRow, + /// Perhaps on some rows only: after a residual filter, or in an operand that DataFusion + /// evaluates lazily, such as a `CASE` branch. The scan evaluates only infallible expressions. + SomeRows, +} + +/// The columns of a scan that DataFusion expressions read after it. +/// +/// An input column that an expression reads whole keeps its name, so DataFusion resolves it by +/// name as before. A pushed-down subexpression gets a name that no input column has. Equal +/// subexpressions with equal Arrow fields share one scan column. +struct ScanColumns<'a, C: ?Sized> { + converter: &'a C, + input_schema: &'a Schema, + /// The name and Vortex expression of each scan column. + columns: Vec<(String, Expression)>, + /// The Arrow field that DataFusion expects of each scan column, named like it. + fields: Vec, + /// The scan column of each input column that is read whole, by input index. + whole: HashMap, + /// The scan column of each pushed-down subexpression, by its conversion and its unnamed Arrow + /// field. + pushed: HashMap<(Expression, Field), usize>, + /// The number of generated names tried, which numbers the next one. + generated: usize, +} + +impl<'a, C: ExpressionConverter + ?Sized> ScanColumns<'a, C> { + fn new(converter: &'a C, input_schema: &'a Schema) -> Self { + Self { + converter, + input_schema, + columns: Vec::new(), + fields: Vec::new(), + whole: HashMap::default(), + pushed: HashMap::default(), + generated: 0, + } + } + + /// Rewrites `expr`, which DataFusion may evaluate on some rows only, to read the scan output. + fn rewrite(&mut self, expr: &Arc) -> DFResult> { + let converted = + if expr.is::() || expr.is::() || !reads_scan(expr)? { + None + } else { + try_convert_or_keep(self.converter, expr, self.input_schema) + }; + self.rewrite_converted(expr, converted, Evaluation::SomeRows) + } + + /// Rewrites `expr`, whose conversion is `converted`, to read the scan output, adding the scan + /// columns that it reads. + fn rewrite_converted( + &mut self, + expr: &Arc, + converted: Option, + evaluation: Evaluation, + ) -> DFResult> { + if let Some(column) = expr.downcast_ref::() { + return self.whole_column(column); + } + // DataFusion cannot evaluate the row index, so the scan always supplies it. + if expr.is::() { + return self.push(expr, row_idx::row_idx()); + } + if !reads_scan(expr)? { + return Ok(Arc::clone(expr)); + } + if let Some(converted) = converted + && (evaluation == Evaluation::EveryRow || is_infallible(&converted)) + { + return self.push(expr, converted); + } + let children = expr + .children() + .into_iter() + .map(|child| self.rewrite(child)) + .collect::>>()?; + Arc::clone(expr).with_new_children(children) + } + + /// Reads the input column `column` whole. + fn whole_column(&mut self, column: &df_expr::Column) -> DFResult> { + let field = self + .input_schema + .fields() + .get(column.index()) + .filter(|field| field.name() == column.name()) + .ok_or_else(|| exec_datafusion_err!("Column {column} is not in the input schema"))?; + let index = match self.whole.entry(column.index()) { + Entry::Occupied(entry) => *entry.get(), + Entry::Vacant(entry) => { + let index = self.columns.len(); + self.columns.push(( + field.name().clone(), + get_item(field.name().as_str(), root()), + )); + self.fields.push(Arc::clone(field)); + *entry.insert(index) + } + }; + Ok(self.column(index)) + } + + /// Evaluates `expr`, which converts to `converted`, in the scan. + fn push( + &mut self, + expr: &Arc, + converted: Expression, + ) -> DFResult> { + let field = expr + .return_field(self.input_schema)? + .as_ref() + .clone() + .with_name(""); + let index = match self.pushed.entry((converted, field)) { + Entry::Occupied(entry) => *entry.get(), + Entry::Vacant(entry) => { + let name = generate_name(self.input_schema, &mut self.generated); + let index = self.columns.len(); + let (converted, field) = entry.key(); + self.columns.push((name.clone(), converted.clone())); + self.fields.push(Arc::new(field.clone().with_name(name))); + *entry.insert(index) + } + }; + Ok(self.column(index)) + } + + /// The DataFusion column that reads scan column `index`. + fn column(&self, index: usize) -> Arc { + Arc::new(df_expr::Column::new(&self.columns[index].0, index)) + } + + /// Returns the scan projection and its reference schema, with `leftover_projection`, which + /// reads the scan output. + fn finish(self, leftover_projection: ProjectionExprs) -> ProcessedProjection { + ProcessedProjection { + scan_projection: pack(self.columns, Nullability::NonNullable), + scan_reference_schema: Schema::new_with_metadata( + self.fields, + self.input_schema.metadata().clone(), + ), + leftover_projection, + } + } +} + +/// Converts `expr`, or returns `None` if it stays in DataFusion. +/// +/// The conversion of a projection is an optimization, so an expression whose conversion fails +/// stays in DataFusion, like an unsupported one, which reports any error when it evaluates it. +pub(super) fn try_convert_or_keep( + converter: &C, + expr: &Arc, + input_schema: &Schema, +) -> Option { + converter + .try_convert(expr, input_schema) + .unwrap_or_else(|error| { + tracing::debug!("{expr} stays in DataFusion: {error}"); + None + }) +} + +/// Returns the next name for a pushed-down subexpression that no column of `input_schema` has. +fn generate_name(input_schema: &Schema, generated: &mut usize) -> String { + loop { + let name = format!("{PUSHED_PREFIX}{generated}"); + *generated += 1; + if input_schema.index_of(&name).is_err() { + return name; + } + } +} + +/// Whether `expr` reads a column or the row index of the scan. +fn reads_scan(expr: &Arc) -> DFResult { + expr.exists(|node| Ok(node.is::() || node.is::())) +} + +/// Whether any of `exprs` contains a lambda. +fn contains_lambda<'e>( + exprs: impl IntoIterator>, +) -> DFResult { + for expr in exprs { + if expr.exists(|node| Ok(node.is::()))? { + return Ok(true); + } + } + Ok(false) +} + +#[cfg(test)] +mod tests; diff --git a/vortex-datafusion/src/convert/exprs/partial/tests.rs b/vortex-datafusion/src/convert/exprs/partial/tests.rs new file mode 100644 index 00000000000..606933e9b4d --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/partial/tests.rs @@ -0,0 +1,490 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::Schema; +use datafusion::common::DFSchema; +use datafusion::execution::context::ExecutionProps; +use datafusion::logical_expr::simplify::SimplifyContext; +use datafusion::optimizer::simplify_expressions::ExprSimplifier; +use datafusion::physical_expr::create_physical_expr; +use datafusion::prelude::SessionContext; +use datafusion_common::Result as DFResult; +use datafusion_common::ScalarValue; +use datafusion_common::config::ConfigOptions; +use datafusion_expr::HigherOrderUDF; +use datafusion_expr::Operator as DFOperator; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions_nested::array_transform::ArrayTransform; +use datafusion_physical_expr::HigherOrderFunctionExpr; +use datafusion_physical_expr::ScalarFunctionExpr; +use rstest::rstest; +use vortex::expr::Expression; +use vortex::expr::get_item; +use vortex::expr::root; + +use super::*; +use crate::convert::DefaultExpressionConverter; +use crate::row_index; + +/// `{id: i64, s: {a: utf8?, b: i64?, inner: {c: utf8?}}?, tags: list?}` +fn schema() -> Schema { + let inner = Field::new_struct("inner", vec![Field::new("c", DataType::Utf8, true)], true); + Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new_struct( + "s", + vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Int64, true), + inner, + ], + true, + ), + Field::new_list("tags", Field::new_list_field(DataType::Int64, true), true), + ]) +} + +/// Plans the SQL expression `sql` against `schema` as DataFusion does. +fn plan(sql: &str, schema: &Schema) -> DFResult> { + let df_schema = Arc::new(DFSchema::try_from(schema.clone())?); + let simplifier = ExprSimplifier::new( + SimplifyContext::builder() + .with_schema(Arc::clone(&df_schema)) + .build(), + ); + let expr = SessionContext::new().parse_sql_expr(sql, &df_schema)?; + let expr = simplifier.simplify(simplifier.coerce(expr, &df_schema)?)?; + create_physical_expr( + &expr, + &df_schema, + &ExecutionProps::new(), + &Default::default(), + ) +} + +/// Plans a projection of `(sql, alias)` pairs against `schema`. +fn projection(exprs: &[(&str, &str)], schema: &Schema) -> DFResult { + exprs + .iter() + .map(|(sql, alias)| Ok(ProjectionExpr::new(plan(sql, schema)?, *alias))) + .collect::>>() + .map(ProjectionExprs::from) +} + +/// Splits `projection` with the default converter. +fn split(projection: ProjectionExprs, schema: &Schema) -> DFResult { + let output_schema = projection.project_schema(schema)?; + DefaultExpressionConverter::default().split_projection(projection, schema, &output_schema) +} + +/// Formats each leftover expression with its alias. +fn leftover(processed: &ProcessedProjection) -> Vec { + processed + .leftover_projection + .iter() + .map(|projection| format!("{} AS {}", projection.expr, projection.alias)) + .collect() +} + +/// The names and Arrow types of the scan output. +fn scan_fields(processed: &ProcessedProjection) -> Vec<(String, DataType)> { + processed + .scan_reference_schema + .fields() + .iter() + .map(|field| (field.name().clone(), field.data_type().clone())) + .collect() +} + +/// The scan projection that reads `columns`. +fn scan(columns: impl IntoIterator) -> Expression { + pack(columns, Nullability::NonNullable) +} + +/// Field access along `path` into the struct column `s`. +fn s_field(path: &[&str]) -> Expression { + path.iter() + .fold(get_item("s", root()), |expr, name| get_item(*name, expr)) +} + +/// Field access under an unsupported function is read in the scan, once for each distinct +/// subexpression, while columns read whole keep their names and constants stay in DataFusion. +#[test] +fn test_unsupported_function_reads_fields_in_scan() -> DFResult<()> { + let schema = schema(); + let processed = split( + projection( + &[ + ("id", "id"), + ("upper(get_field(s, 'a'))", "up"), + ("get_field(s, 'a')", "a"), + ( + "concat(get_field(s, 'a'), get_field(s, 'inner', 'c'))", + "ac", + ), + ("1", "one"), + ], + &schema, + )?, + &schema, + )?; + assert_eq!( + processed.scan_projection, + scan([ + ("id", get_item("id", root())), + ("__vortex_expr_0", s_field(&["a"])), + ("__vortex_expr_1", s_field(&["inner", "c"])), + ]) + ); + assert_eq!( + scan_fields(&processed), + [ + ("id".to_owned(), DataType::Int64), + ("__vortex_expr_0".to_owned(), DataType::Utf8), + ("__vortex_expr_1".to_owned(), DataType::Utf8), + ] + ); + assert_eq!( + leftover(&processed), + [ + "id@0 AS id", + "upper(__vortex_expr_0@1) AS up", + "__vortex_expr_0@1 AS a", + "concat(__vortex_expr_0@1, __vortex_expr_1@2) AS ac", + "1 AS one", + ] + ); + Ok(()) +} + +/// DataFusion evaluates a projection expression on every row, so the scan evaluates a fallible +/// expression that converts whole. Under an unsupported function, DataFusion evaluates it. +#[rstest] +#[case::whole("id + 1", "__vortex_expr_0@0 AS n", "__vortex_expr_0")] +#[case::nested("abs(id + 1)", "abs(id@0 + 1) AS n", "id")] +fn test_fallible_expression_is_pushed_only_whole( + #[case] sql: &str, + #[case] expected: &str, + #[case] column: &str, +) -> DFResult<()> { + let schema = schema(); + let processed = split( + projection(&[(sql, "n"), ("upper(get_field(s, 'a'))", "up")], &schema)?, + &schema, + )?; + assert_eq!(leftover(&processed)[0], expected); + assert_eq!(scan_fields(&processed)[0].0, column); + Ok(()) +} + +/// The scan supplies the row index, which DataFusion cannot evaluate, also under an unsupported +/// expression. +#[test] +fn test_row_index_under_unsupported_expression() -> DFResult<()> { + let schema = schema(); + let parity: Arc = Arc::new(df_expr::BinaryExpr::new( + row_index(), + DFOperator::Modulo, + Arc::new(df_expr::Literal::new(ScalarValue::UInt64(Some(2)))), + )); + let processed = split( + ProjectionExprs::from(vec![ + ProjectionExpr::new(parity, "parity"), + ProjectionExpr::new(row_index(), "row"), + ]), + &schema, + )?; + assert_eq!( + processed.scan_projection, + scan([("__vortex_expr_0", row_idx::row_idx())]) + ); + assert!(!processed.scan_reference_schema.field(0).is_nullable()); + assert_eq!( + leftover(&processed), + [ + "__vortex_expr_0@0 % 2 AS parity", + "__vortex_expr_0@0 AS row" + ] + ); + Ok(()) +} + +/// Generated scan names skip the names of input columns, which columns read whole keep. +#[test] +fn test_generated_names_avoid_input_columns() -> DFResult<()> { + let mut fields = schema().fields().to_vec(); + fields.push(Arc::new(Field::new( + "__vortex_expr_0", + DataType::Utf8, + true, + ))); + let schema = Schema::new(fields); + let processed = split( + projection( + &[ + ("upper(get_field(s, 'a'))", "up"), + ("upper(__vortex_expr_0)", "taken"), + ], + &schema, + )?, + &schema, + )?; + assert_eq!( + scan_fields(&processed), + [ + ("__vortex_expr_1".to_owned(), DataType::Utf8), + ("__vortex_expr_0".to_owned(), DataType::Utf8), + ] + ); + assert_eq!( + leftover(&processed), + [ + "upper(__vortex_expr_1@0) AS up", + "upper(__vortex_expr_0@1) AS taken", + ] + ); + Ok(()) +} + +/// Fails to convert field access, and converts other expressions as the default converter does. +struct FailingFieldAccess(DefaultExpressionConverter); + +impl ExpressionConverter for FailingFieldAccess { + fn try_convert( + &self, + expr: &Arc, + schema: &Schema, + ) -> DFResult> { + let field_access = expr + .downcast_ref::() + .is_some_and(|function| { + ScalarFunctionExpr::try_downcast_func::(function).is_some() + }); + if field_access { + return Err(exec_datafusion_err!("field access fails to convert")); + } + self.0.try_convert(expr, schema) + } +} + +/// An expression whose conversion fails stays in DataFusion instead of failing the split, as a +/// subexpression and as a whole projection expression, whether or not another expression of the +/// projection is unsupported. +#[rstest] +#[case::subexpression( + &[("upper(get_field(s, 'a'))", "up")], + &["upper(get_field(s@0, a)) AS up"] +)] +#[case::after_unsupported( + &[("upper(get_field(s, 'a'))", "up"), ("get_field(s, 'b')", "b")], + &["upper(get_field(s@0, a)) AS up", "get_field(s@0, b) AS b"] +)] +#[case::before_unsupported( + &[("get_field(s, 'b')", "b"), ("upper(get_field(s, 'a'))", "up")], + &["get_field(s@0, b) AS b", "upper(get_field(s@0, a)) AS up"] +)] +#[case::alone(&[("get_field(s, 'b')", "b")], &["get_field(s@0, b) AS b"])] +fn test_failed_conversion_stays_in_datafusion( + #[case] exprs: &[(&str, &str)], + #[case] expected: &[&str], +) -> DFResult<()> { + let schema = schema(); + let projection = projection(exprs, &schema)?; + let output_schema = projection.project_schema(&schema)?; + let processed = FailingFieldAccess(DefaultExpressionConverter::default()).split_projection( + projection, + &schema, + &output_schema, + )?; + assert_eq!( + processed.scan_projection, + scan([("s", get_item("s", root()))]) + ); + assert_eq!(leftover(&processed), expected); + Ok(()) +} + +/// `{name: utf8?, m: map?, k: i64?}` +fn map_schema() -> Schema { + let entries = Field::new_struct( + "entries", + vec![ + Field::new("key", DataType::Int64, false), + Field::new("value", DataType::Utf8, true), + ], + false, + ); + Schema::new(vec![ + Field::new("name", DataType::Utf8, true), + Field::new("m", DataType::Map(Arc::new(entries), false), true), + Field::new("k", DataType::Int64, true), + ]) +} + +/// Map access, whose keys need not be strings, is unsupported rather than a failed conversion, so +/// it stays in DataFusion next to an unsupported expression, in either order. +#[rstest] +#[case::literal_key_after_unsupported( + &[("upper(name)", "u"), ("get_field(m, 1)", "v")], + &["upper(name@0) AS u", "get_field(m@1, 1) AS v"] +)] +#[case::literal_key_before_unsupported( + &[("get_field(m, 1)", "v"), ("upper(name)", "u")], + &["get_field(m@0, 1) AS v", "upper(name@1) AS u"] +)] +#[case::column_key(&[("upper(get_field(m, k))", "u")], &["upper(get_field(m@0, k@1)) AS u"])] +fn test_map_access_stays_in_datafusion( + #[case] exprs: &[(&str, &str)], + #[case] expected: &[&str], +) -> DFResult<()> { + let schema = map_schema(); + let projection = projection(exprs, &schema)?; + for projection in projection.iter() { + assert!( + DefaultExpressionConverter::default() + .try_convert(&projection.expr, &schema)? + .is_none() + ); + } + let processed = split(projection, &schema)?; + assert_eq!(leftover(&processed), expected); + Ok(()) +} + +/// DataFusion numbers lambda parameters after the input columns, so a lambda that stays in +/// DataFusion keeps the raw projection. +#[test] +fn test_lambda_in_datafusion_reads_raw_columns() -> DFResult<()> { + let schema = schema(); + let DataType::List(element) = schema.field(2).data_type() else { + return Err(exec_datafusion_err!("tags must be a list")); + }; + let variable: Arc = Arc::new(df_expr::LambdaVariable::new( + schema.fields().len(), + Arc::new(element.as_ref().clone().with_name("x")), + )); + let body = Arc::new(df_expr::BinaryExpr::new( + variable, + DFOperator::Modulo, + Arc::new(df_expr::Literal::new(ScalarValue::Int64(Some(2)))), + )); + let transform: Arc = Arc::new(HigherOrderFunctionExpr::try_new_with_schema( + Arc::new(HigherOrderUDF::new_from_impl(ArrayTransform::new())), + vec![ + Arc::new(df_expr::Column::new("tags", 2)), + Arc::new(df_expr::LambdaExpr::try_new(vec!["x".to_owned()], body)?), + ], + &schema, + Arc::new(ConfigOptions::new()), + )?); + let source = ProjectionExprs::from(vec![ + ProjectionExpr::new(transform, "odd"), + ProjectionExpr::new(plan("upper(get_field(s, 'a'))", &schema)?, "up"), + ]); + let processed = split(source.clone(), &schema)?; + assert_eq!( + processed.scan_projection, + scan([ + ("s", get_item("s", root())), + ("tags", get_item("tags", root())) + ]) + ); + assert_eq!(processed.leftover_projection, source); + Ok(()) +} + +/// Residual filters and the projection after them share one scan output. DataFusion evaluates +/// both on some rows only, so the scan evaluates only infallible subexpressions. +#[test] +fn test_filtered_projection_pushes_infallible_subexpressions() -> DFResult<()> { + let schema = schema(); + let filters = vec![plan("get_field(s, 'b') % 2 = 0", &schema)?]; + let (processed, filters) = split_filtered_projection( + &DefaultExpressionConverter::default(), + projection( + &[ + ("id + 1", "next"), + ("get_field(s, 'b')", "b"), + ("upper(get_field(s, 'a'))", "up"), + ], + &schema, + )?, + filters, + &schema, + )?; + assert_eq!( + processed.scan_projection, + scan([ + ("__vortex_expr_0", s_field(&["b"])), + ("id", get_item("id", root())), + ("__vortex_expr_1", s_field(&["a"])), + ]) + ); + assert_eq!( + filters.iter().map(ToString::to_string).collect::>(), + ["__vortex_expr_0@0 % 2 = 0"] + ); + assert_eq!( + leftover(&processed), + [ + "id@1 + 1 AS next", + "__vortex_expr_0@0 AS b", + "upper(__vortex_expr_1@2) AS up", + ] + ); + Ok(()) +} + +/// A residual filter can read the row index, which DataFusion cannot evaluate. +#[test] +fn test_residual_filter_reads_row_index_from_scan() -> DFResult<()> { + let schema = schema(); + let even: Arc = Arc::new(df_expr::BinaryExpr::new( + Arc::new(df_expr::BinaryExpr::new( + row_index(), + DFOperator::Modulo, + Arc::new(df_expr::Literal::new(ScalarValue::UInt64(Some(2)))), + )), + DFOperator::Eq, + Arc::new(df_expr::Literal::new(ScalarValue::UInt64(Some(0)))), + )); + let (processed, filters) = split_filtered_projection( + &DefaultExpressionConverter::default(), + projection(&[("id", "id")], &schema)?, + vec![even], + &schema, + )?; + assert_eq!( + processed.scan_projection, + scan([ + ("__vortex_expr_0", row_idx::row_idx()), + ("id", get_item("id", root())), + ]) + ); + assert_eq!( + filters.iter().map(ToString::to_string).collect::>(), + ["__vortex_expr_0@0 % 2 = 0"] + ); + assert_eq!(leftover(&processed), ["id@1 AS id"]); + Ok(()) +} + +/// Without projection pushdown, residual filters and the projection read raw columns. +#[test] +fn test_raw_filtered_projection_reads_filter_columns() -> DFResult<()> { + let schema = schema(); + let filters = vec![plan("get_field(s, 'b') % 2 = 0", &schema)?]; + let source = projection(&[("id", "id")], &schema)?; + let (processed, rewritten) = raw_filtered_projection(source.clone(), filters.clone(), &schema)?; + assert_eq!( + processed.scan_projection, + scan([("id", get_item("id", root())), ("s", get_item("s", root()))]) + ); + assert_eq!(processed.leftover_projection, source); + assert_eq!(rewritten, filters); + Ok(()) +} diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..3999285b340 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -72,7 +72,8 @@ use vortex_utils::parallelism::get_available_parallelism; use crate::VortexAccessPlan; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; -use crate::convert::exprs::raw_projection; +use crate::convert::exprs::raw_filtered_projection; +use crate::convert::exprs::split_filtered_projection; use crate::convert::schema::calculate_physical_schema; use crate::convert::to_record_batch; use crate::metrics::PARTITION_LABEL; @@ -410,7 +411,6 @@ impl FileOpener for VortexOpener { }) .map(|(_, expression)| expression.clone()), ); - let residual_filter = conjunction_opt(residual_filters); let native_filter = and_collect(native_filters) .map(|filter| filter.bind(vxf.dtype())?.optimize_recursive()) .transpose() @@ -418,30 +418,37 @@ impl FileOpener for VortexOpener { exec_datafusion_err!("Couldn't bind Vortex scan filter in {}: {e}", file.path()) })?; - // Residual filters must see raw inputs before computed projections or aliases. - let ProcessedProjection { - scan_projection, - scan_reference_schema, - leftover_projection, - } = if let Some(residual) = &residual_filter { - let mut indices = projection.column_indices(); - indices.extend( - collect_columns(residual) - .iter() - .map(|column| column.index()), - ); - indices.sort_unstable(); - indices.dedup(); - raw_projection(&indices, &this_file_schema, projection)? + // Residual filters run before the projection, so both read the scan output rather than + // computed projections or aliases. + let ( + ProcessedProjection { + scan_projection, + scan_reference_schema, + leftover_projection, + }, + residual_filters, + ) = if residual_filters.is_empty() { + let processed = if projection_pushdown { + expr_converter.split_projection( + projection, + &this_file_schema, + output_schema.as_ref(), + )? + } else { + expr_converter.no_pushdown_projection(projection, &this_file_schema)? + }; + (processed, residual_filters) } else if projection_pushdown { - expr_converter.split_projection( + split_filtered_projection( + expr_converter.as_ref(), projection, + residual_filters, &this_file_schema, - output_schema.as_ref(), )? } else { - expr_converter.no_pushdown_projection(projection, &this_file_schema)? + raw_filtered_projection(projection, residual_filters, &this_file_schema)? }; + let residual_filter = conjunction_opt(residual_filters); // The schema of the stream returned from the vortex scan. // We use a reference schema for types that don't roundtrip (Dictionary, Utf8, etc.). @@ -857,6 +864,7 @@ mod tests { use arrow_schema::Field; use arrow_schema::Fields; use arrow_schema::SchemaRef; + use datafusion::arrow::array::ArrayRef; use datafusion::arrow::array::DictionaryArray; use datafusion::arrow::array::Int32Array; use datafusion::arrow::array::RecordBatch; @@ -882,6 +890,8 @@ mod tests { use datafusion_execution::cache::default_cache::DefaultCache; use datafusion_execution::object_store::ObjectStoreUrl; use datafusion_expr::Operator; + use datafusion_functions::expr_fn::get_field; + use datafusion_functions::expr_fn::upper; use datafusion_physical_expr::PhysicalExpr; use datafusion_physical_expr::expressions as df_expr; use datafusion_physical_expr::projection::ProjectionExpr; @@ -1327,6 +1337,68 @@ mod tests { Ok(()) } + /// A residual filter and the projection after it both read nested fields from the scan output, + /// whether the scan evaluates the field access or DataFusion reads the whole struct. + #[rstest] + #[tokio::test] + async fn test_residual_filter_with_nested_projection( + #[values(false, true)] projection_pushdown: bool, + #[values(false, true)] scan_v2: bool, + ) -> anyhow::Result<()> { + let store: Arc = Arc::new(InMemory::new()); + let s = StructArray::try_new( + vec![ + Field::new("b", DataType::Int32, false), + Field::new("c", DataType::Utf8, false), + ] + .into(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3, 4])), + Arc::new(StringArray::from(vec!["w", "x", "y", "z"])), + ], + None, + )?; + let batch = RecordBatch::try_from_iter([ + ( + "a", + Arc::new(Int32Array::from(vec![10, 20, 30, 40])) as ArrayRef, + ), + ("s", Arc::new(s) as ArrayRef), + ])?; + let size = + write_arrow_to_vortex(Arc::clone(&store), "nested.vortex", batch.clone()).await?; + let schema = batch.schema(); + // The default converter does not support `%`, so the filter stays residual. + let filter = logical2physical(&(get_field(col("s"), "b") % lit(2)).eq(lit(0)), &schema); + let mut opener = make_opener(store, TableSchema::from(Arc::clone(&schema)), Some(filter)); + opener.projection = ProjectionExprs::from(vec![ + ProjectionExpr::new( + logical2physical(&upper(get_field(col("s"), "c")), &schema), + "shout", + ), + ProjectionExpr::new(logical2physical(&col("a"), &schema), "a"), + ]); + opener.projection_pushdown = projection_pushdown; + opener.scan_v2 = scan_v2; + let batches = opener + .open(PartitionedFile::new("nested.vortex", size))? + .await? + .try_collect::>() + .await?; + assert_batches_eq!( + [ + "+-------+----+", + "| shout | a |", + "+-------+----+", + "| X | 20 |", + "| Z | 40 |", + "+-------+----+", + ], + &batches + ); + Ok(()) + } + #[tokio::test] async fn test_open_preserves_declared_schema_metadata() -> anyhow::Result<()> { let object_store = Arc::new(InMemory::new()) as Arc; diff --git a/vortex-datafusion/src/persistent/source.rs b/vortex-datafusion/src/persistent/source.rs index 99b5c528c83..3119240b98b 100644 --- a/vortex-datafusion/src/persistent/source.rs +++ b/vortex-datafusion/src/persistent/source.rs @@ -147,7 +147,9 @@ use crate::persistent::reader::VortexReaderFactory; /// - when disabled, `VortexSource` still prunes unreferenced top-level columns, /// but DataFusion applies the full projection after the scan, /// - when enabled, the default converter evaluates fully supported projections -/// natively. Otherwise, DataFusion evaluates the full projection over raw columns. +/// natively. Otherwise the scan evaluates the supported subexpressions that read +/// its columns, such as nested field access, and DataFusion evaluates the rest +/// over the scan output. /// /// Predicate handling depends on [`VortexTableOptions::predicate_pushdown`]: /// @@ -155,8 +157,10 @@ use crate::persistent::reader::VortexReaderFactory; /// DataFusion file pruning, but reports filters as not pushed down so /// DataFusion evaluates them after the scan, /// - when enabled, supported filters are pushed into the Vortex scan. If file -/// adaptation requires residual filtering, DataFusion filters raw scan batches -/// before the final projection and limit. +/// adaptation requires residual filtering, DataFusion filters scan batches +/// before the final projection and limit. With projection pushdown, the scan +/// still evaluates the infallible supported subexpressions of the residual +/// filters and the projection. /// /// # Observability /// diff --git a/vortex-datafusion/src/tests/mod.rs b/vortex-datafusion/src/tests/mod.rs index e3421f63c67..77694ca966f 100644 --- a/vortex-datafusion/src/tests/mod.rs +++ b/vortex-datafusion/src/tests/mod.rs @@ -1,5 +1,60 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use std::sync::Arc; + +use arrow_schema::Schema; +use datafusion_common::Result as DFResult; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::projection::ProjectionExprs; +use parking_lot::Mutex; +use vortex::expr::Expression; +use vortex::session::VortexSession; + +use crate::convert::DefaultExpressionConverter; +use crate::convert::ExpressionConverter; +use crate::convert::ProcessedProjection; + mod nested_projection; mod schema_evolution; + +/// Converts expressions with the default converter and records each scan projection. +struct RecordingConverter { + inner: DefaultExpressionConverter, + scan_projections: Mutex>, +} + +impl RecordingConverter { + /// Converts with a default converter that resolves Arrow types through `session`. + fn new(session: VortexSession) -> Self { + Self { + inner: DefaultExpressionConverter::new(session), + scan_projections: Mutex::default(), + } + } +} + +impl ExpressionConverter for RecordingConverter { + fn try_convert( + &self, + expr: &Arc, + schema: &Schema, + ) -> DFResult> { + self.inner.try_convert(expr, schema) + } + + fn split_projection( + &self, + source_projection: ProjectionExprs, + input_schema: &Schema, + output_schema: &Schema, + ) -> DFResult { + let processed = + self.inner + .split_projection(source_projection, input_schema, output_schema)?; + self.scan_projections + .lock() + .push(processed.scan_projection.clone()); + Ok(processed) + } +} diff --git a/vortex-datafusion/src/tests/nested_projection.rs b/vortex-datafusion/src/tests/nested_projection.rs index d3c4be02513..3cb5182b1e5 100644 --- a/vortex-datafusion/src/tests/nested_projection.rs +++ b/vortex-datafusion/src/tests/nested_projection.rs @@ -14,10 +14,21 @@ use datafusion::arrow::buffer::NullBuffer; use datafusion_common::assert_batches_eq; use datafusion_common::create_array; use datafusion_expr::col; +use datafusion_expr::registry::FunctionRegistry; use datafusion_functions::expr_fn::get_field; +use datafusion_functions_nested::planner::FieldAccessPlanner; use rstest::rstest; - +use vortex::VortexSessionDefault; +use vortex::dtype::Nullability; +use vortex::expr::get_item; +use vortex::expr::pack; +use vortex::expr::root; +use vortex::session::VortexSession; + +use crate::VortexFormatFactory; +use crate::VortexTableOptions; use crate::common_tests::TestSessionContext; +use crate::tests::RecordingConverter; /// Schema: {id: Int64, outer: {inner: {leaf: Utf8, value: Int64}, extra: Int64}} fn make_nested_batch(parent_nulls: bool) -> RecordBatch { @@ -170,3 +181,75 @@ async fn test_nested_struct_null_parent_projection() -> anyhow::Result<()> { ); Ok(()) } + +/// A projection that mixes nested fields with an unsupported function over one of them reads only +/// those fields in the scan, once each, and DataFusion applies the function to the scan output. +/// +/// The fields follow the converter's nested field access, as they do when the scan evaluates the +/// whole projection: a null `outer` or `inner` makes the fields under it null. +#[rstest] +#[tokio::test] +async fn test_mixed_projection_reads_needed_fields( + #[values(false, true)] scan_v2: bool, +) -> anyhow::Result<()> { + let converter = Arc::new(RecordingConverter::new(VortexSession::default())); + let options = VortexTableOptions { + projection_pushdown: true, + scan_v2, + ..Default::default() + }; + let factory = VortexFormatFactory::new() + .with_options(options) + .with_expression_converter(Arc::clone(&converter) as _); + let mut ctx = TestSessionContext::new_with_factory(Arc::new(factory)); + // The workspace builds DataFusion without its nested expressions, which plan SQL field access. + ctx.session + .register_expr_planner(Arc::new(FieldAccessPlanner))?; + ctx.write_arrow_batch("files/nested.vortex", &make_nested_batch(true)) + .await?; + ctx.session + .sql("CREATE EXTERNAL TABLE nested STORED AS vortex LOCATION '/files/'") + .await?; + + let batches = ctx + .session + .sql( + "SELECT id, upper(\"outer\"['inner']['leaf']) AS shout, \ + \"outer\"['inner']['leaf'] AS leaf, \"outer\"['extra'] AS extra \ + FROM nested ORDER BY id", + ) + .await? + .collect() + .await?; + assert_batches_eq!( + [ + "+----+-------+------+-------+", + "| id | shout | leaf | extra |", + "+----+-------+------+-------+", + "| 1 | A | a | 100 |", + "| 2 | | | |", + "| 3 | | | 300 |", + "+----+-------+------+-------+", + ], + &batches + ); + + let outer = get_item("outer", root()); + let expected = pack( + [ + ("id", get_item("id", root())), + ( + "__vortex_expr_0", + get_item("leaf", get_item("inner", outer.clone())), + ), + ("__vortex_expr_1", get_item("extra", outer)), + ], + Nullability::NonNullable, + ); + let scan_projections = converter.scan_projections.lock(); + assert!(!scan_projections.is_empty()); + for projection in scan_projections.iter() { + assert_eq!(projection, &expected); + } + Ok(()) +} diff --git a/vortex-datafusion/src/v2/tests.rs b/vortex-datafusion/src/v2/tests.rs index 8ad23de2b4a..27ff482578d 100644 --- a/vortex-datafusion/src/v2/tests.rs +++ b/vortex-datafusion/src/v2/tests.rs @@ -7,6 +7,8 @@ use anyhow::anyhow; use arrow_array::ArrayRef; use arrow_array::Int32Array; use arrow_array::RecordBatch; +use arrow_array::StringArray; +use arrow_array::StructArray; use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::DataType; @@ -25,11 +27,16 @@ use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_datasource::source::DataSource; use datafusion_datasource::source::DataSourceExec; use datafusion_expr::Operator; +use datafusion_expr::ScalarUDF; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions::string::upper::UpperFunc; use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_plan::ExecutionPlan; +use datafusion_physical_plan::displayable; use datafusion_physical_plan::expressions as df_expr; use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::filter_pushdown::PushedDown; @@ -579,3 +586,72 @@ async fn test_build_rejects_extension_column_over_plain() -> anyhow::Result<()> Ok(()) } + +/// A projection that mixes a nested field with an unsupported function over it reads the field in +/// the scan once, and DataFusion applies the function to the scan output. +#[tokio::test] +async fn mixed_projection_reads_needed_fields() -> anyhow::Result<()> { + let fields = vec![ + Field::new("a", DataType::Utf8, true), + Field::new("b", DataType::Int32, true), + ]; + let s = StructArray::try_new( + fields.into(), + vec![ + Arc::new(StringArray::from(vec![Some("x"), None, Some("z")])), + Arc::new(Int32Array::from(vec![10, 20, 30])), + ], + None, + )?; + let batch = RecordBatch::try_from_iter([ + ("id", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef), + ("s", Arc::new(s) as ArrayRef), + ])?; + let schema = batch.schema(); + let source = vortex_source_from_batch(batch).await?; + + let function = |udf: ScalarUDF, args| -> anyhow::Result> { + Ok(Arc::new(ScalarFunctionExpr::try_new( + Arc::new(udf), + args, + &schema, + Arc::new(ConfigOptions::new()), + )?)) + }; + let a = function( + GetFieldFunc::new().into(), + vec![Arc::new(df_expr::Column::new("s", 1)), df_expr::lit("a")], + )?; + let projection = ProjectionExprs::from(vec![ + ProjectionExpr::new(Arc::new(df_expr::Column::new("id", 0)), "id"), + ProjectionExpr::new( + function(UpperFunc::new().into(), vec![Arc::clone(&a)])?, + "shout", + ), + ProjectionExpr::new(a, "a"), + ]); + let projected = source + .try_swapping_with_projection(&projection)? + .ok_or_else(|| anyhow!("projection was not swapped"))?; + let plan = Arc::new(DataSourceExec::new(projected)) as Arc; + let display = displayable(plan.as_ref()).one_line().to_string(); + assert!( + display.contains("projection=pack(id: $.id, __vortex_expr_0: $.s.a)"), + "{display}" + ); + + let batches = datafusion_physical_plan::collect(plan, SessionContext::new().task_ctx()).await?; + assert_batches_eq!( + [ + "+----+-------+---+", + "| id | shout | a |", + "+----+-------+---+", + "| 1 | X | x |", + "| 2 | | |", + "| 3 | Z | z |", + "+----+-------+---+", + ], + &batches + ); + Ok(()) +} From c772b02ff691e8edfba0c77c0761cc727050af6c Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 10:58:00 +0000 Subject: [PATCH 06/13] Keep NaN counts beneath nullable structs out of a new aggregate Commit 91dbd9bf9 recorded whether a zone holds no NaN in place of the NaN count for fields beneath a nullable struct, and added `vortex.all_non_nan` to the unstable edition for it. That broke the test that the unstable edition permits only persisted aggregates, and core editions got float zone maps that could never prune. Fields beneath a nullable struct now record the NaN count with the bounds. The hidden values of null struct rows can only add to the count, so a count of zero still proves that a zone holds no NaN, and the scans use it only that way. Float fields beneath nullable structs now prune in every edition, and the unstable edition is as on develop apart from `vortex.ext`. Signed-off-by: Connor Tsui --- docs/developer-guide/benchmarking.md | 5 +- .../src/declarations/unstable/mod.rs | 1 - vortex-file/src/tests.rs | 138 ++++++++++++++++++ vortex-layout/src/layouts/zoned/writer.rs | 82 ++++------- .../editions/unstable/unstable2026.10.0.toml | 8 +- 5 files changed, 171 insertions(+), 63 deletions(-) diff --git a/docs/developer-guide/benchmarking.md b/docs/developer-guide/benchmarking.md index e515f060a78..212751c1a32 100644 --- a/docs/developer-guide/benchmarking.md +++ b/docs/developer-guide/benchmarking.md @@ -255,8 +255,9 @@ factors are configurable per suite (e.g. `--opt scale-factor=10.0` for TPC-H SF= ### Unstable Encodings Benchmark sessions enable the `unstable` edition, so every benchmark measures Vortex files whose -compressor may also choose its encodings. It currently holds only `fastlanes.delta`. -`vortex_bench::enable_unstable_encodings` enables it on a session. +compressor may also choose its encodings. It currently holds the `fastlanes.delta` encoding and the +`vortex.ext` layout, which splits only the extension types that a session opts into, so benchmark +files do not use it. `vortex_bench::enable_unstable_encodings` enables it on a session. ### Running SQL Benchmarks diff --git a/vortex-edition/src/declarations/unstable/mod.rs b/vortex-edition/src/declarations/unstable/mod.rs index 5bf265be04c..73400e7f45b 100644 --- a/vortex-edition/src/declarations/unstable/mod.rs +++ b/vortex-edition/src/declarations/unstable/mod.rs @@ -34,6 +34,5 @@ pub static DECLARATION: EditionDeclaration = EditionDeclaration { added: &[ EditionMember::array(&"fastlanes.delta"), EditionMember::layout(&"vortex.ext"), - EditionMember::aggregate(&"vortex.all_non_nan"), ], }; diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 7cadcaed61d..9e904d66394 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -26,7 +26,11 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::nan_count::NanCount; use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; @@ -49,6 +53,7 @@ use vortex_array::assert_arrays_eq; use vortex_array::builders::MapBuilder; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::FieldNames; use vortex_array::dtype::FieldPath; use vortex_array::dtype::MapDType; use vortex_array::dtype::Nullability; @@ -67,6 +72,7 @@ use vortex_array::expr::cast; use vortex_array::expr::col; use vortex_array::expr::eq; use vortex_array::expr::ext_storage; +use vortex_array::expr::fill_null; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::gt_eq; @@ -127,11 +133,14 @@ use vortex_layout::layouts::struct_::StructStrategy; use vortex_layout::layouts::table::TableStrategy; use vortex_layout::layouts::zoned::LegacyStats; use vortex_layout::layouts::zoned::Zoned; +use vortex_layout::scan::metrics::ScanUsage; use vortex_layout::scan::scan_builder::ScanBuilder; use vortex_layout::scan::split_by::DEFAULT_MAX_SPLIT_ROWS; use vortex_layout::scan::split_by::SplitBy; +use vortex_layout::scan::v2::ScanBuilder as PlannedScanBuilder; use vortex_layout::session::LayoutSession; use vortex_layout::session::LayoutSessionExt; +use vortex_mask::Mask; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -146,6 +155,7 @@ use crate::VortexFile; use crate::WriteOptionsSessionExt; use crate::flatbuffers::footer as fb; use crate::footer::SegmentSpec; +use crate::v2::ScanDriver; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty() .with::() @@ -3804,3 +3814,131 @@ async fn extension_layout_follows_enabled_editions( assert_arrays_eq!(field, a, &mut ctx); Ok(()) } + +/// Scans `file` on the classic or the planner-driven executor, returning the rows that match +/// `filter` projected by `projection`, and the number of segments the scan read. +async fn scan_counting_segments( + file: &VortexFile, + planner: bool, + projection: &Expression, + filter: &Expression, +) -> VortexResult<(ArrayRef, u64)> { + let usage = Arc::new(ScanUsage::default()); + let file = file.clone().with_usage(Arc::clone(&usage)); + let projection = projection.bind(file.dtype())?; + let filter = filter.bind(file.dtype())?; + let dtype = projection.dtype().clone(); + let array = if planner { + let builder = PlannedScanBuilder::new(file.session().clone(), file.scan_file()) + .with_projection(projection) + .with_some_filter(Some(filter)); + let chunks: Vec = ScanDriver::new(TokioRuntime::current(), 1, true) + .run(builder) + .try_collect() + .await?; + ChunkedArray::try_new(chunks, dtype)?.into_array() + } else { + file.scan()? + .with_projection(projection) + .with_filter(filter) + .into_array_stream()? + .read_all() + .await? + }; + Ok((array, usage.snapshot().segments_requested)) +} + +/// A float field beneath a nullable struct, written with the default editions only, records its +/// bounds and its NaN count, which float bounds need to prune and every core edition permits. +/// Filters on it return every row they keep in memory on both scans. +/// +/// Where `s` is null, `f` holds a value above every visible one, so the bounds of every zone are +/// looser than the values read through `s`. Neither `s.f > 1e8` nor `s.f < 0` keeps a row, but +/// only the second is ruled out by the bounds, so it reads fewer segments. +#[rstest] +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn float_beneath_a_nullable_struct_prunes_with_default_editions( + #[values(false, true)] planner: bool, +) -> VortexResult<()> { + const ZONE_ROWS: u32 = 1024; + let session = VortexSession::empty() + .with::() + .with::() + .with::(); + crate::register_default_encodings(&session); + for declaration in EDITION_DECLARATIONS { + session.register_edition(declaration)?; + } + session.enable_edition(CORE_2026_08_3)?; + + let rows = 0..4 * ZONE_ROWS; + let valid = |row: u32| !row.is_multiple_of(3); + let f: Buffer = rows + .clone() + .map(|row| { + if valid(row) { + f64::from(row) + 0.5 + } else { + 1e9 + } + }) + .collect(); + let s = StructArray::try_new( + FieldNames::from(["f"]), + vec![f.into_array()], + rows.len(), + Validity::from_iter(rows.clone().map(valid)), + )?; + let ids: Buffer = rows.map(i64::from).collect(); + let table = + StructArray::from_fields(&[("id", ids.into_array()), ("s", s.into_array())])?.into_array(); + + let strategy = crate::strategy::WriteStrategyBuilder::from_session(&session) + .with_row_block_size(usize::try_from(ZONE_ROWS)?) + .with_data_block_target_bytes(None) + .build(); + let mut buffer = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy) + .write(&mut buffer, table.clone().to_array_stream()) + .await?; + let file = session.open_options().open_buffer(buffer)?; + + let mut recorded = Vec::new(); + for layout in file.footer().layout().depth_first_traversal() { + let layout = layout?; + if layout.is::() && layout.dtype().is_float() { + recorded.push(layout.as_::().present_aggregates()); + } + } + let expected: Arc<[String]> = [ + Max.bind(NumericalAggregateOpts::skip_nans()).to_string(), + Min.bind(NumericalAggregateOpts::skip_nans()).to_string(), + NanCount.bind(EmptyOptions).to_string(), + ] + .into(); + assert_eq!(recorded, [expected]); + + let id = get_item("id", root()); + let f = get_item("f", get_item("s", root())); + let mut ctx = session.create_execution_ctx(); + let mut segments = Vec::new(); + for filter in [ + lt(f.clone(), lit(100.0f64)), + gt(f.clone(), lit(1e8f64)), + lt(f, lit(0.0f64)), + ] { + let (actual, read) = scan_counting_segments(&file, planner, &id, &filter).await?; + let keep = table + .clone() + .apply(&fill_null(filter, lit(false)))? + .execute::(&mut ctx)?; + let expected = table.clone().filter(keep)?.apply(&id)?; + assert_arrays_eq!(actual, expected, &mut ctx); + segments.push(read); + } + assert!(segments[2] < segments[1], "segments read: {segments:?}"); + Ok(()) +} diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index 8a9ac278a57..e9ffc25974f 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -15,7 +15,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; @@ -119,11 +118,11 @@ impl LayoutStrategy for ZonedStrategy { .unwrap_or_else(|| default_zoned_aggregate_fns(stream.dtype(), session)); // Fields of a nullable struct are written unmasked: a field holds values in rows where the // struct is null, which reads through the struct return as nulls. A bound over them, such - // as a max, still bounds the field as read, only less tightly, and so does whether no value - // is NaN. A count does not: the null count misses the rows where only the struct is null, - // so a zone it shows without nulls can still hold rows where `is_null(s.a)` is true. Such a - // field records only the statistics that hold under masking, with whether a zone holds no - // NaN in place of its NaN count, and no legacy zone map, whose statistics are fixed. + // as a max, still bounds the field as read, only less tightly. A count does not: the null + // count misses the rows where only the struct is null, so a zone it shows without nulls can + // still hold rows where `is_null(s.a)` is true. Such a field records only the statistics + // that hold under masking and its NaN count, which scans read through the struct only as a + // proof that a zone holds no NaN, and no legacy zone map, whose statistics are fixed. // // TODO(joe): record every aggregate for fields under a nullable struct. The struct // validity has to travel with each chunk, since repartitioning below the struct writer @@ -131,7 +130,7 @@ impl LayoutStrategy for ZonedStrategy { // data child still receives the unmasked chunk. let nullable_ancestor = ctx.has_nullable_ancestor(); if nullable_ancestor { - aggregate_fns = aggregates_under_masking(&aggregate_fns, &ctx); + aggregate_fns = aggregates_under_masking(&aggregate_fns); } // Readers before `vortex.zoned` only know the legacy `vortex.stats` layout. If the write @@ -323,29 +322,18 @@ impl ZonedStrategy { } /// Returns the aggregates of `aggregate_fns` that a field beneath a nullable struct records: those -/// whose statistics [hold under masking](holds_under_masking), and whether a zone holds no NaN in -/// place of a NaN count, where `ctx` allows it. +/// whose statistics [hold under masking](holds_under_masking), and the NaN count. /// -/// Float bounds prune only with a proof that the zone holds no NaN, so without it no comparison of -/// a float field beneath a nullable struct would prune. -fn aggregates_under_masking( - aggregate_fns: &[AggregateFnRef], - ctx: &LayoutWriterContext, -) -> Arc<[AggregateFnRef]> { - let all_non_nan = AllNonNan.bind(EmptyOptions); - let replaces_nan_count = ctx.allows_aggregate(&all_non_nan.id()); - let mut kept = Vec::with_capacity(aggregate_fns.len()); - for aggregate_fn in aggregate_fns { - let aggregate_fn = if replaces_nan_count && aggregate_fn.is::() { - &all_non_nan - } else { - aggregate_fn - }; - if holds_under_masking(aggregate_fn) && !kept.contains(aggregate_fn) { - kept.push(aggregate_fn.clone()); - } - } - kept.into() +/// Float bounds prune only with a proof that the zone holds no NaN, which readers derive from a +/// NaN count of zero. The NaN count of a field also counts the NaNs in the rows the struct hides, +/// so a zone where it is zero holds no NaN as read through the struct either. Through the struct, +/// scans read it only as that proof, and never as a count. +fn aggregates_under_masking(aggregate_fns: &[AggregateFnRef]) -> Arc<[AggregateFnRef]> { + aggregate_fns + .iter() + .filter(|aggregate_fn| holds_under_masking(aggregate_fn) || aggregate_fn.is::()) + .cloned() + .collect() } fn default_zoned_aggregate_fns(dtype: &DType, session: &VortexSession) -> Arc<[AggregateFnRef]> { @@ -389,6 +377,7 @@ mod tests { use rstest::rstest; use vortex_array::ArrayContext; use vortex_array::IntoArray; + use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; @@ -508,7 +497,7 @@ mod tests { } /// A field of a nullable struct holds values in rows the struct nulls out. They loosen its - /// bounds but falsify its counts, so its zone map records only the bounds. + /// bounds but falsify its counts, so the zone map of an integer field records only the bounds. #[test] fn a_nullable_ancestor_records_only_bounds() -> VortexResult<()> { let written = @@ -546,39 +535,24 @@ mod tests { Ok(()) } - /// Beneath a nullable struct, a float field records whether each zone holds no NaN in place - /// of its NaN count, which float bounds need to prune, where the context permits it. An - /// integer field holds no NaN, so it records only its bounds. + /// Beneath a nullable struct, a float field records its NaN count with its bounds, since float + /// bounds prune only with a proof that the zone holds no NaN. Every core edition permits all + /// three. An integer field holds no NaN, so it records only its bounds. #[rstest] - #[case::float(PType::F64, true, true)] - #[case::float_not_permitted(PType::F64, false, false)] - #[case::integer(PType::I32, true, false)] - fn a_nullable_ancestor_records_whether_floats_hold_no_nan( + #[case::float(PType::F64, &[Max.id(), Min.id(), NanCount.id()])] + #[case::integer(PType::I32, &[Max.id(), Min.id()])] + fn a_nullable_ancestor_records_the_nan_count_of_floats( #[case] ptype: PType, - #[case] permitted: bool, - #[case] records: bool, + #[case] expected: &[AggregateFnId], ) { let dtype = DType::from(ptype); - let mut ctx = LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor(); - if !permitted { - ctx = ctx.with_allowed_aggregates(HashSet::from_iter([ - Min.id(), - Max.id(), - NanCount.id(), - NullCount.id(), - ])); - } let aggregate_fns = - aggregates_under_masking(&default_zoned_aggregate_fns(&dtype, &SESSION), &ctx); + aggregates_under_masking(&default_zoned_aggregate_fns(&dtype, &SESSION)); let recorded = AggregateStatsAccumulator::new(&dtype, &aggregate_fns) .aggregate_fns() .iter() - .map(|aggregate_fn| aggregate_fn.id().to_string()) + .map(|aggregate_fn| aggregate_fn.id()) .collect::>(); - let mut expected = vec![Max.id().to_string(), Min.id().to_string()]; - if records { - expected.push(AllNonNan.id().to_string()); - } assert_eq!(recorded, expected); } diff --git a/vortex/editions/unstable/unstable2026.10.0.toml b/vortex/editions/unstable/unstable2026.10.0.toml index 929a9125600..e5cdc90a3bc 100644 --- a/vortex/editions/unstable/unstable2026.10.0.toml +++ b/vortex/editions/unstable/unstable2026.10.0.toml @@ -19,9 +19,7 @@ layouts = [ "vortex.ext", ] dtypes = [] -aggregates = [ - "vortex.all_non_nan", -] +aggregates = [] # The edition's full membership: the members above, plus every member of earlier # editions of the family. @@ -33,6 +31,4 @@ layouts = [ "vortex.ext", ] dtypes = [] -aggregates = [ - "vortex.all_non_nan", -] +aggregates = [] From caa08674b9eb7e646c13d6b950110c242df2c872 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 10:58:00 +0000 Subject: [PATCH 07/13] Read single fields of list elements on both scans A repeated protobuf message is a list of structs, and reading one of its fields, `list_transform(items, x -> x.sku)`, read every element field: the list reader knew only validity, offsets or everything. The planner scan could not read a list layout at all ("Plan vortex.plan.list_pack has no pipeline implementation"). The classic list reader now projects the elements with the lambda body, so it reads only the element columns that the lambda uses. The planner compiles `ListPack` into a source that reads the offsets and validity of the selected lists first, then scans only the elements of selected, valid lists, with the same element pushdown. Both scans also move strict functions that cannot fail below the validity of a nullable struct, so the pushdown reaches lists inside nullable protobuf messages. A lambda that can fail never runs on elements that in-memory `list_transform` would skip. The list layout stays out of the unstable edition. Signed-off-by: Connor Tsui --- vortex-layout/src/layouts/list/expr.rs | 117 -- vortex-layout/src/layouts/list/expr/mod.rs | 281 ++++ vortex-layout/src/layouts/list/expr/tests.rs | 211 +++ vortex-layout/src/layouts/list/reader.rs | 1332 ----------------- vortex-layout/src/layouts/list/reader/mod.rs | 785 ++++++++++ .../src/layouts/list/reader/tests.rs | 989 ++++++++++++ vortex-layout/src/layouts/struct_/reader.rs | 146 ++ vortex-layout/src/scan/v2/tests/lists.rs | 389 +++++ .../src/scan/v2/{tests.rs => tests/mod.rs} | 119 +- vortex-scan/src/plan/builtins/list_pack.rs | 180 --- .../src/plan/builtins/list_pack/execute.rs | 315 ++++ .../src/plan/builtins/list_pack/expr.rs | 216 +++ .../src/plan/builtins/list_pack/mod.rs | 476 ++++++ .../src/plan/builtins/list_pack/tests.rs | 368 +++++ vortex-scan/src/plan/builtins/mod.rs | 2 + vortex-scan/src/plan/builtins/pack/mask.rs | 98 +- vortex-scan/src/plan/builtins/pack/mod.rs | 5 +- vortex-scan/src/plan/mod.rs | 1 + vortex-scan/src/plan/optimize/registry.rs | 5 + 19 files changed, 4365 insertions(+), 1670 deletions(-) delete mode 100644 vortex-layout/src/layouts/list/expr.rs create mode 100644 vortex-layout/src/layouts/list/expr/mod.rs create mode 100644 vortex-layout/src/layouts/list/expr/tests.rs delete mode 100644 vortex-layout/src/layouts/list/reader.rs create mode 100644 vortex-layout/src/layouts/list/reader/mod.rs create mode 100644 vortex-layout/src/layouts/list/reader/tests.rs create mode 100644 vortex-layout/src/scan/v2/tests/lists.rs rename vortex-layout/src/scan/v2/{tests.rs => tests/mod.rs} (92%) delete mode 100644 vortex-scan/src/plan/builtins/list_pack.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/execute.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/expr.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/mod.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/tests.rs diff --git a/vortex-layout/src/layouts/list/expr.rs b/vortex-layout/src/layouts/list/expr.rs deleted file mode 100644 index 8c10e400ad8..00000000000 --- a/vortex-layout/src/layouts/list/expr.rs +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::bound::not; -use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; -use vortex_array::scalar_fn::fns::is_null::IsNull; -use vortex_array::scalar_fn::fns::list_length::ListLength; -use vortex_error::VortexResult; - -/// The minimal set of list children an expression needs for evaluation. -/// -/// For example: -/// - `is_null(root())` only needs the validity child. -/// - `list_length(root())` only needs the offsets and validity children. -/// - `root()` needs elements, offsets, and validity children. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub(super) enum ListChildrenNeeded { - /// Only the validity child is needed (`is_null` / `is_not_null`). - Validity, - /// Only the offsets and validity children are needed (`list_length`). - OffsetsAndValidity, - /// All children are needed. - All, -} - -/// The minimal set of list children needed to evaluate a bound expression. -pub(super) fn get_necessary_bound_list_children(expr: &BoundExpression) -> ListChildrenNeeded { - if is_bound_null_root(expr) { - return ListChildrenNeeded::Validity; - } - - if is_bound_list_length_root(expr) { - return ListChildrenNeeded::OffsetsAndValidity; - } - - if expr.is_root() { - return ListChildrenNeeded::All; - } - - expr.children() - .iter() - .map(get_necessary_bound_list_children) - .max() - .unwrap_or(ListChildrenNeeded::Validity) -} - -fn is_bound_null_root(expr: &BoundExpression) -> bool { - (expr.as_scalar().is_some_and(|f| f.is::()) - || expr.as_scalar().is_some_and(|f| f.is::())) - && expr.children().len() == 1 - && expr.children()[0].is_root() -} - -fn is_bound_list_length_root(expr: &BoundExpression) -> bool { - expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() -} - -/// Rewrite a validity-class expression so it can be evaluated against the list's validity bool -/// array (`true` == valid row): `is_not_null(root())` becomes `root()` and `is_null(root())` -/// becomes `not(root())`. All other nodes are rebuilt with rewritten children. -pub(super) fn rewrite_validity_expr(expr: &BoundExpression) -> VortexResult { - let validity_dtype = DType::Bool(Nullability::NonNullable); - rewrite_validity_expr_with_root(expr, &validity_dtype) -} - -fn rewrite_validity_expr_with_root( - expr: &BoundExpression, - root_dtype: &DType, -) -> VortexResult { - if expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() - { - return Ok(BoundExpression::new_root(root_dtype.clone())); - } - if expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() - { - return Ok(not(BoundExpression::new_root(root_dtype.clone()))); - } - if expr.is_root() { - return Ok(BoundExpression::new_root(root_dtype.clone())); - } - - let children = expr - .children() - .iter() - .map(|child| rewrite_validity_expr_with_root(child, root_dtype)) - .collect::>>()?; - expr.clone().with_children(children) -} - -/// Rewrite an offsets-class expression so it can be evaluated against an array of list lengths. -/// `list_length(root())` becomes `root()`. Other references to `root()` are left intact: for -/// offsets-class expressions they can only be validity checks, and the lengths array carries the -/// same validity as the original list. -pub(super) fn rewrite_offsets_expr( - expr: &BoundExpression, - lengths_dtype: &DType, -) -> VortexResult { - if is_bound_list_length_root(expr) || expr.is_root() { - return Ok(BoundExpression::new_root(lengths_dtype.clone())); - } - - let children = expr - .children() - .iter() - .map(|child| rewrite_offsets_expr(child, lengths_dtype)) - .collect::>>()?; - expr.clone().with_children(children) -} diff --git a/vortex-layout/src/layouts/list/expr/mod.rs b/vortex-layout/src/layouts/list/expr/mod.rs new file mode 100644 index 00000000000..aef3c5d36a3 --- /dev/null +++ b/vortex-layout/src/layouts/list/expr/mod.rs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Which list children an expression reads, and the rewrites that evaluate it over them. + +#[cfg(test)] +mod tests; + +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::bound::get_item; +use vortex_array::expr::bound::not; +use vortex_array::expr::bound::pack; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_array::scalar_fn::fns::list_length::ListLength; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_scan::plan::ListTransforms; + +/// The minimal set of list children an expression needs for evaluation. +/// +/// For example: +/// - `is_null(root())` only needs the validity child. +/// - `list_length(root())` only needs the offsets and validity children. +/// - `root()` needs elements, offsets, and validity children. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum ListChildrenNeeded { + /// Only the validity child is needed (`is_null` / `is_not_null`). + Validity, + /// Only the offsets and validity children are needed (`list_length`). + OffsetsAndValidity, + /// All children are needed. + All, +} + +/// The minimal set of list children needed to evaluate a bound expression. +pub(super) fn get_necessary_bound_list_children(expr: &BoundExpression) -> ListChildrenNeeded { + if is_bound_null_root(expr) { + return ListChildrenNeeded::Validity; + } + + if is_bound_list_length_root(expr) { + return ListChildrenNeeded::OffsetsAndValidity; + } + + if expr.is_root() { + return ListChildrenNeeded::All; + } + + expr.children() + .iter() + .map(get_necessary_bound_list_children) + .max() + .unwrap_or(ListChildrenNeeded::Validity) +} + +fn is_bound_null_root(expr: &BoundExpression) -> bool { + (expr.as_scalar().is_some_and(|f| f.is::()) + || expr.as_scalar().is_some_and(|f| f.is::())) + && expr.children().len() == 1 + && expr.children()[0].is_root() +} + +fn is_bound_list_length_root(expr: &BoundExpression) -> bool { + expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() +} + +/// Rewrite a validity-class expression so it can be evaluated against the list's validity bool +/// array (`true` == valid row): `is_not_null(root())` becomes `root()` and `is_null(root())` +/// becomes `not(root())`. All other nodes are rebuilt with rewritten children. +pub(super) fn rewrite_validity_expr(expr: &BoundExpression) -> VortexResult { + let validity_dtype = DType::Bool(Nullability::NonNullable); + rewrite_validity_expr_with_root(expr, &validity_dtype) +} + +fn rewrite_validity_expr_with_root( + expr: &BoundExpression, + root_dtype: &DType, +) -> VortexResult { + if expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() + { + return Ok(BoundExpression::new_root(root_dtype.clone())); + } + if expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() + { + return Ok(not(BoundExpression::new_root(root_dtype.clone()))); + } + if expr.is_root() { + return Ok(BoundExpression::new_root(root_dtype.clone())); + } + + let children = expr + .children() + .iter() + .map(|child| rewrite_validity_expr_with_root(child, root_dtype)) + .collect::>>()?; + expr.clone().with_children(children) +} + +/// Rewrite an offsets-class expression so it can be evaluated against an array of list lengths. +/// `list_length(root())` becomes `root()`. Other references to `root()` are left intact: for +/// offsets-class expressions they can only be validity checks, and the lengths array carries the +/// same validity as the original list. +pub(super) fn rewrite_offsets_expr( + expr: &BoundExpression, + lengths_dtype: &DType, +) -> VortexResult { + if is_bound_list_length_root(expr) || expr.is_root() { + return Ok(BoundExpression::new_root(lengths_dtype.clone())); + } + + let children = expr + .children() + .iter() + .map(|child| rewrite_offsets_expr(child, lengths_dtype)) + .collect::>>()?; + expr.clone().with_children(children) +} + +/// An expression over a list that reads the list elements only through the lambdas of +/// `list_transform(root, lambda)` nodes, rewritten so that those lambdas run over the elements +/// child. +/// +/// The reader evaluates [`Self::elements`] over the elements child, rebuilds lists over the +/// projected elements with [`Self::rebuild`], and evaluates [`Self::lists`] over them. A lambda +/// that reads one field of struct elements, as in `list_transform(root, x -> x.sku)`, reaches the +/// elements layout as `$.sku`, so only the column of that field is read. +/// +/// The identity projection reads the elements as stored: its elements expression is the elements +/// root and its list expression is the original expression. +#[derive(Debug)] +pub(super) struct ElementProjection { + elements: BoundExpression, + /// The names of the struct of lists that [`Self::rebuild`] builds, one list per lambda, or + /// `None` when it builds a single list. + lists_fields: Option, + lists: BoundExpression, + fallible: bool, +} + +impl ElementProjection { + /// Reads the elements as stored and evaluates `expr` over the rebuilt list. + pub(super) fn identity(expr: &BoundExpression, elements_dtype: &DType) -> Self { + Self { + elements: BoundExpression::new_root(elements_dtype.clone()), + lists_fields: None, + lists: expr.clone(), + fallible: false, + } + } + + /// Pushes the lambdas of the `list_transform(root, lambda)` nodes of `expr` into the elements. + /// + /// Each lambda body becomes an expression over the elements, with its parameter rebound to + /// the elements root. The bodies of several distinct lambdas are packed into a struct, which + /// rebuilds into a struct of lists that share the offsets and validity. + /// + /// Returns `None` when `expr` has no such node, or reads the list root in another way than + /// through these nodes, `is_null(root)`, `is_not_null(root)` and `list_length(root)`. The last + /// three need only the offsets and validity, which every rebuilt list keeps. + pub(super) fn push_down(expr: &BoundExpression) -> VortexResult> { + let Some(transforms) = ListTransforms::of(expr)? else { + return Ok(None); + }; + + let (elements, lists_fields, lists_root) = + if let ([transform], [body]) = (transforms.transforms(), transforms.bodies()) { + let lists_root = BoundExpression::new_root(transform.dtype().clone()); + (body.clone(), None, lists_root) + } else { + let names: FieldNames = (0..transforms.bodies().len()) + .map(|idx| idx.to_string()) + .collect(); + let elements = pack( + names + .iter() + .cloned() + .zip(transforms.bodies().iter().cloned()), + Nullability::NonNullable, + ); + let lists_dtype = DType::Struct( + StructFields::new( + names.clone(), + transforms + .transforms() + .iter() + .map(|transform| transform.dtype().clone()) + .collect(), + ), + Nullability::NonNullable, + ); + ( + elements, + Some(names), + BoundExpression::new_root(lists_dtype), + ) + }; + + let list_at = |idx: usize| match &lists_fields { + Some(names) => get_item(names[idx].clone(), lists_root.clone()), + None => lists_root.clone(), + }; + let lists = transforms.rewrite(expr, |idx| Ok(list_at(idx)), &list_at(0))?; + + Ok(Some(Self { + elements, + lists_fields, + lists, + fallible: transforms.is_fallible(), + })) + } + + /// The expression over the elements child. + pub(super) fn elements(&self) -> &BoundExpression { + &self.elements + } + + /// The expression over what [`Self::rebuild`] builds. It has the dtype of the original + /// expression. + pub(super) fn lists(&self) -> &BoundExpression { + &self.lists + } + + /// Whether evaluating [`Self::elements`] can fail. + /// + /// `list_transform` runs such a lambda only on the elements of valid lists, so the reader must + /// not evaluate it over the elements of null or unselected lists either. + pub(super) fn is_fallible(&self) -> bool { + self.fallible + } + + /// Rebuilds what [`Self::lists`] reads from the projected `elements` and the `offsets` and + /// `validity` of the lists. + /// + /// # Safety + /// + /// `elements` must hold the projection of every element that `offsets` references, at the + /// position of that element, and `offsets` and `validity` must describe valid lists over them. + pub(super) unsafe fn rebuild( + &self, + elements: ArrayRef, + offsets: ArrayRef, + validity: Validity, + ) -> VortexResult { + let Some(names) = &self.lists_fields else { + // SAFETY: the caller guarantees the list invariants. + return Ok( + unsafe { ListArray::new_unchecked(elements, offsets, validity) }.into_array(), + ); + }; + let len = offsets.len().saturating_sub(1); + let lists = names + .iter() + .map(|name| { + let field = elements.get_item(name.clone())?; + // SAFETY: every field of the packed projection has one value per element, so the + // caller's guarantee holds for each field. + Ok( + unsafe { ListArray::new_unchecked(field, offsets.clone(), validity.clone()) } + .into_array(), + ) + }) + .collect::>>()?; + Ok(StructArray::try_new(names.clone(), lists, len, Validity::NonNullable)?.into_array()) + } +} diff --git a/vortex-layout/src/layouts/list/expr/tests.rs b/vortex-layout/src/layouts/list/expr/tests.rs new file mode 100644 index 00000000000..74d3322ca38 --- /dev/null +++ b/vortex-layout/src/layouts/list/expr/tests.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::list::ListArrayExt; +use vortex_array::arrays::list::ListArraySlotsExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::and; +use vortex_array::expr::checked_add; +use vortex_array::expr::eq; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; + +use super::ElementProjection; +use crate::test::SESSION; + +/// `[{a, b}, {c, d}]`, `null` (hiding `[{e, i32::MAX}]`), `[]` and `[{null, 3}]`, as lists of +/// `{sku: utf8?, qty: i32}`. +fn items() -> VortexResult { + let elements = StructArray::from_fields(&[ + ( + "sku", + VarBinViewArray::from_iter_nullable_str([Some("a"), Some("c"), Some("e"), None]) + .into_array(), + ), + ("qty", buffer![1i32, 2, i32::MAX, 3].into_array()), + ])? + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 4].into_array(), + Validity::from_iter([true, false, true, true]), + &mut ctx, + ) +} + +fn sku(param: &str) -> VortexResult { + Lambda::new([param], get_item("sku", var(param))) +} + +fn qty(param: &str) -> VortexResult { + Lambda::new([param], get_item("qty", var(param))) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on the element of the null list. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// Rewrites `expr` over the lists of [`items`]. +fn push_down(expr: &Expression) -> VortexResult> { + ElementProjection::push_down(&expr.bind(items()?.dtype())?) +} + +/// Evaluates a projection the way the reader does, over the whole of `list`. +fn evaluate(projection: &ElementProjection, list: &ListArray) -> VortexResult { + let elements = list.elements().clone().apply_bound(projection.elements())?; + // SAFETY: the offsets and validity are those of a valid list over the projected elements. + let lists = + unsafe { projection.rebuild(elements, list.offsets().clone(), list.list_validity()) }?; + lists.apply_bound(projection.lists()) +} + +#[rstest] +#[case::one_field(list_transform(root(), sku("x")?), "$.sku", "$")] +#[case::param_name(list_transform(root(), sku("item")?), "$.sku", "$")] +#[case::predicate( + and( + is_not_null(root()), + list_contains(list_transform(root(), sku("x")?), lit("c")), + ), + "$.sku", + "(is_not_null($) and vortex.list.contains($, \"c\"))" +)] +#[case::length( + pack( + [("skus", list_transform(root(), sku("x")?)), ("len", list_length(root()))], + Nullability::NonNullable, + ), + "$.sku", + "pack(skus: $, len: vortex.list.length($))" +)] +#[case::repeated_lambda( + pack( + [("a", list_transform(root(), sku("x")?)), ("b", list_transform(root(), sku("x")?))], + Nullability::NonNullable, + ), + "$.sku", + "pack(a: $, b: $)" +)] +#[case::two_lambdas( + pack( + [ + ("skus", list_transform(root(), sku("x")?)), + ("qtys", list_transform(root(), qty("x")?)), + ("len", list_length(root())), + ], + Nullability::NonNullable, + ), + "pack(0: $.sku, 1: $.qty)", + "pack(skus: $.0, qtys: $.1, len: vortex.list.length($.0))" +)] +#[case::outer_lambda_in_memory( + list_transform( + list_transform(root(), qty("x")?), + Lambda::new(["y"], eq(var("y"), lit(1i32)))?, + ), + "$.qty", + "vortex.list.transform($, (y) -> ($.y = 1i32))" +)] +fn pushes_lambdas_into_elements( + #[case] expr: Expression, + #[case] elements: &str, + #[case] lists: &str, +) -> VortexResult<()> { + let projection = push_down(&expr)?.expect("reads the elements only through lambdas"); + assert_eq!(projection.elements().to_string(), elements); + assert_eq!(projection.lists().to_string(), lists); + assert!(!projection.is_fallible()); + + let list = items()?; + let expected = list.clone().into_array().apply(&expr)?; + let mut ctx = SESSION.create_execution_ctx(); + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} + +/// A lambda that can fail makes the projection fallible, so the reader runs it only on the +/// elements of valid lists. +#[test] +fn fallible_lambda_is_fallible() -> VortexResult<()> { + let projection = push_down(&qty_plus_one()?)?.expect("reads the elements through a lambda"); + assert_eq!(projection.elements().to_string(), "($.qty + 1i32)"); + assert!(projection.is_fallible()); + Ok(()) +} + +#[rstest] +#[case::root(root())] +#[case::no_lambda(list_length(root()))] +#[case::mixed(pack( + [("items", root()), ("skus", list_transform(root(), sku("x")?))], + Nullability::NonNullable, +))] +fn keeps_element_reads(#[case] expr: Expression) -> VortexResult<()> { + assert!(push_down(&expr)?.is_none()); + Ok(()) +} + +/// The identity projection reads the elements as stored and evaluates the expression over the +/// rebuilt list. +#[test] +fn identity_reads_stored_elements() -> VortexResult<()> { + let list = items()?; + let expr = list_contains(list_transform(root(), qty("x")?), lit(3i32)); + let projection = + ElementProjection::identity(&expr.bind(list.dtype())?, list.elements().dtype()); + assert!(projection.elements().is_root()); + assert!(!projection.is_fallible()); + + let expected = list.clone().into_array().apply(&expr)?; + let mut ctx = SESSION.create_execution_ctx(); + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} + +/// Lists of `i32` pushed into a flat elements child keep their shape. +#[test] +fn primitive_elements() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let list = ListArray::try_new( + PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), + buffer![0u32, 0, 2, 3].into_array(), + Validity::NonNullable, + &mut ctx, + )?; + let expr = list_transform(root(), Lambda::new(["x"], eq(var("x"), lit(3i32)))?); + let projection = ElementProjection::push_down(&expr.bind(list.dtype())?)? + .expect("reads the elements through a lambda"); + assert_eq!(projection.elements().to_string(), "($ = 3i32)"); + assert!(matches!(projection.lists().dtype(), DType::List(..))); + + let expected = list.clone().into_array().apply(&expr)?; + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} diff --git a/vortex-layout/src/layouts/list/reader.rs b/vortex-layout/src/layouts/list/reader.rs deleted file mode 100644 index 334a4f21efb..00000000000 --- a/vortex-layout/src/layouts/list/reader.rs +++ /dev/null @@ -1,1332 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::ops::Range; -use std::sync::Arc; - -use futures::FutureExt; -use futures::future::BoxFuture; -use futures::try_join; -use vortex_array::ArrayRef; -use vortex_array::Canonical; -use vortex_array::IntoArray; -use vortex_array::MaskFuture; -use vortex_array::VortexSessionExecute; -use vortex_array::arrays::ConstantArray; -use vortex_array::arrays::ListArray; -use vortex_array::builtins::ArrayBuiltins; -use vortex_array::dtype::DType; -use vortex_array::dtype::FieldMask; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::PType; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::root; -use vortex_array::scalar_fn::fns::operators::Operator; -use vortex_array::validity::Validity; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_mask::Mask; -use vortex_session::VortexSession; - -use crate::ArrayFuture; -use crate::LayoutReader; -use crate::LayoutReaderContext; -use crate::LayoutReaderRef; -use crate::RowSplits; -use crate::SplitRange; -use crate::layouts::list::ListLayout; -use crate::layouts::list::expr::ListChildrenNeeded; -use crate::layouts::list::expr::get_necessary_bound_list_children; -use crate::layouts::list::expr::rewrite_offsets_expr; -use crate::layouts::list::expr::rewrite_validity_expr; -use crate::segments::SegmentSource; - -type OptionalArrayFuture = BoxFuture<'static, VortexResult>>; - -/// The threshold of mask density below which we push the input mask into projection evaluation, -/// and above which we evaluate the expression over all rows and intersect afterward. -const EXPR_EVAL_THRESHOLD: f64 = 0.2; - -/// Minimum size of the outer-row split grid, so lists in small files still fan out. -const MIN_LIST_SPLIT_COUNT: u64 = 64; - -/// Outer rows per grid cell that the grid grows to stay under for large files. -const TARGET_LIST_SPLIT_ROWS: u64 = 8192; - -/// Number of cells in the outer-row split grid: at least [`MIN_LIST_SPLIT_COUNT`], and enough -/// that a cell covers at most about [`TARGET_LIST_SPLIT_ROWS`] outer rows. -fn list_split_grid_size(outer_row_count: u64) -> u64 { - outer_row_count - .div_ceil(TARGET_LIST_SPLIT_ROWS) - .next_power_of_two() - .max(MIN_LIST_SPLIT_COUNT) -} - -/// Reader for [`ListLayout`]. -#[derive(Clone)] -pub struct ListReader { - layout: ListLayout, - name: Arc, - session: VortexSession, - elements: LayoutReaderRef, - offsets: LayoutReaderRef, - validity: Option, -} - -impl ListReader { - pub(super) fn try_new( - layout: ListLayout, - name: Arc, - segment_source: Arc, - session: VortexSession, - ctx: &LayoutReaderContext, - ) -> VortexResult { - let elements = layout.elements()?.new_reader( - format!("{name}.elements").into(), - Arc::clone(&segment_source), - &session, - ctx, - )?; - let offsets = layout.offsets()?.new_reader( - format!("{name}.offsets").into(), - Arc::clone(&segment_source), - &session, - ctx, - )?; - let validity = layout - .validity()? - .map(|v| { - v.new_reader( - format!("{name}.validity").into(), - Arc::clone(&segment_source), - &session, - ctx, - ) - }) - .transpose()?; - - Ok(Self { - layout, - name, - session, - elements, - offsets, - validity, - }) - } - - /// Projection for [`ListChildrenNeeded::Validity`] expressions. Reads only the validity child, - /// synthesizing all-valid for a non-nullable list, and never touches the offsets or elements. - fn project_validity( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let validity_reader = self.validity.clone(); - let nullability = self.layout.dtype().nullability(); - let row_range = row_range.clone(); - // Evaluate the rewritten expression against the validity bool array (true == valid row). - let rewritten = rewrite_validity_expr(expr)?; - - Ok(async move { - let mask = mask.await?; - let row_count = usize::try_from(row_range.end - row_range.start)?; - let out_len = if mask.all_true() { - row_count - } else { - mask.true_count() - }; - - let validity_array = match validity_reader.as_ref() { - Some(v) => { - let root = root().bind(v.dtype())?; - Some( - v.projection_evaluation(&row_range, &root, MaskFuture::ready(mask))? - .await?, - ) - } - None => None, - }; - - let validity = create_validity(validity_array, nullability).to_array(out_len); - - validity.apply_bound(&rewritten) - } - .boxed()) - } - - /// Projection for [`ListChildrenNeeded::All`] expressions. - /// - /// An all-true mask over the full local range reads every child concurrently. Otherwise, the - /// read is bounded to the first and last selected list. - fn project_all( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let is_full_range = row_range.start == 0 && row_range.end == self.layout.row_count(); - let reader = self.clone(); - let row_range = row_range.clone(); - let expr = expr.clone(); - Ok(async move { - let mask = mask.await?; - if is_full_range && mask.all_true() { - reader.project_all_full(&expr)?.await - } else { - reader.project_all_bounded(&row_range, &expr, mask)?.await - } - } - .boxed()) - } - - /// Fetch the complete `elements`, `offsets`, and `validity` children concurrently. - fn project_all_full(&self, expr: &BoundExpression) -> VortexResult { - let row_count = self.layout.row_count(); - let elements_row_count = self.elements.row_count(); - let nullability = self.layout.dtype().nullability(); - let expr = expr.clone(); - - let offsets_fut = self.fetch_raw_offsets(&(0..row_count))?; - let elements_fut = self.fetch_raw_elements(&(0..elements_row_count))?; - let validity_fut = fetch_validity( - self.validity.as_ref(), - &(0..row_count), - MaskFuture::new_true(usize::try_from(row_count)?), - )?; - - Ok(async move { - let (offsets, elements, validity) = try_join!(offsets_fut, elements_fut, validity_fut)?; - // SAFETY: ListLayout is constructed from a valid ListArray and reading its children - // without transformation preserves the list invariants. - let list = unsafe { - ListArray::new_unchecked(elements, offsets, create_validity(validity, nullability)) - } - .into_array(); - list.apply_bound(&expr) - } - .boxed()) - } - - /// Bounded read for a sub-range or selective mask. - /// - /// Crops leading and trailing unselected lists, reads their offsets, and translates the first - /// and last offset into the element-row range to fetch. Any holes in the selection are filtered - /// after reconstructing the list array. - fn project_all_bounded( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: Mask, - ) -> VortexResult { - // Crop to the smallest contiguous row range containing every selected list. - let Some(selected_rows) = selected_row_range(&mask) else { - let empty = Canonical::empty(expr.dtype()).into_array(); - return Ok(async move { Ok(empty) }.boxed()); - }; - - let selected_mask = mask.slice(selected_rows.clone()); - let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) - ..(row_range.start + u64::try_from(selected_rows.end)?); - - let nullability = self.layout.dtype().nullability(); - let expr = expr.clone(); - let reader = self.clone(); - let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; - - Ok(async move { - let offsets = offsets_fut.await?; - - let elements_range = elements_range_from_offsets(&offsets, &reader.session)?; - let elements_fut = reader.fetch_raw_elements(&elements_range)?; - let validity_fut = fetch_validity( - reader.validity.as_ref(), - &selected_row_range, - MaskFuture::new_true(selected_mask.len()), - )?; - let (elements, validity) = try_join!(elements_fut, validity_fut)?; - - let offsets = rebase_offsets(offsets, elements_range.start)?; - // SAFETY: the selected offsets remain monotonically increasing, rebasing them against - // the selected element range preserves their lengths, and validity covers the same - // cropped list rows. - let list = unsafe { - ListArray::new_unchecked(elements, offsets, create_validity(validity, nullability)) - } - .into_array(); - let list = if selected_mask.all_true() { - list - } else { - list.filter(selected_mask)? - }; - list.apply_bound(&expr) - } - .boxed()) - } - - /// Projection for [`ListChildrenNeeded::OffsetsAndValidity`] expressions. Only reads offsets and validity children. - fn project_offsets_validity( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let offsets = self.fetch_raw_offsets(row_range)?; - let reader = self.clone(); - let row_range = row_range.clone(); - let lengths_dtype = DType::Primitive(PType::U64, self.layout.dtype().nullability()); - let rewritten = rewrite_offsets_expr(expr, &lengths_dtype)?; - - Ok(async move { - let mask = mask.await?; - let row_count = usize::try_from(row_range.end - row_range.start)?; - let nullability = reader.layout.dtype().nullability(); - - let validity_mask = if mask.all_true() { - MaskFuture::new_true(row_count) - } else { - MaskFuture::ready(mask.clone()) - }; - let validity_fut = fetch_validity(reader.validity.as_ref(), &row_range, validity_mask)?; - - let offsets = offsets.await?; - let lengths = list_lengths_from_offsets(offsets)?; - let lengths = if mask.all_true() { - lengths - } else { - lengths.filter(mask)? - }; - let validity = validity_fut.await?; - let lengths = apply_lengths_validity(lengths, validity, nullability)?; - - lengths.apply_bound(&rewritten) - } - .boxed()) - } - - /// Fire the offsets read for `row_range` in list row space. The offsets child has an extra entry, so reading - /// `row_range` maps to offsets in `[row_range.start..row_range.end + 1)`. - /// - /// No mask or expression is applied. - fn fetch_raw_offsets(&self, row_range: &Range) -> VortexResult { - let offsets_range = row_range.start..(row_range.end + 1); - let offsets_count = usize::try_from(offsets_range.end - offsets_range.start)?; - let root = root().bind(self.offsets.dtype())?; - self.offsets.projection_evaluation( - &offsets_range, - &root, - MaskFuture::new_true(offsets_count), - ) - } - - /// Fire the elements read for `row_range` in element space. - /// - /// No mask or expression is applied. - fn fetch_raw_elements(&self, row_range: &Range) -> VortexResult { - let row_count = usize::try_from(row_range.end - row_range.start)?; - let root = root().bind(self.elements.dtype())?; - self.elements - .projection_evaluation(row_range, &root, MaskFuture::new_true(row_count)) - } -} - -fn selected_row_range(mask: &Mask) -> Option> { - Some(mask.first()?..mask.last()? + 1) -} - -fn create_validity(validity_array: Option, nullability: Nullability) -> Validity { - match validity_array { - Some(arr) => Validity::Array(arr), - None => match nullability { - Nullability::Nullable => Validity::AllValid, - Nullability::NonNullable => Validity::NonNullable, - }, - } -} - -impl LayoutReader for ListReader { - fn name(&self) -> &Arc { - &self.name - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } - - fn dtype(&self) -> &DType { - self.layout.dtype() - } - - fn row_count(&self) -> u64 { - self.layout.row_count() - } - - fn register_splits( - &self, - _field_mask: &[FieldMask], - split_range: &SplitRange, - splits: &mut RowSplits, - ) -> VortexResult<()> { - split_range.check_bounds(self.layout.row_count())?; - - // Splits are difficult to calculate because all children live in different row coordinate spaces. - // List elements typically comprise the majority of the data in a list, and validity/offsets can be treated - // as metadata. We therefore want to parallelize the scan based on element work. - // - // Scan splits must be expressed in the list layout's outer-row space, but the elements child - // reports its natural boundaries in element-row space. So we translate the element splits using a - // heuristic to outer-row space. - - let element_row_count = self.elements.row_count(); - if element_row_count != 0 { - let mut element_splits = RowSplits::new_capacity(128); - self.elements.register_splits( - &[FieldMask::All], - &SplitRange::root(0..element_row_count)?, - &mut element_splits, - )?; - - let row_range = split_range.row_range(); - let grid_size = list_split_grid_size(self.layout.row_count()); - let mut last_split = None; - for element_split in element_splits.into_sorted_deduped() { - let Some(split) = map_element_split_to_outer_grid( - element_split, - element_row_count, - self.layout.row_count(), - grid_size, - ) else { - continue; - }; - if split <= row_range.start { - continue; - } - if split >= row_range.end { - break; - } - if last_split == Some(split) { - continue; - } - splits.push( - split_range - .row_offset() - .checked_add(split) - .vortex_expect("List layout split offset overflow"), - ); - last_split = Some(split); - } - } - splits.push(split_range.root_row_range().end); - Ok(()) - } - - // TODO(mk): handle zones for list elements - fn pruning_evaluation( - &self, - _row_range: &Range, - _expr: &BoundExpression, - mask: Mask, - ) -> VortexResult { - Ok(MaskFuture::ready(mask)) - } - - fn filter_evaluation( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let len = mask.len(); - let reader = self.clone(); - let row_range = row_range.clone(); - let expr = expr.clone(); - let session = self.session.clone(); - - Ok(MaskFuture::new(len, async move { - let mask = mask.await?; - - if mask.all_false() { - return Ok(mask); - } - - let mut ctx = session.create_execution_ctx(); - if mask.density() < EXPR_EVAL_THRESHOLD { - let predicate = reader - .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? - .await?; - let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; - Ok(mask.intersect_by_rank(&predicate_mask)) - } else { - let predicate = reader - .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? - .await?; - let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; - Ok(mask & &predicate_mask) - } - })) - } - - /// Reads only the list children needed to evaluate `expr`. - /// - /// Validity-only expressions avoid offsets and elements, length expressions read offsets and - /// validity, and general expressions reconstruct a list from all applicable children. - fn projection_evaluation( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - // Read as little as possible based on which list children the expression needs. - match get_necessary_bound_list_children(expr) { - ListChildrenNeeded::Validity => self.project_validity(row_range, expr, mask), - ListChildrenNeeded::OffsetsAndValidity => { - self.project_offsets_validity(row_range, expr, mask) - } - ListChildrenNeeded::All => self.project_all(row_range, expr, mask), - } - } -} - -/// Converts a natural boundary from element-row space into an approximate outer-row scan split. -/// -/// Scan splits must be expressed in the list layout's outer-row space, but the elements child -/// reports its natural boundaries in element-row space. Translating a boundary exactly would -/// require consulting the list offsets, so this function instead preserves its relative position: -/// -/// ```text -/// element_split / element_row_count ≈ outer_split / outer_row_count -/// ``` -/// -/// The relative position is first rounded onto a grid containing at most `max_split_count` scan -/// ranges, then mapped into outer-row space. Multiple element boundaries may therefore map to the -/// same outer split and are deduplicated by the caller. With a grid size of 64, at most 63 interior -/// splits—and therefore 64 scan ranges—can be produced. -/// -/// The result is only a task-sizing hint. It is always between outer rows, but it is not guaranteed -/// to correspond exactly to the original physical element boundary. Endpoint boundaries are -/// omitted because they do not subdivide the scan -fn map_element_split_to_outer_grid( - element_split: u64, - element_row_count: u64, - outer_row_count: u64, - max_split_count: u64, -) -> Option { - if element_split == 0 - || element_split >= element_row_count - || outer_row_count == 0 - || max_split_count < 2 - { - return None; - } - debug_assert!(max_split_count.is_power_of_two()); - - let grid_index = (u128::from(element_split) * u128::from(max_split_count) - + u128::from(element_row_count / 2)) - / u128::from(element_row_count); - if grid_index == 0 || grid_index >= u128::from(max_split_count) { - return None; - } - - let outer_split = grid_index * u128::from(outer_row_count) / u128::from(max_split_count); - let outer_split = u64::try_from(outer_split) - .vortex_expect("Outer split is bounded by the list layout row count"); - (outer_split != 0 && outer_split < outer_row_count).then_some(outer_split) -} - -/// Fetch the validity child for `row_range` under `mask`, yielding `None` for a non-nullable list -/// (which has no validity child). -fn fetch_validity( - validity: Option<&LayoutReaderRef>, - row_range: &Range, - mask: MaskFuture, -) -> VortexResult { - let fut = validity - .map(|v| { - let root = root().bind(v.dtype())?; - v.projection_evaluation(row_range, &root, mask) - }) - .transpose()?; - Ok(async move { - match fut { - Some(f) => f.await.map(Some), - None => Ok(None), - } - } - .boxed()) -} - -/// Read `offsets[0]` and `offsets[-1]` and return the elements range they bound. -fn elements_range_from_offsets( - offsets: &ArrayRef, - session: &VortexSession, -) -> VortexResult> { - if offsets.is_empty() { - return Ok(0..0); - } - let mut exec_ctx = session.create_execution_ctx(); - let start = offsets - .execute_scalar(0, &mut exec_ctx)? - .as_primitive() - .as_::() - .vortex_expect("offset value fits in u64"); - let end = offsets - .execute_scalar(offsets.len() - 1, &mut exec_ctx)? - .as_primitive() - .as_::() - .vortex_expect("offset value fits in u64"); - Ok(start..end) -} - -/// Subtract `first` from every offset so they index into a sliced `elements[first..]` buffer that -/// starts at zero. -fn rebase_offsets(offsets: ArrayRef, first: u64) -> VortexResult { - if first == 0 { - return Ok(offsets); - } - let constant = ConstantArray::new(first, offsets.len()) - .into_array() - .cast(offsets.dtype().clone())?; - offsets.binary(constant, Operator::Sub) -} - -/// Compute `offsets[i + 1] - offsets[i]` as the unmasked list length values. -fn list_lengths_from_offsets(offsets: ArrayRef) -> VortexResult { - let len = offsets.len().saturating_sub(1); - offsets - .slice(1..offsets.len())? - .binary(offsets.slice(0..len)?, Operator::Sub) -} - -fn apply_lengths_validity( - lengths: ArrayRef, - validity: Option, - nullability: Nullability, -) -> VortexResult { - let len = lengths.len(); - let lengths = lengths.cast(DType::Primitive(PType::U64, nullability))?; - - if matches!(nullability, Nullability::Nullable) { - lengths.mask(create_validity(validity, nullability).to_array(len)) - } else { - Ok(lengths) - } -} - -#[cfg(test)] -mod tests { - use std::ops::Range; - - use rstest::rstest; - use vortex_array::ArrayContext; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::BoolArray; - use vortex_array::arrays::ChunkedArray; - use vortex_array::arrays::ListArray; - use vortex_array::arrays::ListViewArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::expr::Expression; - use vortex_array::expr::cast; - use vortex_array::expr::gt; - use vortex_array::expr::is_not_null; - use vortex_array::expr::is_null; - use vortex_array::expr::list_length; - use vortex_array::expr::lit; - use vortex_buffer::buffer; - use vortex_io::session::RuntimeSession; - use vortex_io::session::RuntimeSessionExt; - use vortex_session::VortexSession; - - use super::*; - use crate::LayoutRef; - use crate::LayoutStrategy; - use crate::layouts::chunked::writer::ChunkedLayoutStrategy; - use crate::layouts::flat::writer::FlatLayoutStrategy; - use crate::layouts::list::writer::ListLayoutStrategy; - use crate::layouts::repartition::RepartitionStrategy; - use crate::layouts::repartition::RepartitionWriterOptions; - use crate::scan::split_by::SplitBy; - use crate::segments::CountingSegmentSource; - use crate::segments::SegmentSource; - use crate::segments::TestSegments; - use crate::sequence::SequenceId; - use crate::sequence::SequentialArrayStreamExt; - use crate::session::LayoutSession; - use crate::test::SESSION; - - /// Validity-class projections (`is_null` / `is_not_null` of the list) round-trip through the - /// validity-only read path, for both nullable and non-nullable lists. - #[rstest] - // `create_basic_list_array(true)` has validity `[true, false, true]`. - #[case::nullable(true, vec![true, false, true])] - #[case::non_nullable(false, vec![true, true, true])] - #[tokio::test] - async fn projection_validity_class( - #[case] nullable: bool, - #[case] valid: Vec, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let not_null_expr = is_not_null(root()).bind(reader.dtype())?; - let not_null = reader - .projection_evaluation(&(0..3), ¬_null_expr, MaskFuture::new_true(3))? - .await?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(not_null, BoolArray::from_iter(valid.clone()), &mut exec_ctx); - - let is_null_expr = is_null(root()).bind(reader.dtype())?; - let is_null_res = reader - .projection_evaluation(&(0..3), &is_null_expr, MaskFuture::new_true(3))? - .await?; - assert_arrays_eq!( - is_null_res, - BoolArray::from_iter(valid.iter().map(|v| !v).collect::>()), - &mut exec_ctx - ); - - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_reads_offsets() -> VortexResult<()> { - let list = create_basic_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, buffer![2u64, 2, 1].into_array(), &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_preserves_validity() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = - PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_applies_sparse_mask() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let mask = Mask::from_iter([false, true, true]); - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask))? - .await?; - - let expected = PrimitiveArray::from_option_iter::([None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_cast_list_length() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = cast( - list_length(root()), - DType::Primitive(PType::I64, Nullability::Nullable), - ) - .bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = - PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_list_length() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = gt(list_length(root()), lit(1u64)).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - assert_eq!(result, Mask::from_iter([true, false, false])); - Ok(()) - } - - #[rstest] - #[case::is_not_null_nullable(true, is_not_null(root()), Mask::from_iter([true, false, true]))] - #[case::is_not_null_non_nullable(false, is_not_null(root()), Mask::new_true(3))] - #[case::is_null_nullable(true, is_null(root()), Mask::from_iter([false, true, false]))] - #[case::is_null_non_nullable(false, is_null(root()), Mask::new_false(3))] - #[tokio::test] - async fn filter_evaluation_validity_class( - #[case] nullable: bool, - #[case] expr: Expression, - #[case] expected: Mask, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = expr.bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - assert_eq!(result, expected); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_intersects_with_input_mask() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let input_mask = Mask::from_iter([true, true, false]); - let expr = is_not_null(root()).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::ready(input_mask))? - .await?; - - assert_eq!(result, Mask::from_iter([true, false, false])); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_sparse_mask_maps_by_rank() -> VortexResult<()> { - let list = create_six_list_array(); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let input_mask = Mask::from_iter([false, false, false, false, true, false]); - let expr = is_not_null(root()).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..6), &expr, MaskFuture::ready(input_mask))? - .await?; - - assert_eq!( - result, - Mask::from_iter([false, false, false, false, true, false]) - ); - Ok(()) - } - - fn flat_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default() - } - - fn layout_test_session() -> VortexSession { - VortexSession::empty() - .with::() - .with::() - } - - async fn write_layout( - strategy: &S, - array: ArrayRef, - ) -> VortexResult<(Arc, LayoutRef, VortexSession)> { - let session = layout_test_session().with_tokio(); - let segments = Arc::new(TestSegments::default()); - let segments_ref: Arc = Arc::::clone(&segments); - let (ptr, eof) = SequenceId::root().split(); - let stream = array.to_array_stream().sequenced(ptr); - let layout = strategy - .write_stream( - ArrayContext::empty().into(), - segments, - stream, - eof, - &session, - ) - .await?; - Ok((segments_ref, layout, session)) - } - - fn materialize_u64_array(array: ArrayRef) -> Vec { - let mut ctx = SESSION.create_execution_ctx(); - array - .execute::(&mut ctx) - .unwrap() - .as_slice::() - .to_vec() - } - - fn create_basic_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, false, true]).into_array()) - } else { - Validity::NonNullable - }; - - ListArray::try_new( - buffer![1i32, 2, 3, 4, 5].into_array(), - buffer![0u32, 2, 4, 5].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - fn create_six_list_array() -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = Validity::Array( - BoolArray::from_iter([true, false, true, false, true, true]).into_array(), - ); - - ListArray::try_new( - buffer![1i32, 2, 3, 4, 5, 6].into_array(), - buffer![0u32, 1, 2, 3, 4, 5, 6].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - #[tokio::test] - async fn fetch_offsets_includes_extra_endpoint() -> VortexResult<()> { - let list = create_basic_list_array(false); - - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let ctx = LayoutReaderContext::new(); - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - let reader = reader - .as_any() - .downcast_ref::() - .expect("ListReader"); - - let offsets = reader.fetch_raw_offsets(&(1..3))?.await?; - assert_eq!(materialize_u64_array(offsets), vec![2u64, 4, 5]); - - Ok(()) - } - - #[rstest] - #[case::full_range(0..3, false)] - #[case::partial_start(0..2, false)] - #[case::partial_end(1..3, false)] - #[case::middle_single(1..2, false)] - #[case::empty_range(1..1, false)] - #[case::full_range_null(0..3, true)] - #[tokio::test] - async fn projection_evaluation_round_trips( - #[case] row_range: Range, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - - let len = usize::try_from(row_range.end - row_range.start)?; - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? - .await?; - - let expected = - list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_evaluation_applies_mask() -> VortexResult<()> { - let list = create_basic_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let mask = Mask::from_iter([true, false, true]); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// Build a list with 5 rows and lengths [2, 3, 0, 3, 2]. - fn create_wider_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) - } else { - Validity::NonNullable - }; - ListArray::try_new( - buffer![10i32, 11, 20, 21, 22, 30, 31, 32, 40, 41].into_array(), - buffer![0u32, 2, 5, 5, 8, 10].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - /// Sparse row masks over a whole chunk round-trip: the whole-chunk read is filtered by the - /// mask in memory. - #[rstest] - #[case::single_middle(Mask::from_iter([false, false, false, true, false]), false)] - #[case::two_far_apart(Mask::from_iter([true, false, false, true, false]), false)] - #[case::boundaries(Mask::from_iter([true, false, false, false, true]), false)] - #[case::kept_empty_row(Mask::from_iter([false, false, true, false, false]), false)] - #[case::sparse_nullable(Mask::from_iter([true, false, true, false, true]), true)] - #[case::all_false(Mask::new_false(5), false)] - #[tokio::test] - async fn projection_evaluation_sparse_mask_round_trips( - #[case] mask: Mask, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_wider_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// A partial range against a single flat elements segment takes the bounded path. The flat - /// reader may still fetch its whole segment, but the list reader reconstructs only the requested - /// element range. - #[tokio::test] - async fn projection_evaluation_partial_range_bounded() -> VortexResult<()> { - let list = create_wider_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(1..4), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = list.slice(1..4)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[test] - fn maps_element_splits_to_outer_grid() { - assert_eq!(map_element_split_to_outer_grid(0, 100, 100, 8), None); - assert_eq!(map_element_split_to_outer_grid(20, 100, 100, 8), Some(25)); - assert_eq!(map_element_split_to_outer_grid(25, 100, 100, 8), Some(25)); - assert_eq!(map_element_split_to_outer_grid(50, 100, 100, 8), Some(50)); - assert_eq!(map_element_split_to_outer_grid(75, 100, 100, 8), Some(75)); - assert_eq!(map_element_split_to_outer_grid(100, 100, 100, 8), None); - - let mut splits = (1..1_000) - .filter_map(|split| { - map_element_split_to_outer_grid(split, 1_000, 100_000, MIN_LIST_SPLIT_COUNT) - }) - .collect::>(); - splits.dedup(); - - let expected = (1..MIN_LIST_SPLIT_COUNT) - .map(|grid_index| grid_index * 100_000 / MIN_LIST_SPLIT_COUNT) - .collect::>(); - assert_eq!(splits, expected); - } - - #[rstest] - #[case::empty(0, 64)] - #[case::small(100_000, 64)] - #[case::floor_boundary(64 * 8192, 64)] - #[case::past_floor(64 * 8192 + 1, 128)] - #[case::million(1_000_000, 128)] - #[case::ten_million(10_000_000, 2048)] - fn split_grid_grows_with_row_count(#[case] outer_row_count: u64, #[case] expected: u64) { - assert_eq!(list_split_grid_size(outer_row_count), expected); - } - - #[tokio::test] - async fn nested_list_propagates_element_splits() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let inner = ListArray::try_new( - PrimitiveArray::from_iter(0..128_i32).into_array(), - PrimitiveArray::from_iter((0..=8_u32).map(|idx| idx * 16)).into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let outer = ListArray::try_new( - inner, - buffer![0u32, 2, 4, 6, 8].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - - let inner_strategy = - ListLayoutStrategy::default().with_elements(chunked_elements_strategy()); - let strategy = ListLayoutStrategy::default().with_elements(Arc::new(inner_strategy)); - let (segments, layout, session) = write_layout(&strategy, outer).await?; - let reader = - layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; - - let splits = SplitBy::Layout.splits(reader.as_ref(), &(0..4), &[FieldMask::All])?; - assert_eq!(splits, vec![0, 1, 2, 3, 4]); - Ok(()) - } - - /// A list strategy whose `elements` child is repartitioned into two-element chunks, so the - /// reader takes the bounded (chunk-skipping) path for strict sub-ranges. Offsets stay flat. - fn chunked_elements_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default().with_elements(chunked_elements_strategy()) - } - - fn chunked_elements_strategy() -> Arc { - Arc::new(RepartitionStrategy::new( - ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), - RepartitionWriterOptions { - block_size_minimum: 0, - block_len_multiple: 2, - block_size_target: None, - canonicalize: true, - }, - )) - } - - /// The chunked-elements strategy must actually produce a chunked `elements` layout, otherwise - /// the reader would silently take the whole-chunk path and the bounded read would be untested. - #[tokio::test] - async fn chunked_elements_produces_chunked_layout() -> VortexResult<()> { - let list = create_wider_list_array(false); - let (_segments, layout, _session) = - write_layout(&chunked_elements_list_strategy(), list).await?; - let tree = layout.display_tree().to_string(); - assert!( - tree.contains("elements: vortex.chunked"), - "elements should be chunked:\n{tree}" - ); - Ok(()) - } - - /// A sparse mask must remain selective even when the requested row range covers the complete - /// local list layout. The selected first list touches one element chunk plus the offsets - /// segment; reading all five element chunks would make the count six. - #[tokio::test] - async fn full_range_sparse_mask_crops_element_read() -> VortexResult<()> { - let list = create_wider_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = - write_layout(&chunked_elements_list_strategy(), list.clone()).await?; - let source = Arc::new(CountingSegmentSource::new(segments)); - let reader = layout.new_reader("".into(), Arc::clone(&source) as _, &session, &ctx)?; - - let mask = Mask::from_iter([true, false, false, false, false]); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - assert_eq!(source.requests(), 2); - Ok(()) - } - - /// With chunked elements, sub-range projections take the bounded read path. Every - /// range/mask/nullability combination must match the same projection over the ground-truth - /// array (`list.slice(range).filter(mask)`). - #[rstest] - #[case::full_all_true(0..5, Mask::new_true(5), false)] - #[case::subrange_all_true(1..4, Mask::new_true(3), false)] - #[case::subrange_sparse(1..4, Mask::from_iter([true, false, true]), false)] - #[case::partial_start(0..2, Mask::new_true(2), false)] - #[case::partial_end(2..5, Mask::new_true(3), false)] - #[case::single_non_empty(0..1, Mask::new_true(1), false)] - #[case::single_empty_row(2..3, Mask::from_iter([true]), false)] - #[case::empty_range(2..2, Mask::new_true(0), false)] - #[case::subrange_all_false(1..4, Mask::new_false(3), false)] - #[case::subrange_single_interior(0..4, Mask::from_iter([false, true, false, false]), false)] - #[case::subrange_sparse_nullable(1..4, Mask::from_iter([true, false, true]), true)] - #[case::partial_end_nullable(2..5, Mask::new_true(3), true)] - #[tokio::test] - async fn chunked_elements_round_trips( - #[case] row_range: Range, - #[case] mask: Mask, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_wider_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = - write_layout(&chunked_elements_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let sliced = - list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; - let expected = sliced.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// Lists `[0, 1, 2]`, `[]`, `[3, 4, 5]`, `[6, 7]`, `[8, 9]`. When nullable, the third is null - /// and keeps its elements. - fn create_ten_element_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) - } else { - Validity::NonNullable - }; - ListArray::try_new( - PrimitiveArray::from_iter(0..10i32).into_array(), - buffer![0u32, 3, 3, 6, 8, 10].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - /// Slices of one list share its whole `elements`, so every chunk but the first starts at a - /// nonzero offset and every chunk but the last leaves trailing elements unreferenced. - fn sliced_chunks(array: &ArrayRef, cuts: &[usize]) -> VortexResult> { - let mut bounds = vec![0]; - bounds.extend_from_slice(cuts); - bounds.push(array.len()); - bounds - .windows(2) - .map(|range| array.slice(range[0]..range[1])) - .collect() - } - - fn chunked_flat() -> Arc { - Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())) - } - - /// A list strategy that keeps every chunk, so a multi-chunk stream reaches the list writer. - fn chunked_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default() - .with_elements(chunked_flat()) - .with_offsets(chunked_flat()) - .with_validity(chunked_flat()) - } - - async fn assert_round_trips( - strategy: &S, - chunks: Vec, - expected: ArrayRef, - ) -> VortexResult<()> { - let chunked = ChunkedArray::try_new(chunks, expected.dtype().clone())?.into_array(); - let (segments, layout, session) = write_layout(strategy, chunked).await?; - let reader = - layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; - - let len = expected.len(); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..len as u64), &expr, MaskFuture::new_true(len))? - .await?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[rstest] - #[case::one_cut(&[2], false, false)] - #[case::two_cuts(&[1, 3], false, false)] - #[case::null_and_empty_at_cuts(&[1, 3], true, false)] - #[case::list_view_chunks(&[1, 3], true, true)] - #[case::non_nullable_list_view_chunks(&[1, 3], false, true)] - #[tokio::test] - async fn sliced_list_chunks_round_trip( - #[case] cuts: &[usize], - #[case] nullable: bool, - #[case] as_list_view: bool, - ) -> VortexResult<()> { - let list = create_ten_element_list_array(nullable); - let source = if as_list_view { - let mut ctx = SESSION.create_execution_ctx(); - list.clone() - .execute::(&mut ctx)? - .into_array() - } else { - list.clone() - }; - let chunks = sliced_chunks(&source, cuts)?; - assert_round_trips(&chunked_list_strategy(), chunks, list).await - } - - #[tokio::test] - async fn sliced_nested_list_chunks_round_trip() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let inner = ListArray::try_new( - PrimitiveArray::from_iter(0..12i32).into_array(), - buffer![0u32, 2, 2, 5, 7, 9, 12].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let outer = ListArray::try_new( - inner, - buffer![0u32, 2, 3, 5, 6].into_array(), - Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()), - &mut ctx, - )? - .into_array(); - - let strategy = chunked_list_strategy().with_elements(Arc::new(chunked_list_strategy())); - assert_round_trips(&strategy, sliced_chunks(&outer, &[1, 2])?, outer).await - } -} diff --git a/vortex-layout/src/layouts/list/reader/mod.rs b/vortex-layout/src/layouts/list/reader/mod.rs new file mode 100644 index 00000000000..a709b8aa5e0 --- /dev/null +++ b/vortex-layout/src/layouts/list/reader/mod.rs @@ -0,0 +1,785 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#[cfg(test)] +mod tests; + +use std::ops::Range; +use std::sync::Arc; +use std::sync::OnceLock; + +use futures::FutureExt; +use futures::future::BoxFuture; +use futures::try_join; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::ExactBoundExpr; +use vortex_array::expr::root; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_utils::aliases::dash_map::DashMap; + +use crate::ArrayFuture; +use crate::LayoutReader; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::RowSplits; +use crate::SplitRange; +use crate::layouts::list::ListLayout; +use crate::layouts::list::expr::ElementProjection; +use crate::layouts::list::expr::ListChildrenNeeded; +use crate::layouts::list::expr::get_necessary_bound_list_children; +use crate::layouts::list::expr::rewrite_offsets_expr; +use crate::layouts::list::expr::rewrite_validity_expr; +use crate::segments::SegmentSource; + +type OptionalArrayFuture = BoxFuture<'static, VortexResult>>; + +/// The threshold of mask density below which we push the input mask into projection evaluation, +/// and above which we evaluate the expression over all rows and intersect afterward. +const EXPR_EVAL_THRESHOLD: f64 = 0.2; + +/// Minimum size of the outer-row split grid, so lists in small files still fan out. +const MIN_LIST_SPLIT_COUNT: u64 = 64; + +/// Outer rows per grid cell that the grid grows to stay under for large files. +const TARGET_LIST_SPLIT_ROWS: u64 = 8192; + +/// Number of cells in the outer-row split grid: at least [`MIN_LIST_SPLIT_COUNT`], and enough +/// that a cell covers at most about [`TARGET_LIST_SPLIT_ROWS`] outer rows. +fn list_split_grid_size(outer_row_count: u64) -> u64 { + outer_row_count + .div_ceil(TARGET_LIST_SPLIT_ROWS) + .next_power_of_two() + .max(MIN_LIST_SPLIT_COUNT) +} + +/// Reader for [`ListLayout`]. +/// +/// An expression that reads the list elements only through `list_transform(root, lambda)` runs +/// the lambda bodies over the elements child, so a lambda that reads one field of struct elements +/// reads only the column of that field. See [`ElementProjection`]. +#[derive(Clone)] +pub struct ListReader { + layout: ListLayout, + name: Arc, + session: VortexSession, + elements: LayoutReaderRef, + offsets: LayoutReaderRef, + validity: Option, + /// Element projections keyed by the identity of the expression they were derived from. + /// Cached so the elements reader sees the same tree on every split, keeping its own + /// identity-keyed caches warm. + projections: Arc, +} + +type ProjectionCache = DashMap>>>; + +impl ListReader { + pub(super) fn try_new( + layout: ListLayout, + name: Arc, + segment_source: Arc, + session: VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + let elements = layout.elements()?.new_reader( + format!("{name}.elements").into(), + Arc::clone(&segment_source), + &session, + ctx, + )?; + let offsets = layout.offsets()?.new_reader( + format!("{name}.offsets").into(), + Arc::clone(&segment_source), + &session, + ctx, + )?; + let validity = layout + .validity()? + .map(|v| { + v.new_reader( + format!("{name}.validity").into(), + Arc::clone(&segment_source), + &session, + ctx, + ) + }) + .transpose()?; + + Ok(Self { + layout, + name, + session, + elements, + offsets, + validity, + projections: Arc::new(DashMap::with_hasher_and_shard_amount(Default::default(), 8)), + }) + } + + /// Returns how the [`ListChildrenNeeded::All`] expression `expr` reads the elements child: the + /// lambdas of its `list_transform(root, lambda)` nodes when it reads the elements only through + /// them, or the elements as stored. + fn element_projection(&self, expr: &BoundExpression) -> VortexResult> { + let key = ExactBoundExpr(expr.clone()); + let cell = match self.projections.get(&key) { + Some(entry) => Arc::clone(entry.value()), + None => Arc::clone( + self.projections + .entry(key) + .or_insert_with(|| Arc::new(OnceLock::new())) + .value(), + ), + }; + if let Some(projection) = cell.get() { + return Ok(Arc::clone(projection)); + } + let projection = match ElementProjection::push_down(expr)? { + Some(projection) => projection, + None => ElementProjection::identity(expr, self.layout.elements_dtype()), + }; + Ok(Arc::clone(cell.get_or_init(|| Arc::new(projection)))) + } + + /// Projection for [`ListChildrenNeeded::Validity`] expressions. Reads only the validity child, + /// synthesizing all-valid for a non-nullable list, and never touches the offsets or elements. + fn project_validity( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let validity_reader = self.validity.clone(); + let nullability = self.layout.dtype().nullability(); + let row_range = row_range.clone(); + // Evaluate the rewritten expression against the validity bool array (true == valid row). + let rewritten = rewrite_validity_expr(expr)?; + + Ok(async move { + let mask = mask.await?; + let row_count = usize::try_from(row_range.end - row_range.start)?; + let out_len = if mask.all_true() { + row_count + } else { + mask.true_count() + }; + + let validity_array = match validity_reader.as_ref() { + Some(v) => { + let root = root().bind(v.dtype())?; + Some( + v.projection_evaluation(&row_range, &root, MaskFuture::ready(mask))? + .await?, + ) + } + None => None, + }; + + let validity = create_validity(validity_array, nullability).to_array(out_len); + + validity.apply_bound(&rewritten) + } + .boxed()) + } + + /// Projection for [`ListChildrenNeeded::All`] expressions. + /// + /// The elements child is read through the [`ElementProjection`] of `expr`. A projection that + /// can fail reads only the elements of the selected valid lists. Otherwise, an all-true mask + /// over the full local range reads every child concurrently, and any other read is bounded to + /// the first and last selected list. + fn project_all( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let projection = self.element_projection(expr)?; + let is_full_range = row_range.start == 0 && row_range.end == self.layout.row_count(); + let reader = self.clone(); + let row_range = row_range.clone(); + Ok(async move { + let mask = mask.await?; + if projection.is_fallible() { + reader + .project_all_compacted(&row_range, projection, mask)? + .await + } else if is_full_range && mask.all_true() { + reader.project_all_full(projection)?.await + } else { + reader + .project_all_bounded(&row_range, projection, mask)? + .await + } + } + .boxed()) + } + + /// Fetch the complete `elements`, `offsets`, and `validity` children concurrently. + fn project_all_full(&self, projection: Arc) -> VortexResult { + let row_count = self.layout.row_count(); + let elements_row_count = self.elements.row_count(); + let nullability = self.layout.dtype().nullability(); + + let offsets_fut = self.fetch_raw_offsets(&(0..row_count))?; + let elements_fut = self.fetch_elements( + &(0..elements_row_count), + projection.elements(), + MaskFuture::new_true(usize::try_from(elements_row_count)?), + )?; + let validity_fut = fetch_validity( + self.validity.as_ref(), + &(0..row_count), + MaskFuture::new_true(usize::try_from(row_count)?), + )?; + + Ok(async move { + let (offsets, elements, validity) = try_join!(offsets_fut, elements_fut, validity_fut)?; + // SAFETY: ListLayout is constructed from a valid ListArray, and the element-wise + // projection keeps one value per element. + let lists = unsafe { + projection.rebuild(elements, offsets, create_validity(validity, nullability)) + }?; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Bounded read for a sub-range or selective mask. + /// + /// Crops leading and trailing unselected lists, reads their offsets, and translates the first + /// and last offset into the element-row range to fetch. Any holes in the selection are filtered + /// after reconstructing the lists. + fn project_all_bounded( + &self, + row_range: &Range, + projection: Arc, + mask: Mask, + ) -> VortexResult { + // Crop to the smallest contiguous row range containing every selected list. + let Some(selected_rows) = selected_row_range(&mask) else { + let empty = Canonical::empty(projection.lists().dtype()).into_array(); + return Ok(async move { Ok(empty) }.boxed()); + }; + + let selected_mask = mask.slice(selected_rows.clone()); + let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) + ..(row_range.start + u64::try_from(selected_rows.end)?); + + let nullability = self.layout.dtype().nullability(); + let reader = self.clone(); + let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; + + Ok(async move { + let offsets = offsets_fut.await?; + + let elements_range = elements_range_from_offsets(&offsets, &reader.session)?; + let elements_fut = reader.fetch_elements( + &elements_range, + projection.elements(), + MaskFuture::new_true(usize::try_from(elements_range.end - elements_range.start)?), + )?; + let validity_fut = fetch_validity( + reader.validity.as_ref(), + &selected_row_range, + MaskFuture::new_true(selected_mask.len()), + )?; + let (elements, validity) = try_join!(elements_fut, validity_fut)?; + + let offsets = rebase_offsets(offsets, elements_range.start)?; + // SAFETY: the selected offsets remain monotonically increasing, rebasing them against + // the selected element range preserves their lengths, the element-wise projection + // keeps one value per element, and validity covers the same cropped list rows. + let lists = unsafe { + projection.rebuild(elements, offsets, create_validity(validity, nullability)) + }?; + let lists = if selected_mask.all_true() { + lists + } else { + lists.filter(selected_mask)? + }; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Read for an element projection that can fail. + /// + /// `list_transform` runs a lambda that can fail only on the elements of valid lists, so this + /// read evaluates the projection only on the elements of the selected valid lists. It reads + /// the offsets and validity from the first to the last selected list, then the projected + /// elements under a mask of the elements of the selected valid lists, and rebuilds the + /// selected lists over just those elements. + fn project_all_compacted( + &self, + row_range: &Range, + projection: Arc, + mask: Mask, + ) -> VortexResult { + let Some(selected_rows) = selected_row_range(&mask) else { + let empty = Canonical::empty(projection.lists().dtype()).into_array(); + return Ok(async move { Ok(empty) }.boxed()); + }; + + let selected_mask = mask.slice(selected_rows.clone()); + let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) + ..(row_range.start + u64::try_from(selected_rows.end)?); + + let nullability = self.layout.dtype().nullability(); + let reader = self.clone(); + let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; + let validity_fut = fetch_validity( + self.validity.as_ref(), + &selected_row_range, + MaskFuture::new_true(selected_mask.len()), + )?; + + Ok(async move { + let (offsets, validity) = try_join!(offsets_fut, validity_fut)?; + let mut ctx = reader.session.create_execution_ctx(); + let offsets = offsets + .cast(DType::Primitive(PType::U64, Nullability::NonNullable))? + .execute::(&mut ctx)?; + let valid = match &validity { + Some(validity) => validity.clone().execute::(&mut ctx)?, + None => Mask::new_true(selected_mask.len()), + }; + let compacted = compact_lists(offsets.as_slice::(), &selected_mask, &valid)?; + + let elements = reader + .fetch_elements( + &compacted.elements_range, + projection.elements(), + MaskFuture::ready(compacted.elements_mask), + )? + .await?; + let validity = validity + .map(|validity| validity.filter(selected_mask)) + .transpose()?; + // SAFETY: the compacted offsets index exactly the masked elements, the element-wise + // projection keeps one value per element, and validity is filtered to the same + // selected lists. + let lists = unsafe { + projection.rebuild( + elements, + compacted.offsets.into_array(), + create_validity(validity, nullability), + ) + }?; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Projection for [`ListChildrenNeeded::OffsetsAndValidity`] expressions. Only reads offsets and validity children. + fn project_offsets_validity( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let offsets = self.fetch_raw_offsets(row_range)?; + let reader = self.clone(); + let row_range = row_range.clone(); + let lengths_dtype = DType::Primitive(PType::U64, self.layout.dtype().nullability()); + let rewritten = rewrite_offsets_expr(expr, &lengths_dtype)?; + + Ok(async move { + let mask = mask.await?; + let row_count = usize::try_from(row_range.end - row_range.start)?; + let nullability = reader.layout.dtype().nullability(); + + let validity_mask = if mask.all_true() { + MaskFuture::new_true(row_count) + } else { + MaskFuture::ready(mask.clone()) + }; + let validity_fut = fetch_validity(reader.validity.as_ref(), &row_range, validity_mask)?; + + let offsets = offsets.await?; + let lengths = list_lengths_from_offsets(offsets)?; + let lengths = if mask.all_true() { + lengths + } else { + lengths.filter(mask)? + }; + let validity = validity_fut.await?; + let lengths = apply_lengths_validity(lengths, validity, nullability)?; + + lengths.apply_bound(&rewritten) + } + .boxed()) + } + + /// Fire the offsets read for `row_range` in list row space. The offsets child has an extra entry, so reading + /// `row_range` maps to offsets in `[row_range.start..row_range.end + 1)`. + /// + /// No mask or expression is applied. + fn fetch_raw_offsets(&self, row_range: &Range) -> VortexResult { + let offsets_range = row_range.start..(row_range.end + 1); + let offsets_count = usize::try_from(offsets_range.end - offsets_range.start)?; + let root = root().bind(self.offsets.dtype())?; + self.offsets.projection_evaluation( + &offsets_range, + &root, + MaskFuture::new_true(offsets_count), + ) + } + + /// Fire the read of `expr` over the elements in `row_range`, in element space, under `mask`. + fn fetch_elements( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + self.elements.projection_evaluation(row_range, expr, mask) + } +} + +fn selected_row_range(mask: &Mask) -> Option> { + Some(mask.first()?..mask.last()? + 1) +} + +fn create_validity(validity_array: Option, nullability: Nullability) -> Validity { + match validity_array { + Some(arr) => Validity::Array(arr), + None => match nullability { + Nullability::Nullable => Validity::AllValid, + Nullability::NonNullable => Validity::NonNullable, + }, + } +} + +impl LayoutReader for ListReader { + fn name(&self) -> &Arc { + &self.name + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn dtype(&self) -> &DType { + self.layout.dtype() + } + + fn row_count(&self) -> u64 { + self.layout.row_count() + } + + fn register_splits( + &self, + _field_mask: &[FieldMask], + split_range: &SplitRange, + splits: &mut RowSplits, + ) -> VortexResult<()> { + split_range.check_bounds(self.layout.row_count())?; + + // Splits are difficult to calculate because all children live in different row coordinate spaces. + // List elements typically comprise the majority of the data in a list, and validity/offsets can be treated + // as metadata. We therefore want to parallelize the scan based on element work. + // + // Scan splits must be expressed in the list layout's outer-row space, but the elements child + // reports its natural boundaries in element-row space. So we translate the element splits using a + // heuristic to outer-row space. + + let element_row_count = self.elements.row_count(); + if element_row_count != 0 { + let mut element_splits = RowSplits::new_capacity(128); + self.elements.register_splits( + &[FieldMask::All], + &SplitRange::root(0..element_row_count)?, + &mut element_splits, + )?; + + let row_range = split_range.row_range(); + let grid_size = list_split_grid_size(self.layout.row_count()); + let mut last_split = None; + for element_split in element_splits.into_sorted_deduped() { + let Some(split) = map_element_split_to_outer_grid( + element_split, + element_row_count, + self.layout.row_count(), + grid_size, + ) else { + continue; + }; + if split <= row_range.start { + continue; + } + if split >= row_range.end { + break; + } + if last_split == Some(split) { + continue; + } + splits.push( + split_range + .row_offset() + .checked_add(split) + .vortex_expect("List layout split offset overflow"), + ); + last_split = Some(split); + } + } + splits.push(split_range.root_row_range().end); + Ok(()) + } + + // TODO(mk): handle zones for list elements + fn pruning_evaluation( + &self, + _row_range: &Range, + _expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + Ok(MaskFuture::ready(mask)) + } + + fn filter_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let len = mask.len(); + let reader = self.clone(); + let row_range = row_range.clone(); + let expr = expr.clone(); + let session = self.session.clone(); + + Ok(MaskFuture::new(len, async move { + let mask = mask.await?; + + if mask.all_false() { + return Ok(mask); + } + + let mut ctx = session.create_execution_ctx(); + if mask.density() < EXPR_EVAL_THRESHOLD { + let predicate = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? + .await?; + let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; + Ok(mask.intersect_by_rank(&predicate_mask)) + } else { + let predicate = reader + .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? + .await?; + let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; + Ok(mask & &predicate_mask) + } + })) + } + + /// Reads only the list children needed to evaluate `expr`. + /// + /// Validity-only expressions avoid offsets and elements, length expressions read offsets and + /// validity, and general expressions reconstruct a list from all applicable children. + fn projection_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + // Read as little as possible based on which list children the expression needs. + match get_necessary_bound_list_children(expr) { + ListChildrenNeeded::Validity => self.project_validity(row_range, expr, mask), + ListChildrenNeeded::OffsetsAndValidity => { + self.project_offsets_validity(row_range, expr, mask) + } + ListChildrenNeeded::All => self.project_all(row_range, expr, mask), + } + } +} + +/// Converts a natural boundary from element-row space into an approximate outer-row scan split. +/// +/// Scan splits must be expressed in the list layout's outer-row space, but the elements child +/// reports its natural boundaries in element-row space. Translating a boundary exactly would +/// require consulting the list offsets, so this function instead preserves its relative position: +/// +/// ```text +/// element_split / element_row_count ≈ outer_split / outer_row_count +/// ``` +/// +/// The relative position is first rounded onto a grid containing at most `max_split_count` scan +/// ranges, then mapped into outer-row space. Multiple element boundaries may therefore map to the +/// same outer split and are deduplicated by the caller. With a grid size of 64, at most 63 interior +/// splits, and therefore 64 scan ranges, can be produced. +/// +/// The result is only a task-sizing hint. It is always between outer rows, but it is not guaranteed +/// to correspond exactly to the original physical element boundary. Endpoint boundaries are +/// omitted because they do not subdivide the scan +fn map_element_split_to_outer_grid( + element_split: u64, + element_row_count: u64, + outer_row_count: u64, + max_split_count: u64, +) -> Option { + if element_split == 0 + || element_split >= element_row_count + || outer_row_count == 0 + || max_split_count < 2 + { + return None; + } + debug_assert!(max_split_count.is_power_of_two()); + + let grid_index = (u128::from(element_split) * u128::from(max_split_count) + + u128::from(element_row_count / 2)) + / u128::from(element_row_count); + if grid_index == 0 || grid_index >= u128::from(max_split_count) { + return None; + } + + let outer_split = grid_index * u128::from(outer_row_count) / u128::from(max_split_count); + let outer_split = u64::try_from(outer_split) + .vortex_expect("Outer split is bounded by the list layout row count"); + (outer_split != 0 && outer_split < outer_row_count).then_some(outer_split) +} + +/// Fetch the validity child for `row_range` under `mask`, yielding `None` for a non-nullable list +/// (which has no validity child). +fn fetch_validity( + validity: Option<&LayoutReaderRef>, + row_range: &Range, + mask: MaskFuture, +) -> VortexResult { + let fut = validity + .map(|v| { + let root = root().bind(v.dtype())?; + v.projection_evaluation(row_range, &root, mask) + }) + .transpose()?; + Ok(async move { + match fut { + Some(f) => f.await.map(Some), + None => Ok(None), + } + } + .boxed()) +} + +/// Read `offsets[0]` and `offsets[-1]` and return the elements range they bound. +fn elements_range_from_offsets( + offsets: &ArrayRef, + session: &VortexSession, +) -> VortexResult> { + if offsets.is_empty() { + return Ok(0..0); + } + let mut exec_ctx = session.create_execution_ctx(); + let start = offsets + .execute_scalar(0, &mut exec_ctx)? + .as_primitive() + .as_::() + .vortex_expect("offset value fits in u64"); + let end = offsets + .execute_scalar(offsets.len() - 1, &mut exec_ctx)? + .as_primitive() + .as_::() + .vortex_expect("offset value fits in u64"); + Ok(start..end) +} + +/// The elements of the selected valid lists, and offsets that index them once the other elements +/// are dropped. +struct CompactedLists { + /// The element rows from the first to the last of the lists. + elements_range: Range, + /// The elements of the selected valid lists, relative to `elements_range`. + elements_mask: Mask, + /// The offsets of the selected lists into the masked elements. Null lists are empty. + offsets: Buffer, +} + +/// Compacts the lists that `offsets` describe to the `selected` ones, keeping only the elements +/// of the `valid` ones, as `list_transform` does before it runs a lambda that can fail. +fn compact_lists(offsets: &[u64], selected: &Mask, valid: &Mask) -> VortexResult { + let (Some(&first), Some(&last)) = (offsets.first(), offsets.last()) else { + vortex_bail!("List offsets must hold at least one entry"); + }; + let mut slices: Vec<(usize, usize)> = Vec::new(); + let mut compacted = BufferMut::::with_capacity(selected.true_count() + 1); + let mut kept = 0; + compacted.push(kept); + for (row, (selected, valid)) in selected.iter().zip(valid.iter()).enumerate() { + if !selected { + continue; + } + let (start, end) = (offsets[row], offsets[row + 1]); + if valid && start < end { + kept += end - start; + let slice = ( + usize::try_from(start - first)?, + usize::try_from(end - first)?, + ); + match slices.last_mut() { + Some((_, previous_end)) if *previous_end == slice.0 => *previous_end = slice.1, + _ => slices.push(slice), + } + } + compacted.push(kept); + } + Ok(CompactedLists { + elements_range: first..last, + elements_mask: Mask::from_slices(usize::try_from(last - first)?, slices), + offsets: compacted.freeze(), + }) +} + +/// Subtract `first` from every offset so they index into a sliced `elements[first..]` buffer that +/// starts at zero. +fn rebase_offsets(offsets: ArrayRef, first: u64) -> VortexResult { + if first == 0 { + return Ok(offsets); + } + let constant = ConstantArray::new(first, offsets.len()) + .into_array() + .cast(offsets.dtype().clone())?; + offsets.binary(constant, Operator::Sub) +} + +/// Compute `offsets[i + 1] - offsets[i]` as the unmasked list length values. +fn list_lengths_from_offsets(offsets: ArrayRef) -> VortexResult { + let len = offsets.len().saturating_sub(1); + offsets + .slice(1..offsets.len())? + .binary(offsets.slice(0..len)?, Operator::Sub) +} + +fn apply_lengths_validity( + lengths: ArrayRef, + validity: Option, + nullability: Nullability, +) -> VortexResult { + let len = lengths.len(); + let lengths = lengths.cast(DType::Primitive(PType::U64, nullability))?; + + if matches!(nullability, Nullability::Nullable) { + lengths.mask(create_validity(validity, nullability).to_array(len)) + } else { + Ok(lengths) + } +} diff --git a/vortex-layout/src/layouts/list/reader/tests.rs b/vortex-layout/src/layouts/list/reader/tests.rs new file mode 100644 index 00000000000..7b25d6faa1f --- /dev/null +++ b/vortex-layout/src/layouts/list/reader/tests.rs @@ -0,0 +1,989 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use rstest::rstest; +use vortex_array::ArrayContext; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::FieldNames; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::cast; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::var; +use vortex_buffer::buffer; +use vortex_io::session::RuntimeSession; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::*; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::list::writer::ListLayoutStrategy; +use crate::layouts::repartition::RepartitionStrategy; +use crate::layouts::repartition::RepartitionWriterOptions; +use crate::layouts::struct_::writer::StructStrategy; +use crate::scan::split_by::SplitBy; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSource; +use crate::segments::TestSegments; +use crate::sequence::SequenceId; +use crate::sequence::SequentialArrayStreamExt; +use crate::session::LayoutSession; +use crate::test::SESSION; + +/// Validity-class projections (`is_null` / `is_not_null` of the list) round-trip through the +/// validity-only read path, for both nullable and non-nullable lists. +#[rstest] +// `create_basic_list_array(true)` has validity `[true, false, true]`. +#[case::nullable(true, vec![true, false, true])] +#[case::non_nullable(false, vec![true, true, true])] +#[tokio::test] +async fn projection_validity_class( + #[case] nullable: bool, + #[case] valid: Vec, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let not_null_expr = is_not_null(root()).bind(reader.dtype())?; + let not_null = reader + .projection_evaluation(&(0..3), ¬_null_expr, MaskFuture::new_true(3))? + .await?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(not_null, BoolArray::from_iter(valid.clone()), &mut exec_ctx); + + let is_null_expr = is_null(root()).bind(reader.dtype())?; + let is_null_res = reader + .projection_evaluation(&(0..3), &is_null_expr, MaskFuture::new_true(3))? + .await?; + assert_arrays_eq!( + is_null_res, + BoolArray::from_iter(valid.iter().map(|v| !v).collect::>()), + &mut exec_ctx + ); + + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_reads_offsets() -> VortexResult<()> { + let list = create_basic_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, buffer![2u64, 2, 1].into_array(), &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_preserves_validity() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = + PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_applies_sparse_mask() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let mask = Mask::from_iter([false, true, true]); + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask))? + .await?; + + let expected = PrimitiveArray::from_option_iter::([None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_cast_list_length() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = cast( + list_length(root()), + DType::Primitive(PType::I64, Nullability::Nullable), + ) + .bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = + PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_list_length() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = gt(list_length(root()), lit(1u64)).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + assert_eq!(result, Mask::from_iter([true, false, false])); + Ok(()) +} + +#[rstest] +#[case::is_not_null_nullable(true, is_not_null(root()), Mask::from_iter([true, false, true]))] +#[case::is_not_null_non_nullable(false, is_not_null(root()), Mask::new_true(3))] +#[case::is_null_nullable(true, is_null(root()), Mask::from_iter([false, true, false]))] +#[case::is_null_non_nullable(false, is_null(root()), Mask::new_false(3))] +#[tokio::test] +async fn filter_evaluation_validity_class( + #[case] nullable: bool, + #[case] expr: Expression, + #[case] expected: Mask, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = expr.bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + assert_eq!(result, expected); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_intersects_with_input_mask() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let input_mask = Mask::from_iter([true, true, false]); + let expr = is_not_null(root()).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::ready(input_mask))? + .await?; + + assert_eq!(result, Mask::from_iter([true, false, false])); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_sparse_mask_maps_by_rank() -> VortexResult<()> { + let list = create_six_list_array(); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let input_mask = Mask::from_iter([false, false, false, false, true, false]); + let expr = is_not_null(root()).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..6), &expr, MaskFuture::ready(input_mask))? + .await?; + + assert_eq!( + result, + Mask::from_iter([false, false, false, false, true, false]) + ); + Ok(()) +} + +fn flat_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default() +} + +fn layout_test_session() -> VortexSession { + VortexSession::empty() + .with::() + .with::() +} + +async fn write_layout( + strategy: &S, + array: ArrayRef, +) -> VortexResult<(Arc, LayoutRef, VortexSession)> { + let session = layout_test_session().with_tokio(); + let segments = Arc::new(TestSegments::default()); + let segments_ref: Arc = Arc::::clone(&segments); + let (ptr, eof) = SequenceId::root().split(); + let stream = array.to_array_stream().sequenced(ptr); + let layout = strategy + .write_stream( + ArrayContext::empty().into(), + segments, + stream, + eof, + &session, + ) + .await?; + Ok((segments_ref, layout, session)) +} + +fn materialize_u64_array(array: ArrayRef) -> Vec { + let mut ctx = SESSION.create_execution_ctx(); + array + .execute::(&mut ctx) + .unwrap() + .as_slice::() + .to_vec() +} + +fn create_basic_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, false, true]).into_array()) + } else { + Validity::NonNullable + }; + + ListArray::try_new( + buffer![1i32, 2, 3, 4, 5].into_array(), + buffer![0u32, 2, 4, 5].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +fn create_six_list_array() -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = + Validity::Array(BoolArray::from_iter([true, false, true, false, true, true]).into_array()); + + ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 1, 2, 3, 4, 5, 6].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +#[tokio::test] +async fn fetch_offsets_includes_extra_endpoint() -> VortexResult<()> { + let list = create_basic_list_array(false); + + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let ctx = LayoutReaderContext::new(); + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + let reader = reader + .as_any() + .downcast_ref::() + .expect("ListReader"); + + let offsets = reader.fetch_raw_offsets(&(1..3))?.await?; + assert_eq!(materialize_u64_array(offsets), vec![2u64, 4, 5]); + + Ok(()) +} + +#[rstest] +#[case::full_range(0..3, false)] +#[case::partial_start(0..2, false)] +#[case::partial_end(1..3, false)] +#[case::middle_single(1..2, false)] +#[case::empty_range(1..1, false)] +#[case::full_range_null(0..3, true)] +#[tokio::test] +async fn projection_evaluation_round_trips( + #[case] row_range: Range, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + + let len = usize::try_from(row_range.end - row_range.start)?; + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? + .await?; + + let expected = + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_evaluation_applies_mask() -> VortexResult<()> { + let list = create_basic_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let mask = Mask::from_iter([true, false, true]); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// Build a list with 5 rows and lengths [2, 3, 0, 3, 2]. +fn create_wider_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) + } else { + Validity::NonNullable + }; + ListArray::try_new( + buffer![10i32, 11, 20, 21, 22, 30, 31, 32, 40, 41].into_array(), + buffer![0u32, 2, 5, 5, 8, 10].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +/// Sparse row masks over a whole chunk round-trip: the whole-chunk read is filtered by the +/// mask in memory. +#[rstest] +#[case::single_middle(Mask::from_iter([false, false, false, true, false]), false)] +#[case::two_far_apart(Mask::from_iter([true, false, false, true, false]), false)] +#[case::boundaries(Mask::from_iter([true, false, false, false, true]), false)] +#[case::kept_empty_row(Mask::from_iter([false, false, true, false, false]), false)] +#[case::sparse_nullable(Mask::from_iter([true, false, true, false, true]), true)] +#[case::all_false(Mask::new_false(5), false)] +#[tokio::test] +async fn projection_evaluation_sparse_mask_round_trips( + #[case] mask: Mask, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_wider_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// A partial range against a single flat elements segment takes the bounded path. The flat +/// reader may still fetch its whole segment, but the list reader reconstructs only the requested +/// element range. +#[tokio::test] +async fn projection_evaluation_partial_range_bounded() -> VortexResult<()> { + let list = create_wider_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(1..4), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = list.slice(1..4)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[test] +fn maps_element_splits_to_outer_grid() { + assert_eq!(map_element_split_to_outer_grid(0, 100, 100, 8), None); + assert_eq!(map_element_split_to_outer_grid(20, 100, 100, 8), Some(25)); + assert_eq!(map_element_split_to_outer_grid(25, 100, 100, 8), Some(25)); + assert_eq!(map_element_split_to_outer_grid(50, 100, 100, 8), Some(50)); + assert_eq!(map_element_split_to_outer_grid(75, 100, 100, 8), Some(75)); + assert_eq!(map_element_split_to_outer_grid(100, 100, 100, 8), None); + + let mut splits = (1..1_000) + .filter_map(|split| { + map_element_split_to_outer_grid(split, 1_000, 100_000, MIN_LIST_SPLIT_COUNT) + }) + .collect::>(); + splits.dedup(); + + let expected = (1..MIN_LIST_SPLIT_COUNT) + .map(|grid_index| grid_index * 100_000 / MIN_LIST_SPLIT_COUNT) + .collect::>(); + assert_eq!(splits, expected); +} + +#[rstest] +#[case::empty(0, 64)] +#[case::small(100_000, 64)] +#[case::floor_boundary(64 * 8192, 64)] +#[case::past_floor(64 * 8192 + 1, 128)] +#[case::million(1_000_000, 128)] +#[case::ten_million(10_000_000, 2048)] +fn split_grid_grows_with_row_count(#[case] outer_row_count: u64, #[case] expected: u64) { + assert_eq!(list_split_grid_size(outer_row_count), expected); +} + +#[tokio::test] +async fn nested_list_propagates_element_splits() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let inner = ListArray::try_new( + PrimitiveArray::from_iter(0..128_i32).into_array(), + PrimitiveArray::from_iter((0..=8_u32).map(|idx| idx * 16)).into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let outer = ListArray::try_new( + inner, + buffer![0u32, 2, 4, 6, 8].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + + let inner_strategy = ListLayoutStrategy::default().with_elements(chunked_elements_strategy()); + let strategy = ListLayoutStrategy::default().with_elements(Arc::new(inner_strategy)); + let (segments, layout, session) = write_layout(&strategy, outer).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + + let splits = SplitBy::Layout.splits(reader.as_ref(), &(0..4), &[FieldMask::All])?; + assert_eq!(splits, vec![0, 1, 2, 3, 4]); + Ok(()) +} + +/// A list strategy whose `elements` child is repartitioned into two-element chunks, so the +/// reader takes the bounded (chunk-skipping) path for strict sub-ranges. Offsets stay flat. +fn chunked_elements_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default().with_elements(chunked_elements_strategy()) +} + +fn chunked_elements_strategy() -> Arc { + Arc::new(RepartitionStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + RepartitionWriterOptions { + block_size_minimum: 0, + block_len_multiple: 2, + block_size_target: None, + canonicalize: true, + }, + )) +} + +/// The chunked-elements strategy must actually produce a chunked `elements` layout, otherwise +/// the reader would silently take the whole-chunk path and the bounded read would be untested. +#[tokio::test] +async fn chunked_elements_produces_chunked_layout() -> VortexResult<()> { + let list = create_wider_list_array(false); + let (_segments, layout, _session) = + write_layout(&chunked_elements_list_strategy(), list).await?; + let tree = layout.display_tree().to_string(); + assert!( + tree.contains("elements: vortex.chunked"), + "elements should be chunked:\n{tree}" + ); + Ok(()) +} + +/// A sparse mask must remain selective even when the requested row range covers the complete +/// local list layout. The selected first list touches one element chunk plus the offsets +/// segment; reading all five element chunks would make the count six. +#[tokio::test] +async fn full_range_sparse_mask_crops_element_read() -> VortexResult<()> { + let list = create_wider_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = + write_layout(&chunked_elements_list_strategy(), list.clone()).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader("".into(), Arc::clone(&source) as _, &session, &ctx)?; + + let mask = Mask::from_iter([true, false, false, false, false]); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + assert_eq!(source.requests(), 2); + Ok(()) +} + +/// With chunked elements, sub-range projections take the bounded read path. Every +/// range/mask/nullability combination must match the same projection over the ground-truth +/// array (`list.slice(range).filter(mask)`). +#[rstest] +#[case::full_all_true(0..5, Mask::new_true(5), false)] +#[case::subrange_all_true(1..4, Mask::new_true(3), false)] +#[case::subrange_sparse(1..4, Mask::from_iter([true, false, true]), false)] +#[case::partial_start(0..2, Mask::new_true(2), false)] +#[case::partial_end(2..5, Mask::new_true(3), false)] +#[case::single_non_empty(0..1, Mask::new_true(1), false)] +#[case::single_empty_row(2..3, Mask::from_iter([true]), false)] +#[case::empty_range(2..2, Mask::new_true(0), false)] +#[case::subrange_all_false(1..4, Mask::new_false(3), false)] +#[case::subrange_single_interior(0..4, Mask::from_iter([false, true, false, false]), false)] +#[case::subrange_sparse_nullable(1..4, Mask::from_iter([true, false, true]), true)] +#[case::partial_end_nullable(2..5, Mask::new_true(3), true)] +#[tokio::test] +async fn chunked_elements_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_wider_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = + write_layout(&chunked_elements_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let sliced = list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; + let expected = sliced.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// Lists `[0, 1, 2]`, `[]`, `[3, 4, 5]`, `[6, 7]`, `[8, 9]`. When nullable, the third is null +/// and keeps its elements. +fn create_ten_element_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) + } else { + Validity::NonNullable + }; + ListArray::try_new( + PrimitiveArray::from_iter(0..10i32).into_array(), + buffer![0u32, 3, 3, 6, 8, 10].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +/// Slices of one list share its whole `elements`, so every chunk but the first starts at a +/// nonzero offset and every chunk but the last leaves trailing elements unreferenced. +fn sliced_chunks(array: &ArrayRef, cuts: &[usize]) -> VortexResult> { + let mut bounds = vec![0]; + bounds.extend_from_slice(cuts); + bounds.push(array.len()); + bounds + .windows(2) + .map(|range| array.slice(range[0]..range[1])) + .collect() +} + +fn chunked_flat() -> Arc { + Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())) +} + +/// A list strategy that keeps every chunk, so a multi-chunk stream reaches the list writer. +fn chunked_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default() + .with_elements(chunked_flat()) + .with_offsets(chunked_flat()) + .with_validity(chunked_flat()) +} + +async fn assert_round_trips( + strategy: &S, + chunks: Vec, + expected: ArrayRef, +) -> VortexResult<()> { + let chunked = ChunkedArray::try_new(chunks, expected.dtype().clone())?.into_array(); + let (segments, layout, session) = write_layout(strategy, chunked).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + + let len = expected.len(); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..len as u64), &expr, MaskFuture::new_true(len))? + .await?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[rstest] +#[case::one_cut(&[2], false, false)] +#[case::two_cuts(&[1, 3], false, false)] +#[case::null_and_empty_at_cuts(&[1, 3], true, false)] +#[case::list_view_chunks(&[1, 3], true, true)] +#[case::non_nullable_list_view_chunks(&[1, 3], false, true)] +#[tokio::test] +async fn sliced_list_chunks_round_trip( + #[case] cuts: &[usize], + #[case] nullable: bool, + #[case] as_list_view: bool, +) -> VortexResult<()> { + let list = create_ten_element_list_array(nullable); + let source = if as_list_view { + let mut ctx = SESSION.create_execution_ctx(); + list.clone() + .execute::(&mut ctx)? + .into_array() + } else { + list.clone() + }; + let chunks = sliced_chunks(&source, cuts)?; + assert_round_trips(&chunked_list_strategy(), chunks, list).await +} + +#[tokio::test] +async fn sliced_nested_list_chunks_round_trip() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let inner = ListArray::try_new( + PrimitiveArray::from_iter(0..12i32).into_array(), + buffer![0u32, 2, 2, 5, 7, 9, 12].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let outer = ListArray::try_new( + inner, + buffer![0u32, 2, 3, 5, 6].into_array(), + Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()), + &mut ctx, + )? + .into_array(); + + let strategy = chunked_list_strategy().with_elements(Arc::new(chunked_list_strategy())); + assert_round_trips(&strategy, sliced_chunks(&outer, &[1, 2])?, outer).await +} + +/// Lists `[{a, 1}, null]`, null (hiding `[{c, i32::MAX}]`), `[]`, `[{null, 3}, {e, 4}]` and +/// `[{f, i32::MAX}]`, of nullable `{sku: utf8?, qty: i32}` elements. +fn create_items_list_array() -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let elements = StructArray::try_new( + FieldNames::from(["sku", "qty"]), + vec![ + VarBinViewArray::from_iter_nullable_str([ + Some("a"), + Some("b"), + Some("c"), + None, + Some("e"), + Some("f"), + ]) + .into_array(), + buffer![1i32, 2, i32::MAX, 3, 4, i32::MAX].into_array(), + ], + 6, + Validity::from_iter([true, false, true, true, true, true]), + )? + .into_array(); + Ok(ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 5, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// A list strategy that writes struct elements as a struct layout, so each element field and the +/// element validity is a flat layout of one segment. +fn struct_elements_list_strategy() -> ListLayoutStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + ListLayoutStrategy::default() + .with_elements(Arc::new(StructStrategy::new(Arc::clone(&flat), flat))) +} + +fn sku_lambda() -> VortexResult { + Lambda::new(["x"], get_item("sku", var("x"))) +} + +fn qty_lambda() -> VortexResult { + Lambda::new(["x"], get_item("qty", var("x"))) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on `i32::MAX`. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// Projects `expr` over `row_range` under `mask` and counts the segments the read requests. +async fn project_counting( + list: ArrayRef, + expr: &Expression, + row_range: Range, + mask: Mask, +) -> VortexResult<(ArrayRef, usize)> { + let (segments, layout, session) = write_layout(&struct_elements_list_strategy(), list).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &session, + &LayoutReaderContext::new(), + )?; + let expr = expr.bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask))? + .await?; + // Execute so lazy results surface their errors before the count is read. + let result = result + .execute::(&mut session.create_execution_ctx())? + .0 + .into_array(); + Ok((result, source.requests())) +} + +/// The expected projection: `expr` over the rows of `list` in `row_range` that `mask` selects. +fn expected_projection( + list: &ArrayRef, + expr: &Expression, + row_range: &Range, + mask: Mask, +) -> VortexResult { + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)? + .filter(mask)? + .apply(expr) +} + +/// A projection that reads the elements only through `list_transform` lambdas reads the element +/// columns those lambdas read, plus the offsets, the list validity and the element validity. The +/// stored list has five segments: offsets, list validity, element validity, `sku` and `qty`. +#[rstest] +#[case::root(root(), 5)] +#[case::sku(list_transform(root(), sku_lambda()?), 4)] +#[case::qty(list_transform(root(), qty_lambda()?), 4)] +#[case::both( + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("qtys", list_transform(root(), qty_lambda()?)), + ], + Nullability::NonNullable, + ), + 5 +)] +#[case::with_length( + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("len", list_length(root())), + ], + Nullability::NonNullable, + ), + 4 +)] +#[case::predicate(list_contains(list_transform(root(), sku_lambda()?), lit("e")), 4)] +#[tokio::test] +async fn element_projection_reads_needed_fields( + #[case] expr: Expression, + #[case] segments: usize, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let (result, requests) = project_counting(list.clone(), &expr, 0..5, Mask::new_true(5)).await?; + let expected = list.apply(&expr)?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// Pushed-down lambdas keep the semantics of `list_transform` for null lists, empty lists and +/// null elements, over every read path: full, bounded and sparse. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(1..4, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, true, false, true]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[case::empty_list_only(2..3, Mask::new_true(1))] +#[case::none_selected(0..5, Mask::new_false(5))] +#[case::empty_range(2..2, Mask::new_true(0))] +#[tokio::test] +async fn element_projection_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + list_transform(root(), sku_lambda()?), + list_transform(root(), qty_lambda()?), + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("valid", is_not_null(root())), + ], + Nullability::NonNullable, + ) + )] + expr: Expression, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let expected = expected_projection(&list, &expr, &row_range, mask.clone())?; + let (result, _) = project_counting(list, &expr, row_range, mask).await?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists, as in memory: +/// the `i32::MAX` under the null list never reaches it, nor does the one in the last list when the +/// mask leaves that list out. Only `qty` is read. +#[rstest] +#[case::full_without_last(0..4, Mask::new_true(4))] +#[case::masked_last(0..5, Mask::from_iter([true, true, true, true, false]))] +#[case::sparse(0..5, Mask::from_iter([false, true, false, true, false]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[tokio::test] +async fn fallible_lambda_runs_on_selected_valid_lists( + #[case] row_range: Range, + #[case] mask: Mask, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let expr = qty_plus_one()?; + let expected = expected_projection(&list, &expr, &row_range, mask.clone())?; + let (result, requests) = project_counting(list, &expr, row_range, mask).await?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(requests, 4); + Ok(()) +} + +/// The reader fails where the lambda fails in memory: on the `i32::MAX` of a selected valid list. +#[tokio::test] +async fn fallible_lambda_fails_on_selected_overflow() -> VortexResult<()> { + let list = create_items_list_array()?; + let expr = qty_plus_one()?; + let mut ctx = SESSION.create_execution_ctx(); + assert!( + list.clone() + .apply(&expr)? + .execute::(&mut ctx) + .is_err() + ); + assert!( + project_counting(list, &expr, 4..5, Mask::new_true(1)) + .await + .is_err() + ); + Ok(()) +} + +/// A filter through a pushed-down lambda reads only the element column it tests. +#[rstest] +#[case::dense(Mask::new_true(5))] +#[case::sparse(Mask::from_iter([false, false, false, true, false]))] +#[tokio::test] +async fn filter_evaluation_pushes_lambda(#[case] input: Mask) -> VortexResult<()> { + let list = create_items_list_array()?; + let (segments, layout, session) = + write_layout(&struct_elements_list_strategy(), list.clone()).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &session, + &LayoutReaderContext::new(), + )?; + + let filter = list_contains(list_transform(root(), sku_lambda()?), lit("e")); + let result = reader + .filter_evaluation( + &(0..5), + &filter.bind(reader.dtype())?, + MaskFuture::ready(input.clone()), + )? + .await?; + + let mut ctx = session.create_execution_ctx(); + let matches = list + .apply(&filter)? + .fill_null(false)? + .execute::(&mut ctx)?; + assert_eq!(result, &input & &matches); + assert_eq!(source.requests(), 4); + Ok(()) +} + +/// Every split sees the same element projection, so the elements reader's identity-keyed caches +/// stay warm. +#[tokio::test] +async fn element_projection_is_cached() -> VortexResult<()> { + let list = create_items_list_array()?; + let (segments, layout, session) = write_layout(&struct_elements_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + let reader = reader + .as_any() + .downcast_ref::() + .expect("ListReader"); + + let expr = list_transform(root(), sku_lambda()?).bind(reader.dtype())?; + let first = reader.element_projection(&expr)?; + assert!(Arc::ptr_eq(&first, &reader.element_projection(&expr)?)); + Ok(()) +} diff --git a/vortex-layout/src/layouts/struct_/reader.rs b/vortex-layout/src/layouts/struct_/reader.rs index a3535bf8f37..00e1404e724 100644 --- a/vortex-layout/src/layouts/struct_/reader.rs +++ b/vortex-layout/src/layouts/struct_/reader.rs @@ -356,6 +356,21 @@ fn expand_struct_root( }); } + // A strict function of a field is null wherever the struct is, so it can run on the + // field inside the struct validity. It then stays with the field when the expression + // is partitioned, and the field reader can push it down, as a list reader pushes the + // lambda of `list_transform($.items, x -> x.sku)` into its elements. Only a function + // that cannot fail may run on the values that null structs hide. + if let Some(validity) = validity + && is_strict_field_function(&node) + { + return Ok(Transformed { + value: mask(node, validity.clone()), + changed: true, + order: TraversalOrder::Skip, + }); + } + let Some(scalar_fn) = node.as_scalar() else { return Ok(Transformed::no(node)); }; @@ -424,6 +439,20 @@ fn expand_struct_root( .into_inner()) } +/// Whether `expr` applies only strict functions of one argument that cannot fail to a field of the +/// root, as `list_transform($.items, x -> x.sku)` does. +fn is_strict_field_function(expr: &BoundExpression) -> bool { + let [child] = expr.children() else { + return false; + }; + let strict = expr.as_scalar().is_some_and(|scalar_fn| { + let signature = scalar_fn.signature(); + signature.is_strict() && signature.is_infallible() + }); + strict + && ((child.is::() && child.child(0).is_root()) || is_strict_field_function(child)) +} + // Same as make_bound_free_field_annotator, but handles is_not_null($) as the // struct's own validity coordinate fn make_struct_item_annotator( @@ -720,6 +749,7 @@ mod tests { use vortex_array::VortexSessionExecute; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; @@ -734,13 +764,17 @@ mod tests { use vortex_array::dtype::RESERVED_VALIDITY_FIELD_NAME; use vortex_array::dtype::StructFields; use vortex_array::expr::Expression; + use vortex_array::expr::Lambda; use vortex_array::expr::and; + use vortex_array::expr::checked_add; use vortex_array::expr::col; use vortex_array::expr::eq; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::is_not_null; use vortex_array::expr::is_null; + use vortex_array::expr::list_length; + use vortex_array::expr::list_transform; use vortex_array::expr::lit; use vortex_array::expr::lt; use vortex_array::expr::mask; @@ -750,6 +784,7 @@ mod tests { use vortex_array::expr::root; use vortex_array::expr::select; use vortex_array::expr::select_exclude; + use vortex_array::expr::var; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_buffer::buffer; @@ -2354,4 +2389,115 @@ mod tests { Ok(()) }) } + + /// Writes `{s: {inner: {x, y}, items: list<{sku, qty}>}?}` with the list layout, where `s` is + /// null in row 1, and returns the table too. The item of row 1 has the SKU `i32::MAX`, which + /// overflows when added to. + #[fixture] + fn nullable_struct_with_nested_columns() -> (Arc, LayoutRef, ArrayRef) { + let mut ctx = SESSION.create_execution_ctx(); + let inner = StructArray::try_from_iter([ + ("x", buffer![1i32, 2, 3].into_array()), + ("y", buffer![4i32, 5, 6].into_array()), + ]) + .unwrap(); + let elements = StructArray::try_from_iter([ + ("sku", buffer![10i32, 11, i32::MAX, 13].into_array()), + ("qty", buffer![20i32, 21, 22, 23].into_array()), + ]) + .unwrap(); + let items = ListArray::try_new( + elements.into_array(), + buffer![0u32, 2, 3, 4].into_array(), + Validity::NonNullable, + &mut ctx, + ) + .unwrap(); + let s = StructArray::try_from_iter_with_validity( + [("inner", inner.into_array()), ("items", items.into_array())], + Validity::Array(BoolArray::from_iter([true, false, true]).into_array()), + ) + .unwrap(); + let table = StructArray::try_from_iter([("s", s.into_array())]) + .unwrap() + .into_array(); + + let segments = Arc::new(TestSegments::default()); + let (ptr, eof) = SequenceId::root().split(); + let strategy = TableStrategy::new( + Arc::new(FlatLayoutStrategy::default()), + Arc::new(FlatLayoutStrategy::default()), + ) + .with_list_layout(); + let segments2 = Arc::::clone(&segments); + let stream = table.to_array_stream().sequenced(ptr); + let layout = block_on(|handle| async move { + let session = new_session().with_handle(handle); + strategy + .write_stream( + ArrayContext::empty().into(), + segments2, + stream, + eof, + &session, + ) + .await + }) + .unwrap(); + + (segments, layout, table) + } + + /// A strict function of a field of a nullable struct reaches the field reader inside the + /// struct validity, so the field reader reads only the columns the function needs. + #[rstest] + // The validity of `s` and `s.inner.x`, not `s.inner.y`. + #[case::nested_field(get_item("x", get_item("inner", get_item("s", root()))), 2)] + // The validity of `s`, the offsets of `s.items` and the `sku` elements, not the `qty` ones. + #[case::list_transform( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], get_item("sku", var("item")))?, + ), + 3 + )] + // The validity of `s` and the offsets of `s.items`, not their elements. + #[case::list_length(list_length(get_item("items", get_item("s", root()))), 2)] + // A lambda that can fail must not run on the items of null structs, where it would overflow, + // so it stays outside the struct validity and the items are read whole. + #[case::fallible_lambda( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], checked_add(get_item("sku", var("item")), lit(1i32)))?, + ), + 4 + )] + fn test_strict_function_of_nullable_struct_field_reads_needed_columns( + #[from(nullable_struct_with_nested_columns)] (segments, layout, table): ( + Arc, + LayoutRef, + ArrayRef, + ), + #[case] expr: Expression, + #[case] expected_requests: usize, + ) -> VortexResult<()> { + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &SESSION, + &Default::default(), + )?; + let bound = expr.bind(reader.dtype())?; + let project = reader.projection_evaluation(&(0..3), &bound, MaskFuture::new_true(3))?; + let result = block_on(move |_| project)?; + + assert_arrays_eq!( + result, + table.apply(&expr)?, + &mut SESSION.create_execution_ctx() + ); + assert_eq!(source.requests(), expected_requests); + Ok(()) + } } diff --git a/vortex-layout/src/scan/v2/tests/lists.rs b/vortex-layout/src/scan/v2/tests/lists.rs new file mode 100644 index 00000000000..8255c55ee94 --- /dev/null +++ b/vortex-layout/src/scan/v2/tests/lists.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! List layouts on the planner-driven scan, mirroring the layout reader tests of the list layout. + +use std::ops::Range; +use std::sync::Arc; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; +use vortex_mask::Mask; +use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; +use vortex_session::VortexSession; + +use super::builder; +use super::collect_scan; +use super::write_chunks; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::list::writer::ListLayoutStrategy; +use crate::layouts::struct_::writer::StructStrategy; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSource; +use crate::test::new_session; + +/// Lists `[{a, 1}, null]`, null (hiding `[{c, i32::MAX}]`), `[]`, `[{null, 3}, {e, 4}]` and +/// `[{f, i32::MAX}]`, of nullable `{sku: utf8?, qty: i32}` elements, as the only chunk of a file +/// whatever row it starts at. +fn items(_start: usize) -> VortexResult { + let mut ctx = new_session().create_execution_ctx(); + let elements = StructArray::try_new( + FieldNames::from(["sku", "qty"]), + vec![ + VarBinViewArray::from_iter_nullable_str([ + Some("a"), + Some("b"), + Some("c"), + None, + Some("e"), + Some("f"), + ]) + .into_array(), + buffer![1i32, 2, i32::MAX, 3, 4, i32::MAX].into_array(), + ], + 6, + Validity::from_iter([true, false, true, true, true, true]), + )? + .into_array(); + Ok(ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 5, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// Writes struct elements as a struct layout, so the list has five segments: its offsets, its +/// validity, the element validity, `sku` and `qty`. +fn struct_elements_list_strategy() -> ListLayoutStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + ListLayoutStrategy::default() + .with_elements(Arc::new(StructStrategy::new(Arc::clone(&flat), flat))) +} + +fn sku() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("sku", var("x")))?, + )) +} + +fn qty() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("qty", var("x")))?, + )) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on `i32::MAX`. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// A list written with `strategy` from `list`, its segments, and a session for scanning it. +async fn write( + strategy: &dyn LayoutStrategy, + list: fn(usize) -> VortexResult, +) -> VortexResult<(VortexSession, Arc, LayoutRef)> { + let session = new_session().with_tokio(); + let (segments, layout) = write_chunks(&session, strategy, list, 1).await?; + Ok((session, segments, layout)) +} + +/// Scans `expr` over the rows of `row_range` that `mask` selects, filtered by `filter`, and counts +/// the segments the scan requests. +async fn scan_counting( + strategy: &dyn LayoutStrategy, + list: fn(usize) -> VortexResult, + expr: &Expression, + filter: Option<&Expression>, + row_range: Range, + mask: &Mask, +) -> VortexResult<(ArrayRef, usize)> { + let (session, segments, layout) = write(strategy, list).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let segments: Arc = Arc::::clone(&source); + let projection = expr.bind(layout.dtype())?; + let dtype = projection.dtype().clone(); + let start = row_range.start; + let rows = (0..mask.len()) + .filter(|&row| mask.value(row)) + .map(|row| start + row as u64); + let scan = builder(&session, &segments, &layout)? + .with_projection(projection) + .with_some_filter( + filter + .map(|filter| filter.bind(layout.dtype())) + .transpose()?, + ) + .with_row_range(row_range) + .with_row_indices(StrictSortedBuffer::try_new(Buffer::from_iter(rows))?); + let result = collect_scan(dtype, scan).await?; + // Execute so lazy results surface their errors before the count is read. + let result = result + .execute::(&mut session.create_execution_ctx())? + .0 + .into_array(); + Ok((result, source.requests())) +} + +/// `expr` over the rows of `list` in `row_range` that `mask` selects. +fn expected( + list: &ArrayRef, + expr: &Expression, + row_range: &Range, + mask: &Mask, +) -> VortexResult { + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)? + .filter(mask.clone())? + .apply(expr) +} + +/// A projection reads only the list children it needs: the validity for a null check, the offsets +/// and the validity for the lengths, and for `list_transform` lambdas the element columns they +/// read, the element validity, the offsets and the validity. These are the reads of the layout +/// reader. +#[rstest] +#[case::root(root(), 5)] +#[case::is_null(is_null(root()), 1)] +#[case::length(list_length(root()), 2)] +#[case::sku(sku()?, 4)] +#[case::qty(qty()?, 4)] +#[case::both( + pack([("skus", sku()?), ("qtys", qty()?)], Nullability::NonNullable), + 5 +)] +#[case::with_length( + pack([("skus", sku()?), ("len", list_length(root()))], Nullability::NonNullable), + 4 +)] +#[case::predicate(list_contains(sku()?, lit("e")), 4)] +#[tokio::test] +async fn element_projection_reads_needed_fields( + #[case] expr: Expression, + #[case] segments: usize, +) -> VortexResult<()> { + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + items, + &expr, + None, + 0..5, + &Mask::new_true(5), + ) + .await?; + let expected = items(0)?.apply(&expr)?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// Lists and their pushed-down lambdas keep the semantics of `list_transform` for null lists, +/// empty lists and null elements over any rows: whole, a range, or a selection. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(1..4, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, true, false, true]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[case::empty_list_only(2..3, Mask::new_true(1))] +#[case::none_selected(0..5, Mask::new_false(5))] +#[case::empty_range(2..2, Mask::new_true(0))] +#[tokio::test] +async fn element_projection_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + root(), + sku()?, + qty()?, + list_length(root()), + pack( + [("skus", sku()?), ("valid", is_not_null(root()))], + Nullability::NonNullable, + ) + )] + expr: Expression, +) -> VortexResult<()> { + let expected = expected(&items(0)?, &expr, &row_range, &mask)?; + let (result, _) = scan_counting( + &struct_elements_list_strategy(), + items, + &expr, + None, + row_range, + &mask, + ) + .await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists, as in memory: +/// the `i32::MAX` under the null list never reaches it, nor does the one in the last list when the +/// selection leaves that list out. Only `qty`, the element validity, the offsets and the validity +/// are read, and no element at all when no selected list is valid. +#[rstest] +#[case::full_without_last(0..4, Mask::new_true(4), 4)] +#[case::unselected_last(0..5, Mask::from_iter([true, true, true, true, false]), 4)] +#[case::sparse(0..5, Mask::from_iter([false, true, false, true, false]), 4)] +#[case::null_list_only(1..2, Mask::new_true(1), 2)] +#[tokio::test] +async fn fallible_lambda_runs_on_selected_valid_lists( + #[case] row_range: Range, + #[case] mask: Mask, + #[case] segments: usize, +) -> VortexResult<()> { + let expr = qty_plus_one()?; + let expected = expected(&items(0)?, &expr, &row_range, &mask)?; + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + items, + &expr, + None, + row_range, + &mask, + ) + .await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// The scan fails where the lambda fails in memory: on the `i32::MAX` of a selected valid list. +#[tokio::test] +async fn fallible_lambda_fails_on_selected_overflow() -> VortexResult<()> { + let expr = qty_plus_one()?; + let mut ctx = new_session().create_execution_ctx(); + assert!( + items(0)? + .apply(&expr)? + .execute::(&mut ctx) + .is_err() + ); + let scan = scan_counting( + &struct_elements_list_strategy(), + items, + &expr, + None, + 4..5, + &Mask::new_true(1), + ) + .await; + assert!(scan.is_err()); + Ok(()) +} + +/// A filter through a pushed-down lambda reads the element column it tests and keeps the rows +/// the filter keeps in memory. The projection of the null checks shares the filter's read of the +/// validity. +#[rstest] +#[case::dense(Mask::new_true(5))] +#[case::sparse(Mask::from_iter([false, false, false, true, false]))] +#[tokio::test] +async fn filter_pushes_lambda(#[case] mask: Mask) -> VortexResult<()> { + let filter = list_contains(sku()?, lit("e")); + let projection = is_not_null(root()); + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + items, + &projection, + Some(&filter), + 0..5, + &mask, + ) + .await?; + + let list = items(0)?.filter(mask)?; + let mut ctx = new_session().create_execution_ctx(); + let keep = list + .clone() + .apply(&filter)? + .fill_null(false)? + .execute::(&mut ctx)?; + assert_arrays_eq!(result, list.filter(keep)?.apply(&projection)?, &mut ctx); + assert_eq!(requests, 4); + Ok(()) +} + +/// `[[1, 2], null, []]`, `null`, `[[3]]`, `[]` and `[[], [4, 5, 6]]`, lists of nullable lists, as +/// the only chunk of a file whatever row it starts at. +fn nested(_start: usize) -> VortexResult { + let mut ctx = new_session().create_execution_ctx(); + let inner = ListArray::try_new( + buffer![1i64, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 2, 2, 3, 3, 6].into_array(), + Validity::from_iter([true, false, true, true, true, true]), + &mut ctx, + )? + .into_array(); + Ok(ListArray::try_new( + inner, + buffer![0u32, 3, 3, 4, 4, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// A list of lists reads the inner lists of its selected lists, and their elements through their +/// own offsets. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(2..5, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, false, false, true]))] +#[tokio::test] +async fn nested_lists_round_trip( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + root(), + list_transform(root(), Lambda::new(["x"], list_length(var("x")))?) + )] + expr: Expression, +) -> VortexResult<()> { + let chunked: Arc = + Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())); + let strategy = ListLayoutStrategy::default() + .with_elements(Arc::new(ListLayoutStrategy::default())) + .with_offsets(Arc::clone(&chunked)) + .with_validity(chunked); + let expected = expected(&nested(0)?, &expr, &row_range, &mask)?; + let (result, _) = scan_counting(&strategy, nested, &expr, None, row_range, &mask).await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + Ok(()) +} diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests/mod.rs similarity index 92% rename from vortex-layout/src/scan/v2/tests.rs rename to vortex-layout/src/scan/v2/tests/mod.rs index 1ddabcb5a2d..4ef5cd6d126 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +mod lists; + use std::future::poll_fn; use std::num::NonZeroUsize; use std::ops::Range; @@ -32,6 +34,7 @@ use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtVTable; use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; use vortex_array::expr::and; use vortex_array::expr::cast; use vortex_array::expr::checked_add; @@ -41,12 +44,16 @@ use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::is_not_null; use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; use vortex_array::expr::lit; use vortex_array::expr::lt; use vortex_array::expr::not; use vortex_array::expr::or; use vortex_array::expr::pack; use vortex_array::expr::root; +use vortex_array::expr::var; use vortex_array::validity::Validity; use vortex_arrow::ArrowSessionExt; use vortex_buffer::Alignment; @@ -173,7 +180,8 @@ fn points_chunk(start: usize, extension: bool, nullability: Nullability) -> Vort /// every seventh. /// /// `x` is the row, `y` ten times the row and `list` holds the row twice. The fields keep their -/// values in rows where a struct above them is null. +/// values in rows where a struct above them is null, except that a list there holds `i64::MAX` in +/// place of its second row, which overflows when added to. fn message_chunk(start: usize) -> VortexResult { let mut ctx = SESSION.create_execution_ctx(); let rows = start..start + CHUNK_ROWS; @@ -191,11 +199,17 @@ fn message_chunk(start: usize) -> VortexResult { CHUNK_ROWS, Validity::from_iter(rows.clone().map(|row| row % 7 != 0)), )?; - let elements = Buffer::from_iter( - rows.clone() - .flat_map(|row| [row, row]) - .map(|row| i64::try_from(row).unwrap_or(i64::MAX)), - ); + let elements = Buffer::from_iter(rows.clone().flat_map(|row| { + let value = i64::try_from(row).unwrap_or(i64::MAX); + [ + value, + if row.is_multiple_of(5) { + i64::MAX + } else { + value + }, + ] + })); let offsets = Buffer::from_iter((0..=CHUNK_ROWS).map(|i| u32::try_from(2 * i).unwrap_or(0))); let list = ListArray::try_new( elements.into_array(), @@ -675,27 +689,63 @@ async fn arrow_stream_projects_across_chunks() -> VortexResult<()> { Ok(()) } -/// V2 rejects list layouts: their element ranges are only known once their offsets are read. -#[tokio::test] -async fn list_layouts_return_an_error() -> VortexResult<()> { - let session = new_session().with_tokio(); - let strategy = TableStrategy::new(chunked_flat(), chunked_flat()).with_list_layout(); - let (segments, layout) = write(&session, &strategy).await?; - let error = run_scan(builder(&session, &segments, &layout)?) - .await - .expect_err("V2 must reject an unsupported layout"); - assert!(error.to_string().contains("vortex.plan.list_pack")); - Ok(()) -} - +/// List layouts scan the same on both executors, over row ranges, row indices and filters, whose +/// rows of lists map to the elements the offsets of those lists give. +#[rstest] +#[case::whole(root(), None, None, None)] +#[case::row_range(get_item("lists", root()), None, Some(250..3_100), None)] +#[case::row_indices( + get_item("lists", root()), + None, + None, + Some(&[0, 1, 999, 1000, 2500, 3999][..]) +)] +#[case::filter( + get_item("lists", root()), + Some(gt(get_item("ints", root()), lit(1500i32))), + Some(900..3_100), + None +)] +#[case::filter_on_lists( + get_item("ints", root()), + Some(list_contains(get_item("lists", root()), lit(4001i64))), + None, + None +)] +#[case::lengths(list_length(get_item("lists", root())), None, Some(10..20), None)] #[tokio::test] -async fn projection_skips_unsupported_unselected_layouts() -> VortexResult<()> { +async fn list_layouts_match_v1( + #[values(false, true)] zoned: bool, + #[case] projection: Expression, + #[case] filter: Option, + #[case] row_range: Option>, + #[case] rows: Option<&'static [u64]>, +) -> VortexResult<()> { let session = new_session().with_tokio(); - let strategy = TableStrategy::new(chunked_flat(), chunked_flat()).with_list_layout(); + let strategy = if zoned { + zoned_table_strategy() + } else { + table_strategy() + } + .with_list_layout(); let (segments, layout) = write(&session, &strategy).await?; assert_same_as_v1(&session, || { - Ok(builder(&session, &segments, &layout)? - .with_projection(get_item("ints", root()).bind(layout.dtype())?)) + let mut builder = builder(&session, &segments, &layout)? + .with_projection(projection.bind(layout.dtype())?) + .with_some_filter( + filter + .as_ref() + .map(|filter| filter.bind(layout.dtype())) + .transpose()?, + ); + if let Some(row_range) = row_range.clone() { + builder = builder.with_row_range(row_range); + } + if let Some(rows) = rows { + builder = + builder.with_row_indices(StrictSortedBuffer::try_new(Buffer::copy_from(rows))?); + } + Ok(builder) }) .await } @@ -745,10 +795,25 @@ fn msg(field: &str) -> Expression { get_item(field, get_item("msg", root())) } -/// A nullable struct with a list field, written with the list layout, scans on the planner-driven -/// executor whenever the scan reads no list. Its fields are null wherever a struct above them is. +/// A nullable struct with a list field, written with the list layout, scans the same on both +/// executors, also where the scan reads the list. Its fields are null wherever a struct above them +/// is. #[rstest] #[case::sibling_of_list(msg("x"), None)] +#[case::list(msg("list"), None)] +#[case::list_length(list_length(msg("list")), None)] +#[case::list_transform( + list_transform(msg("list"), Lambda::new(["x"], gt(var("x"), lit(2500i64)))?), + None +)] +#[case::fallible_list_transform( + list_transform( + msg("list"), + Lambda::new(["x"], checked_add(var("x"), lit(1i64)))?, + ), + None +)] +#[case::filter_on_list(get_item("id", root()), Some(list_contains(msg("list"), lit(2500i64))))] #[case::nested_nullable(get_item("y", msg("inner")), None)] #[case::struct_validity(is_null(get_item("msg", root())), None)] #[case::pack( @@ -847,8 +912,8 @@ async fn pruning_beneath_a_nullable_struct_keeps_rows_of_any_filter( /// A filter the bounds of the field cannot prune reads its zone map and, in each of the four /// zones, the field, the validity of `s` and `id`: 13 segments. The pruned filter holds only in /// zone 0, so it reads the three there alone. The classic scan still reads `id` in every zone. A -/// float field prunes too: its zone map records whether each zone holds no NaN, which the bounds -/// of a float need. +/// float field prunes too: its zone map records the NaN count of each zone, and a count of zero +/// proves what the bounds of a float need, that the zone holds no NaN. #[rstest] #[case::v1(false, hidden_values_chunk, s_a(), lit(100i64), lit(10_000_000i64), 7)] #[case::v2(true, hidden_values_chunk, s_a(), lit(100i64), lit(10_000_000i64), 4)] diff --git a/vortex-scan/src/plan/builtins/list_pack.rs b/vortex-scan/src/plan/builtins/list_pack.rs deleted file mode 100644 index f5f1369c167..00000000000 --- a/vortex-scan/src/plan/builtins/list_pack.rs +++ /dev/null @@ -1,180 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::borrow::Cow; -use std::sync::Arc; - -use vortex_array::EmptyMetadata; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_err; -use vortex_session::registry::CachedId; - -use crate::plan::Plan; -use crate::plan::PlanId; -use crate::plan::PlanParts; -use crate::plan::PlanRef; -use crate::plan::PlanSlots; -use crate::plan::PlanVTable; - -const ELEMENTS: usize = 0; -const OFFSETS: usize = 1; -const VALIDITY: usize = 2; - -/// Assembles a list from slots `[elements, offsets, validity]`, with validity present exactly -/// when the list is nullable. -#[derive(Clone, Debug)] -pub struct ListPack; - -/// Operator-specific list assembly data. -#[derive(Clone, Debug)] -pub struct ListPackData; - -/// A plan that assembles a list from its children. -pub type ListPackPlan = Plan; - -impl ListPackPlan { - /// Creates a list assembly from potentially unbuilt slots without validation. - /// - /// # Safety - /// - /// `slots` must be `[elements, offsets, validity]`. `dtype` must be a list whose element - /// dtype matches the elements child. The offsets child must be a non-nullable integer with - /// `row_count + 1` rows. A non-nullable boolean validity child with `row_count` rows must be - /// present exactly when `dtype` is nullable. - pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { - PlanParts { - vtable: ListPack, - dtype, - row_count, - slots, - data: ListPackData, - } - .into_typed() - } - - /// Creates a list assembly from `elements` and `offsets`. - /// - /// `validity` is required exactly when `nullability` is [`Nullability::Nullable`]. The row - /// domain is one fewer than the number of offsets. - pub fn try_new( - nullability: Nullability, - row_count: u64, - elements: PlanRef, - offsets: PlanRef, - validity: Option, - ) -> VortexResult { - let dtype = DType::List(Arc::new(elements.dtype().clone()), nullability); - let slots = [Some(elements), Some(offsets), validity] - .into_iter() - .collect(); - validate_slots(&dtype, row_count, &slots)?; - - // SAFETY: All slot shape invariants were validated above. - Ok(unsafe { Self::from_slots_unchecked(dtype, row_count, slots) }) - } - - /// Returns the plan producing list elements. - pub fn elements(&self) -> VortexResult { - self.slot_required(ELEMENTS) - } - - /// Returns the plan producing list offsets. - pub fn offsets(&self) -> VortexResult { - self.slot_required(OFFSETS) - } - - /// Returns the plan producing list validity, if the list is nullable. - pub fn validity(&self) -> VortexResult> { - self.slot(VALIDITY) - } -} - -impl PlanVTable for ListPack { - type PlanData = ListPackData; - type Metadata = EmptyMetadata; - - fn id(&self) -> PlanId { - static ID: CachedId = CachedId::new("vortex.plan.list_pack"); - *ID - } - - fn metadata(_plan: &Plan) -> Option { - // Nullability is recoverable from the plan dtype. - Some(EmptyMetadata) - } - - fn with_slots( - plan: &Plan, - slots: &PlanSlots, - _data: &mut Self::PlanData, - ) -> VortexResult<()> { - validate_slots(plan.dtype(), plan.row_count(), slots) - } - - fn slot_name(_plan: &Plan, slot: usize) -> Cow<'_, str> { - match slot { - ELEMENTS => Cow::Borrowed("elements"), - OFFSETS => Cow::Borrowed("offsets"), - VALIDITY => Cow::Borrowed("validity"), - _ => Cow::Owned(format!("slot[{slot}]")), - } - } -} - -fn validate_slots(dtype: &DType, row_count: u64, slots: &PlanSlots) -> VortexResult<()> { - let elements_dtype = dtype - .as_list_element_opt() - .ok_or_else(|| vortex_err!("ListPack output dtype must be a list, got {dtype}"))?; - slots.check_len("ListPack", VALIDITY + 1)?; - - let elements = slots.required(ELEMENTS)?; - if elements.dtype() != elements_dtype.as_ref() { - vortex_bail!( - "ListPack elements child has dtype {} but the list element dtype is {}", - elements.dtype(), - elements_dtype - ); - } - - let offsets = slots.required(OFFSETS)?; - if !offsets.dtype().is_int() || offsets.dtype().is_nullable() { - vortex_bail!( - "ListPack offsets child must have a non-nullable integer dtype, got {}", - offsets.dtype() - ); - } - let offsets_row_count = row_count - .checked_add(1) - .ok_or_else(|| vortex_err!("ListPack offsets row count overflow"))?; - if offsets.row_count() != offsets_row_count { - vortex_bail!( - "ListPack offsets child has {} rows but must have {offsets_row_count}", - offsets.row_count() - ); - } - - match (dtype.is_nullable(), slots.get(VALIDITY)?) { - (true, Some(validity)) => { - let validity_dtype = DType::Bool(Nullability::NonNullable); - if validity.dtype() != &validity_dtype { - vortex_bail!( - "ListPack validity child has dtype {} but must have dtype {validity_dtype}", - validity.dtype() - ); - } - if validity.row_count() != row_count { - vortex_bail!( - "ListPack validity child has {} rows but the plan has {row_count}", - validity.row_count() - ); - } - } - (false, None) => {} - (true, None) => vortex_bail!("Nullable ListPack has no validity child"), - (false, Some(_)) => vortex_bail!("Non-nullable ListPack has a validity child"), - } - Ok(()) -} diff --git a/vortex-scan/src/plan/builtins/list_pack/execute.rs b/vortex-scan/src/plan/builtins/list_pack/execute.rs new file mode 100644 index 00000000000..87d3588ccb9 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/execute.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Assembling lists, reading their elements once their offsets give the element rows. + +use std::ops::Range; + +use rustc_hash::FxHashMap; +use smallvec::SmallVec; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::IntoArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::execution::operators::join; +use crate::execution::operators::join_inlet; +use crate::execution::pipeline::ReadId; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::execution::pipeline::Turn; +use crate::execution::pipeline::ValueCache; +use crate::plan::ListPackPlan; +use crate::source::SegmentId; + +const OFFSETS: usize = 0; +const VALIDITY: usize = 1; + +/// Assembles the selected lists of a row range from its inlets, the offsets of the range and the +/// validity of its selected lists, and from the elements those lists hold. +/// +/// The element rows of a list are known only once its offsets are read, so the elements cannot be +/// compiled with the lists. Once both inlets have closed, the source compiles the elements plan +/// over the elements of the selected valid lists as a scan of its own, which it runs within its +/// readiness checks: the reads that scan asks for are this source's reads, and their bytes go +/// back to it. The lists are emitted as one batch once every element has arrived. +pub(crate) struct ListSource { + plan: ListPackPlan, + /// The selected lists of the row range the offsets inlet covers. + selected: Mask, + session: VortexSession, + values: ValueCache, + state: State, +} + +enum State { + /// Waiting for the offsets and the validity. + Lists, + /// Reading the elements of the selected valid lists. + Elements(Box), + /// The lists, built and not yet emitted. + Built(ArrayRef), + Done, +} + +/// The scan of the elements of the selected valid lists. +struct ElementScan { + scan: Scan, + /// The scan's reads that have not arrived, by segment, oldest first. + reads: FxHashMap>, + /// What the scan produced, in element order. + elements: Vec, + dtype: DType, + lists: CompactedLists, +} + +impl ListSource { + /// A source of the `selected` lists of a row range, whose offsets inlet holds the offsets of + /// every list of the range, one more than `selected` is long, and whose validity inlet, present + /// exactly when the list is nullable, holds the validity of the selected lists. + pub(crate) fn new( + plan: ListPackPlan, + selected: Mask, + session: VortexSession, + values: ValueCache, + ) -> Self { + Self { + plan, + selected, + session, + values, + state: State::Lists, + } + } + + /// Compacts the lists once their offsets and validity have arrived, and starts the scan of + /// their elements. + fn read_lists(&mut self, cx: &mut Cx<'_>) -> VortexResult { + let offsets_dtype = self.plan.offsets()?.dtype().clone(); + let offsets = join_inlet(cx, OFFSETS, &offsets_dtype)? + .cast(DType::Primitive(PType::U64, Nullability::NonNullable))? + .execute::(cx.exec())?; + let validity = if self.plan.dtype().is_nullable() { + let validity = join_inlet(cx, VALIDITY, &DType::Bool(Nullability::NonNullable))?; + let valid = validity.clone().execute::(cx.exec())?; + Some((validity, valid)) + } else { + None + }; + let elements_plan = self.plan.elements()?; + let lists = CompactedLists::try_new( + offsets.as_slice::(), + &self.selected, + validity, + elements_plan.row_count(), + )?; + if lists.elements_mask.all_false() { + let elements = Canonical::empty(elements_plan.dtype()).into_array(); + return Ok(State::Built(lists.build(elements)?)); + } + let split = Split { + rows: lists.elements_range.clone(), + mask: lists.elements_mask.clone(), + }; + let dtype = elements_plan.dtype().clone(); + let scan = Scan::try_new(self.session.clone(), elements_plan, vec![split])? + .with_value_cache(self.values.clone()); + Ok(State::Elements(Box::new(ElementScan { + scan, + reads: FxHashMap::default(), + elements: Vec::new(), + dtype, + lists, + }))) + } +} + +impl ElementScan { + /// Hands the bytes that have arrived to the scan and runs it until it waits for more or has + /// finished, returning the lists once it has. + fn advance(&mut self, cx: &mut Cx<'_>) -> VortexResult> { + while let Some((segment, bytes)) = cx.take_segment() { + let read = self + .reads + .get_mut(&segment) + .filter(|reads| !reads.is_empty()) + .map(|reads| reads.remove(0)) + .ok_or_else(|| vortex_err!("List elements received {segment}, never asked for"))?; + self.scan.deliver(read, bytes)?; + } + loop { + match self.scan.step()? { + Turn::Read(read) => { + cx.request_read(read.segment_id); + self.reads.entry(read.segment_id).or_default().push(read.id); + } + Turn::Output(_, elements) => self.elements.push(elements), + Turn::Waiting => return Ok(None), + Turn::Done => { + let elements = join(&self.dtype, std::mem::take(&mut self.elements))?; + return self.lists.build(elements).map(Some); + } + } + } + } +} + +impl Source for ListSource { + fn ready(&mut self, cx: &mut Cx<'_>) -> VortexResult { + loop { + self.state = match &mut self.state { + State::Lists => { + if !cx.inlet(OFFSETS).closed() { + return Ok(SourceReady::Blocked(SourceBlocked::Inlet(OFFSETS))); + } + if self.plan.dtype().is_nullable() && !cx.inlet(VALIDITY).closed() { + return Ok(SourceReady::Blocked(SourceBlocked::Inlet(VALIDITY))); + } + self.read_lists(cx)? + } + State::Elements(scan) => match scan.advance(cx)? { + Some(lists) => State::Built(lists), + None => return Ok(SourceReady::Blocked(SourceBlocked::Io)), + }, + State::Built(_) | State::Done => return Ok(SourceReady::Ready), + }; + } + } +} + +impl Operator for ListSource { + fn compute(&mut self, _input: Input, _cx: &mut Cx<'_>) -> VortexResult { + Ok(match std::mem::replace(&mut self.state, State::Done) { + State::Built(lists) => Step::Final(lists), + State::Done => Step::End, + State::Lists | State::Elements(_) => { + vortex_bail!("List source computed before its lists were ready") + } + }) + } +} + +/// The selected lists of a row range, with only the elements of the valid ones. +/// +/// `list_transform` runs a lambda that can fail only on the elements of valid lists, and an +/// expression over the elements may be such a lambda's body, so the elements of a null or +/// unselected list are never read. +struct CompactedLists { + /// The element rows from the first list of the range to its last. + elements_range: Range, + /// The elements of the selected valid lists, relative to `elements_range`. + elements_mask: Mask, + /// The offsets of the selected lists into those elements. A null list is empty. + offsets: PrimitiveArray, + validity: Validity, +} + +impl CompactedLists { + /// Compacts the `selected` lists of a range whose lists start at `offsets`, one more offset than + /// `selected` is long, into an elements child of `elements_row_count` rows. `validity` holds + /// the validity of the selected lists of a nullable list, as an array and as a mask. + fn try_new( + offsets: &[u64], + selected: &Mask, + validity: Option<(ArrayRef, Mask)>, + elements_row_count: u64, + ) -> VortexResult { + vortex_ensure!( + offsets.len() == selected.len() + 1, + "{} list offsets cannot bound {} lists", + offsets.len(), + selected.len() + ); + let first = offsets[0]; + let last = offsets[selected.len()]; + vortex_ensure!( + first <= last && last <= elements_row_count, + "List offsets {first}..{last} exceed the {elements_row_count} elements" + ); + let mut slices: Vec<(usize, usize)> = Vec::new(); + let mut compacted = BufferMut::::with_capacity(selected.true_count() + 1); + let mut kept = 0; + compacted.push(kept); + let mut valid = validity.as_ref().map(|(_, valid)| valid.iter()); + for (row, is_selected) in selected.iter().enumerate() { + if !is_selected { + continue; + } + let is_valid = match valid.as_mut() { + Some(valid) => valid + .next() + .ok_or_else(|| vortex_err!("List validity is shorter than the selection"))?, + None => true, + }; + let (start, end) = (offsets[row], offsets[row + 1]); + vortex_ensure!( + first <= start && start <= end && end <= last, + "List offsets {start}..{end} are out of order" + ); + if is_valid && start < end { + kept += end - start; + let slice = ( + usize::try_from(start - first)?, + usize::try_from(end - first)?, + ); + match slices.last_mut() { + Some((_, previous_end)) if *previous_end == slice.0 => *previous_end = slice.1, + _ => slices.push(slice), + } + } + compacted.push(kept); + } + let len = usize::try_from(last - first)?; + let elements_mask = match slices.as_slice() { + [] => Mask::new_false(len), + [(0, end)] if *end == len => Mask::new_true(len), + _ => Mask::from_slices(len, slices), + }; + Ok(Self { + elements_range: first..last, + elements_mask, + offsets: PrimitiveArray::new(compacted.freeze(), Validity::NonNullable), + validity: validity.map_or(Validity::NonNullable, |(validity, _)| { + Validity::Array(validity) + }), + }) + } + + /// The lists over `elements`, the elements the mask keeps. + fn build(&self, elements: ArrayRef) -> VortexResult { + vortex_ensure!( + elements.len() == self.elements_mask.true_count(), + "List elements produced {} rows for {} elements", + elements.len(), + self.elements_mask.true_count() + ); + // SAFETY: the compacted offsets start at zero, never decrease and end at the number of + // elements the mask keeps, which the elements hold, and the validity covers one value per + // selected list. + let offsets = self.offsets.clone().into_array(); + Ok( + unsafe { ListArray::new_unchecked(elements, offsets, self.validity.clone()) } + .into_array(), + ) + } +} diff --git a/vortex-scan/src/plan/builtins/list_pack/expr.rs b/vortex-scan/src/plan/builtins/list_pack/expr.rs new file mode 100644 index 00000000000..9733cee8c79 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/expr.rs @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! What an expression over a list reads of the list. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::BoundLambda; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::expr::traversal::pre_order_visit_down; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_array::scalar_fn::fns::list_length::ListLength; +use vortex_array::scalar_fn::fns::list_transform::ListTransform; +use vortex_array::scalar_fn::fns::list_transform::ListTransformOptions; +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +/// What an expression over a list reads of the list. +pub(crate) enum ListRead { + /// At most the validity, through `is_null($)` and `is_not_null($)`. + Validity, + /// At most the offsets and the validity, through these and `list_length($)`. + Lengths, + /// The elements, through the lambdas of `list_transform($, lambda)` nodes alone. + Transforms(ListTransforms), + /// The elements in any other way, such as the list itself. + Elements, +} + +impl ListRead { + /// What `expr`, an expression over a list, reads of the list. + pub(crate) fn of(expr: &BoundExpression) -> VortexResult { + let mut transforms: Vec = Vec::new(); + let mut reads_lengths = false; + let mut reads_elements = false; + pre_order_visit_down(expr, |node: &BoundExpression| { + if is_root_transform(node) { + if !transforms.contains(node) { + transforms.push(node.clone()); + } + return Ok(TraversalOrder::Skip); + } + if is_validity_read(node) { + return Ok(TraversalOrder::Skip); + } + if is_root_read::(node) { + reads_lengths = true; + return Ok(TraversalOrder::Skip); + } + if node.is_root() { + reads_elements = true; + return Ok(TraversalOrder::Stop); + } + Ok(TraversalOrder::Continue) + })?; + if reads_elements { + return Ok(Self::Elements); + } + if transforms.is_empty() { + return Ok(if reads_lengths { + Self::Lengths + } else { + Self::Validity + }); + } + Ok(ListTransforms::try_new(transforms)?.map_or(Self::Elements, Self::Transforms)) + } +} + +/// The `list_transform($, lambda)` nodes through which an expression over a list reads the list +/// elements, with the body of each lambda as an expression over the elements. +/// +/// A lambda that reads one field of struct elements, as in `list_transform($, x -> x.sku)`, has +/// the body `$.sku`, so a reader can evaluate it over the elements and read the column of that +/// field alone. +#[derive(Debug)] +pub struct ListTransforms { + transforms: Vec, + bodies: Vec, + fallible: bool, +} + +impl ListTransforms { + /// The `list_transform($, lambda)` nodes of `expr`, an expression over a list. + /// + /// Returns `None` when `expr` has no such node, or reads the list in another way than through + /// these nodes, `is_null($)`, `is_not_null($)` and `list_length($)`. The last three need only + /// the offsets and the validity of the list. + pub fn of(expr: &BoundExpression) -> VortexResult> { + Ok(match ListRead::of(expr)? { + ListRead::Transforms(transforms) => Some(transforms), + ListRead::Validity | ListRead::Lengths | ListRead::Elements => None, + }) + } + + fn try_new(transforms: Vec) -> VortexResult> { + let mut bodies = Vec::with_capacity(transforms.len()); + let mut fallible = false; + for transform in &transforms { + let ListTransformOptions::Bound(lambda) = transform.as_::() else { + return Ok(None); + }; + let Some(body) = body_over_elements(lambda)? else { + return Ok(None); + }; + fallible |= !lambda.is_infallible(); + bodies.push(body); + } + Ok(Some(Self { + transforms, + bodies, + fallible, + })) + } + + /// The distinct `list_transform($, lambda)` nodes, in the order they first occur. + pub fn transforms(&self) -> &[BoundExpression] { + &self.transforms + } + + /// The body of the lambda of each node, as an expression over the list elements. + pub fn bodies(&self) -> &[BoundExpression] { + &self.bodies + } + + /// Whether a lambda can fail. + /// + /// `list_transform` runs such a lambda only on the elements of valid lists, so a reader must + /// not evaluate its body over the elements of null or unselected lists either. + pub fn is_fallible(&self) -> bool { + self.fallible + } + + /// Rewrites `expr`, from which these nodes were taken, to read the results of the lambda + /// bodies instead of the elements. + /// + /// Node `i` becomes `transformed(i)`, and the list in `is_null($)`, `is_not_null($)` and + /// `list_length($)` becomes `list`, which must have the offsets and the validity of the list. + pub fn rewrite( + &self, + expr: &BoundExpression, + transformed: impl Fn(usize) -> VortexResult, + list: &BoundExpression, + ) -> VortexResult { + Ok(expr + .clone() + .transform_down(|node| { + let value = if is_root_transform(&node) { + let index = self + .transforms + .iter() + .position(|transform| *transform == node) + .ok_or_else(|| vortex_err!("{node} is not a transform of the list"))?; + transformed(index)? + } else if is_validity_read(&node) || is_root_read::(&node) { + node.with_children([list.clone()])? + } else { + return Ok(Transformed::no(node)); + }; + Ok(Transformed { + value, + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner()) + } +} + +/// Whether `expr` is `is_null($)` or `is_not_null($)`. +pub(crate) fn is_validity_read(expr: &BoundExpression) -> bool { + is_root_read::(expr) || is_root_read::(expr) +} + +/// Whether `expr` applies the function `F` to the root alone. +fn is_root_read(expr: &BoundExpression) -> bool { + expr.is::() && matches!(expr.children(), [child] if child.is_root()) +} + +fn is_root_transform(expr: &BoundExpression) -> bool { + is_root_read::(expr) +} + +/// The body of a `list_transform` lambda as an expression over the list elements. +/// +/// Binding made the lambda's parameter `x` the field `$.x` of the struct of its inputs, so every +/// `$.x` becomes the elements root. Returns `None` when the body reads the inputs in any other +/// way, which a lambda cannot do. +fn body_over_elements(lambda: &BoundLambda) -> VortexResult> { + let params = lambda.params(); + let ([param], Some(element_dtype)) = (params.names().as_ref(), params.field_by_index(0)) else { + return Ok(None); + }; + let elements_root = BoundExpression::new_root(element_dtype); + let mut reads_inputs = false; + let body = lambda + .body() + .clone() + .transform_down(|node| { + if node.as_opt::() == Some(param) && node.child(0).is_root() { + return Ok(Transformed { + value: elements_root.clone(), + changed: true, + order: TraversalOrder::Skip, + }); + } + reads_inputs |= node.is_root(); + Ok(Transformed::no(node)) + })? + .into_inner(); + Ok((!reads_inputs).then_some(body)) +} diff --git a/vortex-scan/src/plan/builtins/list_pack/mod.rs b/vortex-scan/src/plan/builtins/list_pack/mod.rs new file mode 100644 index 00000000000..0dfe7bee0b1 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/mod.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +pub(crate) mod execute; +mod expr; +#[cfg(test)] +mod tests; + +use std::borrow::Cow; +use std::ops::Range; +use std::sync::Arc; + +use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Lambda; +use vortex_array::expr::bound; +use vortex_array::expr::get_item; +use vortex_array::expr::list_transform; +use vortex_array::expr::root; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::expr::var; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_err; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use self::execute::ListSource; +use self::expr::ListRead; +pub use self::expr::ListTransforms; +use self::expr::is_validity_read; +use crate::execution::operators::UNBOUNDED; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Eval; +use crate::plan::EvalPlan; +use crate::plan::PackPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::selection::selected_slice; + +const ELEMENTS: usize = 0; +const OFFSETS: usize = 1; +const VALIDITY: usize = 2; + +/// Assembles a list from slots `[elements, offsets, validity]`, with validity present exactly +/// when the list is nullable. +/// +/// The elements live in a row domain of their own: list `i` holds the elements from +/// `offsets[i]` to `offsets[i + 1]`, so the element rows of a range of lists are known only once +/// their offsets are read. Compiled over a range of lists, a list reads the offsets of the range +/// and the validity of its selected lists, then compiles the elements plan over the elements of +/// the selected valid lists alone and reads them as a scan of their own. Compiling therefore +/// registers the segments of the offsets and the validity, but not those of the elements. +/// +/// An [`Eval`] above a list reads only the children its expression needs: the validity for +/// `is_null($)`, the offsets and the validity for `list_length($)`, and for the lambdas of +/// `list_transform($, lambda)` nodes the elements that the lambdas read. +#[derive(Clone, Debug)] +pub struct ListPack; + +/// Operator-specific list assembly data. +#[derive(Clone, Debug)] +pub struct ListPackData; + +/// A plan that assembles a list from its children. +pub type ListPackPlan = Plan; + +impl ListPackPlan { + /// Creates a list assembly from potentially unbuilt slots without validation. + /// + /// # Safety + /// + /// `slots` must be `[elements, offsets, validity]`. `dtype` must be a list whose element + /// dtype matches the elements child. The offsets child must be a non-nullable integer with + /// `row_count + 1` rows. A non-nullable boolean validity child with `row_count` rows must be + /// present exactly when `dtype` is nullable. + pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { + PlanParts { + vtable: ListPack, + dtype, + row_count, + slots, + data: ListPackData, + } + .into_typed() + } + + /// Creates a list assembly from `elements` and `offsets`. + /// + /// `validity` is required exactly when `nullability` is [`Nullability::Nullable`]. The row + /// domain is one fewer than the number of offsets. + pub fn try_new( + nullability: Nullability, + row_count: u64, + elements: PlanRef, + offsets: PlanRef, + validity: Option, + ) -> VortexResult { + let dtype = DType::List(Arc::new(elements.dtype().clone()), nullability); + let slots = [Some(elements), Some(offsets), validity] + .into_iter() + .collect(); + validate_slots(&dtype, row_count, &slots)?; + + // SAFETY: All slot shape invariants were validated above. + Ok(unsafe { Self::from_slots_unchecked(dtype, row_count, slots) }) + } + + /// Returns the plan producing list elements. + pub fn elements(&self) -> VortexResult { + self.slot_required(ELEMENTS) + } + + /// Returns the plan producing list offsets. + pub fn offsets(&self) -> VortexResult { + self.slot_required(OFFSETS) + } + + /// Returns the plan producing list validity, if the list is nullable. + pub fn validity(&self) -> VortexResult> { + self.slot(VALIDITY) + } +} + +impl PlanVTable for ListPack { + type PlanData = ListPackData; + type Metadata = EmptyMetadata; + + fn id(&self) -> PlanId { + static ID: CachedId = CachedId::new("vortex.plan.list_pack"); + *ID + } + + fn metadata(_plan: &Plan) -> Option { + // Nullability is recoverable from the plan dtype. + Some(EmptyMetadata) + } + + fn with_slots( + plan: &Plan, + slots: &PlanSlots, + _data: &mut Self::PlanData, + ) -> VortexResult<()> { + validate_slots(plan.dtype(), plan.row_count(), slots) + } + + fn slot_name(_plan: &Plan, slot: usize) -> Cow<'_, str> { + match slot { + ELEMENTS => Cow::Borrowed("elements"), + OFFSETS => Cow::Borrowed("offsets"), + VALIDITY => Cow::Borrowed("validity"), + _ => Cow::Owned(format!("slot[{slot}]")), + } + } + + /// Reads the offsets from the first selected list to the last and the validity of the + /// selected lists, as inlets `[offsets, validity]` of a source that reads the elements once + /// those have arrived. + fn compile( + plan: &Plan, + rows: Range, + mask: &Mask, + compiler: &mut Compiler<'_>, + ) -> VortexResult> { + let Some((span, selected)) = selected_slice(mask, 0..mask.len()) else { + return Ok(None); + }; + let lists = rows.start + u64::try_from(span.start)?..rows.start + u64::try_from(span.end)?; + let offsets = compiler + .compile( + &plan.offsets()?, + lists.start..lists.end + 1, + &Mask::new_true(span.len() + 1), + )? + .ok_or_else(|| vortex_err!("ListPack offsets produced no rows"))?; + let mut chains = vec![offsets]; + if let Some(validity) = plan.validity()? { + chains.push( + compiler + .compile(&validity, lists, &selected)? + .ok_or_else(|| vortex_err!("ListPack validity produced no rows"))?, + ); + } + let source = ListSource::new( + plan.clone(), + selected, + compiler.session().clone(), + compiler.values().clone(), + ); + Ok(Some(compiler.join_with(chains, |_| UNBOUNDED, source))) + } +} + +fn validate_slots(dtype: &DType, row_count: u64, slots: &PlanSlots) -> VortexResult<()> { + let elements_dtype = dtype + .as_list_element_opt() + .ok_or_else(|| vortex_err!("ListPack output dtype must be a list, got {dtype}"))?; + slots.check_len("ListPack", VALIDITY + 1)?; + + let elements = slots.required(ELEMENTS)?; + if elements.dtype() != elements_dtype.as_ref() { + vortex_bail!( + "ListPack elements child has dtype {} but the list element dtype is {}", + elements.dtype(), + elements_dtype + ); + } + + let offsets = slots.required(OFFSETS)?; + if !offsets.dtype().is_int() || offsets.dtype().is_nullable() { + vortex_bail!( + "ListPack offsets child must have a non-nullable integer dtype, got {}", + offsets.dtype() + ); + } + let offsets_row_count = row_count + .checked_add(1) + .ok_or_else(|| vortex_err!("ListPack offsets row count overflow"))?; + if offsets.row_count() != offsets_row_count { + vortex_bail!( + "ListPack offsets child has {} rows but must have {offsets_row_count}", + offsets.row_count() + ); + } + + match (dtype.is_nullable(), slots.get(VALIDITY)?) { + (true, Some(validity)) => { + let validity_dtype = DType::Bool(Nullability::NonNullable); + if validity.dtype() != &validity_dtype { + vortex_bail!( + "ListPack validity child has dtype {} but must have dtype {validity_dtype}", + validity.dtype() + ); + } + if validity.row_count() != row_count { + vortex_bail!( + "ListPack validity child has {} rows but the plan has {row_count}", + validity.row_count() + ); + } + } + (false, None) => {} + (true, None) => vortex_bail!("Nullable ListPack has no validity child"), + (false, Some(_)) => vortex_bail!("Non-nullable ListPack has a validity child"), + } + Ok(()) +} + +/// Reads only the children of a [`ListPack`] that the expression of an [`Eval`] above it needs. +/// +/// - An expression that reads at most the validity, through `is_null($)` and `is_not_null($)`, +/// evaluates over the validity child, or over no child at all for a non-nullable list. +/// - One that also reads the lengths, through `list_length($)`, evaluates over lists of empty +/// structs, which read only the offsets and the validity. +/// - One that reads the elements only through the lambdas of `list_transform($, lambda)` nodes +/// evaluates their bodies over the elements child, and the rest over the lists of the results. +/// So `list_transform($, x -> x.sku)` reads the column of `sku` alone. The bodies of several +/// lambdas are packed into one struct, so the lambdas share one read of the offsets and the +/// validity, and each node takes its field from the lists of those structs. +/// +/// A list reads only the elements of its selected valid lists, so a body runs on no element that +/// `list_transform` would not run it on, even when it can fail. +#[derive(Debug)] +pub(crate) struct ExpressionListPackRule; + +impl PlanParentReduceRule for ExpressionListPackRule { + type Parent = Eval; + + fn reduce_parent( + &self, + child: &ListPackPlan, + parent: &Plan, + _child_idx: usize, + _session: &VortexSession, + ) -> VortexResult> { + let expression = parent.expression(); + let rewritten = match ListRead::of(expression)? { + ListRead::Validity => read_validity(child, expression)?, + ListRead::Lengths => read_lengths(child, expression)?, + ListRead::Transforms(transforms) => read_transforms(child, expression, &transforms)?, + ListRead::Elements => None, + }; + Ok(rewritten.filter(|plan| plan.dtype() == parent.dtype())) + } +} + +/// Evaluates `expression`, which reads at most the validity of `list`, over the validity child. +fn read_validity( + list: &ListPackPlan, + expression: &BoundExpression, +) -> VortexResult> { + let Some(validity) = list.validity()? else { + let expression = replace_validity_reads(expression, |is_null| bound::lit(!is_null))?; + let empty = PackPlan::try_new( + StructFields::empty(), + Nullability::NonNullable, + list.row_count(), + Vec::new(), + None, + )?; + return Ok(Some( + EvalPlan::try_new(expression, empty.into_plan())?.into_plan(), + )); + }; + let valid = BoundExpression::new_root(validity.dtype().clone()); + let expression = replace_validity_reads(expression, |is_null| { + if is_null { + bound::not(valid.clone()) + } else { + valid.clone() + } + })?; + Ok(Some(EvalPlan::try_new(expression, validity)?.into_plan())) +} + +/// `expression` with each `is_null($)` and `is_not_null($)` replaced by `replacement`, which is +/// told whether it replaces `is_null($)`. +fn replace_validity_reads( + expression: &BoundExpression, + replacement: impl Fn(bool) -> BoundExpression, +) -> VortexResult { + Ok(expression + .clone() + .transform_down(|node| { + if !is_validity_read(&node) { + return Ok(Transformed::no(node)); + } + Ok(Transformed { + value: replacement(node.is::()), + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner()) +} + +/// Evaluates `expression`, which reads at most the lengths and the validity of `list`, over lists +/// of empty structs, which read no element. +fn read_lengths( + list: &ListPackPlan, + expression: &BoundExpression, +) -> VortexResult> { + let elements = list.elements()?; + if is_empty_struct(elements.dtype()) { + return Ok(None); + } + let empty = PackPlan::try_new( + StructFields::empty(), + Nullability::NonNullable, + elements.row_count(), + Vec::new(), + None, + )?; + let lengths = list.with_elements(empty.into_plan())?; + let expression = rebind_root(expression, lengths.dtype())?; + Ok(Some( + EvalPlan::try_new(expression, lengths.into_plan())?.into_plan(), + )) +} + +/// Evaluates the lambda bodies of `transforms` over the elements of `list`, and `expression` over +/// the lists of their results. +fn read_transforms( + list: &ListPackPlan, + expression: &BoundExpression, + transforms: &ListTransforms, +) -> VortexResult> { + let elements = list.elements()?; + if let [body] = transforms.bodies() { + let projected = list.with_elements(eval_unless_root(body, elements)?)?; + let lists = BoundExpression::new_root(projected.dtype().clone()); + let expression = transforms.rewrite(expression, |_| Ok(lists.clone()), &lists)?; + return Ok(Some( + EvalPlan::try_new(expression, projected.into_plan())?.into_plan(), + )); + } + if is_projection_of_every_field(transforms.bodies(), elements.dtype()) { + // Packing these bodies would only rename the fields of the elements. + return Ok(None); + } + let names: FieldNames = (0..transforms.bodies().len()) + .map(|index| index.to_string()) + .collect(); + let packed = bound::pack( + names + .iter() + .cloned() + .zip(transforms.bodies().iter().cloned()), + Nullability::NonNullable, + ); + let projected = list.with_elements(EvalPlan::try_new(packed, elements)?.into_plan())?; + let lists = BoundExpression::new_root(projected.dtype().clone()); + let expression = transforms.rewrite( + expression, + |index| { + let field = Lambda::new(["element"], get_item(names[index].clone(), var("element")))?; + list_transform(root(), field).bind(projected.dtype()) + }, + &lists, + )?; + Ok(Some( + EvalPlan::try_new(expression, projected.into_plan())?.into_plan(), + )) +} + +impl ListPackPlan { + /// This list over `elements` in place of its elements child, with the same offsets and + /// validity. + fn with_elements(&self, elements: PlanRef) -> VortexResult { + Self::try_new( + self.dtype().nullability(), + self.row_count(), + elements, + self.offsets()?, + self.validity()?, + ) + } +} + +/// `elements`, or an evaluation of `body` over them unless `body` is the root. +fn eval_unless_root(body: &BoundExpression, elements: PlanRef) -> VortexResult { + if body.is_root() { + return Ok(elements); + } + Ok(EvalPlan::try_new(body.clone(), elements)?.into_plan()) +} + +/// `expression` with every root bound to `dtype` instead. +fn rebind_root(expression: &BoundExpression, dtype: &DType) -> VortexResult { + Ok(expression + .clone() + .transform_down(|node| { + if !node.is_root() { + return Ok(Transformed::no(node)); + } + Ok(Transformed::yes(BoundExpression::new_root(dtype.clone()))) + })? + .into_inner()) +} + +/// Whether `dtype` is a non-nullable struct with no field. +fn is_empty_struct(dtype: &DType) -> bool { + !dtype.is_nullable() + && dtype + .as_struct_fields_opt() + .is_some_and(|fields| fields.nfields() == 0) +} + +/// Whether `bodies` read every field of non-nullable struct elements of `dtype`, one each and in +/// field order, and nothing else. +fn is_projection_of_every_field(bodies: &[BoundExpression], dtype: &DType) -> bool { + let Some(fields) = dtype.as_struct_fields_opt() else { + return false; + }; + !dtype.is_nullable() + && bodies.len() == fields.nfields() + && bodies + .iter() + .zip(fields.names().iter()) + .all(|(body, name)| body.as_opt::() == Some(name) && body.child(0).is_root()) +} diff --git a/vortex-scan/src/plan/builtins/list_pack/tests.rs b/vortex-scan/src/plan/builtins/list_pack/tests.rs new file mode 100644 index 00000000000..af88903f4d1 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/tests.rs @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::execution::pipeline::Turn; +use crate::plan::EvalPlan; +use crate::plan::ListPackPlan; +use crate::plan::PlanRef; +use crate::plan::optimize; +use crate::test::SESSION; +use crate::test::Store; +use crate::test::flat; +use crate::test::struct_plan; + +fn i32() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) +} + +/// A non-nullable struct of `i32` fields named `names`. +fn struct_of(names: &[&str]) -> DType { + DType::Struct( + StructFields::from_iter(names.iter().map(|name| (*name, i32()))), + Nullability::NonNullable, + ) +} + +/// A shape-only list of `{sku: i32, qty: i32, price: i32}` elements whose fields are separate +/// sources, as a list layout with struct elements is lowered. +fn items_plan(nullability: Nullability) -> PlanRef { + let fields = (0..3).map(|segment| flat(6, i32(), segment)).collect(); + let elements = struct_plan(6, struct_of(&["sku", "qty", "price"]), fields); + let offsets = flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 3); + let validity = nullability + .is_nullable() + .then(|| flat(5, DType::Bool(Nullability::NonNullable), 4)); + ListPackPlan::try_new(nullability, 5, elements, offsets, validity) + .expect("valid test list") + .into_plan() +} + +fn sku() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("sku", var("x")))?, + )) +} + +fn qty() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("qty", var("x")))?, + )) +} + +fn optimized(expr: &Expression, plan: PlanRef) -> VortexResult { + let plan = EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(); + Ok(optimize(plan, &SESSION)?.display_tree().to_string()) +} + +#[test] +fn validity_reads_evaluate_over_the_validity() -> VortexResult<()> { + insta::assert_snapshot!(optimized(&is_null(root()), items_plan(Nullability::Nullable))?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.not($) + child: vortex.plan.filter(bool, rows=5) + child: vortex.test.source(bool, rows=5) + "); + insta::assert_snapshot!( + optimized(&is_not_null(root()), items_plan(Nullability::NonNullable))?, + @r" + root: vortex.plan.eval(bool, rows=5) expr=true + child: vortex.plan.pack({}, rows=5) + " + ); + Ok(()) +} + +#[test] +fn length_reads_assemble_lists_of_empty_structs() -> VortexResult<()> { + let expr = pack( + [("len", list_length(root())), ("valid", is_not_null(root()))], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::Nullable))?, @r" + root: vortex.plan.eval({len=u64?, valid=bool}, rows=5) expr=pack(len: vortex.list.length($), valid: is_not_null($)) + child: vortex.plan.list_pack(list({})?, rows=5) + elements: vortex.plan.pack({}, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + validity: vortex.plan.filter(bool, rows=5) + child: vortex.test.source(bool, rows=5) + "); + Ok(()) +} + +#[test] +fn lambda_bodies_push_into_the_elements() -> VortexResult<()> { + let expr = list_contains(sku()?, lit(3i32)); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::NonNullable))?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.list.contains($, 3i32) + child: vortex.plan.list_pack(list(i32), rows=5) + elements: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Two lambdas share one read of the offsets: their bodies are packed into one struct of results, +/// whose fields the transforms take, so `price` is never read. +#[test] +fn lambda_bodies_share_the_offsets() -> VortexResult<()> { + let expr = pack( + [("skus", sku()?), ("qtys", qty()?)], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::NonNullable))?, @r" + root: vortex.plan.eval({skus=list(i32), qtys=list(i32)}, rows=5) expr=pack(skus: vortex.list.transform($, (element) -> $.element.0), qtys: vortex.list.transform($, (element) -> $.element.1)) + child: vortex.plan.list_pack(list({0=i32, 1=i32}), rows=5) + elements: vortex.plan.eval({0=i32, 1=i32}, rows=6) expr=pack(0: $.0, 1: $.1) + child: vortex.plan.pack({0=i32, 1=i32}, rows=6) + 0: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + 1: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Lambdas that read every field of the elements in order read the elements as stored, as packing +/// their bodies would only rename the fields. +#[test] +fn lambda_bodies_reading_every_field_keep_the_elements() -> VortexResult<()> { + let elements = struct_plan( + 6, + struct_of(&["sku", "qty"]), + vec![flat(6, i32(), 0), flat(6, i32(), 1)], + ); + let offsets = flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 2); + let plan = ListPackPlan::try_new(Nullability::NonNullable, 5, elements, offsets, None)?; + let expr = pack( + [("skus", sku()?), ("qtys", qty()?)], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, plan.into_plan())?, @r" + root: vortex.plan.eval({skus=list(i32), qtys=list(i32)}, rows=5) expr=pack(skus: vortex.list.transform($, (x) -> $.x.sku), qtys: vortex.list.transform($, (x) -> $.x.qty)) + child: vortex.plan.list_pack(list({sku=i32, qty=i32}), rows=5) + elements: vortex.plan.pack({sku=i32, qty=i32}, rows=6) + sku: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + qty: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// An expression that reads the list itself reads every child. +#[test] +fn list_reads_keep_the_list() -> VortexResult<()> { + let expr = list_contains(root(), lit(3i32)); + let plan = ListPackPlan::try_new( + Nullability::NonNullable, + 5, + flat(6, i32(), 0), + flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 1), + None, + )? + .into_plan(); + insta::assert_snapshot!(optimized(&expr, plan)?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.list.contains($, 3i32) + child: vortex.plan.list_pack(list(i32), rows=5) + elements: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Lists `[{1, 10}, {2, 20}]`, null (hiding `[{3, i32::MAX}]`), `[]`, `[{4, 40}, {5, 50}]` and +/// `[{6, i32::MAX}]`, of `{sku: i32, qty: i32}` elements, stored with their element fields in two +/// chunks each, and a plan reading them. +fn stored_items(store: &Store) -> VortexResult<(ArrayRef, PlanRef)> { + let mut ctx = SESSION.create_execution_ctx(); + let skus = buffer![1i32, 2, 3, 4, 5, 6].into_array(); + let qtys = buffer![10i32, 20, i32::MAX, 40, 50, i32::MAX].into_array(); + let offsets = buffer![0u32, 2, 3, 3, 5, 6].into_array(); + let validity = Validity::from_iter([true, false, true, true, true]); + let elements = StructArray::from_fields(&[("sku", skus.clone()), ("qty", qtys.clone())])?; + let list = ListArray::try_new( + elements.into_array(), + offsets.clone(), + validity.clone(), + &mut ctx, + )? + .into_array(); + + let elements = struct_plan( + 6, + struct_of(&["sku", "qty"]), + vec![ + store.chunked(&skus, &[3, 3])?, + store.chunked(&qtys, &[3, 3])?, + ], + ); + let validity = validity.to_array(5); + let plan = ListPackPlan::try_new( + Nullability::Nullable, + 5, + elements, + store.flat(&offsets)?, + Some(store.flat(&validity)?), + )? + .into_plan(); + Ok((list, plan)) +} + +/// Runs `plan` over the rows of `rows` that `mask` selects, delivering the bytes of `store`, and +/// counts the segments it reads. +fn run( + store: &Store, + plan: PlanRef, + rows: Range, + mask: Mask, +) -> VortexResult<(ArrayRef, usize)> { + let dtype = plan.dtype().clone(); + let mut scan = Scan::try_new(SESSION.clone(), plan, vec![Split { rows, mask }])?; + let mut outputs = Vec::new(); + let mut reads = 0; + loop { + match scan.step()? { + Turn::Read(read) => { + reads += 1; + scan.deliver(read.id, store.read(read.segment_id))?; + } + Turn::Output(_, array) => outputs.push(array), + Turn::Waiting => unreachable!("every read is delivered at once"), + Turn::Done => break, + } + } + let array = ChunkedArray::try_new(outputs, dtype)?.into_array(); + let array = array + .execute::(&mut SESSION.create_execution_ctx())? + .0 + .into_array(); + Ok((array, reads)) +} + +/// A list reads the offsets of its selected rows, the validity of the selected lists and, of each +/// element field its expression reads, the chunks that hold the elements of the selected valid +/// lists: `chunks` of the two. A null or empty list reads no element. +#[rstest] +#[case::full(0..5, Mask::new_true(5), 2)] +#[case::first_chunk(0..1, Mask::new_true(1), 1)] +#[case::second_chunk(3..5, Mask::from_iter([true, false]), 1)] +#[case::spanning(0..4, Mask::from_iter([true, false, true, true]), 2)] +#[case::null_list(1..2, Mask::new_true(1), 0)] +#[case::empty_list(2..3, Mask::new_true(1), 0)] +fn lists_read_elements_of_selected_valid_lists( + #[case] rows: Range, + #[case] mask: Mask, + #[case] chunks: usize, + #[values((root(), 2), (sku()?, 1), (qty()?, 1))] read: (Expression, usize), +) -> VortexResult<()> { + let (expr, fields) = read; + let store = Store::default(); + let (list, plan) = stored_items(&store)?; + let plan = optimize( + EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(), + &SESSION, + )?; + let expected = list + .slice(usize::try_from(rows.start)?..usize::try_from(rows.end)?)? + .filter(mask.clone())? + .apply(&expr)?; + let (actual, reads) = run(&store, plan, rows, mask)?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(reads, 2 + chunks * fields); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists. +#[rstest] +#[case::hidden_by_null(0..4, Mask::new_true(4), true)] +#[case::hidden_by_selection(3..5, Mask::from_iter([true, false]), true)] +#[case::selected(4..5, Mask::new_true(1), false)] +fn fallible_lambdas_run_on_selected_valid_lists( + #[case] rows: Range, + #[case] mask: Mask, + #[case] succeeds: bool, +) -> VortexResult<()> { + let expr = list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + ); + let store = Store::default(); + let (list, plan) = stored_items(&store)?; + let plan = optimize( + EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(), + &SESSION, + )?; + let result = run(&store, plan, rows.clone(), mask.clone()); + assert_eq!(result.is_ok(), succeeds); + if let Ok((actual, _)) = result { + let expected = list + .slice(usize::try_from(rows.start)?..usize::try_from(rows.end)?)? + .filter(mask)? + .apply(&expr)?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + } + Ok(()) +} + +/// Offsets that decrease or run past the elements fail the read rather than build invalid lists. +#[rstest] +#[case::decreasing(buffer![0u32, 2, 1].into_array())] +#[case::past_the_elements(buffer![0u32, 2, 4].into_array())] +fn corrupt_offsets_fail(#[case] offsets: ArrayRef) -> VortexResult<()> { + let store = Store::default(); + let plan = ListPackPlan::try_new( + Nullability::NonNullable, + 2, + store.flat(&buffer![1i32, 2, 3].into_array())?, + store.flat(&offsets)?, + None, + )? + .into_plan(); + assert!(run(&store, plan, 0..2, Mask::new_true(2)).is_err()); + Ok(()) +} diff --git a/vortex-scan/src/plan/builtins/mod.rs b/vortex-scan/src/plan/builtins/mod.rs index 75c038e6eb1..1bcf1a4c763 100644 --- a/vortex-scan/src/plan/builtins/mod.rs +++ b/vortex-scan/src/plan/builtins/mod.rs @@ -24,9 +24,11 @@ pub use eval::EvalPlan; pub use filter::Filter; pub use filter::FilterData; pub use filter::FilterPlan; +pub(crate) use list_pack::ExpressionListPackRule; pub use list_pack::ListPack; pub use list_pack::ListPackData; pub use list_pack::ListPackPlan; +pub use list_pack::ListTransforms; pub(crate) use pack::ExpressionPackRule; pub use pack::Pack; pub use pack::PackData; diff --git a/vortex-scan/src/plan/builtins/pack/mask.rs b/vortex-scan/src/plan/builtins/pack/mask.rs index 21042334e8a..20d0fbfdc51 100644 --- a/vortex-scan/src/plan/builtins/pack/mask.rs +++ b/vortex-scan/src/plan/builtins/pack/mask.rs @@ -16,7 +16,7 @@ use vortex_error::VortexResult; use crate::plan::builtins::zoned::holds_under_masking; -/// Moves field reads and statistics of `expr` below the masks over their input. +/// Moves field reads, statistics and strict functions of `expr` below the masks over their input. /// /// The partition rules read a field of a nullable struct as `mask(field, validity)`. An expression /// over that mask stays above the struct, so this moves what it can below the mask, where the next @@ -24,6 +24,10 @@ use crate::plan::builtins::zoned::holds_under_masking; /// /// - `mask(s, v).name` becomes `mask(s.name, v)`: a field of a masked struct is null wherever the /// struct is. Reading a nested field then reads only that field. +/// - `f(mask(x, v))` becomes `mask(f(x), v)` for a function `f` of one argument that is strict and +/// cannot fail, such as `list_transform(mask(l, v), x -> x.sku)`. A strict function is null +/// wherever its argument is, and one that cannot fail may run on the values that `v` hides. The +/// field's plan can then push the function down, as a list reads only the column of `sku`. /// - `stat(mask(x, v), agg)` becomes `stat(x, agg)` when `agg` [holds under /// masking](holds_under_masking), such as a bound, and every function above the statistic is /// infallible. Masking only replaces values with nulls, so the statistic of `x` still holds for @@ -66,24 +70,43 @@ impl NodeRewriter for MaskLifter { return Ok(Transformed::yes(bound::mask(field, validity))); } - let Some(options) = node.as_opt::() else { - return Ok(Transformed::no(node)); - }; - if holds_under_masking(options.aggregate_fn()) && !self.fallible.contains(&true) { - let unmasked = node.clone().with_children([input])?; - // A statistic's dtype is nullable, so the unmasked input rarely changes it. Should it, - // the expressions above it would change type, so the statistic is left unknown. - if unmasked.dtype() == node.dtype() { - return Ok(Transformed::yes(unmasked)); + if let Some(options) = node.as_opt::() { + if holds_under_masking(options.aggregate_fn()) && !self.fallible.contains(&true) { + let unmasked = node.clone().with_children([input])?; + // A statistic's dtype is nullable, so the unmasked input rarely changes it. Should + // it, the expressions above it would change type, so the statistic is left unknown. + if unmasked.dtype() == node.dtype() { + return Ok(Transformed::yes(unmasked)); + } } + let unknown = Scalar::null(node.dtype().clone()); + return Ok(Transformed::yes(bound::lit(unknown))); } - let unknown = Scalar::null(node.dtype().clone()); - Ok(Transformed::yes(bound::lit(unknown))) + + if node.children().len() == 1 && is_strict_and_infallible(&node) { + let lifted = bound::mask(node.clone().with_children([input])?, validity); + // Masking makes the result nullable, which the result of a nullable input usually + // already is. Should it not be, the expressions above it would change type. + if lifted.dtype() == node.dtype() { + return Ok(Transformed::yes(lifted)); + } + } + Ok(Transformed::no(node)) } } +/// Whether `node` is a function that is null wherever an argument is, and cannot fail. +fn is_strict_and_infallible(node: &BoundExpression) -> bool { + node.as_scalar().is_some_and(|scalar_fn| { + let signature = scalar_fn.signature(); + signature.is_strict() && signature.is_infallible() + }) +} + #[cfg(test)] mod tests { + use std::sync::Arc; + use rstest::rstest; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; @@ -97,15 +120,22 @@ mod tests { use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; use vortex_array::expr::Expression; + use vortex_array::expr::Lambda; use vortex_array::expr::and; use vortex_array::expr::cast; + use vortex_array::expr::checked_add; use vortex_array::expr::eq; use vortex_array::expr::get_item; use vortex_array::expr::is_not_null; + use vortex_array::expr::is_null; + use vortex_array::expr::list_length; + use vortex_array::expr::list_transform; use vortex_array::expr::lit; use vortex_array::expr::lt_eq; use vortex_array::expr::mask; + use vortex_array::expr::not; use vortex_array::expr::root; + use vortex_array::expr::var; use vortex_array::scalar_fn::ScalarFnVTableExt; use vortex_array::scalar_fn::fns::stat::StatFn; use vortex_array::scalar_fn::fns::stat::StatOptions; @@ -168,4 +198,48 @@ mod tests { assert_eq!(lifted(expr)?, expected); Ok(()) } + + /// The list `l` of a nullable `{l: list(i64)}`, read through the struct's validity. + fn masked_list() -> Expression { + mask(get_item("l", root()), is_not_null(root())) + } + + /// A strict function of one argument that cannot fail moves below the mask, so the list's plan + /// can push it into the elements. A function that can fail, such as a lambda that can overflow, + /// would run on the lists that the mask hides, and one that is not strict, such as `is_null`, + /// is not null where the struct is, so both stay above it. + #[rstest] + #[case::transform( + list_transform(masked_list(), Lambda::new(["x"], not(eq(var("x"), lit(0i64))))?), + "vortex.mask(vortex.list.transform($.l, (x) -> vortex.not(($.x = 0i64))), is_not_null($))" + )] + #[case::length( + not(eq(list_length(masked_list()), lit(0u64))), + "vortex.not((vortex.mask(vortex.list.length($.l), is_not_null($)) = 0u64))" + )] + #[case::fallible( + list_transform(masked_list(), Lambda::new(["x"], checked_add(var("x"), lit(1i64)))?), + "vortex.list.transform(vortex.mask($.l, is_not_null($)), (x) -> ($.x + 1i64))" + )] + #[case::not_strict( + is_null(masked_list()), + "vortex.is_null(vortex.mask($.l, is_not_null($)))" + )] + fn lifts_strict_functions_that_cannot_fail( + #[case] expr: Expression, + #[case] expected: &str, + ) -> VortexResult<()> { + let dtype = DType::Struct( + StructFields::from_iter([( + "l", + DType::List( + Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), + Nullability::NonNullable, + ), + )]), + Nullability::Nullable, + ); + assert_eq!(lift_masks(expr.bind(&dtype)?)?.to_string(), expected); + Ok(()) + } } diff --git a/vortex-scan/src/plan/builtins/pack/mod.rs b/vortex-scan/src/plan/builtins/pack/mod.rs index 8771c178b9a..f251331e1ce 100644 --- a/vortex-scan/src/plan/builtins/pack/mod.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -339,8 +339,9 @@ impl PackPlan { /// /// Over a nullable struct, the partition rules read a field as `mask(field, validity)`, so the /// pruned struct reads the validity alongside the fields and the expression above it still sees -/// a field as null wherever the struct is null. Nested field reads and statistics above such a -/// mask move below it, so a later rewrite pushes them into the field's plan. +/// a field as null wherever the struct is null. Nested field reads, statistics and strict functions +/// that cannot fail above such a mask move below it, so a later rewrite pushes them into the +/// field's plan. #[derive(Debug)] pub(crate) struct ExpressionPackRule; diff --git a/vortex-scan/src/plan/mod.rs b/vortex-scan/src/plan/mod.rs index f7da9063515..d472020ace7 100644 --- a/vortex-scan/src/plan/mod.rs +++ b/vortex-scan/src/plan/mod.rs @@ -36,6 +36,7 @@ pub use builtins::FilterPlan; pub use builtins::ListPack; pub use builtins::ListPackData; pub use builtins::ListPackPlan; +pub use builtins::ListTransforms; pub use builtins::Pack; pub use builtins::PackData; pub use builtins::PackPlan; diff --git a/vortex-scan/src/plan/optimize/registry.rs b/vortex-scan/src/plan/optimize/registry.rs index e5d9a736c9f..846c9ab769e 100644 --- a/vortex-scan/src/plan/optimize/registry.rs +++ b/vortex-scan/src/plan/optimize/registry.rs @@ -9,6 +9,7 @@ use vortex_session::VortexSession; use super::rules::*; use crate::plan::Concat; use crate::plan::Eval; +use crate::plan::ListPack; use crate::plan::Pack; use crate::plan::PlanRef; use crate::plan::Take; @@ -17,6 +18,7 @@ use crate::plan::builtins::EvalEvalRule; use crate::plan::builtins::EvalIdentityRule; use crate::plan::builtins::EvalPackRule; use crate::plan::builtins::ExpressionConcatRule; +use crate::plan::builtins::ExpressionListPackRule; use crate::plan::builtins::ExpressionPackRule; use crate::plan::builtins::ExpressionTakeRule; use crate::plan::builtins::ExpressionZonedRule; @@ -42,12 +44,15 @@ static EXPRESSION_PACK_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionZonedRule); +static EXPRESSION_LIST_PACK_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(ExpressionListPackRule); static PARENT_RULES: PlanParentRuleSet = PlanParentRuleSet::new(&[ &PlanParentReduceRuleAdapter::new(EvalEvalRule), &EXPRESSION_CONCAT_RULE, &EXPRESSION_TAKE_RULE, &EXPRESSION_PACK_RULE, &EXPRESSION_ZONED_RULE, + &EXPRESSION_LIST_PACK_RULE, ]); /// Attempts a static rewrite for `plan`. From eb60212958e9ad4e77528d6cbfa276d930794ce0 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 10:58:00 +0000 Subject: [PATCH 08/13] Let expression converters split projections after residual filters `ExpressionConverter` gains `split_filtered_projection` and `no_pushdown_filtered_projection`, so the opener's residual-filter path uses a converter's overrides instead of always splitting with the default converter. DataFusion may evaluate an expression that stays with it on some rows only, so inside such an expression the scan evaluates only subexpressions that cannot fail. Partial projection pushdown no longer falls back to raw columns when a lambda appears inside an expression that stays in DataFusion. Taken from the general changes of 0cb27a3cf, without the protobuf functions. Signed-off-by: Connor Tsui --- vortex-datafusion/src/convert/exprs/mod.rs | 43 +++++- .../src/convert/exprs/partial/mod.rs | 51 ++++--- .../src/convert/exprs/partial/tests.rs | 126 ++++++++++++++++-- vortex-datafusion/src/persistent/opener.rs | 92 +++++++++---- vortex-datafusion/src/tests/mod.rs | 51 +++++-- 5 files changed, 291 insertions(+), 72 deletions(-) diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index a22316bda41..647edc5d4c4 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -85,8 +85,6 @@ use crate::row_index::RowIndex; mod partial; -pub(crate) use partial::split_filtered_projection; - /// Result of splitting a projection into Vortex expressions and leftover DataFusion projections. pub struct ProcessedProjection { /// Projection evaluated by the Vortex scan. @@ -154,10 +152,18 @@ pub trait ExpressionConverter: Send + Sync { /// is not read whole for one field. Converting a subexpression applies its conversion's /// semantics, including [`DefaultExpressionConverter`]'s nested field access. /// + /// DataFusion may evaluate an expression that stays with it on some rows only, as it does a + /// `CASE` branch, while the scan evaluates every row. So inside such an expression, the scan + /// evaluates only subexpressions that cannot fail: in `abs(id + 1)`, it reads `id`, and + /// DataFusion evaluates `id + 1`. + /// /// An expression or subexpression whose conversion fails stays in DataFusion, like an /// unsupported one, and DataFusion reports any error when it evaluates it. Duplicate aliases, /// and a lambda that would stay in DataFusion, evaluate the complete projection in DataFusion /// over deduplicated raw inputs. + /// + /// A projection after residual filters is split by + /// [`split_filtered_projection`](Self::split_filtered_projection) instead. fn split_projection( &self, source_projection: ProjectionExprs, @@ -214,6 +220,37 @@ pub trait ExpressionConverter: Send + Sync { source_projection, ) } + + /// Split a projection and the residual filters that DataFusion evaluates before it, which + /// both read the scan output. Returns the split projection and the residual filters rewritten + /// to read the scan output. + /// + /// The scan evaluates no residual filter whole, and DataFusion evaluates the projection only on + /// the rows that the filters keep. So by default the scan evaluates the convertible + /// subexpressions of either that cannot fail, as [`split_projection`](Self::split_projection) + /// does inside an expression that stays in DataFusion. A converter that overrides + /// `split_projection` should override this method too, so that a residual filter does not + /// change how its projections evaluate. + fn split_filtered_projection( + &self, + projection: ProjectionExprs, + residual_filters: Vec>, + input_schema: &Schema, + ) -> DFResult<(ProcessedProjection, Vec>)> { + partial::split_filtered_projection(self, projection, residual_filters, input_schema) + } + + /// Create a projection that reads only the columns that the projection and the residual + /// filters read, without pushing down any expressions. Returns the residual filters + /// unchanged. + fn no_pushdown_filtered_projection( + &self, + projection: ProjectionExprs, + residual_filters: Vec>, + input_schema: &Schema, + ) -> DFResult<(ProcessedProjection, Vec>)> { + raw_filtered_projection(projection, residual_filters, input_schema) + } } /// Read raw columns and any physical row index needed by the leftover projection, @@ -272,7 +309,7 @@ pub(crate) fn raw_projection( /// Read the raw columns of a projection and of the residual filters that DataFusion evaluates /// before it, returning the filters unchanged. -pub(crate) fn raw_filtered_projection( +fn raw_filtered_projection( projection: ProjectionExprs, residual_filters: Vec>, input_schema: &Schema, diff --git a/vortex-datafusion/src/convert/exprs/partial/mod.rs b/vortex-datafusion/src/convert/exprs/partial/mod.rs index 30132a61264..59ecd4ca126 100644 --- a/vortex-datafusion/src/convert/exprs/partial/mod.rs +++ b/vortex-datafusion/src/convert/exprs/partial/mod.rs @@ -48,7 +48,6 @@ use vortex_utils::aliases::hash_map::HashMap; use super::ExpressionConverter; use super::ProcessedProjection; use super::is_infallible; -use super::raw_filtered_projection; use crate::row_index::RowIndex; /// The prefix of the names of scan columns that hold pushed-down subexpressions. @@ -60,23 +59,16 @@ const PUSHED_PREFIX: &str = "__vortex_expr_"; /// projection on every row that the scan returns, so the scan evaluates each converted expression /// whole, and the largest convertible subexpressions of the others. /// -/// Returns `None` when DataFusion would evaluate a lambda over the scan output. DataFusion numbers -/// lambda parameters after the columns of the input schema, so the caller reads the raw input -/// columns instead, which never outnumber them. +/// Returns `None` when DataFusion would still evaluate a lambda over the scan output, one that no +/// subexpression evaluated in the scan contains. DataFusion numbers lambda parameters after the +/// columns of the input schema, so the caller reads the raw input columns instead, which never +/// outnumber them. pub(super) fn split_projection_partially( converter: &C, source_projection: &ProjectionExprs, converted: Vec>, input_schema: &Schema, ) -> DFResult> { - let unconverted = source_projection - .iter() - .zip(&converted) - .filter(|(_, converted)| converted.is_none()) - .map(|(projection, _)| &projection.expr); - if contains_lambda(unconverted)? { - return Ok(None); - } let mut scan = ScanColumns::new(converter, input_schema); let leftover = source_projection .iter() @@ -86,6 +78,9 @@ pub(super) fn split_projection_partially( Ok(ProjectionExpr::new(expr, projection.alias.clone())) }) .collect::>>()?; + if contains_lambda(leftover.iter().map(|projection| &projection.expr))? { + return Ok(None); + } Ok(Some(scan.finish(leftover.into()))) } @@ -96,20 +91,15 @@ pub(super) fn split_projection_partially( /// So the scan evaluates only infallible subexpressions of either. Returns the residual filters /// rewritten to read the scan output. /// -/// When an expression contains a lambda, falls back to [`raw_filtered_projection`], for the reason -/// given on [`split_projection_partially`]. -pub(crate) fn split_filtered_projection( +/// When DataFusion would still evaluate a lambda over the scan output, falls back to +/// [`ExpressionConverter::no_pushdown_filtered_projection`], for the reason given on +/// [`split_projection_partially`]. +pub(super) fn split_filtered_projection( converter: &C, projection: ProjectionExprs, residual_filters: Vec>, input_schema: &Schema, ) -> DFResult<(ProcessedProjection, Vec>)> { - let exprs = residual_filters - .iter() - .chain(projection.iter().map(|projection| &projection.expr)); - if contains_lambda(exprs)? { - return raw_filtered_projection(projection, residual_filters, input_schema); - } let mut scan = ScanColumns::new(converter, input_schema); let rewritten_filters = residual_filters .iter() @@ -122,6 +112,16 @@ pub(crate) fn split_filtered_projection( Ok(ProjectionExpr::new(expr, projection.alias.clone())) }) .collect::>>()?; + let exprs = rewritten_filters + .iter() + .chain(leftover.iter().map(|projection| &projection.expr)); + if contains_lambda(exprs)? { + return converter.no_pushdown_filtered_projection( + projection, + residual_filters, + input_schema, + ); + } Ok((scan.finish(leftover.into()), rewritten_filters)) } @@ -204,6 +204,15 @@ impl<'a, C: ExpressionConverter + ?Sized> ScanColumns<'a, C> { { return self.push(expr, converted); } + // A function that applies a lambda stays in DataFusion whole, so the caller reads the raw + // input columns. Its lambda reads parameters that the scan cannot supply. + if expr + .children() + .iter() + .any(|child| child.is::()) + { + return Ok(Arc::clone(expr)); + } let children = expr .children() .into_iter() diff --git a/vortex-datafusion/src/convert/exprs/partial/tests.rs b/vortex-datafusion/src/convert/exprs/partial/tests.rs index 606933e9b4d..1e29c8c9887 100644 --- a/vortex-datafusion/src/convert/exprs/partial/tests.rs +++ b/vortex-datafusion/src/convert/exprs/partial/tests.rs @@ -12,19 +12,27 @@ use datafusion::logical_expr::simplify::SimplifyContext; use datafusion::optimizer::simplify_expressions::ExprSimplifier; use datafusion::physical_expr::create_physical_expr; use datafusion::prelude::SessionContext; +use datafusion_common::DataFusionError; use datafusion_common::Result as DFResult; use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; use datafusion_expr::HigherOrderUDF; use datafusion_expr::Operator as DFOperator; +use datafusion_expr::ScalarUDF; use datafusion_functions::core::getfield::GetFieldFunc; use datafusion_functions_nested::array_transform::ArrayTransform; +use datafusion_functions_nested::cardinality::Cardinality; use datafusion_physical_expr::HigherOrderFunctionExpr; use datafusion_physical_expr::ScalarFunctionExpr; use rstest::rstest; use vortex::expr::Expression; +use vortex::expr::Lambda; +use vortex::expr::eq; use vortex::expr::get_item; +use vortex::expr::list_transform; +use vortex::expr::lit; use vortex::expr::root; +use vortex::expr::var; use super::*; use crate::convert::DefaultExpressionConverter; @@ -355,11 +363,8 @@ fn test_map_access_stays_in_datafusion( Ok(()) } -/// DataFusion numbers lambda parameters after the input columns, so a lambda that stays in -/// DataFusion keeps the raw projection. -#[test] -fn test_lambda_in_datafusion_reads_raw_columns() -> DFResult<()> { - let schema = schema(); +/// `array_transform(tags, x -> x 2)`. +fn transform_tags(schema: &Schema, operator: DFOperator) -> DFResult> { let DataType::List(element) = schema.field(2).data_type() else { return Err(exec_datafusion_err!("tags must be a list")); }; @@ -369,20 +374,36 @@ fn test_lambda_in_datafusion_reads_raw_columns() -> DFResult<()> { )); let body = Arc::new(df_expr::BinaryExpr::new( variable, - DFOperator::Modulo, + operator, Arc::new(df_expr::Literal::new(ScalarValue::Int64(Some(2)))), )); - let transform: Arc = Arc::new(HigherOrderFunctionExpr::try_new_with_schema( + Ok(Arc::new(HigherOrderFunctionExpr::try_new_with_schema( Arc::new(HigherOrderUDF::new_from_impl(ArrayTransform::new())), vec![ Arc::new(df_expr::Column::new("tags", 2)), Arc::new(df_expr::LambdaExpr::try_new(vec!["x".to_owned()], body)?), ], - &schema, + schema, Arc::new(ConfigOptions::new()), - )?); + )?)) +} + +/// `list_transform($.tags, x -> x = 2)`, the conversion of `transform_tags` with `=`. +fn tags_equal_two() -> DFResult { + Ok(list_transform( + get_item("tags", root()), + Lambda::new(["x"], eq(var("x"), lit(2i64))) + .map_err(|err| DataFusionError::External(Box::new(err)))?, + )) +} + +/// DataFusion numbers lambda parameters after the input columns, so a lambda that stays in +/// DataFusion keeps the raw projection. +#[test] +fn test_lambda_in_datafusion_reads_raw_columns() -> DFResult<()> { + let schema = schema(); let source = ProjectionExprs::from(vec![ - ProjectionExpr::new(transform, "odd"), + ProjectionExpr::new(transform_tags(&schema, DFOperator::Modulo)?, "odd"), ProjectionExpr::new(plan("upper(get_field(s, 'a'))", &schema)?, "up"), ]); let processed = split(source.clone(), &schema)?; @@ -397,6 +418,88 @@ fn test_lambda_in_datafusion_reads_raw_columns() -> DFResult<()> { Ok(()) } +/// A lambda in a subexpression that the scan evaluates does not stay in DataFusion, so the +/// projection still splits: an `array_transform` whose lambda converts is read in the scan under +/// an unsupported function, and so is a field read under another. +#[test] +fn test_lambda_under_unsupported_function_is_read_in_scan() -> DFResult<()> { + let schema = schema(); + let cardinality: Arc = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::new_from_impl(Cardinality::new())), + vec![transform_tags(&schema, DFOperator::Eq)?], + &schema, + Arc::new(ConfigOptions::new()), + )?); + let source = ProjectionExprs::from(vec![ + ProjectionExpr::new(cardinality, "n"), + ProjectionExpr::new(plan("upper(get_field(s, 'a'))", &schema)?, "up"), + ]); + let processed = split(source, &schema)?; + assert_eq!( + processed.scan_projection, + scan([ + ("__vortex_expr_0", tags_equal_two()?), + ("__vortex_expr_1", s_field(&["a"])), + ]) + ); + assert_eq!( + leftover(&processed), + [ + "cardinality(__vortex_expr_0@0) AS n", + "upper(__vortex_expr_1@1) AS up" + ] + ); + Ok(()) +} + +/// After a residual filter, the projection reads an `array_transform` whose lambda converts from +/// the scan, which evaluates it on every row since it cannot fail. One whose lambda stays in +/// DataFusion makes both the filter and the projection read raw columns. +#[test] +fn test_filtered_projection_with_lambda() -> DFResult<()> { + let schema = schema(); + let converter = DefaultExpressionConverter::default(); + let filters = vec![plan("get_field(s, 'b') % 2 = 0", &schema)?]; + let pushed = ProjectionExprs::from(vec![ProjectionExpr::new( + transform_tags(&schema, DFOperator::Eq)?, + "twos", + )]); + let (processed, rewritten) = + split_filtered_projection(&converter, pushed, filters.clone(), &schema)?; + assert_eq!( + processed.scan_projection, + scan([ + ("__vortex_expr_0", s_field(&["b"])), + ("__vortex_expr_1", tags_equal_two()?), + ]) + ); + assert_eq!( + rewritten + .iter() + .map(ToString::to_string) + .collect::>(), + ["__vortex_expr_0@0 % 2 = 0"] + ); + assert_eq!(leftover(&processed), ["__vortex_expr_1@1 AS twos"]); + + let kept = ProjectionExprs::from(vec![ProjectionExpr::new( + transform_tags(&schema, DFOperator::Modulo)?, + "odd", + )]); + let (processed, rewritten) = + split_filtered_projection(&converter, kept.clone(), filters.clone(), &schema)?; + assert_eq!( + processed.scan_projection, + scan([ + ("s", get_item("s", root())), + ("tags", get_item("tags", root())) + ]) + ); + assert_eq!(processed.leftover_projection, kept); + assert_eq!(rewritten, filters); + Ok(()) +} + /// Residual filters and the projection after them share one scan output. DataFusion evaluates /// both on some rows only, so the scan evaluates only infallible subexpressions. #[test] @@ -479,7 +582,8 @@ fn test_raw_filtered_projection_reads_filter_columns() -> DFResult<()> { let schema = schema(); let filters = vec![plan("get_field(s, 'b') % 2 = 0", &schema)?]; let source = projection(&[("id", "id")], &schema)?; - let (processed, rewritten) = raw_filtered_projection(source.clone(), filters.clone(), &schema)?; + let (processed, rewritten) = DefaultExpressionConverter::default() + .no_pushdown_filtered_projection(source.clone(), filters.clone(), &schema)?; assert_eq!( processed.scan_projection, scan([("id", get_item("id", root())), ("s", get_item("s", root()))]) diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3999285b340..db9e098db26 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -72,8 +72,6 @@ use vortex_utils::parallelism::get_available_parallelism; use crate::VortexAccessPlan; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; -use crate::convert::exprs::raw_filtered_projection; -use crate::convert::exprs::split_filtered_projection; use crate::convert::schema::calculate_physical_schema; use crate::convert::to_record_batch; use crate::metrics::PARTITION_LABEL; @@ -439,14 +437,17 @@ impl FileOpener for VortexOpener { }; (processed, residual_filters) } else if projection_pushdown { - split_filtered_projection( - expr_converter.as_ref(), + expr_converter.split_filtered_projection( projection, residual_filters, &this_file_schema, )? } else { - raw_filtered_projection(projection, residual_filters, &this_file_schema)? + expr_converter.no_pushdown_filtered_projection( + projection, + residual_filters, + &this_file_schema, + )? }; let residual_filter = conjunction_opt(residual_filters); @@ -903,6 +904,10 @@ mod tests { use rstest::rstest; use vortex::VortexSessionDefault; use vortex::buffer::Buffer; + use vortex::dtype::Nullability; + use vortex::expr::get_item; + use vortex::expr::pack; + use vortex::expr::root; use vortex::file::WriteOptionsSessionExt; use vortex::io::VortexWrite; use vortex::io::object_store::ObjectStoreWrite; @@ -918,6 +923,7 @@ mod tests { use crate::VortexSource; use crate::convert::exprs::DefaultExpressionConverter; use crate::persistent::reader::DefaultVortexReaderFactory; + use crate::tests::RecordingConverter; static SESSION: LazyLock = LazyLock::new(VortexSession::default); @@ -1337,14 +1343,10 @@ mod tests { Ok(()) } - /// A residual filter and the projection after it both read nested fields from the scan output, - /// whether the scan evaluates the field access or DataFusion reads the whole struct. - #[rstest] - #[tokio::test] - async fn test_residual_filter_with_nested_projection( - #[values(false, true)] projection_pushdown: bool, - #[values(false, true)] scan_v2: bool, - ) -> anyhow::Result<()> { + /// Writes `{a: i32, s: {b: i32, c: utf8}}` and returns an opener for it whose filter + /// `s.b % 2 = 0` stays residual, since the default converter does not support `%`, and whose + /// projection is `upper(s.c) AS shout, a`. + async fn residual_filter_opener() -> anyhow::Result<(VortexOpener, PartitionedFile)> { let store: Arc = Arc::new(InMemory::new()); let s = StructArray::try_new( vec![ @@ -1368,7 +1370,6 @@ mod tests { let size = write_arrow_to_vortex(Arc::clone(&store), "nested.vortex", batch.clone()).await?; let schema = batch.schema(); - // The default converter does not support `%`, so the filter stays residual. let filter = logical2physical(&(get_field(col("s"), "b") % lit(2)).eq(lit(0)), &schema); let mut opener = make_opener(store, TableSchema::from(Arc::clone(&schema)), Some(filter)); opener.projection = ProjectionExprs::from(vec![ @@ -1378,24 +1379,57 @@ mod tests { ), ProjectionExpr::new(logical2physical(&col("a"), &schema), "a"), ]); + Ok((opener, PartitionedFile::new("nested.vortex", size))) + } + + /// The rows of [`residual_filter_opener`] that its filter keeps. + const RESIDUAL_FILTER_ROWS: [&str; 6] = [ + "+-------+----+", + "| shout | a |", + "+-------+----+", + "| X | 20 |", + "| Z | 40 |", + "+-------+----+", + ]; + + /// A residual filter and the projection after it both read nested fields from the scan output, + /// whether the scan evaluates the field access or DataFusion reads the whole struct. + #[rstest] + #[tokio::test] + async fn test_residual_filter_with_nested_projection( + #[values(false, true)] projection_pushdown: bool, + #[values(false, true)] scan_v2: bool, + ) -> anyhow::Result<()> { + let (mut opener, file) = residual_filter_opener().await?; opener.projection_pushdown = projection_pushdown; opener.scan_v2 = scan_v2; - let batches = opener - .open(PartitionedFile::new("nested.vortex", size))? - .await? - .try_collect::>() - .await?; - assert_batches_eq!( - [ - "+-------+----+", - "| shout | a |", - "+-------+----+", - "| X | 20 |", - "| Z | 40 |", - "+-------+----+", - ], - &batches + let batches = opener.open(file)?.await?.try_collect::>().await?; + assert_batches_eq!(RESIDUAL_FILTER_ROWS, &batches); + Ok(()) + } + + /// A converter that keeps projections in DataFusion keeps them there after a residual filter + /// too: the scan reads the raw columns that the filter and the projection read. + #[rstest] + #[tokio::test] + async fn test_residual_filter_follows_converter_projection_split( + #[values(false, true)] scan_v2: bool, + ) -> anyhow::Result<()> { + let (mut opener, file) = residual_filter_opener().await?; + let converter = Arc::new(RecordingConverter::without_projection_pushdown( + SESSION.clone(), + )); + opener.expression_converter = Arc::clone(&converter) as _; + opener.projection_pushdown = true; + opener.scan_v2 = scan_v2; + let batches = opener.open(file)?.await?.try_collect::>().await?; + assert_batches_eq!(RESIDUAL_FILTER_ROWS, &batches); + + let expected = pack( + [("a", get_item("a", root())), ("s", get_item("s", root()))], + Nullability::NonNullable, ); + assert_eq!(*converter.scan_projections.lock(), [expected]); Ok(()) } diff --git a/vortex-datafusion/src/tests/mod.rs b/vortex-datafusion/src/tests/mod.rs index 77694ca966f..126b7aff75e 100644 --- a/vortex-datafusion/src/tests/mod.rs +++ b/vortex-datafusion/src/tests/mod.rs @@ -19,19 +19,37 @@ mod nested_projection; mod schema_evolution; /// Converts expressions with the default converter and records each scan projection. -struct RecordingConverter { +pub(crate) struct RecordingConverter { inner: DefaultExpressionConverter, - scan_projections: Mutex>, + /// Whether the scan evaluates the projection expressions it can, or reads raw columns. + projection_pushdown: bool, + pub(crate) scan_projections: Mutex>, } impl RecordingConverter { /// Converts with a default converter that resolves Arrow types through `session`. - fn new(session: VortexSession) -> Self { + pub(crate) fn new(session: VortexSession) -> Self { Self { inner: DefaultExpressionConverter::new(session), + projection_pushdown: true, scan_projections: Mutex::default(), } } + + /// Converts filters like [`Self::new`], but keeps every projection expression in DataFusion, + /// as a converter does that applies DataFusion's own field access semantics to projections. + pub(crate) fn without_projection_pushdown(session: VortexSession) -> Self { + Self { + projection_pushdown: false, + ..Self::new(session) + } + } + + fn record(&self, processed: &ProcessedProjection) { + self.scan_projections + .lock() + .push(processed.scan_projection.clone()); + } } impl ExpressionConverter for RecordingConverter { @@ -49,12 +67,29 @@ impl ExpressionConverter for RecordingConverter { input_schema: &Schema, output_schema: &Schema, ) -> DFResult { - let processed = + let processed = if self.projection_pushdown { self.inner - .split_projection(source_projection, input_schema, output_schema)?; - self.scan_projections - .lock() - .push(processed.scan_projection.clone()); + .split_projection(source_projection, input_schema, output_schema)? + } else { + self.no_pushdown_projection(source_projection, input_schema)? + }; + self.record(&processed); Ok(processed) } + + fn split_filtered_projection( + &self, + projection: ProjectionExprs, + residual_filters: Vec>, + input_schema: &Schema, + ) -> DFResult<(ProcessedProjection, Vec>)> { + let (processed, residual_filters) = if self.projection_pushdown { + self.inner + .split_filtered_projection(projection, residual_filters, input_schema)? + } else { + self.no_pushdown_filtered_projection(projection, residual_filters, input_schema)? + }; + self.record(&processed); + Ok((processed, residual_filters)) + } } From a9aa3952e4b9597740eb3e97f20105b29c600689 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Fri, 20 Nov 2026 15:17:33 -0500 Subject: [PATCH 09/13] Prune zones using zone maps beneath nullable structs A field of a nullable struct reaches the reader wrapped in the struct's mask, so neither scan could prune with its zone map. Both scans now look through the mask and keep only proofs that stay true when the zone map also covers values the struct hides, because releases up to 0.88.0 wrote zone maps over the stored values and no file records whether a zone map excludes them. Signed-off-by: Connor Tsui --- vortex-layout/src/layouts/struct_/mod.rs | 6 + vortex-layout/src/layouts/struct_/pruning.rs | 100 +++++ vortex-layout/src/layouts/struct_/reader.rs | 55 ++- vortex-layout/src/scan/v2/tests.rs | 393 +++++++++++++++++- vortex-scan/src/execution/filter.rs | 24 +- vortex-scan/src/execution/tests.rs | 93 ++++- vortex-scan/src/plan/builtins/pack/mod.rs | 16 +- vortex-scan/src/plan/builtins/pack/pruning.rs | 226 ++++++++++ vortex-scan/src/plan/optimize/mod.rs | 46 +- vortex-scan/src/plan/optimize/registry.rs | 40 +- 10 files changed, 951 insertions(+), 48 deletions(-) create mode 100644 vortex-layout/src/layouts/struct_/pruning.rs create mode 100644 vortex-scan/src/plan/builtins/pack/pruning.rs diff --git a/vortex-layout/src/layouts/struct_/mod.rs b/vortex-layout/src/layouts/struct_/mod.rs index 389d04f9423..2ca859e67ec 100644 --- a/vortex-layout/src/layouts/struct_/mod.rs +++ b/vortex-layout/src/layouts/struct_/mod.rs @@ -1,6 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! A layout that stores struct fields separately from the struct's validity. +//! +//! The child layout reads the stored field. The struct's validity can mask additional rows of +//! that field in the query result. + +mod pruning; mod reader; pub mod writer; diff --git a/vortex-layout/src/layouts/struct_/pruning.rs b/vortex-layout/src/layouts/struct_/pruning.rs new file mode 100644 index 00000000000..5d6a4500065 --- /dev/null +++ b/vortex-layout/src/layouts/struct_/pruning.rs @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Lets the classic scan use a field's zone map beneath a nullable struct. +//! +//! Removing `s`'s validity from `s.x < 10` can expose a stored value in a row that was null. +//! This can add matches, so a zone that rules out the broader filter also rules out the original. +//! Exact filtering still applies the parent mask. +//! +//! The child reader proves this with the field's own zone map. Releases up to 0.88.0 wrote zone +//! maps beneath nullable structs over the stored values, so their null counts miss the struct's +//! nulls. No file records whether a zone map excludes hidden values, so the mask must only be +//! removed where showing a hidden value cannot remove a match. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::traversal::Transformed; +use vortex_array::scalar_fn::fns::between::Between; +use vortex_array::scalar_fn::fns::binary::Binary; +use vortex_array::scalar_fn::fns::dynamic::DynamicComparison; +use vortex_array::scalar_fn::fns::mask::Mask; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_error::VortexResult; + +/// Removes masks for `parent_validity` where every original match is preserved. +/// +/// Each struct reader owns the mask for its own level. +pub(super) fn unmask_pruning_filter( + filter: BoundExpression, + parent_validity: &BoundExpression, +) -> VortexResult { + Ok(unmask(filter, parent_validity, true)?.into_inner()) +} + +fn unmask( + expr: BoundExpression, + parent_validity: &BoundExpression, + in_filter_connectives: bool, +) -> VortexResult> { + if expr.is::() && expr.child(1) == parent_validity { + return Ok(Transformed::yes(expr.child(0).clone())); + } + + let Some(scalar_fn) = expr.as_scalar() else { + return Ok(Transformed::no(expr)); + }; + let signature = scalar_fn.signature(); + + // A fallible function could error on a value previously hidden by the mask. + if !signature.is_infallible() { + return Ok(Transformed::no(expr)); + } + + let in_filter_connectives = in_filter_connectives + && matches!(expr.as_opt::(), Some(Operator::And | Operator::Or)); + let unmaskable = unmaskable_children(&expr, signature.is_strict(), in_filter_connectives); + + let mut changed = false; + let children = expr + .children() + .iter() + .enumerate() + .map(|(idx, child)| { + if idx >= unmaskable { + return Ok(child.clone()); + } + let child = unmask(child.clone(), parent_validity, in_filter_connectives)?; + changed |= child.changed; + Ok(child.into_inner()) + }) + .collect::>>()?; + if !changed { + return Ok(Transformed::no(expr)); + } + + Ok(Transformed::yes(expr.with_children(children)?)) +} + +/// Returns how many leading children of `expr` can gain a stored value in a masked row without +/// removing a match of `expr`. +fn unmaskable_children( + expr: &BoundExpression, + is_strict: bool, + in_filter_connectives: bool, +) -> usize { + // A strict function propagates the null from a masked input, so exposing a value can only + // change a null result. At the top of the filter, `AND` and `OR` preserve a true result when a + // null operand gains a value. + if is_strict || in_filter_connectives { + return expr.children().len(); + } + + // `Between` is not strict, because `NULL AND false` is false for a null bound. A + // `DynamicComparison` is not strict, because it returns its default while it has no value. A + // null in the first child, the compared value, still gives a null result or the default. + if expr.is::() || expr.is::() { + return 1; + } + + 0 +} diff --git a/vortex-layout/src/layouts/struct_/reader.rs b/vortex-layout/src/layouts/struct_/reader.rs index 06b3a722bae..a7127f17301 100644 --- a/vortex-layout/src/layouts/struct_/reader.rs +++ b/vortex-layout/src/layouts/struct_/reader.rs @@ -52,6 +52,7 @@ use crate::RowSplits; use crate::SplitRange; use crate::layouts::partitioned::PartitionedEval; use crate::layouts::struct_::StructLayout; +use crate::layouts::struct_::pruning::unmask_pruning_filter; use crate::segments::SegmentSource; #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -78,6 +79,14 @@ impl From for FieldName { } } +#[derive(Clone, Copy, Hash, PartialEq, Eq)] +enum PartitionMode { + /// Preserves the nulls introduced by the parent struct. + Exact, + /// Can expose stored values when the resulting filter keeps every possible match. + Pruning, +} + pub struct StructReader { layout: StructLayout, name: Arc, @@ -90,7 +99,9 @@ pub struct StructReader { expanded_root_expr: BoundExpression, field_lookup: Option>, - partitioned_expr_cache: DashMap>>, + /// Pruning may remove the parent mask. Cache its partition separately so exact reads + /// still apply the mask. + partitioned_expr_cache: DashMap<(ExactBoundExpr, PartitionMode), Arc>>, } impl StructReader { @@ -193,9 +204,17 @@ impl StructReader { .transpose() } - /// Utility for partitioning an expression over the fields of a struct. - fn partition_expr(&self, expr: &BoundExpression) -> VortexResult { - let key = ExactBoundExpr(expr.clone()); + fn partition_expr( + &self, + expr: &BoundExpression, + mode: PartitionMode, + ) -> VortexResult { + let mode = if self.dtype().is_nullable() { + mode + } else { + PartitionMode::Exact + }; + let key = (ExactBoundExpr(expr.clone()), mode); // Look up the cell under a shared shard lock; only a miss takes the write lock, and // only for as long as it takes to insert an empty cell. @@ -216,18 +235,23 @@ impl StructReader { } // Cache the bound trees themselves: rebinding would create fresh child identity and defeat // downstream `ExactBoundExpr` caches on every split. - let result = self.compute_partitioned_expr(expr)?; + let result = self.compute_partitioned_expr(expr, mode)?; Ok(cell.get_or_init(|| result).clone()) } - fn compute_partitioned_expr(&self, expr: &BoundExpression) -> VortexResult { - // First, we expand the root scope into the fields of the struct to ensure - // that partitioning works correctly. - let expr = + fn compute_partitioned_expr( + &self, + expr: &BoundExpression, + mode: PartitionMode, + ) -> VortexResult { + let mut expr = expand_struct_root(expr.clone(), &self.expanded_root_expr, self.struct_fields())?; + if mode == PartitionMode::Pruning { + // The nullable root expands to `mask(fields, validity)`. Pass just this struct's + // validity so each child reader remains responsible for its own mask. + expr = unmask_pruning_filter(expr, self.expanded_root_expr.child(1))?; + } - // Partition the expression into expressions that can be evaluated - // over individual coordinates. let fields = self .dtype() .as_struct_fields_opt() @@ -550,8 +574,7 @@ impl LayoutReader for StructReader { expr: &BoundExpression, mask: Mask, ) -> VortexResult { - // Partition the expression into expressions that can be evaluated over individual fields - match &self.partition_expr(expr)? { + match &self.partition_expr(expr, PartitionMode::Pruning)? { Partitioned::Single(name, partition) => { let reader = self.field_reader(name)?; reader @@ -592,8 +615,7 @@ impl LayoutReader for StructReader { expr: &BoundExpression, mask: MaskFuture, ) -> VortexResult { - // Partition the expression into expressions that can be evaluated over individual fields - match &self.partition_expr(expr)? { + match &self.partition_expr(expr, PartitionMode::Exact)? { Partitioned::Single(name, partition) => { let reader = self.field_reader(name)?; reader @@ -633,8 +655,7 @@ impl LayoutReader for StructReader { expr: &BoundExpression, mask_fut: MaskFuture, ) -> VortexResult { - // Partition the expression into expressions that can be evaluated over individual fields - match &self.partition_expr(expr)? { + match &self.partition_expr(expr, PartitionMode::Exact)? { Partitioned::Single(name, partition) => { let reader = self.field_reader(name)?; reader diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests.rs index a8219d3014e..b09939511fa 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests.rs @@ -10,6 +10,7 @@ use std::sync::LazyLock; use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::Field; +use async_trait::async_trait; use futures::Stream; use futures::TryStreamExt; use futures::stream; @@ -18,6 +19,7 @@ use vortex_array::ArrayContext; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; @@ -26,16 +28,29 @@ use vortex_array::arrays::VarBinArray; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::expr::Expression; use vortex_array::expr::and; +use vortex_array::expr::cast; +use vortex_array::expr::checked_add; +use vortex_array::expr::dynamic; use vortex_array::expr::eq; +use vortex_array::expr::fill_null; use vortex_array::expr::get_item; use vortex_array::expr::gt; +use vortex_array::expr::gt_eq; +use vortex_array::expr::is_nan; use vortex_array::expr::is_null; use vortex_array::expr::lit; use vortex_array::expr::lt; +use vortex_array::expr::not; +use vortex_array::expr::not_eq; +use vortex_array::expr::or; use vortex_array::expr::pack; use vortex_array::expr::root; +use vortex_array::scalar::ScalarValue; +use vortex_array::scalar_fn::fns::operators::CompareOperator; use vortex_array::validity::Validity; use vortex_arrow::ArrowSessionExt; use vortex_buffer::Alignment; @@ -53,6 +68,7 @@ use vortex_scan::planning::planner::Planner; use vortex_scan::planning::planner::WorkScope; use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; use vortex_session::VortexSession; +use vortex_utils::aliases::hash_set::HashSet; use super::ChunkPlanner; use super::PreparedScan; @@ -62,18 +78,27 @@ use super::ScanBuilder; use super::ScanFile; use crate::LayoutRef; use crate::LayoutStrategy; +use crate::LayoutWriterContext; +use crate::VTable as _; +use crate::layouts::chunked::Chunked; use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::flat::Flat; use crate::layouts::flat::writer::FlatLayoutStrategy; use crate::layouts::row_idx::row_idx; use crate::layouts::table::TableStrategy; +use crate::layouts::zoned::LegacyStats; +use crate::layouts::zoned::Zoned; use crate::layouts::zoned::writer::ZonedLayoutOptions; use crate::layouts::zoned::writer::ZonedStrategy; use crate::scan::arrow::to_record_batch; use crate::scan::scan_builder::ScanBuilder as V1ScanBuilder; use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSinkRef; use crate::segments::SegmentSource; use crate::segments::TestSegments; +use crate::sequence::SendableSequentialStream; use crate::sequence::SequenceId; +use crate::sequence::SequencePointer; use crate::sequence::SequentialStreamAdapter; use crate::sequence::SequentialStreamExt as _; use crate::test::new_session; @@ -159,17 +184,21 @@ fn table() -> Arc { Arc::new(TableStrategy::new(chunked_flat(), chunked_flat())) } -/// Every column is shredded into chunked leaves with zone statistics. -fn zoned_table() -> Arc { - let zoned = ZonedStrategy::new( +/// A chunked leaf with one zone per chunk. +fn zoned_leaf() -> ZonedStrategy { + ZonedStrategy::new( ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), FlatLayoutStrategy::default(), ZonedLayoutOptions { block_size: NonZeroUsize::new(CHUNK_ROWS).unwrap_or(NonZeroUsize::MIN), ..Default::default() }, - ); - Arc::new(TableStrategy::new(chunked_flat(), Arc::new(zoned))) + ) +} + +/// Every column is shredded into chunked leaves with zone statistics. +fn zoned_table() -> Arc { + Arc::new(TableStrategy::new(chunked_flat(), Arc::new(zoned_leaf()))) } /// A [`ScanFile`] over test segments. They have no byte offsets, and the scan fetches them by id, @@ -568,6 +597,360 @@ async fn nullable_struct_projection_preserves_validity( Ok(()) } +/// The zone map layout that [`StoredValueZones`] writes. +#[derive(Clone, Copy, Debug)] +enum ZoneMapLayout { + /// The `vortex.zoned` layout. + Zoned, + /// The legacy `vortex.stats` layout, which older releases wrote. + LegacyStats, +} + +/// Writes each column's zone map over its stored values, even beneath a nullable struct. +/// +/// Releases up to 0.88.0 wrote zone maps this way, so the null count of a struct field misses the +/// rows where the struct is null. Readers must still prune those files correctly. Develop writes +/// no zone map beneath a nullable struct, so the tests need this writer to produce one. +struct StoredValueZones { + layout: ZoneMapLayout, + zoned: ZonedStrategy, +} + +#[async_trait] +impl LayoutStrategy for StoredValueZones { + async fn write_stream( + &self, + ctx: LayoutWriterContext, + segment_sink: SegmentSinkRef, + stream: SendableSequentialStream, + eof: SequencePointer, + session: &VortexSession, + ) -> VortexResult { + // NB: A fresh context drops the nullable-ancestor flag that the struct writer set. The old + // writers had no such flag. + let stored_ctx = LayoutWriterContext::new(ctx.array_ctx().clone()); + let stored_ctx = match self.layout { + ZoneMapLayout::Zoned => stored_ctx, + ZoneMapLayout::LegacyStats => stored_ctx.with_allowed_layouts(HashSet::from_iter([ + LegacyStats.id(), + Chunked.id(), + Flat.id(), + ])), + }; + + self.zoned + .write_stream(stored_ctx, segment_sink, stream, eof, session) + .await + } +} + +/// Every column is shredded into chunked leaves with zone maps over their stored values. +fn stored_zones_table(layout: ZoneMapLayout) -> Arc { + let zoned = zoned_leaf(); + Arc::new(TableStrategy::new( + chunked_flat(), + Arc::new(StoredValueZones { layout, zoned }), + )) +} + +/// The number of leaf columns in a [`nullable_zone`]. +const NULLABLE_ZONE_LEAVES: usize = 5; + +/// A table whose zone maps include values that nullable structs hide. +/// +/// Each scan gets a fresh reader and cache so its segment count includes every required read. +struct NullableZones { + session: VortexSession, + input: ArrayRef, + segments: Arc, + layout: LayoutRef, +} + +impl NullableZones { + async fn write(zone_maps: ZoneMapLayout, with_nans: bool) -> VortexResult { + let session = new_session().with_tokio(); + let chunks = (0..CHUNKS) + .map(|zone| nullable_zone(zone, with_nans)) + .collect::>>()?; + let strategy = stored_zones_table(zone_maps); + let (segments, layout) = write_chunks(&session, strategy.as_ref(), chunks.clone()).await?; + assert_stored_zone_maps(&layout, zone_maps)?; + let input = ChunkedArray::try_new(chunks, layout.dtype().clone())?.into_array(); + + Ok(Self { + session, + input, + segments, + layout, + }) + } + + async fn assert_scan(&self, use_v2: bool, predicate: Expression) -> VortexResult { + let projection = get_item("id", root()); + let bound_projection = projection.bind(self.layout.dtype())?; + let dtype = bound_projection.dtype().clone(); + let filter = predicate.bind(self.layout.dtype())?; + let source = Arc::new(CountingSegmentSource::new(Arc::clone(&self.segments))); + let segments: Arc = Arc::::clone(&source); + + let actual = if use_v2 { + let scan = builder(&self.session, &segments, &self.layout)? + .with_projection(bound_projection) + .with_some_filter(Some(filter)); + collect_scan(dtype, scan).await? + } else { + let reader = + self.layout + .new_reader("".into(), segments, &self.session, &Default::default())?; + let scan = V1ScanBuilder::new(self.session.clone(), reader) + .with_projection(bound_projection) + .with_filter(filter); + collect(dtype, scan.into_stream()?).await? + }; + + let mut ctx = self.session.create_execution_ctx(); + let keep = self + .input + .clone() + .apply(&fill_null(predicate, lit(false)))? + .execute::(&mut ctx)?; + let expected = self.input.clone().filter(keep)?.apply(&projection)?; + assert_arrays_eq!(actual, expected, &mut ctx); + + Ok(source.requests()) + } +} + +/// Asserts that every leaf column has a zone map in the `zone_maps` layout with a null count. +/// Beneath a nullable struct, that count misses the rows where the struct is null, so the scans +/// must never trust it. +#[track_caller] +fn assert_stored_zone_maps(layout: &LayoutRef, zone_maps: ZoneMapLayout) -> VortexResult<()> { + let mut written = 0; + for layout in layout.depth_first_traversal() { + let layout = layout?; + let aggregate_fns = if let Some(zoned) = layout.as_opt::() { + assert!(matches!(zone_maps, ZoneMapLayout::Zoned)); + zoned.aggregate_fns() + } else if let Some(legacy) = layout.as_opt::() { + assert!(matches!(zone_maps, ZoneMapLayout::LegacyStats)); + legacy.aggregate_fns() + } else { + continue; + }; + assert!( + aggregate_fns + .iter() + .any(|aggregate_fn| aggregate_fn.is::()) + ); + written += 1; + } + + assert_eq!(written, NULLABLE_ZONE_LEAVES); + Ok(()) +} + +/// Builds zone `zone` of a table with an `id` column and a nullable struct `nested`. +/// +/// `nested` hides zone 1 and the odd rows of zone 2. Its nullable struct field `deep` also hides +/// zone 3. Hidden integers and strings sort after every visible value, so they widen the stored +/// bounds. The optional NaNs include a visible value in zone 2 and values hidden by `nested` in +/// zone 1. +fn nullable_zone(zone: usize, with_nans: bool) -> VortexResult { + let first_row = i32::try_from(zone * CHUNK_ROWS)?; + let rows = first_row..first_row + i32::try_from(CHUNK_ROWS)?; + let visible = |row: i32| zone != 1 && (zone != 2 || row % 2 == 0); + let deep_visible = |row: i32| visible(row) && zone != 3; + + let ids = Buffer::from_iter(rows.clone()); + let ints = Buffer::from_iter(rows.clone().map(|row| stored_int(row, visible(row)))); + let deep_ints = Buffer::from_iter(rows.clone().map(|row| stored_int(row, deep_visible(row)))); + let floats = PrimitiveArray::from_option_iter(rows.clone().map(|row| { + let value = if with_nans && (zone == 1 || (zone == 2 && row == first_row)) { + f64::NAN + } else if visible(row) { + f64::from(row) + } else { + 1e9_f64 + }; + (zone != 3 || row != first_row).then_some(value) + })); + let texts = VarBinArray::from_iter( + rows.clone().map(|row| { + Some(if visible(row) { + format!("row {row:04}") + } else { + "~hidden".to_string() + }) + }), + DType::Utf8(Nullability::NonNullable), + ); + + let deep = StructArray::try_new( + FieldNames::from(["int"]), + [deep_ints.into_array()], + CHUNK_ROWS, + Validity::from_iter(rows.clone().map(|_| zone != 3)), + )?; + let nested = StructArray::try_new( + FieldNames::from(["int", "float", "text", "deep"]), + [ + ints.into_array(), + floats.into_array(), + texts.into_array(), + deep.into_array(), + ], + CHUNK_ROWS, + Validity::from_iter(rows.map(visible)), + )?; + + Ok( + StructArray::from_fields(&[("id", ids.into_array()), ("nested", nested.into_array())])? + .into_array(), + ) +} + +/// A hidden integer would overflow when adding one. A fallible filter must still see its row as +/// null after pruning. +fn stored_int(row: i32, visible: bool) -> i64 { + if visible { i64::from(row) } else { i64::MAX } +} + +fn nested_field(field: &str) -> Expression { + get_item(field, get_item("nested", root())) +} + +fn deep_int() -> Expression { + get_item("int", nested_field("deep")) +} + +/// `nested.int < cutoff()`, which is true for every row while `cutoff()` returns no value. +fn int_below_dynamic( + cutoff: impl Fn() -> Option + Send + Sync + 'static, +) -> Expression { + dynamic( + CompareOperator::Lt, + cutoff, + DType::Primitive(PType::I64, Nullability::NonNullable), + true, + nested_field("int"), + ) +} + +/// The segments that a scan of `id` reads when it filters on a field beneath `depth` nullable +/// structs: the field's zone map, then the field, each struct's validity, and the IDs of each zone +/// it keeps. The classic scan also reads the IDs of the zones it skips. +fn expected_reads(use_v2: bool, depth: usize, kept_zones: usize) -> usize { + let per_kept_zone = 1 + depth + 1; + let skipped_ids = if use_v2 { 0 } else { CHUNKS - kept_zones }; + + 1 + kept_zones * per_kept_zone + skipped_ids +} + +/// Only zone 0 holds visible values below each cutoff, and the stored bounds of the other zones +/// still rule them out. +#[rstest] +#[case::int_bound(lt(nested_field("int"), lit(100i64)), 1)] +#[case::int_range( + and( + gt_eq(nested_field("int"), lit(0i64)), + lt(nested_field("int"), lit(100i64)), + ), + 1 +)] +#[case::float_bound(lt(nested_field("float"), lit(100.0f64)), 1)] +#[case::text_bound(lt(nested_field("text"), lit("row 0100")), 1)] +#[case::text_range( + and( + gt_eq(nested_field("text"), lit("row 0000")), + lt(nested_field("text"), lit("row 0100")), + ), + 1 +)] +#[case::deep_bound(lt(deep_int(), lit(100i64)), 2)] +#[tokio::test] +async fn bounds_under_nullable_structs_skip_zone_reads( + #[values(false, true)] use_v2: bool, + #[values(ZoneMapLayout::Zoned, ZoneMapLayout::LegacyStats)] zone_maps: ZoneMapLayout, + #[case] filter: Expression, + #[case] depth: usize, +) -> VortexResult<()> { + let table = NullableZones::write(zone_maps, false).await?; + let reads = table.assert_scan(use_v2, filter).await?; + assert_eq!(reads, expected_reads(use_v2, depth, 1)); + Ok(()) +} + +/// Only the classic scan prunes a dynamic filter on a scan this small. The V2 scan skips the +/// pruning plans of dynamic conjuncts on scans of at most one filtered chunk. +#[rstest] +#[tokio::test] +async fn dynamic_bounds_under_nullable_structs_skip_classic_zone_reads( + #[values(ZoneMapLayout::Zoned, ZoneMapLayout::LegacyStats)] zone_maps: ZoneMapLayout, +) -> VortexResult<()> { + let table = NullableZones::write(zone_maps, false).await?; + let reads = table + .assert_scan(false, int_below_dynamic(|| Some(100i64.into()))) + .await?; + assert_eq!(reads, expected_reads(false, 1, 1)); + Ok(()) +} + +/// Zones 0 and 3 store no NaNs. Zone 1 stores NaNs hidden by `nested`, so a scan must read it. +#[rstest] +#[tokio::test] +async fn nan_counts_under_nullable_structs_skip_zone_reads( + #[values(false, true)] use_v2: bool, + #[values(ZoneMapLayout::Zoned, ZoneMapLayout::LegacyStats)] zone_maps: ZoneMapLayout, +) -> VortexResult<()> { + let table = NullableZones::write(zone_maps, true).await?; + let reads = table + .assert_scan(use_v2, is_nan(nested_field("float"))) + .await?; + assert_eq!(reads, expected_reads(use_v2, 1, 2)); + Ok(()) +} + +#[rstest] +#[case::parent_nulls(is_null(nested_field("int")))] +#[case::deep_parent_nulls(is_null(deep_int()))] +#[case::loose_bound(lt(nested_field("int"), lit(2050i64)))] +#[case::loose_range(and( + gt_eq(nested_field("int"), lit(10i64)), + lt(nested_field("int"), lit(2050i64)), +))] +#[case::nulls_or_bounds(or( + is_null(nested_field("float")), + lt(nested_field("float"), lit(10.0f64)), +))] +#[case::text_not_eq(not_eq(nested_field("text"), lit("row 0000")))] +#[case::deep_or_text(or(lt(deep_int(), lit(10i64)), eq(nested_field("text"), lit("row 3000")),))] +#[case::narrow_cast(gt( + cast( + nested_field("int"), + DType::Primitive(PType::I16, Nullability::Nullable) + ), + lit(10i16), +))] +#[case::overflow(gt(checked_add(nested_field("int"), lit(1i64)), lit(10i64)))] +#[case::dynamic_bound(int_below_dynamic(|| Some(2050i64.into())))] +#[case::dynamic_without_value(int_below_dynamic(|| None))] +#[case::nan(is_nan(nested_field("float")))] +#[case::not_nan(not(is_nan(nested_field("float"))))] +#[case::float_bounds_with_nans(lt(nested_field("float"), lit(100.0f64)))] +#[tokio::test] +async fn pruning_under_nullable_structs_preserves_matching_rows( + #[values(false, true)] use_v2: bool, + #[values(ZoneMapLayout::Zoned, ZoneMapLayout::LegacyStats)] zone_maps: ZoneMapLayout, + #[case] filter: Expression, +) -> VortexResult<()> { + NullableZones::write(zone_maps, true) + .await? + .assert_scan(use_v2, filter) + .await?; + Ok(()) +} + #[test] fn partition_rows_tile_the_file_on_row_blocks() { let (file_size, row_count) = (1_000u64, 100_000u64); diff --git a/vortex-scan/src/execution/filter.rs b/vortex-scan/src/execution/filter.rs index 16cc3db2292..a3f9959aacc 100644 --- a/vortex-scan/src/execution/filter.rs +++ b/vortex-scan/src/execution/filter.rs @@ -9,6 +9,7 @@ use rustc_hash::FxHashSet; use vortex_array::VortexSessionExecute; use vortex_array::builtins::ArrayBuiltins; use vortex_array::expr::BoundExpression; +use vortex_array::scalar_fn::fns::literal::Literal; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure_eq; @@ -35,10 +36,12 @@ use super::segment_target; use crate::execution::filter_expr::FilterExpr; use crate::execution::pipeline::Scan; use crate::execution::pipeline::Split; +use crate::plan::Eval; use crate::plan::FilterPlan; use crate::plan::PlanRef; use crate::plan::Zoned; use crate::plan::optimize; +use crate::plan::optimize::optimize_pruning; use crate::plan::plan_row_idx_expression; use crate::planning::planner::Planner; use crate::planning::planner::PlannerOutput; @@ -86,7 +89,7 @@ impl FilterPlans { .map(|expr| { expr.falsify(session)? .map(|pruning| { - optimize( + optimize_pruning( plan_row_idx_expression(pruning, root.clone(), session)?, session, ) @@ -96,7 +99,7 @@ impl FilterPlans { .map(|plan| { let plan = plan?; match plan { - Some(plan) if metadata_only(&plan)? => Ok(Some(plan)), + Some(plan) if metadata_only(&plan)? && may_prune(&plan)? => Ok(Some(plan)), _ => Ok(None), } }) @@ -143,6 +146,23 @@ impl FilterPlans { } } +/// Returns false for a pruning plan that folds to a constant false or null. +/// +/// Such a plan never discards a row, so running it only costs time. This happens when the +/// optimizer drops every clause of a proof that it cannot keep, for example a null-count clause +/// beneath a nullable struct. A plan that folds to true still runs, because it discards every row +/// without reading them. +fn may_prune(plan: &PlanRef) -> VortexResult { + let Some(eval) = plan.as_opt::() else { + return Ok(true); + }; + let expression = eval.expression().clone().optimize()?; + + Ok(expression + .as_opt::() + .is_none_or(|value| value.as_bool().value() == Some(true))) +} + /// A pruning plan must not fetch data when its requested statistics are unavailable. fn metadata_only(plan: &PlanRef) -> VortexResult { if plan diff --git a/vortex-scan/src/execution/tests.rs b/vortex-scan/src/execution/tests.rs index 4d44390813d..f1083c86950 100644 --- a/vortex-scan/src/execution/tests.rs +++ b/vortex-scan/src/execution/tests.rs @@ -11,8 +11,12 @@ use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::null_count::NullCount; +use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; @@ -21,17 +25,23 @@ use vortex_array::arrays::VarBinArray; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; use vortex_array::expr::Expression; use vortex_array::expr::dynamic; use vortex_array::expr::eq; use vortex_array::expr::get_item; use vortex_array::expr::gt; +use vortex_array::expr::is_null; use vortex_array::expr::lit; +use vortex_array::expr::lt; use vortex_array::expr::root; use vortex_array::scalar_fn::fns::operators::CompareOperator; use vortex_array::validity::Validity; use vortex_buffer::Alignment; use vortex_buffer::Buffer; +use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_io::session::RuntimeSessionExt; @@ -342,7 +352,7 @@ async fn dictionary_values_are_reused_between_splits() -> VortexResult<()> { segments.flat(&PrimitiveArray::from_iter(start..end).into_array()) }) .collect::>>()?; - let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); + let dtype = DType::Primitive(PType::I32, false.into()); let ints = ConcatPlan::try_new(dtype, arrays)?.into_plan(); // Codes index the same values across fixed work chunks and stored chunk boundaries. let layout = dict(ints.clone(), ints); @@ -433,7 +443,7 @@ async fn primitive_column() -> VortexResult<()> { let (segments, layout) = source(&session, Strategy::Table).await?; let dtype = layout.dtype().clone(); let actual = collect_scan( - DType::Primitive(vortex_array::dtype::PType::I32, false.into()), + DType::Primitive(PType::I32, false.into()), builder(&session, &segments, &layout)? .with_projection(get_item("ints", root()).bind(&dtype)?) .with_row_range(990..1010), @@ -472,7 +482,7 @@ async fn chunked_ints(_session: &VortexSession, segments: &Arc) -> Vortex segments.flat(&PrimitiveArray::from_iter(index * 10..index * 10 + 10).into_array()) }) .collect::>>()?; - let dtype = DType::Primitive(vortex_array::dtype::PType::I32, false.into()); + let dtype = DType::Primitive(PType::I32, false.into()); Ok(ConcatPlan::try_new(dtype, arrays)?.into_plan()) } @@ -563,7 +573,7 @@ async fn repeated_projections_reuse_their_values() -> VortexResult<()> { let actual = collect_scan(projection.dtype().clone(), scan).await?; assert_arrays_eq!( actual, - vortex_array::arrays::BoolArray::from_iter([false, true]), + BoolArray::from_iter([false, true]), &mut session.create_execution_ctx() ); reads.push(counted.requests() - before); @@ -851,3 +861,78 @@ async fn shared_cache_prunes_zones_once() -> VortexResult<()> { assert_eq!(reads, vec![2, 1]); Ok(()) } + +/// A table with one nullable struct `s`, whose non-nullable field `x` has a zone map with a +/// minimum, a maximum, and a stored null count. +fn nullable_struct_with_zones(store: &Store) -> VortexResult { + let zones = 2; + let rows = (zones * CHUNK_ROWS) as u64; + let x_dtype = DType::Primitive(PType::I64, Nullability::NonNullable); + + let validity = (0..zones) + .map(|_| { + store.flat(&BoolArray::from_iter((0..CHUNK_ROWS).map(|row| row % 2 == 0)).into_array()) + }) + .collect::>>()?; + let validity = + ConcatPlan::try_new(DType::Bool(Nullability::NonNullable), validity)?.into_plan(); + + let data = (0..zones) + .map(|zone| { + let first_row = i64::try_from(zone * CHUNK_ROWS)?; + let values = Buffer::from_iter(first_row..first_row + i64::try_from(CHUNK_ROWS)?); + store.flat(&values.into_array()) + }) + .collect::>>()?; + let data = ConcatPlan::try_new(x_dtype.clone(), data)?.into_plan(); + + let min = Min.bind(NumericalAggregateOpts::skip_nans()); + let max = Max.bind(NumericalAggregateOpts::skip_nans()); + let null_count = NullCount.bind(EmptyOptions); + let table = StructArray::from_fields(&[ + (min.to_string().as_str(), buffer![0i64, 1000].into_array()), + (max.to_string().as_str(), buffer![999i64, 1999].into_array()), + ( + null_count.to_string().as_str(), + buffer![0u64, 0].into_array(), + ), + ])? + .into_array(); + let x = ZonedPlan::new( + data, + store.flat(&table)?, + CHUNK_ROWS as u64, + vec![min, max, null_count].into(), + ) + .into_plan(); + + let s_dtype = DType::Struct( + StructFields::new(["x"].into(), vec![x_dtype]), + Nullability::Nullable, + ); + let s = struct_plan(rows, s_dtype.clone(), vec![validity, x]); + let root_dtype = DType::Struct( + StructFields::new(["s"].into(), vec![s_dtype]), + Nullability::NonNullable, + ); + + Ok(struct_plan(rows, root_dtype, vec![s])) +} + +/// Beneath a nullable struct, the scan drops proofs that use the stored null count, because that +/// count misses the struct's nulls. A filter with no other proof gets no pruning plan. A proof +/// that folds to true still discards every zone without reading it. +#[rstest] +#[case::null_check(is_null(get_item("x", get_item("s", root()))), 0)] +#[case::bound(lt(get_item("x", get_item("s", root())), lit(10i64)), 1)] +#[case::always_false(lit(false), 1)] +fn nullable_struct_pruning_plans( + #[case] filter: Expression, + #[case] pruning_plans: usize, +) -> VortexResult<()> { + let store = Store::default(); + let root = nullable_struct_with_zones(&store)?; + let plans = FilterPlans::new(filter.bind(root.dtype())?, &root, &new_session(), false)?; + assert_eq!(plans.pruning().count(), pruning_plans); + Ok(()) +} diff --git a/vortex-scan/src/plan/builtins/pack/mod.rs b/vortex-scan/src/plan/builtins/pack/mod.rs index a76ed8d34ed..06c319fdd0d 100644 --- a/vortex-scan/src/plan/builtins/pack/mod.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -7,6 +7,7 @@ //! expression that uses part of the struct can read the relevant children directly. pub(crate) mod execute; +mod pruning; use std::borrow::Cow; use std::iter; @@ -41,6 +42,7 @@ use vortex_mask::Mask; use vortex_session::VortexSession; use vortex_session::registry::CachedId; +use self::pruning::weaken_pruning_proof; use crate::execution::operators::OnceSource; use crate::execution::operators::PackSource; use crate::execution::operators::WrapStage; @@ -55,6 +57,7 @@ use crate::plan::PlanParts; use crate::plan::PlanRef; use crate::plan::PlanSlots; use crate::plan::PlanVTable; +use crate::plan::is_zone_pruning; use crate::plan::optimizer::PlanParentReduceRule; use crate::plan::partition::PartitionRule; use crate::plan::partition::PartitionSession; @@ -353,7 +356,12 @@ impl PackPlan { /// The next pass pushes the lookup into the `address` child as `$.zip`. The scan can /// skip `city` and read just `zip` and the validity of each nullable ancestor. #[derive(Debug)] -pub(crate) struct ExpressionPackRule; +pub(crate) enum ExpressionPackRule { + /// Preserves the value of the expression for every row. + Exact, + /// Preserves only the proof that rows can be discarded. + Pruning, +} impl PlanParentReduceRule for ExpressionPackRule { type Parent = Eval; @@ -390,6 +398,12 @@ impl PlanParentReduceRule for ExpressionPackRule { let nullable = child.dtype().is_nullable(); if nullable { combiner = combiner.rewrite(&mut ProjectMaskedFields)?.into_inner(); + + // Stored statistics can weaken a proof. This rewrite is valid only when a true + // result means the zone can be discarded. + if matches!(self, Self::Pruning) && is_zone_pruning(parent)? { + combiner = weaken_pruning_proof(combiner)?; + } } // The combiner's root is non-nullable even when it uses every original field. diff --git a/vortex-scan/src/plan/builtins/pack/pruning.rs b/vortex-scan/src/plan/builtins/pack/pruning.rs new file mode 100644 index 00000000000..8ebb525b974 --- /dev/null +++ b/vortex-scan/src/plan/builtins/pack/pruning.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Uses stored zone statistics to prove that filters on a nullable [`Pack`](super::Pack) +//! cannot match. +//! +//! For an integer `s.x`, `min(s.x) >= 10` proves that `s.x < 10` has no matches. A value hidden +//! by `s` can lower the stored minimum, making the proof harder to satisfy. When the stored +//! minimum is still at least 10, the scan can skip the zone. +//! +//! Every zone map beneath a nullable struct must be treated as covering hidden values. Releases +//! up to 0.88.0 wrote them over the stored values, so their null counts miss the struct's nulls, +//! and no file records whether a zone map excludes hidden values. + +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; +use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; +use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; +use vortex_array::aggregate_fn::fns::nan_count::NanCount; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::bound; +use vortex_array::expr::stats::Stat; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::fns::binary::Binary; +use vortex_array::scalar_fn::fns::literal::Literal; +use vortex_array::scalar_fn::fns::mask::Mask; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_array::scalar_fn::fns::stat::StatFn; +use vortex_error::VortexResult; +use vortex_expr::stats; + +/// Weakens a proof over masked fields so it can use their stored statistics. +/// +/// Every true result still proves that a zone can be skipped. +pub(super) fn weaken_pruning_proof(proof: BoundExpression) -> VortexResult { + if matches!(proof.as_opt::(), Some(Operator::And | Operator::Or)) { + let left = weaken_pruning_proof(proof.child(0).clone())?; + let right = weaken_pruning_proof(proof.child(1).clone())?; + return proof.with_children([left, right]); + } + + if !proof.contains::()? { + return Ok(proof); + } + + if let Some(physical) = unmask_proof_clause(&proof)? { + return Ok(physical); + } + + // Drop the whole clause. Putting a null placeholder inside `is_null(stat)` would turn + // an unsupported statistic into a true proof. + Ok(if proof.dtype().is_nullable() { + bound::lit(Scalar::null(proof.dtype().clone())) + } else { + bound::lit(false) + }) +} + +fn unmask_proof_clause(proof: &BoundExpression) -> VortexResult> { + if let Some(input) = unmasked_stat_input(proof, |agg| agg.is::())? { + return Ok(Some(stats::bound::all_non_nan(input))); + } + + let Some(operator) = proof.as_opt::() else { + return Ok(None); + }; + let (left, right) = (proof.child(0), proof.child(1)); + + if *operator == Operator::Eq { + let (zero, count) = if left.is::() { + (left, right) + } else { + (right, left) + }; + if zero.as_opt::().and_then(Scalar::is_zero) != Some(true) { + return Ok(None); + } + + // A stored count of zero proves all visible values are non-NaN. A positive count + // can come from hidden rows, so it gives no proof about the visible values. + let input = unmasked_stat_input(count, |agg| agg.is::())?; + return Ok(input.map(stats::bound::all_non_nan)); + } + + // For `<`, hidden values can raise the left upper bound or lower the right lower bound. + // Both changes make the proof harder to satisfy. + let (left_bound, right_bound) = match operator { + Operator::Lt | Operator::Lte => (StatBound::Upper, StatBound::Lower), + Operator::Gt | Operator::Gte => (StatBound::Lower, StatBound::Upper), + _ => return Ok(None), + }; + + // Only move bounds used directly by a comparison. A fallible function between a bound and + // the comparison could fail on a stored value hidden by the parent. + let Some(left) = comparison_operand(left, left_bound)? else { + return Ok(None); + }; + let Some(right) = comparison_operand(right, right_bound)? else { + return Ok(None); + }; + + Ok(Some(proof.clone().with_children([left, right])?)) +} + +#[derive(Clone, Copy)] +enum StatBound { + Lower, + Upper, +} + +impl StatBound { + fn matches(self, aggregate: &AggregateFnRef) -> bool { + let stat = Stat::from_aggregate_fn(aggregate); + match self { + Self::Lower => stat == Some(Stat::Min) || aggregate.is::(), + Self::Upper => stat == Some(Stat::Max) || aggregate.is::(), + } + } +} + +fn comparison_operand( + expr: &BoundExpression, + bound: StatBound, +) -> VortexResult> { + if !expr.contains::()? { + return Ok(Some(expr.clone())); + } + + let Some(input) = unmasked_stat_input(expr, |agg| bound.matches(agg))? else { + return Ok(None); + }; + let unmasked = expr.clone().with_children([input])?; + + Ok((unmasked.dtype() == expr.dtype()).then_some(unmasked)) +} + +fn unmasked_stat_input( + stat: &BoundExpression, + allow: impl FnOnce(&AggregateFnRef) -> bool, +) -> VortexResult> { + let Some(opts) = stat.as_opt::() else { + return Ok(None); + }; + let mut input = stat.child(0); + if !input.is::() || !allow(opts.aggregate_fn()) { + return Ok(None); + } + + while input.is::() { + input = input.child(0); + } + + Ok((!input.contains::()?).then(|| input.clone())) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::aggregate_fn::fns::max::Max; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::expr::Expression; + use vortex_array::expr::cast; + use vortex_array::expr::eq; + use vortex_array::expr::gt; + use vortex_array::expr::is_not_null; + use vortex_array::expr::is_null; + use vortex_array::expr::lit; + use vortex_array::expr::lt_eq; + use vortex_array::expr::mask; + use vortex_array::expr::root; + use vortex_array::scalar::Scalar; + use vortex_error::VortexResult; + use vortex_expr::stats; + + use super::weaken_pruning_proof; + + fn masked_input() -> Expression { + mask(root(), is_not_null(root())) + } + + fn max(input: Expression) -> Expression { + stats::stat(input, Max.bind(NumericalAggregateOpts::skip_nans())) + } + + fn unknown() -> Expression { + lit(Scalar::null(DType::Bool(Nullability::Nullable))) + } + + #[rstest] + #[case::widening_weakens_proof( + lt_eq(max(masked_input()), lit(5.0f64)), + lt_eq(max(root()), lit(5.0f64)) + )] + #[case::widening_strengthens_proof(gt(max(masked_input()), lit(5.0f64)), unknown())] + #[case::zero_nan_count( + eq(stats::nan_count(masked_input()), lit(0u64)), + stats::all_non_nan(root()) + )] + #[case::nonzero_nan_count(eq(stats::nan_count(masked_input()), lit(1u64)), unknown())] + #[case::null_test(is_null(stats::null_count(masked_input())), lit(false))] + #[case::fallible_bound( + lt_eq( + cast( + max(masked_input()), + DType::Primitive(PType::I8, Nullability::Nullable) + ), + lit(5i8), + ), + unknown() + )] + fn uses_only_conservative_facts_from_stored_values( + #[case] proof: Expression, + #[case] expected: Expression, + ) -> VortexResult<()> { + let dtype = DType::Primitive(PType::F64, Nullability::Nullable); + assert_eq!( + weaken_pruning_proof(proof.bind(&dtype)?)?, + expected.bind(&dtype)?, + ); + Ok(()) + } +} diff --git a/vortex-scan/src/plan/optimize/mod.rs b/vortex-scan/src/plan/optimize/mod.rs index a42d18839ee..6a1a4871024 100644 --- a/vortex-scan/src/plan/optimize/mod.rs +++ b/vortex-scan/src/plan/optimize/mod.rs @@ -20,12 +20,24 @@ use crate::plan::LazyPlanRef; use crate::plan::PlanRef; use crate::plan::PlanSlots; -fn reduce(plan: &PlanRef, session: &VortexSession) -> VortexResult> { +#[derive(Clone, Copy)] +enum OptimizeMode { + /// Preserves the result of the plan at each row. + Exact, + /// Allows weaker falsifiers as long as true still proves that a row can be discarded. + Pruning, +} + +fn reduce( + plan: &PlanRef, + session: &VortexSession, + mode: OptimizeMode, +) -> VortexResult> { if let Some(rewritten) = reduce_plan(plan, session)? { return Ok(Some(rewritten)); } for (slot, child) in plan.slots().present() { - if let Some(rewritten) = reduce_parent(child.get()?, plan, slot, session)? { + if let Some(rewritten) = reduce_parent(child.get()?, plan, slot, session, mode)? { return Ok(Some(rewritten)); } } @@ -34,16 +46,34 @@ fn reduce(plan: &PlanRef, session: &VortexSession) -> VortexResult VortexResult { + optimize_with_mode(plan, session, OptimizeMode::Exact) +} + +/// Optimizes a proof that rows cannot match a filter. +/// +/// A true result lets the scan discard rows. A rewrite may make the proof harder to satisfy, +/// which leaves more rows for exact evaluation. +pub(crate) fn optimize_pruning(plan: PlanRef, session: &VortexSession) -> VortexResult { + optimize_with_mode(plan, session, OptimizeMode::Pruning) +} + +fn optimize_with_mode( + plan: PlanRef, + session: &VortexSession, + mode: OptimizeMode, +) -> VortexResult { // Concat has no local rewrites. Optimizing its independent chunks eagerly traverses the // entire file even when a partition only scans a small row range. if let Some(concat) = plan.as_opt::() { let session = session.clone(); return Ok(concat - .map_chunks(plan.dtype().clone(), move |chunk| optimize(chunk, &session)) + .map_chunks(plan.dtype().clone(), move |chunk| { + optimize_with_mode(chunk, &session, mode) + }) .into_plan()); } - if let Some(rewritten) = reduce(&plan, session)? { - return optimize(rewritten, session); + if let Some(rewritten) = reduce(&plan, session, mode)? { + return optimize_with_mode(rewritten, session, mode); } // Absent slots stay absent, and unchanged slots keep their shared lazy slot. @@ -56,7 +86,7 @@ pub fn optimize(plan: PlanRef, session: &VortexSession) -> VortexResult return Ok(None); }; let child = lazy.get()?; - let optimized = optimize(child.clone(), session)?; + let optimized = optimize_with_mode(child.clone(), session, mode)?; if PlanRef::ptr_eq(child, &optimized) { return Ok(Some(lazy.clone())); } @@ -69,8 +99,8 @@ pub fn optimize(plan: PlanRef, session: &VortexSession) -> VortexResult } let plan = plan.with_slots(slots)?; - if let Some(rewritten) = reduce(&plan, session)? { - return optimize(rewritten, session); + if let Some(rewritten) = reduce(&plan, session, mode)? { + return optimize_with_mode(rewritten, session, mode); } Ok(plan) } diff --git a/vortex-scan/src/plan/optimize/registry.rs b/vortex-scan/src/plan/optimize/registry.rs index e5d9a736c9f..e6b256e49d6 100644 --- a/vortex-scan/src/plan/optimize/registry.rs +++ b/vortex-scan/src/plan/optimize/registry.rs @@ -6,6 +6,7 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; +use super::OptimizeMode; use super::rules::*; use crate::plan::Concat; use crate::plan::Eval; @@ -34,21 +35,33 @@ static PLAN_RULES: PlanRuleSet = PlanRuleSet::new(&[ &ZONED_DATA_RULE, ]); +static EVAL_EVAL_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(EvalEvalRule); static EXPRESSION_CONCAT_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionConcatRule); static EXPRESSION_TAKE_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionTakeRule); -static EXPRESSION_PACK_RULE: PlanParentReduceRuleAdapter = - PlanParentReduceRuleAdapter::new(ExpressionPackRule); +static EXACT_PACK_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(ExpressionPackRule::Exact); +static PRUNING_PACK_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(ExpressionPackRule::Pruning); static EXPRESSION_ZONED_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionZonedRule); -static PARENT_RULES: PlanParentRuleSet = PlanParentRuleSet::new(&[ - &PlanParentReduceRuleAdapter::new(EvalEvalRule), - &EXPRESSION_CONCAT_RULE, - &EXPRESSION_TAKE_RULE, - &EXPRESSION_PACK_RULE, - &EXPRESSION_ZONED_RULE, -]); + +const fn parent_rules( + pack_rule: &'static dyn DynPlanParentReduceRule, +) -> [&'static dyn DynPlanParentReduceRule; 5] { + [ + &EVAL_EVAL_RULE, + &EXPRESSION_CONCAT_RULE, + &EXPRESSION_TAKE_RULE, + pack_rule, + &EXPRESSION_ZONED_RULE, + ] +} + +static EXACT_PARENT_RULES: [&dyn DynPlanParentReduceRule; 5] = parent_rules(&EXACT_PACK_RULE); +static PRUNING_PARENT_RULES: [&dyn DynPlanParentReduceRule; 5] = parent_rules(&PRUNING_PACK_RULE); /// Attempts a static rewrite for `plan`. pub(crate) fn reduce_plan( @@ -62,13 +75,18 @@ pub(crate) fn reduce_plan( } /// Attempts a static rewrite for `parent` and `child`, its child in `slot`. -pub(crate) fn reduce_parent( +pub(super) fn reduce_parent( child: &PlanRef, parent: &PlanRef, slot: usize, session: &VortexSession, + mode: OptimizeMode, ) -> VortexResult> { - match PARENT_RULES.evaluate(child, parent, slot, session)? { + let rules = match mode { + OptimizeMode::Exact => &EXACT_PARENT_RULES, + OptimizeMode::Pruning => &PRUNING_PARENT_RULES, + }; + match PlanParentRuleSet::new(rules).evaluate(child, parent, slot, session)? { Some(plan) => Ok(Some(plan)), None => child.reduce_parent(parent, slot, session), } From b2e20bd5f6a688a87f8faa381b995ed2182dc06d Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 11:14:57 -0500 Subject: [PATCH 10/13] Push DataFusion field reads through extension storage DataFusion can see a struct where Vortex sees an opaque extension value. Expose the storage explicitly when the Arrow field uses storage export, so the scan can project the requested field without bypassing exporters that transform values. Signed-off-by: Connor Tsui --- vortex-arrow/src/executor/mod.rs | 17 +- vortex-arrow/src/session.rs | 45 +++ vortex-datafusion/src/convert/exprs/mod.rs | 93 ++++--- vortex-datafusion/src/convert/exprs/tests.rs | 275 +++++++++++++++++++ 4 files changed, 381 insertions(+), 49 deletions(-) diff --git a/vortex-arrow/src/executor/mod.rs b/vortex-arrow/src/executor/mod.rs index a5e88a498a9..6a69861e260 100644 --- a/vortex-arrow/src/executor/mod.rs +++ b/vortex-arrow/src/executor/mod.rs @@ -69,9 +69,7 @@ use crate::executor::struct_::to_arrow_struct; use crate::executor::temporal::to_arrow_date; use crate::executor::temporal::to_arrow_time; use crate::executor::temporal::to_arrow_timestamp; -use crate::ext_metadata::decode_arrow_ext_metadata; use crate::session::ArrowSessionExt; -use crate::session::ensure_ext_metadata; /// Execution of a Vortex array into an Arrow array, for every type that implements [`IntoArray`]. /// @@ -326,20 +324,9 @@ fn execute_arrow_ext_storage( options: &ArrowExportOptions, ctx: &mut ExecutionCtx, ) -> VortexResult { - if let Some(importer_dtype) = ctx - .session() + ctx.session() .arrow() - .infer_field_dtype_with_importers(target)? - { - vortex_ensure_eq!( - importer_dtype.as_nullable(), - array.dtype().as_nullable(), - "Arrow field {:?} must describe the source extension type", - target.name() - ); - } else { - ensure_ext_metadata(target, &decode_arrow_ext_metadata(target)?, ext_dtype)?; - } + .ensure_ext_storage_metadata(target, ext_dtype)?; let target_dtype = ctx .session() diff --git a/vortex-arrow/src/session.rs b/vortex-arrow/src/session.rs index d0bc576d14d..3f27a9109fa 100644 --- a/vortex-arrow/src/session.rs +++ b/vortex-arrow/src/session.rs @@ -559,6 +559,51 @@ impl ArrowSession { Ok(field) } + /// Checks whether `field` routes the registered `ext_dtype` through storage export. + /// + /// A plugin registered for the target's extension name can transform values even when its + /// Arrow type matches the storage. Encoded targets use separate export routes. + #[expect(clippy::disallowed_methods, reason = "interning a dynamic id")] + pub fn is_extension_storage_field(&self, field: &Field, ext_dtype: &ExtDTypeRef) -> bool { + let Some(name) = field.extension_type_name() else { + return false; + }; + + let id = Id::new(name); + if self.known_vortex_id(&id) != Some(ext_dtype.id()) + || !self.exporters(&id).is_empty() + || matches!( + field.data_type(), + DataType::Dictionary(..) | DataType::RunEndEncoded(..) + ) + { + return false; + } + + self.from_arrow_datatype(field.data_type(), ext_dtype.nullability()) + .is_ok_and(|dtype| &dtype == ext_dtype.storage_dtype()) + && self.ensure_ext_storage_metadata(field, ext_dtype).is_ok() + } + + /// Checks that a Vortex-ID export target describes the source extension type. + pub(crate) fn ensure_ext_storage_metadata( + &self, + field: &Field, + ext_dtype: &ExtDTypeRef, + ) -> VortexResult<()> { + if let Some(importer_dtype) = self.infer_field_dtype_with_importers(field)? { + vortex_ensure_eq!( + importer_dtype.as_nullable(), + DType::Extension(ext_dtype.with_nullability(Nullability::Nullable)), + "Arrow field {:?} must describe the source extension type", + field.name() + ); + Ok(()) + } else { + ensure_ext_metadata(field, &decode_arrow_ext_metadata(field)?, ext_dtype) + } + } + /// Returns the Vortex ID that the extension name `id` resolves to, or `None` if the session does /// not know it. The registry can hold an alias, so the result can differ from `id`. pub(crate) fn known_vortex_id(&self, id: &Id) -> Option { diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 2b0bb323993..8340430587d 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -51,6 +51,7 @@ use vortex::expr::Expression; use vortex::expr::Lambda; use vortex::expr::byte_length; use vortex::expr::cast; +use vortex::expr::ext_storage; use vortex::expr::get_item; use vortex::expr::in_list_of; use vortex::expr::is_not_null; @@ -266,6 +267,7 @@ type Conversion = Result; /// Nested struct field access also uses Vortex semantics: a null parent produces a null child, /// whereas DataFusion extracts the child without applying parent validity. These differences /// are accepted for both filters and projections. +/// Field access through an extension can run natively when Arrow exposes its Vortex storage. /// Searched `CASE WHEN` expressions preserve short-circuit evaluation: conditions and /// branch values only execute on the rows that reach them, including fallible branches. /// Other expressions require compatible SQL semantics or remain in DataFusion. @@ -746,40 +748,7 @@ impl DefaultExpressionConverter { } if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - // DataFusion's GetFieldFunc flattens nested field access into a single call - // with multiple field name arguments, e.g. `outer.inner.leaf` becomes - // get_field(Column("outer"), "inner", "leaf"). - let [source, paths @ ..] = scalar_fn.args() else { - return Err( - exec_datafusion_err!("get_field requires a source and field path").into(), - ); - }; - if paths.is_empty() { - return Err(exec_datafusion_err!("get_field requires a field path").into()); - } - let mut source_type = source.data_type(schema)?; - let mut names = Vec::with_capacity(paths.len()); - for path in paths { - let name = path - .downcast_ref::() - .and_then(|literal| literal.value().try_as_str().flatten()) - .ok_or_else(|| { - exec_datafusion_err!("get_field path must be a non-null string literal") - })?; - let DataType::Struct(fields) = &source_type else { - return Err(Unconverted::Unsupported); - }; - let (_, field) = fields.find(name).ok_or_else(|| { - exec_datafusion_err!("get_field references missing field {name}") - })?; - source_type = field.data_type().clone(); - names.push(name); - } - let mut result = self.convert_expr(source, schema, input_dtype)?; - for name in names { - result = get_item(name, result); - } - return Ok(result); + return self.convert_get_field(scalar_fn, schema, input_dtype); } if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { @@ -823,6 +792,62 @@ impl DefaultExpressionConverter { Ok(cast(length(input), return_dtype)) } + fn convert_get_field( + &self, + scalar_fn: &ScalarFunctionExpr, + schema: &Schema, + input_dtype: &DType, + ) -> Conversion { + let [source, paths @ ..] = scalar_fn.args() else { + return Err(exec_datafusion_err!("get_field requires a source and field path").into()); + }; + if paths.is_empty() { + return Err(exec_datafusion_err!("get_field requires a field path").into()); + } + + // DataFusion can flatten nested accesses into one call, so each step needs its own + // Arrow field metadata to identify the representation that DataFusion sees. + let source_field = source.return_field(schema)?; + let mut parent_field = source_field.as_ref(); + let mut steps = Vec::with_capacity(paths.len()); + for path in paths { + let name = path + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str().flatten()) + .ok_or_else(|| { + exec_datafusion_err!("get_field path must be a non-null string literal") + })?; + let DataType::Struct(fields) = parent_field.data_type() else { + return Err(Unconverted::Unsupported); + }; + let (_, child_field) = fields + .find(name) + .ok_or_else(|| exec_datafusion_err!("get_field references missing field {name}"))?; + steps.push((parent_field, name)); + parent_field = child_field.as_ref(); + } + + let mut result = self.convert_expr(source, schema, input_dtype)?; + for (parent_field, name) in steps { + if parent_field.extension_type_name().is_some() { + let DType::Extension(ext_dtype) = converted_dtype(&result, input_dtype)? else { + return Err(Unconverted::Unsupported); + }; + if !self + .session + .arrow() + .is_extension_storage_field(parent_field, &ext_dtype) + { + return Err(Unconverted::Unsupported); + } + result = ext_storage(result); + } + result = get_item(name, result); + } + + Ok(result) + } + /// Converts `array_sum` to `list_sum`. /// /// DataFusion casts the list to `List`, then adds each list's valid elements in diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index b0ae212c934..b634b1abd7e 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -19,6 +19,7 @@ use arrow_array::StructArray; use arrow_array::UInt8Array; use arrow_array::UInt32Array; use arrow_array::UInt64Array; +use arrow_array::cast::AsArray; use arrow_array::types::Float64Type; use arrow_array::types::Int32Type; use arrow_array::types::Int64Type; @@ -54,18 +55,27 @@ use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_plan::expressions as df_expr; use insta::assert_snapshot; use rstest::rstest; +use vortex::array::ArrayRef; use vortex::array::Canonical; +use vortex::array::EmptyMetadata; +use vortex::array::ExecutionCtx; use vortex::array::IntoArray; use vortex::array::arrays::ConstantArray; use vortex::array::arrays::PrimitiveArray; use vortex::array::builtins::ArrayBuiltins; use vortex::dtype::PType; +use vortex::dtype::extension::ExtDType; +use vortex::dtype::extension::ExtDTypeRef; +use vortex::dtype::extension::ExtId; +use vortex::dtype::extension::ExtVTable; +use vortex::dtype::session::DTypeSessionExt; use vortex::encodings::uuid::Uuid; use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::expr::between; use vortex::expr::proto::ExprSerializeProtoExt; use vortex::scalar::Scalar; +use vortex::scalar::ScalarValue as VortexScalarValue; use vortex::scalar_fn::fns::between::BetweenOptions; use vortex::scalar_fn::fns::between::StrictComparison; use vortex::scalar_fn::fns::cast::Cast; @@ -74,9 +84,13 @@ use vortex::scalar_fn::fns::literal::Literal; use vortex::session::registry::CachedId; use vortex::session::registry::Id; use vortex_array::assert_arrays_eq; +use vortex_arrow::ArrowExport; +use vortex_arrow::ArrowExportOptions; +use vortex_arrow::ArrowExportVTable; use vortex_arrow::ArrowImport; use vortex_arrow::ArrowImportVTable; use vortex_arrow::ArrowSession; +use vortex_arrow::ExecuteArrowExt; use super::*; use crate::common_tests::TestSessionContext; @@ -2596,6 +2610,267 @@ fn test_native_nested_get_field( Ok(()) } +static POINT_ID: CachedId = CachedId::new("test.point"); + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct Point; + +impl ExtVTable for Point { + type Metadata = EmptyMetadata; + type StoredMetadata = EmptyMetadata; + type NativeValue<'a> = &'a VortexScalarValue; + + fn id(&self) -> ExtId { + *POINT_ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(Vec::new()) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(EmptyMetadata) + } + + fn metadata_from_storage( + &self, + metadata: Self::StoredMetadata, + _storage_dtype: &DType, + ) -> VortexResult { + Ok(metadata) + } + + fn storage_dtype(_metadata: &Self::Metadata) -> DType { + let coordinate = DType::Primitive(PType::I32, Nullability::NonNullable); + DType::struct_( + [("x", coordinate.clone()), ("y", coordinate)], + Nullability::NonNullable, + ) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + value: &'a VortexScalarValue, + ) -> VortexResult> { + Ok(value) + } +} + +fn point_dtype(nullable: bool) -> VortexResult { + Ok(ExtDType::::try_new(EmptyMetadata, nullable.into())?.erased()) +} + +fn point_batch(session: &VortexSession) -> anyhow::Result { + let point = session + .arrow() + .to_arrow_field("point", &DType::Extension(point_dtype(true)?))?; + let DataType::Struct(fields) = point.data_type() else { + anyhow::bail!("Expected point storage as a struct, got {point}"); + }; + let points: ArrowArrayRef = Arc::new(StructArray::try_new( + fields.clone(), + vec![ + Arc::new(Int32Array::from(vec![10, 20, 30, 40])), + Arc::new(Int32Array::from(vec![11, 21, 31, 41])), + ], + Some(NullBuffer::from(vec![true, false, true, true])), + )?); + let outer = StructArray::try_new( + vec![point.clone()].into(), + vec![Arc::clone(&points)], + Some(NullBuffer::from(vec![true, true, false, true])), + )?; + let schema = Schema::new(vec![ + point, + Field::new("outer", outer.data_type().clone(), true), + ]); + Ok(RecordBatch::try_new( + Arc::new(schema), + vec![points, Arc::new(outer)], + )?) +} + +#[rstest] +#[case::column( "point", &["x"], false, [Some(10), None, Some(30), Some(40)])] +#[case::flattened("outer", &["point", "x"], false, [Some(10), None, None, Some(40)])] +#[case::chained( "outer", &["point", "x"], true, [Some(10), None, None, Some(40)])] +fn test_get_field_reads_extension_storage( + #[case] column: &str, + #[case] path: &[&str], + #[case] chained: bool, + #[case] expected: [Option; 4], +) -> anyhow::Result<()> { + let session = VortexSession::default(); + session.dtypes().register(Point); + let batch = point_batch(&session)?; + let schema = batch.schema(); + let source = Arc::new(df_expr::Column::new(column, schema.index_of(column)?)); + let expr = if chained { + let (first, rest) = path.split_at(1); + get_field_expr(get_field_expr(source, first, &schema)?, rest, &schema)? + } else { + get_field_expr(source, path, &schema)? + }; + + let converted = DefaultExpressionConverter::new(session.clone()) + .try_convert(&expr, &schema)? + .ok_or_else(|| anyhow::anyhow!("Expected native conversion for {expr}"))?; + let point = if column == "point" { + get_item("point", root()) + } else { + get_item("point", get_item("outer", root())) + }; + assert_eq!(converted, get_item("x", ext_storage(point))); + + let input = session.arrow().from_arrow_record_batch(batch, &schema)?; + assert_arrays_eq!( + input.apply(&converted)?, + PrimitiveArray::from_option_iter(expected), + &mut session.create_execution_ctx() + ); + Ok(()) +} + +#[rstest] +#[case::column("point", &["x"])] +#[case::nested("outer", &["point", "x"])] +fn test_get_field_on_unknown_extension_stays_in_datafusion( + #[case] column: &str, + #[case] path: &[&str], +) -> anyhow::Result<()> { + let batch = point_batch(&VortexSession::default())?; + let schema = batch.schema(); + let source = Arc::new(df_expr::Column::new(column, schema.index_of(column)?)); + let expr = get_field_expr(source, path, &schema)?; + + assert!(!converts(&expr, &schema)?); + Ok(()) +} + +/// Swaps the values of `x` and `y` while keeping the same Arrow field and storage type. +#[derive(Debug)] +struct SwappedPoint; + +impl SwappedPoint { + fn swap_coordinates(points: &StructArray) -> VortexResult { + Ok(Arc::new(StructArray::try_new( + points.fields().clone(), + vec![Arc::clone(points.column(1)), Arc::clone(points.column(0))], + points.nulls().cloned(), + )?)) + } +} + +impl ArrowExportVTable for SwappedPoint { + fn arrow_ext_id(&self) -> Id { + *POINT_ID + } + + fn vortex_id(&self) -> Id { + *POINT_ID + } + + fn to_arrow_field( + &self, + _name: &str, + _dtype: &DType, + _session: &ArrowSession, + ) -> VortexResult> { + // Inference falls back to the Vortex-ID field, which still reaches this exporter. + Ok(None) + } + + fn execute_arrow( + &self, + array: ArrayRef, + target: &Field, + options: &ArrowExportOptions, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !array + .dtype() + .as_extension_opt() + .is_some_and(|ext_dtype| ext_dtype.is::()) + { + return Ok(ArrowExport::Unsupported(array)); + } + + let target = Field::new( + target.name(), + target.data_type().clone(), + target.is_nullable(), + ); + let storage = array + .apply(&ext_storage(root()))? + .execute_arrow_with_options(Some(&target), options, ctx)?; + Ok(ArrowExport::Exported(Self::swap_coordinates( + storage.as_struct(), + )?)) + } +} + +impl ArrowImportVTable for SwappedPoint { + fn arrow_ext_id(&self) -> Id { + *POINT_ID + } + + fn from_arrow_field( + &self, + field: &Field, + _session: &ArrowSession, + ) -> VortexResult> { + Ok(Some(DType::Extension(point_dtype(field.is_nullable())?))) + } + + fn from_arrow_array( + &self, + array: ArrowArrayRef, + _field: &Field, + dtype: &DType, + session: &ArrowSession, + ) -> VortexResult { + let DType::Extension(ext_dtype) = dtype else { + return Ok(ArrowImport::Unsupported(array)); + }; + + let storage = Self::swap_coordinates(array.as_struct())?; + Ok(ArrowImport::Imported( + session.from_arrow_storage(storage, ext_dtype)?, + )) + } +} + +#[test] +fn test_get_field_on_custom_extension_export_stays_in_datafusion() -> anyhow::Result<()> { + let session = VortexSession::default(); + session.dtypes().register(Point); + let batch = point_batch(&session)?; + let schema = batch.schema(); + let point_field = schema.field(0); + let points = session + .arrow() + .from_arrow_array(Arc::clone(batch.column(0)), point_field)?; + + session.arrow().register_exporter(Arc::new(SwappedPoint)); + session.arrow().register_importer(Arc::new(SwappedPoint)); + let exported_field = session.arrow().to_arrow_field("point", points.dtype())?; + assert_eq!(&exported_field, point_field); + let exported = + points.execute_arrow(Some(&exported_field), &mut session.create_execution_ctx())?; + assert_eq!(exported.data_type(), point_field.data_type()); + + let schema = Arc::new(Schema::new(vec![exported_field])); + let batch = RecordBatch::try_new(Arc::clone(&schema), vec![exported])?; + let source = Arc::new(df_expr::Column::new("point", 0)); + let expr = get_field_expr(source, &["x"], &schema)?; + let converter = DefaultExpressionConverter::new(session); + assert!(converter.try_convert(&expr, &schema)?.is_none()); + + let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?; + assert_eq!(result.as_primitive::().value(0), 11); + Ok(()) +} + #[rstest] fn test_nested_functions_reject_unknown_children( #[values(false, true)] list: bool, From e86c498da82a420957362b69823e0f9d6e161049 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Thu, 19 Nov 2026 11:17:27 -0500 Subject: [PATCH 11/13] Push struct field reads through DataFusion projection fallback A single unsupported projection makes the scan read whole struct inputs. Supply provably equivalent field reads from the scan so DataFusion can finish the enclosing expressions without reading unused siblings. Custom converters retain control of the projection split. Signed-off-by: Connor Tsui --- vortex-datafusion/src/convert/exprs/mod.rs | 14 + .../src/convert/exprs/projection_fields.rs | 286 ++++++++++++++++++ vortex-datafusion/src/persistent/opener.rs | 11 +- vortex-datafusion/src/v2/source.rs | 18 +- vortex-datafusion/src/v2/tests.rs | 219 ++++++++++++++ 5 files changed, 544 insertions(+), 4 deletions(-) create mode 100644 vortex-datafusion/src/convert/exprs/projection_fields.rs diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 8340430587d..dd8ffe0768e 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -7,6 +7,7 @@ //! extension metadata, or inherit missing metadata from the operand they are compared with. This //! supplies the logical dtype that Vortex requires without adding implicit casts. +mod projection_fields; use std::sync::Arc; use arrow_schema::DataType; @@ -40,6 +41,7 @@ use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_plan::expressions as df_expr; use itertools::Itertools; +pub(crate) use projection_fields::push_down_projection_fields; use vortex::VortexSessionDefault; use vortex::aggregate_fn::NumericalAggregateOpts; use vortex::array::VortexSessionExecute; @@ -174,6 +176,14 @@ pub trait ExpressionConverter: Send + Sync { }) } + /// Allow scans to refine the raw fallback returned by [`Self::split_projection`]. + /// + /// Defaults to `false`. Opt in if scans may replace whole struct inputs with the plain fields + /// the remaining DataFusion projection needs. + fn allows_projection_field_pushdown(&self) -> bool { + false + } + /// Create a projection that reads only the required columns without pushing down /// any expressions. All projection logic is applied after the scan. fn no_pushdown_projection( @@ -951,6 +961,10 @@ impl ExpressionConverter for DefaultExpressionConverter { Err(Unconverted::Failed(error)) => Err(error), } } + + fn allows_projection_field_pushdown(&self) -> bool { + true + } } /// Whether evaluating `expr` cannot fail, so Vortex may evaluate it on rows DataFusion skips. diff --git a/vortex-datafusion/src/convert/exprs/projection_fields.rs b/vortex-datafusion/src/convert/exprs/projection_fields.rs new file mode 100644 index 00000000000..ba76e9468fd --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/projection_fields.rs @@ -0,0 +1,286 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Prunes struct fields from the raw inputs of a DataFusion projection. +//! +//! DataFusion still evaluates the projection. The scan substitutes columns only for field reads +//! whose Arrow field and values are the same as in the raw projection. + +use std::iter; +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use datafusion_common::tree_node::Transformed; +use datafusion_common::tree_node::TreeNode; +use datafusion_common::tree_node::TreeNodeRecursion; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_expr::expressions as df_expr; +use datafusion_physical_expr::utils::reassign_expr_columns; +use itertools::Itertools; +use vortex::dtype::DType; +use vortex::dtype::Nullability; +use vortex::dtype::StructFields; +use vortex::error::VortexResult; +use vortex::expr::Expression; +use vortex::expr::get_item; +use vortex::expr::pack; +use vortex::expr::root; +use vortex::layout::layouts::row_idx; +use vortex::scalar_fn::fns::get_item::GetItem; +use vortex::scalar_fn::fns::pack::Pack; +use vortex_arrow::ArrowSession; +use vortex_utils::aliases::hash_map::HashMap; + +use super::ExpressionConverter; +use super::ProcessedProjection; + +/// Refine a raw fallback if it can omit at least one whole struct column. Resolve the actual scan +/// dtype lazily because the Arrow reference schema can describe stricter nullability than the data. +pub(crate) fn push_down_projection_fields( + projection: ProcessedProjection, + converter: &dyn ExpressionConverter, + scan_dtype: impl FnOnce(&Expression) -> VortexResult, + arrow: &ArrowSession, +) -> ProcessedProjection { + if !converter.allows_projection_field_pushdown() { + return projection; + } + + try_push_down_fields(&projection, converter, scan_dtype, arrow).unwrap_or(projection) +} + +fn try_push_down_fields( + projection: &ProcessedProjection, + converter: &dyn ExpressionConverter, + scan_dtype: impl FnOnce(&Expression) -> VortexResult, + arrow: &ArrowSession, +) -> Option { + let raw_schema = &projection.scan_reference_schema; + let raw_fields = raw_schema.fields(); + let raw_columns = projection.scan_projection.children(); + let options = projection.scan_projection.as_opt::()?; + if options.nullability.is_nullable() + || options.names.len() != raw_fields.len() + || raw_columns.len() != raw_fields.len() + || !raw_fields + .iter() + .any(|field| matches!(field.data_type(), DataType::Struct(_))) + || !raw_fields.iter().map(|field| field.name()).all_unique() + || !options + .names + .iter() + .zip(raw_fields) + .zip(raw_columns) + .all(|((name, field), expr)| { + name.as_ref() == field.name() + && (expr.as_opt::() == Some(name) && expr.child(0) == &root() + || *expr == row_idx::row_idx()) + }) + { + return None; + } + + let leftover = &projection.leftover_projection; + if !leftover.iter().map(|output| &output.alias).all_unique() { + return None; + } + + let mut has_field_read = false; + for output in leftover.iter() { + if output + .expr + .exists(|expr| { + has_field_read |= get_field_function(expr).is_some(); + Ok(!can_rewrite(expr)) + }) + .ok()? + { + return None; + } + } + if !has_field_read { + return None; + } + + let DType::Struct(scan_fields, _) = scan_dtype(&projection.scan_projection).ok()? else { + return None; + }; + + let mut fields = raw_fields.to_vec(); + let mut columns = raw_columns.to_vec(); + let mut indices: HashMap = fields + .iter() + .enumerate() + .map(|(index, field)| (field.name().clone(), index)) + .collect(); + let leftover = leftover + .clone() + .try_map_exprs(|expr| { + // The fallback keeps the original column indices until the caller remaps by name. + // Assign indices before adding columns so rebuilding a CASE sees distinct inputs. + reassign_expr_columns(expr, raw_schema)? + .transform_down(|expr| { + if get_field_function(&expr).is_none() { + return Ok(Transformed::no(expr)); + } + + let keep = + || Transformed::new(Arc::clone(&expr), false, TreeNodeRecursion::Jump); + let Some((field, read)) = + convert_field_read(&expr, raw_schema, &scan_fields, converter, arrow) + else { + return Ok(keep()); + }; + + // UDFs receive the argument's full Arrow field. Its name must survive the + // rewrite, so a collision with a different read keeps the original expression. + let index = if let Some(&index) = indices.get(field.name()) { + if index < raw_fields.len() || columns[index] != read { + return Ok(keep()); + } + index + } else { + let index = columns.len(); + indices.insert(field.name().clone(), index); + fields.push(Arc::clone(&field)); + columns.push(read); + index + }; + + Ok(Transformed::yes( + Arc::new(df_expr::Column::new(field.name(), index)) as _, + )) + }) + .map(|transformed| transformed.data) + }) + .ok()?; + + let used = leftover.column_indices(); + let retained_raw = used.partition_point(|&index| index < raw_fields.len()); + if retained_raw == raw_fields.len() || retained_raw == used.len() { + return None; + } + + let schema = Schema::new_with_metadata(fields, raw_schema.metadata().clone()); + let scan_reference_schema = schema.project(&used).ok()?; + let scan_projection = pack( + used.iter() + .map(|&index| (schema.field(index).name().clone(), columns[index].clone())), + Nullability::NonNullable, + ); + Some(ProcessedProjection { + scan_projection, + scan_reference_schema, + leftover_projection: leftover, + }) +} + +/// Allow only expressions whose children describe their input bindings. A lambda or a physical +/// expression with its own bindings needs the original fallback layout. +fn can_rewrite(expr: &PhysicalExprRef) -> bool { + if let Some(function) = expr.downcast_ref::() { + // DataFusion passes return fields to UDFs, and the default return field uses the + // expression's display name. These argument types preserve their fields when remapped. + return function.args().iter().all(|arg| { + arg.is::() + || arg.is::() + || arg.is::() + }); + } + + expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() + || expr.is::() +} + +fn get_field_function(expr: &PhysicalExprRef) -> Option<&ScalarFunctionExpr> { + ScalarFunctionExpr::try_downcast_func::(expr.as_ref()) +} + +fn convert_field_read( + expr: &PhysicalExprRef, + schema: &Schema, + scan_fields: &StructFields, + converter: &dyn ExpressionConverter, + arrow: &ArrowSession, +) -> Option<(FieldRef, Expression)> { + let (field, dtype, read) = struct_field_path(expr, schema, scan_fields)?; + // Importing an Arrow field can erase dictionary and run-end encoding. Check the Arrow + // type directly, since a UDF can observe that encoding even when the values are equivalent. + let arrow_type = field.data_type(); + let plain_type = arrow_type.is_integer() + || arrow_type.is_floating() + || arrow_type.is_string() + || matches!( + arrow_type, + DataType::Boolean | DataType::Binary | DataType::LargeBinary | DataType::BinaryView + ); + if !plain_type + || field.extension_type_name().is_some() + || arrow.from_arrow_field(&field).ok()? != dtype + { + return None; + } + + // A custom converter may reject the read or give it different semantics. + let converted = converter.try_convert(expr, schema).ok().flatten()?; + (converted == read).then_some((field, read)) +} + +/// Resolve both flattened and nested get_field calls. Vortex applies parent validity to a child, +/// so every traversed parent must be a non-nullable struct in both schemas. +fn struct_field_path( + expr: &PhysicalExprRef, + schema: &Schema, + scan_fields: &StructFields, +) -> Option<(FieldRef, DType, Expression)> { + if let Some(column) = expr.downcast_ref::() { + let field = schema.fields().get(column.index())?; + let dtype = scan_fields.field(field.name())?; + let read = get_item(field.name().as_str(), root()); + return Some((Arc::clone(field), dtype, read)); + } + + let function = get_field_function(expr)?; + let [source, first, rest @ ..] = function.args() else { + return None; + }; + let (mut field, mut dtype, mut read) = struct_field_path(source, schema, scan_fields)?; + + for path in iter::once(first).chain(rest) { + if field.is_nullable() || field.extension_type_name().is_some() { + return None; + } + let (DataType::Struct(fields), DType::Struct(children, Nullability::NonNullable)) = + (field.data_type(), &dtype) + else { + return None; + }; + let name = path + .downcast_ref::()? + .value() + .try_as_str() + .flatten() + .filter(|name| !name.is_empty())?; + let mut matching = fields.iter().filter(|field| field.name() == name); + let child = matching.next()?; + if matching.next().is_some() { + return None; + } + + field = Arc::clone(child); + dtype = children.field(name)?; + read = get_item(name, read); + } + + (expr.return_field(schema).ok()? == field).then_some((field, dtype, read)) +} diff --git a/vortex-datafusion/src/persistent/opener.rs b/vortex-datafusion/src/persistent/opener.rs index 3ba227d6ca5..4b9ebcfd052 100644 --- a/vortex-datafusion/src/persistent/opener.rs +++ b/vortex-datafusion/src/persistent/opener.rs @@ -72,6 +72,7 @@ use vortex_utils::parallelism::get_available_parallelism; use crate::VortexAccessPlan; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; +use crate::convert::exprs::push_down_projection_fields; use crate::convert::exprs::raw_projection; use crate::convert::schema::calculate_physical_schema; use crate::convert::to_record_batch; @@ -434,11 +435,17 @@ impl FileOpener for VortexOpener { indices.dedup(); raw_projection(&indices, &this_file_schema, projection)? } else if projection_pushdown { - expr_converter.split_projection( + let projection = expr_converter.split_projection( projection, &this_file_schema, output_schema.as_ref(), - )? + )?; + push_down_projection_fields( + projection, + expr_converter.as_ref(), + |expr| expr.return_dtype(vxf.dtype()), + &session.arrow(), + ) } else { expr_converter.no_pushdown_projection(projection, &this_file_schema)? }; diff --git a/vortex-datafusion/src/v2/source.rs b/vortex-datafusion/src/v2/source.rs index cefefb0f696..712434c9482 100644 --- a/vortex-datafusion/src/v2/source.rs +++ b/vortex-datafusion/src/v2/source.rs @@ -142,6 +142,7 @@ use super::dynamic_filters::convert_dynamic_filter; use crate::convert::exprs::DefaultExpressionConverter; use crate::convert::exprs::ExpressionConverter; use crate::convert::exprs::ProcessedProjection; +use crate::convert::exprs::push_down_projection_fields; use crate::convert::schema::calculate_physical_schema; use crate::convert::stats::stats_set_to_df; use crate::convert::to_record_batch; @@ -873,15 +874,28 @@ impl DataSource for VortexDataSource { let converter = &self.expression_converter; let input_schema = self.initial_schema.as_ref(); let projected_schema = projection.project_schema(input_schema)?; + let arrow = self.session.arrow(); // Use the shared ExpressionConverter to split the projection into a Vortex // scan_projection and a leftover DataFusion projection for expressions that // can't be pushed down (e.g., unsupported scalar functions, decimal binary). + let processed = + converter.split_projection(projection.clone(), input_schema, &projected_schema)?; let ProcessedProjection { scan_projection, scan_reference_schema, leftover_projection, - } = converter.split_projection(projection.clone(), input_schema, &projected_schema)?; + } = push_down_projection_fields( + processed, + converter.as_ref(), + |expr| { + let initial_dtype = self + .initial_projection + .return_dtype(self.data_source.dtype())?; + expr.return_dtype(&initial_dtype) + }, + &arrow, + ); // Compose with the initial projection so the scan operates on the original // source columns, not the initial projection's output columns. @@ -894,7 +908,7 @@ impl DataSource for VortexDataSource { let scan_output_schema = Arc::new(calculate_physical_schema( &scan_dtype, &scan_reference_schema, - &self.session.arrow(), + &arrow, )?); // Remap the leftover column references to match the scan output schema. diff --git a/vortex-datafusion/src/v2/tests.rs b/vortex-datafusion/src/v2/tests.rs index 8ad23de2b4a..a82102679c2 100644 --- a/vortex-datafusion/src/v2/tests.rs +++ b/vortex-datafusion/src/v2/tests.rs @@ -4,9 +4,12 @@ use std::sync::Arc; use anyhow::anyhow; +use arrow_array::Array; use arrow_array::ArrayRef; use arrow_array::Int32Array; use arrow_array::RecordBatch; +use arrow_array::StringArray; +use arrow_array::StructArray; use arrow_array::cast::AsArray; use arrow_array::types::Int32Type; use arrow_schema::DataType; @@ -16,7 +19,9 @@ use arrow_schema::extension::Json as ArrowJson; use arrow_schema::extension::Uuid as ArrowUuid; use datafusion::assert_batches_eq; use datafusion::prelude::SessionContext; +use datafusion_common::Result as DFResult; use datafusion_common::ScalarValue; +use datafusion_common::arrow::buffer::NullBuffer; use datafusion_common::arrow::compute::concat_batches; use datafusion_common::config::ConfigOptions; use datafusion_common::stats::Precision; @@ -25,11 +30,17 @@ use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_datasource::source::DataSource; use datafusion_datasource::source::DataSourceExec; use datafusion_expr::Operator; +use datafusion_expr::ScalarUDF; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions::string::upper::UpperFunc; use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_plan::ExecutionPlan; +use datafusion_physical_plan::displayable; use datafusion_physical_plan::expressions as df_expr; use datafusion_physical_plan::filter::FilterExec; use datafusion_physical_plan::filter_pushdown::PushedDown; @@ -37,6 +48,7 @@ use futures::TryStreamExt; use rstest::rstest; use vortex::VortexSessionDefault; use vortex::buffer::ByteBufferMut; +use vortex::expr::Expression; use vortex::file::OpenOptionsSessionExt; use vortex::file::WriteOptionsSessionExt; use vortex::scan::DataSourceRef; @@ -44,6 +56,10 @@ use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; use super::VortexDataSource; +use crate::convert::DefaultExpressionConverter; +use crate::convert::ExpressionConverter; +use crate::convert::ProcessedProjection; +use crate::row_index; async fn vortex_source() -> anyhow::Result { let batch = @@ -84,6 +100,209 @@ async fn data_source_from_batch( Ok(file.data_source()?) } +#[rstest] +#[case::non_nullable(false, false, false)] +#[case::nullable_outer(true, true, false)] +#[case::nullable_outer_in_storage(true, false, false)] +#[case::nullable_inner(false, false, true)] +#[tokio::test] +async fn test_partial_projection_reads_struct_leaf( + #[case] stored_outer_nullable: bool, + #[case] declared_outer_nullable: bool, + #[case] inner_nullable: bool, +) -> anyhow::Result<()> { + let label_field = Field::new("label", DataType::Utf8, true) + .with_metadata([("source".to_owned(), "test".to_owned())].into()); + let inner = StructArray::try_new( + vec![ + label_field.clone(), + Field::new("unused", DataType::Int32, false), + ] + .into(), + vec![ + Arc::new(StringArray::from(vec![Some("x"), Some("20"), None])), + Arc::new(Int32Array::from(vec![10, 20, 30])), + ], + inner_nullable.then(|| NullBuffer::from(vec![false, true, true])), + )?; + let outer = StructArray::try_new( + vec![Field::new( + "inner", + inner.data_type().clone(), + inner_nullable, + )] + .into(), + vec![Arc::new(inner)], + stored_outer_nullable.then(|| NullBuffer::from(vec![false, true, true])), + )?; + let batch = RecordBatch::try_from_iter([ + ("id", Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef), + ("s", Arc::new(outer) as ArrayRef), + ])?; + let schema = Arc::new(Schema::new(vec![ + batch.schema().field(0).clone(), + batch + .schema() + .field(1) + .clone() + .with_nullable(declared_outer_nullable), + ])); + let session = VortexSession::default(); + let data_source = data_source_from_batch(batch, &session).await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(Arc::clone(&schema)) + .build() + .await?; + + let function = |udf: ScalarUDF, args| -> anyhow::Result { + Ok(Arc::new(ScalarFunctionExpr::try_new( + Arc::new(udf), + args, + &schema, + Arc::new(ConfigOptions::new()), + )?)) + }; + let id: PhysicalExprRef = Arc::new(df_expr::Column::new("id", 0)); + let label = function( + GetFieldFunc::new().into(), + vec![ + Arc::new(df_expr::Column::new("s", 1)), + df_expr::lit("inner"), + df_expr::lit("label"), + ], + )?; + let upper = function(UpperFunc::new().into(), vec![Arc::clone(&label)])?; + // The cast would fail on "x" if the scan evaluated it before the CASE selected rows. + let parse_label = Arc::new(df_expr::CastExpr::new( + Arc::clone(&label), + DataType::Int32, + None, + )); + let format_label: PhysicalExprRef = + Arc::new(df_expr::CastExpr::new(parse_label, DataType::Utf8, None)); + let is_second_row: PhysicalExprRef = Arc::new(df_expr::BinaryExpr::new( + Arc::clone(&id), + Operator::Eq, + df_expr::lit(2i32), + )); + let formatted = Arc::new(df_expr::CaseExpr::try_new( + None, + vec![(is_second_row, format_label)], + Some(upper), + )?); + let inner = function( + GetFieldFunc::new().into(), + vec![ + Arc::new(df_expr::Column::new("s", 1)), + df_expr::lit("inner"), + ], + )?; + let original = function( + GetFieldFunc::new().into(), + vec![inner, df_expr::lit("label")], + )?; + let projection = ProjectionExprs::from(vec![ + ProjectionExpr::new(id, "id"), + ProjectionExpr::new(formatted, "formatted"), + ProjectionExpr::new(original, "original"), + ProjectionExpr::new(row_index(), "position"), + ]); + let projected = source + .try_swapping_with_projection(&projection)? + .ok_or_else(|| anyhow!("projection was not swapped"))?; + let plan = Arc::new(DataSourceExec::new(projected)) as Arc; + let display = displayable(plan.as_ref()).one_line().to_string(); + let expected_scan = if stored_outer_nullable || inner_nullable { + "projection=pack(id: $.id, s: $.s, __vortex_row_index: #row_idx)" + } else { + "projection=pack(id: $.id, __vortex_row_index: #row_idx, label: $.s.inner.label)" + }; + assert!(display.contains(expected_scan), "{display}"); + + let batches = datafusion_physical_plan::collect(plan, SessionContext::new().task_ctx()).await?; + assert_batches_eq!( + [ + "+----+-----------+----------+----------+", + "| id | formatted | original | position |", + "+----+-----------+----------+----------+", + "| 1 | X | x | 0 |", + "| 2 | 20 | 20 | 1 |", + "| 3 | | | 2 |", + "+----+-----------+----------+----------+", + ], + &batches + ); + for batch in batches { + assert_eq!(batch.schema().field(2).metadata(), label_field.metadata()); + } + + Ok(()) +} + +#[derive(Default)] +struct RawProjectionConverter(DefaultExpressionConverter); + +impl ExpressionConverter for RawProjectionConverter { + fn try_convert(&self, expr: &PhysicalExprRef, schema: &Schema) -> DFResult> { + self.0.try_convert(expr, schema) + } + + fn split_projection( + &self, + projection: ProjectionExprs, + input_schema: &Schema, + _output_schema: &Schema, + ) -> DFResult { + self.no_pushdown_projection(projection, input_schema) + } +} + +#[tokio::test] +async fn test_custom_converter_keeps_raw_projection() -> anyhow::Result<()> { + let input = StructArray::try_new( + vec![ + Field::new("value", DataType::Int32, false), + Field::new("unused", DataType::Int32, false), + ] + .into(), + vec![ + Arc::new(Int32Array::from(vec![1, 2])), + Arc::new(Int32Array::from(vec![10, 20])), + ], + None, + )?; + let batch = RecordBatch::try_from_iter([("s", Arc::new(input) as ArrayRef)])?; + let schema = batch.schema(); + let field: PhysicalExprRef = Arc::new(ScalarFunctionExpr::try_new( + Arc::new(GetFieldFunc::new().into()), + vec![ + Arc::new(df_expr::Column::new("s", 0)), + df_expr::lit("value"), + ], + &schema, + Arc::new(ConfigOptions::new()), + )?); + let converter = RawProjectionConverter::default(); + assert!(converter.try_convert(&field, &schema)?.is_some()); + + let session = VortexSession::default(); + let data_source = data_source_from_batch(batch, &session).await?; + let source = VortexDataSource::builder(data_source, session) + .with_arrow_schema(schema) + .with_expression_converter(Arc::new(converter)) + .build() + .await?; + let projection = vec![ProjectionExpr::new(field, "value")].into(); + let projected = source + .try_swapping_with_projection(&projection)? + .ok_or_else(|| anyhow!("projection was not swapped"))?; + let plan = DataSourceExec::new(projected); + let display = displayable(&plan).one_line().to_string(); + assert!(display.contains("projection=pack(s: $.s)"), "{display}"); + + Ok(()) +} + #[tokio::test] async fn projection_filters_use_scan_schema() -> anyhow::Result<()> { let source = vortex_source().await?; From 24ccbe5fbd422a381548e7a902958f45fb2b5428 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Fri, 20 Nov 2026 16:35:46 -0500 Subject: [PATCH 12/13] Write zone maps of bounds beneath nullable structs A field beneath a nullable struct holds values in rows where the struct is null, so develop writes no zone map for it, and filters on fields inside nullable structs never prune. Bounds stay correct for the field as read through the struct, because the hidden values can only loosen them, and a NaN count of zero still proves that a zone holds no NaN. Such a field now records its bounds and its NaN count, and no counts that the hidden rows would make wrong. The scans from #11710 read these zone maps only in that conservative way. This is the writer half of the prototype's pruning beneath nullable structs (91dbd9bf9 and 7ac0dbbd0). #10961 rewrites the same writer to aggregate only the visible values. Signed-off-by: Connor Tsui --- vortex-file/src/tests/mod.rs | 1 + .../src/tests/nullable_struct_zones.rs | 179 ++++++++++++++++++ vortex-layout/src/layouts/struct_/writer.rs | 52 +++-- vortex-layout/src/layouts/zoned/writer.rs | 144 ++++++++++++-- vortex-layout/src/strategy.rs | 6 +- 5 files changed, 341 insertions(+), 41 deletions(-) create mode 100644 vortex-file/src/tests/nullable_struct_zones.rs diff --git a/vortex-file/src/tests/mod.rs b/vortex-file/src/tests/mod.rs index fdba49d93f6..56c721b96bd 100644 --- a/vortex-file/src/tests/mod.rs +++ b/vortex-file/src/tests/mod.rs @@ -9,6 +9,7 @@ #![expect(clippy::cast_possible_truncation)] mod extension_layout; +mod nullable_struct_zones; mod scan_metrics; use std::fs; diff --git a/vortex-file/src/tests/nullable_struct_zones.rs b/vortex-file/src/tests/nullable_struct_zones.rs new file mode 100644 index 00000000000..527732d1200 --- /dev/null +++ b/vortex-file/src/tests/nullable_struct_zones.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! File round trips for the zone maps of fields beneath a nullable struct. + +use std::sync::Arc; + +use futures::TryStreamExt; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::nan_count::NanCount; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::FieldNames; +use vortex_array::expr::Expression; +use vortex_array::expr::fill_null; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::lit; +use vortex_array::expr::lt; +use vortex_array::expr::root; +use vortex_array::stream::ArrayStreamExt; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::ByteBufferMut; +use vortex_edition::EDITION_DECLARATIONS; +use vortex_edition::EditionSession; +use vortex_edition::EditionSessionExt; +use vortex_edition::declarations::core::CORE_2026_08_3; +use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; +use vortex_layout::layouts::zoned::Zoned; +use vortex_layout::scan::metrics::ScanUsage; +use vortex_layout::scan::v2; +use vortex_layout::session::LayoutSession; +use vortex_mask::Mask; +use vortex_scan::execution::driver::ScanDriver; +use vortex_session::VortexSession; + +use crate::OpenOptionsSessionExt; +use crate::VortexFile; +use crate::WriteOptionsSessionExt; +use crate::strategy::WriteStrategyBuilder; + +/// Scans `file` on the classic or the planner-driven executor, returning the rows that match +/// `filter` projected by `projection`, and the number of segments the scan read. +async fn scan_counting_segments( + file: &VortexFile, + planner: bool, + projection: &Expression, + filter: &Expression, +) -> VortexResult<(ArrayRef, u64)> { + let usage = Arc::new(ScanUsage::default()); + let file = file.clone().with_usage(Arc::clone(&usage)); + let projection = projection.bind(file.dtype())?; + let filter = filter.bind(file.dtype())?; + let dtype = projection.dtype().clone(); + let array = if planner { + let scan = v2::ScanBuilder::new(file.session().clone(), file.scan_file()) + .with_projection(projection) + .with_some_filter(Some(filter)); + let chunks: Vec = ScanDriver::new(file.session().handle(), 1, true) + .run(scan) + .try_collect() + .await?; + ChunkedArray::try_new(chunks, dtype)?.into_array() + } else { + file.scan()? + .with_projection(projection) + .with_filter(filter) + .into_array_stream()? + .read_all() + .await? + }; + Ok((array, usage.snapshot().segments_requested)) +} + +/// A float field beneath a nullable struct, written with the default editions only, records its +/// bounds and its NaN count, which float bounds need to prune and every core edition permits. +/// Filters on it return every row they keep in memory on both scans. +/// +/// Where `s` is null, `f` holds a value above every visible one, so the bounds of every zone are +/// looser than the values read through `s`. Neither `s.f > 1e8` nor `s.f < 0` keeps a row, but +/// only the second is ruled out by the bounds, so it reads fewer segments. +#[rstest] +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn float_beneath_a_nullable_struct_prunes_with_default_editions( + #[values(false, true)] planner: bool, +) -> VortexResult<()> { + const ZONE_ROWS: u32 = 1024; + let session = VortexSession::empty() + .with::() + .with::() + .with_tokio(); + crate::register_default_encodings(&session); + for declaration in EDITION_DECLARATIONS { + session.register_edition(declaration)?; + } + session.enable_edition(CORE_2026_08_3)?; + + let rows = 0..4 * ZONE_ROWS; + let valid = |row: u32| !row.is_multiple_of(3); + let f: Buffer = rows + .clone() + .map(|row| { + if valid(row) { + f64::from(row) + 0.5 + } else { + 1e9 + } + }) + .collect(); + let s = StructArray::try_new( + FieldNames::from(["f"]), + vec![f.into_array()], + rows.len(), + Validity::from_iter(rows.clone().map(valid)), + )?; + let ids: Buffer = rows.map(i64::from).collect(); + let table = + StructArray::from_fields(&[("id", ids.into_array()), ("s", s.into_array())])?.into_array(); + + let strategy = WriteStrategyBuilder::from_session(&session) + .with_row_block_size(usize::try_from(ZONE_ROWS)?) + .with_data_block_target_bytes(None) + .build(); + let mut buffer = ByteBufferMut::empty(); + session + .write_options() + .with_strategy(strategy) + .write(&mut buffer, table.clone().to_array_stream()) + .await?; + let file = session.open_options().open_buffer(buffer)?; + + let mut recorded = Vec::new(); + for layout in file.footer().layout().depth_first_traversal() { + let layout = layout?; + if layout.is::() && layout.dtype().is_float() { + recorded.push(layout.as_::().present_aggregates()); + } + } + let expected: Arc<[String]> = [ + Max.bind(NumericalAggregateOpts::skip_nans()).to_string(), + Min.bind(NumericalAggregateOpts::skip_nans()).to_string(), + NanCount.bind(EmptyOptions).to_string(), + ] + .into(); + assert_eq!(recorded, [expected]); + + let id = get_item("id", root()); + let f = get_item("f", get_item("s", root())); + let mut ctx = session.create_execution_ctx(); + let mut segments = Vec::new(); + for filter in [ + lt(f.clone(), lit(100.0f64)), + gt(f.clone(), lit(1e8f64)), + lt(f, lit(0.0f64)), + ] { + let (actual, read) = scan_counting_segments(&file, planner, &id, &filter).await?; + let keep = table + .clone() + .apply(&fill_null(filter, lit(false)))? + .execute::(&mut ctx)?; + let expected = table.clone().filter(keep)?.apply(&id)?; + assert_arrays_eq!(actual, expected, &mut ctx); + segments.push(read); + } + assert!(segments[2] < segments[1], "segments read: {segments:?}"); + Ok(()) +} diff --git a/vortex-layout/src/layouts/struct_/writer.rs b/vortex-layout/src/layouts/struct_/writer.rs index b842c121168..45aadabefe0 100644 --- a/vortex-layout/src/layouts/struct_/writer.rs +++ b/vortex-layout/src/layouts/struct_/writer.rs @@ -274,6 +274,7 @@ mod tests { use std::num::NonZeroUsize; use vortex_array::ArrayContext; + use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::validity::Validity; @@ -295,8 +296,21 @@ mod tests { use crate::test::SESSION; use crate::test::new_session; - /// Write a single-field struct with zoned fields, returning whether the field got a zone map. - fn field_has_zone_map(validity: Validity) -> VortexResult { + /// Whether `layout` is a zone map that records null counts. + /// + /// A field beneath a nullable struct records no counts, which the rows where only the struct + /// is null make wrong, so this tells the leaves below a nullable struct from the others. + fn counts_nulls(layout: &LayoutRef) -> bool { + layout.as_opt::().is_some_and(|zoned| { + zoned + .aggregate_fns() + .iter() + .any(|aggregate_fn| aggregate_fn.is::()) + }) + } + + /// Write a single-field struct with zoned fields, returning the layout of the field. + fn write_field(validity: Validity) -> VortexResult { let strategy = StructStrategy::new( Arc::new(FlatLayoutStrategy::default()), Arc::new(ZonedStrategy::new( @@ -332,7 +346,7 @@ mod tests { })?; // The validity child, when present, precedes the fields. - Ok(layout.children()?[usize::from(is_nullable)].is::()) + Ok(Arc::clone(&layout.children()?[usize::from(is_nullable)])) } /// Write `array` through a [`TableStrategy`] with zoned leaves, returning the layout. @@ -366,17 +380,19 @@ mod tests { #[test] fn non_nullable_struct_fields_get_a_zone_map() -> VortexResult<()> { - assert!(field_has_zone_map(Validity::NonNullable)?); + assert!(counts_nulls(&write_field(Validity::NonNullable)?)); Ok(()) } - /// The field holds values in rows the struct nulls out, so no aggregate over it is exact for - /// the logical column and no zone map is written. + /// The field holds values in rows the struct nulls out, which keep its bounds valid but make + /// its counts wrong, so its zone map records only bounds. #[test] - fn nullable_struct_fields_get_no_zone_map() -> VortexResult<()> { - assert!(!field_has_zone_map(Validity::Array( + fn nullable_struct_fields_get_a_zone_map_of_bounds() -> VortexResult<()> { + let field = write_field(Validity::Array( BoolArray::from_iter([false, true, true]).into_array(), - ))?); + ))?; + assert!(field.is::()); + assert!(!counts_nulls(&field)); Ok(()) } @@ -396,10 +412,10 @@ mod tests { )?; let layout = write_table(outer_nullable)?; let inner = &layout.children()?[1]; - assert!(!inner.children()?[0].is::()); + assert!(!counts_nulls(&inner.children()?[0])); - // Non-nullable outer struct: a leaf beside the nullable inner struct keeps its zone map, - // the leaf below it loses it. + // Non-nullable outer struct: a leaf beside the nullable inner struct keeps its counts, the + // leaf below it loses them. let inner_nullable = StructArray::try_from_iter([ ("sibling", buffer![1, 2, 3].into_array()), ( @@ -413,8 +429,8 @@ mod tests { ])?; let layout = write_table(inner_nullable)?; let children = layout.children()?; - assert!(children[0].is::()); - assert!(!children[1].children()?[1].is::()); + assert!(counts_nulls(&children[0])); + assert!(!counts_nulls(&children[1].children()?[1])); Ok(()) } @@ -447,10 +463,10 @@ mod tests { let layout = write_table(root)?; // Skip the root's validity child, then walk every non-nullable level to the leaf. let leaf = descend(&layout.children()?[1], DEPTH)?; - assert!(!leaf.is::()); + assert!(!counts_nulls(&leaf)); // Non-nullable levels above, a nullable struct in the middle, non-nullable levels below. - // A leaf above the nullable level keeps its zone map, the leaf below it does not. + // A leaf above the nullable level keeps its counts, the leaf below it does not. let middle = StructArray::try_from_iter_with_validity( [("below", nest(buffer![1, 2, 3].into_array(), DEPTH)?)], some_nulls(), @@ -467,10 +483,10 @@ mod tests { let layout = write_table(root)?; let holder = descend(&layout, DEPTH)?; let holder_children = holder.children()?; - assert!(holder_children[0].is::()); + assert!(counts_nulls(&holder_children[0])); // The nullable middle struct's children are `[validity, below]`. let leaf = descend(&holder_children[1].children()?[1], DEPTH)?; - assert!(!leaf.is::()); + assert!(!counts_nulls(&leaf)); Ok(()) } diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index 8331567b399..c5dd36a276a 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -15,6 +15,8 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; +use vortex_array::aggregate_fn::fns::all_null::AllNull; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; @@ -110,31 +112,32 @@ impl LayoutStrategy for ZonedStrategy { mut eof: SequencePointer, session: &VortexSession, ) -> VortexResult { - let aggregate_fns = self + let mut aggregate_fns = self .options .aggregate_fns .clone() .unwrap_or_else(|| default_zoned_aggregate_fns(stream.dtype(), session)); - // Fields of a nullable struct are written unmasked, so every aggregate over them sees - // values the logical column does not contain: counts come out wrong and min/max come out - // wider than the truth. Zone maps hold exact values only, so until the aggregates are - // computed over the masked values no zone map is written for such a field. + // Fields of a nullable struct are written unmasked: a field holds values in rows where the + // struct is null, which reads through the struct return as nulls. A bound over them, such + // as a max, still bounds the field as read, only less tightly. A count does not: the null + // count misses the rows where only the struct is null, so a zone it shows without nulls can + // still hold rows where `is_null(s.a)` is true. Such a field records only the statistics + // that hold under masking and its NaN count, which scans read through the struct only as a + // proof that a zone holds no NaN, and no legacy zone map, whose statistics are fixed. // - // TODO(joe): write zone maps for fields under a nullable struct. The struct validity has - // to travel with each chunk, since repartitioning below the struct writer re-chunks the - // stream, and the aggregates then run over `chunk.mask(validity)` while the data child - // still receives the unmasked chunk. - if ctx.has_nullable_ancestor() { - return self - .child - .write_stream(ctx, segment_sink, stream, eof, session) - .await; + // TODO(joe): record every aggregate for fields under a nullable struct. The struct + // validity has to travel with each chunk, since repartitioning below the struct writer + // re-chunks the stream, and the aggregates then run over `chunk.mask(validity)` while the + // data child still receives the unmasked chunk. + let nullable_ancestor = ctx.has_nullable_ancestor(); + if nullable_ancestor { + aggregate_fns = aggregates_under_masking(&aggregate_fns); } // Readers before `vortex.zoned` only know the legacy `vortex.stats` layout. If the write // does not permit either layout, the column gets no zone map. if !ctx.allows_layout(&Zoned.id()) { - if ctx.allows_layout(&LegacyStats.id()) { + if ctx.allows_layout(&LegacyStats.id()) && !nullable_ancestor { return self .write_legacy_stream(ctx, segment_sink, stream, eof, session) .await; @@ -145,6 +148,12 @@ impl LayoutStrategy for ZonedStrategy { .write_stream(ctx, segment_sink, stream, eof, session) .await; } + if aggregate_fns.is_empty() { + return self + .child + .write_stream(ctx, segment_sink, stream, eof, session) + .await; + } let compute_session = session.clone(); @@ -313,6 +322,39 @@ impl ZonedStrategy { } } +/// Returns the aggregates of `aggregate_fns` that a field beneath a nullable struct records: those +/// whose statistics [hold under masking](holds_under_masking), and the NaN count. +/// +/// Float bounds prune only with a proof that the zone holds no NaN, which readers derive from a +/// NaN count of zero. The NaN count of a field also counts the NaNs in the rows the struct hides, +/// so a zone where it is zero holds no NaN as read through the struct either. Through the struct, +/// scans read it only as that proof, and never as a count. +fn aggregates_under_masking(aggregate_fns: &[AggregateFnRef]) -> Arc<[AggregateFnRef]> { + aggregate_fns + .iter() + .filter(|aggregate_fn| holds_under_masking(aggregate_fn) || aggregate_fn.is::()) + .cloned() + .collect() +} + +/// Whether a statistic of `aggregate_fn` over a column also holds, if less tightly, for the column +/// with some of its values replaced by nulls. +/// +/// Min and max bound the non-null values, which such a replacement only removes, and so does +/// whether no value is NaN, or whether every value is null. The fields of a nullable struct hold +/// values in rows where the struct is null, so these statistics of a field also hold for the field +/// as read through the struct. Counts do not: a field's null count misses the rows where only the +/// struct is null. Scans read a zone map beneath a nullable struct as covering those hidden values, +/// so they prune with its bounds and never with its counts. +fn holds_under_masking(aggregate_fn: &AggregateFnRef) -> bool { + aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() + || aggregate_fn.is::() +} + fn default_zoned_aggregate_fns(dtype: &DType, session: &VortexSession) -> Arc<[AggregateFnRef]> { let (max, min) = match dtype { DType::Utf8(_) | DType::Binary(_) => ( @@ -354,6 +396,7 @@ mod tests { use rstest::rstest; use vortex_array::ArrayContext; use vortex_array::IntoArray; + use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; @@ -424,6 +467,15 @@ mod tests { ..Default::default() }, ); + write_layout_with(&strategy, ctx) + } + + /// Write three zones of primitives with `strategy` through `ctx`, returning the resulting + /// layout. + fn write_layout_with( + strategy: &ZonedStrategy, + ctx: LayoutWriterContext, + ) -> VortexResult { let (ptr, eof) = SequenceId::root().split(); let stream = ChunkedArray::from_iter([ buffer![1, 2, 3].into_array(), @@ -463,16 +515,66 @@ mod tests { Ok(()) } - /// A field of a nullable struct is written unmasked, so no aggregate over it is exact and no - /// zone map is written. + /// A field of a nullable struct holds values in rows the struct nulls out. They loosen its + /// bounds but falsify its counts, so the zone map of an integer field records only the bounds. + #[test] + fn a_nullable_ancestor_records_only_bounds() -> VortexResult<()> { + let written = + write_zones(LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor())?; + assert_eq!(written, [Max.id().to_string(), Min.id().to_string()]); + Ok(()) + } + + /// A legacy zone map records a fixed set of statistics, counts among them, so a field of a + /// nullable struct gets none. #[test] - fn a_nullable_ancestor_writes_no_zone_map() -> VortexResult<()> { - let layout = - write_layout(LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor())?; - assert!(!layout.is::()); + fn a_nullable_ancestor_writes_no_legacy_zone_map() -> VortexResult<()> { + let ctx = LayoutWriterContext::new(ArrayContext::empty()) + .with_allowed_layouts(HashSet::from_iter([LegacyStats.id()])); + assert!(write_layout(ctx.clone())?.is::()); + assert!(!write_layout(ctx.with_nullable_ancestor())?.is::()); Ok(()) } + /// Explicitly requested counts are dropped under a nullable ancestor like the default ones, + /// and a field left with no bound gets no zone map. + #[test] + fn a_nullable_ancestor_without_bounds_writes_no_zone_map() -> VortexResult<()> { + let strategy = ZonedStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + FlatLayoutStrategy::default(), + ZonedLayoutOptions { + block_size: NonZeroUsize::new(3).vortex_expect("non zero"), + aggregate_fns: Some([NullCount.bind(EmptyOptions)].into()), + ..Default::default() + }, + ); + let ctx = LayoutWriterContext::new(ArrayContext::empty()).with_nullable_ancestor(); + assert!(!write_layout_with(&strategy, ctx)?.is::()); + Ok(()) + } + + /// Beneath a nullable struct, a float field records its NaN count with its bounds, since float + /// bounds prune only with a proof that the zone holds no NaN. Every core edition permits all + /// three. An integer field holds no NaN, so it records only its bounds. + #[rstest] + #[case::float(PType::F64, &[Max.id(), Min.id(), NanCount.id()])] + #[case::integer(PType::I32, &[Max.id(), Min.id()])] + fn a_nullable_ancestor_records_the_nan_count_of_floats( + #[case] ptype: PType, + #[case] expected: &[AggregateFnId], + ) { + let dtype = DType::from(ptype); + let aggregate_fns = + aggregates_under_masking(&default_zoned_aggregate_fns(&dtype, &SESSION)); + let recorded = AggregateStatsAccumulator::new(&dtype, &aggregate_fns) + .aggregate_fns() + .iter() + .map(|aggregate_fn| aggregate_fn.id()) + .collect::>(); + assert_eq!(recorded, expected); + } + #[test] fn a_permitted_set_covering_the_defaults_writes_them() -> VortexResult<()> { let ctx = LayoutWriterContext::new(ArrayContext::empty()).with_allowed_aggregates( diff --git a/vortex-layout/src/strategy.rs b/vortex-layout/src/strategy.rs index 3e5bcedd5ec..e7d2b3153b4 100644 --- a/vortex-layout/src/strategy.rs +++ b/vortex-layout/src/strategy.rs @@ -135,8 +135,10 @@ impl LayoutWriterContext { /// /// Container writers store their children unmasked: a field holds a value even in rows where /// the containing struct is null, and the struct's validity is written separately. Statistics - /// computed over such a child therefore see values the logical column does not contain, so - /// writers that record statistics must omit them rather than record inexact values. + /// computed over such a child therefore see values the logical column does not contain. + /// Writers that record statistics must record only those that stay correct for the logical + /// column, such as bounds on its values, which these values only loosen. Counts do not stay + /// correct: a null count misses the rows where only the container is null. pub fn with_nullable_ancestor(mut self) -> Self { self.nullable_ancestor = true; self From 227250b968bc3b81310ec4824d04052af6bac155 Mon Sep 17 00:00:00 2001 From: Connor Tsui Date: Fri, 20 Nov 2026 16:52:13 -0500 Subject: [PATCH 13/13] Read single fields of list elements on both scans A repeated protobuf message is a list of structs, and reading one of its fields, `list_transform(items, x -> x.sku)`, read every element field: the list reader knew only validity, offsets or everything. The planner scan could not read a list layout at all ("Plan vortex.plan.list_pack has no pipeline implementation"). The classic list reader now projects the elements with the lambda body, so it reads only the element columns that the lambda uses. The planner compiles `ListPack` into a source that reads the offsets and validity of the selected lists first, then scans only the elements of selected, valid lists, with the same element pushdown. Both scans also move strict functions that cannot fail below the validity of a nullable struct, so the pushdown reaches lists inside nullable protobuf messages. A lambda that can fail never runs on elements that in-memory `list_transform` would skip. Signed-off-by: Connor Tsui --- vortex-layout/src/layouts/list/expr.rs | 117 -- vortex-layout/src/layouts/list/expr/mod.rs | 281 ++++ vortex-layout/src/layouts/list/expr/tests.rs | 211 +++ vortex-layout/src/layouts/list/reader.rs | 1332 ----------------- vortex-layout/src/layouts/list/reader/mod.rs | 785 ++++++++++ .../src/layouts/list/reader/tests.rs | 989 ++++++++++++ vortex-layout/src/layouts/struct_/reader.rs | 146 ++ vortex-layout/src/scan/v2/tests/lists.rs | 456 ++++++ .../src/scan/v2/{tests.rs => tests/mod.rs} | 85 +- vortex-scan/src/plan/builtins/list_pack.rs | 180 --- .../src/plan/builtins/list_pack/execute.rs | 315 ++++ .../src/plan/builtins/list_pack/expr.rs | 216 +++ .../src/plan/builtins/list_pack/mod.rs | 476 ++++++ .../src/plan/builtins/list_pack/tests.rs | 368 +++++ vortex-scan/src/plan/builtins/mod.rs | 2 + vortex-scan/src/plan/builtins/pack/mod.rs | 8 + .../plan/builtins/pack/strict_functions.rs | 160 ++ vortex-scan/src/plan/mod.rs | 1 + vortex-scan/src/plan/optimize/registry.rs | 11 +- 19 files changed, 4499 insertions(+), 1640 deletions(-) delete mode 100644 vortex-layout/src/layouts/list/expr.rs create mode 100644 vortex-layout/src/layouts/list/expr/mod.rs create mode 100644 vortex-layout/src/layouts/list/expr/tests.rs delete mode 100644 vortex-layout/src/layouts/list/reader.rs create mode 100644 vortex-layout/src/layouts/list/reader/mod.rs create mode 100644 vortex-layout/src/layouts/list/reader/tests.rs create mode 100644 vortex-layout/src/scan/v2/tests/lists.rs rename vortex-layout/src/scan/v2/{tests.rs => tests/mod.rs} (92%) delete mode 100644 vortex-scan/src/plan/builtins/list_pack.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/execute.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/expr.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/mod.rs create mode 100644 vortex-scan/src/plan/builtins/list_pack/tests.rs create mode 100644 vortex-scan/src/plan/builtins/pack/strict_functions.rs diff --git a/vortex-layout/src/layouts/list/expr.rs b/vortex-layout/src/layouts/list/expr.rs deleted file mode 100644 index 8c10e400ad8..00000000000 --- a/vortex-layout/src/layouts/list/expr.rs +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::bound::not; -use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; -use vortex_array::scalar_fn::fns::is_null::IsNull; -use vortex_array::scalar_fn::fns::list_length::ListLength; -use vortex_error::VortexResult; - -/// The minimal set of list children an expression needs for evaluation. -/// -/// For example: -/// - `is_null(root())` only needs the validity child. -/// - `list_length(root())` only needs the offsets and validity children. -/// - `root()` needs elements, offsets, and validity children. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub(super) enum ListChildrenNeeded { - /// Only the validity child is needed (`is_null` / `is_not_null`). - Validity, - /// Only the offsets and validity children are needed (`list_length`). - OffsetsAndValidity, - /// All children are needed. - All, -} - -/// The minimal set of list children needed to evaluate a bound expression. -pub(super) fn get_necessary_bound_list_children(expr: &BoundExpression) -> ListChildrenNeeded { - if is_bound_null_root(expr) { - return ListChildrenNeeded::Validity; - } - - if is_bound_list_length_root(expr) { - return ListChildrenNeeded::OffsetsAndValidity; - } - - if expr.is_root() { - return ListChildrenNeeded::All; - } - - expr.children() - .iter() - .map(get_necessary_bound_list_children) - .max() - .unwrap_or(ListChildrenNeeded::Validity) -} - -fn is_bound_null_root(expr: &BoundExpression) -> bool { - (expr.as_scalar().is_some_and(|f| f.is::()) - || expr.as_scalar().is_some_and(|f| f.is::())) - && expr.children().len() == 1 - && expr.children()[0].is_root() -} - -fn is_bound_list_length_root(expr: &BoundExpression) -> bool { - expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() -} - -/// Rewrite a validity-class expression so it can be evaluated against the list's validity bool -/// array (`true` == valid row): `is_not_null(root())` becomes `root()` and `is_null(root())` -/// becomes `not(root())`. All other nodes are rebuilt with rewritten children. -pub(super) fn rewrite_validity_expr(expr: &BoundExpression) -> VortexResult { - let validity_dtype = DType::Bool(Nullability::NonNullable); - rewrite_validity_expr_with_root(expr, &validity_dtype) -} - -fn rewrite_validity_expr_with_root( - expr: &BoundExpression, - root_dtype: &DType, -) -> VortexResult { - if expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() - { - return Ok(BoundExpression::new_root(root_dtype.clone())); - } - if expr.as_scalar().is_some_and(|f| f.is::()) - && expr.children().len() == 1 - && expr.children()[0].is_root() - { - return Ok(not(BoundExpression::new_root(root_dtype.clone()))); - } - if expr.is_root() { - return Ok(BoundExpression::new_root(root_dtype.clone())); - } - - let children = expr - .children() - .iter() - .map(|child| rewrite_validity_expr_with_root(child, root_dtype)) - .collect::>>()?; - expr.clone().with_children(children) -} - -/// Rewrite an offsets-class expression so it can be evaluated against an array of list lengths. -/// `list_length(root())` becomes `root()`. Other references to `root()` are left intact: for -/// offsets-class expressions they can only be validity checks, and the lengths array carries the -/// same validity as the original list. -pub(super) fn rewrite_offsets_expr( - expr: &BoundExpression, - lengths_dtype: &DType, -) -> VortexResult { - if is_bound_list_length_root(expr) || expr.is_root() { - return Ok(BoundExpression::new_root(lengths_dtype.clone())); - } - - let children = expr - .children() - .iter() - .map(|child| rewrite_offsets_expr(child, lengths_dtype)) - .collect::>>()?; - expr.clone().with_children(children) -} diff --git a/vortex-layout/src/layouts/list/expr/mod.rs b/vortex-layout/src/layouts/list/expr/mod.rs new file mode 100644 index 00000000000..aef3c5d36a3 --- /dev/null +++ b/vortex-layout/src/layouts/list/expr/mod.rs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Which list children an expression reads, and the rewrites that evaluate it over them. + +#[cfg(test)] +mod tests; + +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::bound::get_item; +use vortex_array::expr::bound::not; +use vortex_array::expr::bound::pack; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_array::scalar_fn::fns::list_length::ListLength; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_scan::plan::ListTransforms; + +/// The minimal set of list children an expression needs for evaluation. +/// +/// For example: +/// - `is_null(root())` only needs the validity child. +/// - `list_length(root())` only needs the offsets and validity children. +/// - `root()` needs elements, offsets, and validity children. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum ListChildrenNeeded { + /// Only the validity child is needed (`is_null` / `is_not_null`). + Validity, + /// Only the offsets and validity children are needed (`list_length`). + OffsetsAndValidity, + /// All children are needed. + All, +} + +/// The minimal set of list children needed to evaluate a bound expression. +pub(super) fn get_necessary_bound_list_children(expr: &BoundExpression) -> ListChildrenNeeded { + if is_bound_null_root(expr) { + return ListChildrenNeeded::Validity; + } + + if is_bound_list_length_root(expr) { + return ListChildrenNeeded::OffsetsAndValidity; + } + + if expr.is_root() { + return ListChildrenNeeded::All; + } + + expr.children() + .iter() + .map(get_necessary_bound_list_children) + .max() + .unwrap_or(ListChildrenNeeded::Validity) +} + +fn is_bound_null_root(expr: &BoundExpression) -> bool { + (expr.as_scalar().is_some_and(|f| f.is::()) + || expr.as_scalar().is_some_and(|f| f.is::())) + && expr.children().len() == 1 + && expr.children()[0].is_root() +} + +fn is_bound_list_length_root(expr: &BoundExpression) -> bool { + expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() +} + +/// Rewrite a validity-class expression so it can be evaluated against the list's validity bool +/// array (`true` == valid row): `is_not_null(root())` becomes `root()` and `is_null(root())` +/// becomes `not(root())`. All other nodes are rebuilt with rewritten children. +pub(super) fn rewrite_validity_expr(expr: &BoundExpression) -> VortexResult { + let validity_dtype = DType::Bool(Nullability::NonNullable); + rewrite_validity_expr_with_root(expr, &validity_dtype) +} + +fn rewrite_validity_expr_with_root( + expr: &BoundExpression, + root_dtype: &DType, +) -> VortexResult { + if expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() + { + return Ok(BoundExpression::new_root(root_dtype.clone())); + } + if expr.as_scalar().is_some_and(|f| f.is::()) + && expr.children().len() == 1 + && expr.children()[0].is_root() + { + return Ok(not(BoundExpression::new_root(root_dtype.clone()))); + } + if expr.is_root() { + return Ok(BoundExpression::new_root(root_dtype.clone())); + } + + let children = expr + .children() + .iter() + .map(|child| rewrite_validity_expr_with_root(child, root_dtype)) + .collect::>>()?; + expr.clone().with_children(children) +} + +/// Rewrite an offsets-class expression so it can be evaluated against an array of list lengths. +/// `list_length(root())` becomes `root()`. Other references to `root()` are left intact: for +/// offsets-class expressions they can only be validity checks, and the lengths array carries the +/// same validity as the original list. +pub(super) fn rewrite_offsets_expr( + expr: &BoundExpression, + lengths_dtype: &DType, +) -> VortexResult { + if is_bound_list_length_root(expr) || expr.is_root() { + return Ok(BoundExpression::new_root(lengths_dtype.clone())); + } + + let children = expr + .children() + .iter() + .map(|child| rewrite_offsets_expr(child, lengths_dtype)) + .collect::>>()?; + expr.clone().with_children(children) +} + +/// An expression over a list that reads the list elements only through the lambdas of +/// `list_transform(root, lambda)` nodes, rewritten so that those lambdas run over the elements +/// child. +/// +/// The reader evaluates [`Self::elements`] over the elements child, rebuilds lists over the +/// projected elements with [`Self::rebuild`], and evaluates [`Self::lists`] over them. A lambda +/// that reads one field of struct elements, as in `list_transform(root, x -> x.sku)`, reaches the +/// elements layout as `$.sku`, so only the column of that field is read. +/// +/// The identity projection reads the elements as stored: its elements expression is the elements +/// root and its list expression is the original expression. +#[derive(Debug)] +pub(super) struct ElementProjection { + elements: BoundExpression, + /// The names of the struct of lists that [`Self::rebuild`] builds, one list per lambda, or + /// `None` when it builds a single list. + lists_fields: Option, + lists: BoundExpression, + fallible: bool, +} + +impl ElementProjection { + /// Reads the elements as stored and evaluates `expr` over the rebuilt list. + pub(super) fn identity(expr: &BoundExpression, elements_dtype: &DType) -> Self { + Self { + elements: BoundExpression::new_root(elements_dtype.clone()), + lists_fields: None, + lists: expr.clone(), + fallible: false, + } + } + + /// Pushes the lambdas of the `list_transform(root, lambda)` nodes of `expr` into the elements. + /// + /// Each lambda body becomes an expression over the elements, with its parameter rebound to + /// the elements root. The bodies of several distinct lambdas are packed into a struct, which + /// rebuilds into a struct of lists that share the offsets and validity. + /// + /// Returns `None` when `expr` has no such node, or reads the list root in another way than + /// through these nodes, `is_null(root)`, `is_not_null(root)` and `list_length(root)`. The last + /// three need only the offsets and validity, which every rebuilt list keeps. + pub(super) fn push_down(expr: &BoundExpression) -> VortexResult> { + let Some(transforms) = ListTransforms::of(expr)? else { + return Ok(None); + }; + + let (elements, lists_fields, lists_root) = + if let ([transform], [body]) = (transforms.transforms(), transforms.bodies()) { + let lists_root = BoundExpression::new_root(transform.dtype().clone()); + (body.clone(), None, lists_root) + } else { + let names: FieldNames = (0..transforms.bodies().len()) + .map(|idx| idx.to_string()) + .collect(); + let elements = pack( + names + .iter() + .cloned() + .zip(transforms.bodies().iter().cloned()), + Nullability::NonNullable, + ); + let lists_dtype = DType::Struct( + StructFields::new( + names.clone(), + transforms + .transforms() + .iter() + .map(|transform| transform.dtype().clone()) + .collect(), + ), + Nullability::NonNullable, + ); + ( + elements, + Some(names), + BoundExpression::new_root(lists_dtype), + ) + }; + + let list_at = |idx: usize| match &lists_fields { + Some(names) => get_item(names[idx].clone(), lists_root.clone()), + None => lists_root.clone(), + }; + let lists = transforms.rewrite(expr, |idx| Ok(list_at(idx)), &list_at(0))?; + + Ok(Some(Self { + elements, + lists_fields, + lists, + fallible: transforms.is_fallible(), + })) + } + + /// The expression over the elements child. + pub(super) fn elements(&self) -> &BoundExpression { + &self.elements + } + + /// The expression over what [`Self::rebuild`] builds. It has the dtype of the original + /// expression. + pub(super) fn lists(&self) -> &BoundExpression { + &self.lists + } + + /// Whether evaluating [`Self::elements`] can fail. + /// + /// `list_transform` runs such a lambda only on the elements of valid lists, so the reader must + /// not evaluate it over the elements of null or unselected lists either. + pub(super) fn is_fallible(&self) -> bool { + self.fallible + } + + /// Rebuilds what [`Self::lists`] reads from the projected `elements` and the `offsets` and + /// `validity` of the lists. + /// + /// # Safety + /// + /// `elements` must hold the projection of every element that `offsets` references, at the + /// position of that element, and `offsets` and `validity` must describe valid lists over them. + pub(super) unsafe fn rebuild( + &self, + elements: ArrayRef, + offsets: ArrayRef, + validity: Validity, + ) -> VortexResult { + let Some(names) = &self.lists_fields else { + // SAFETY: the caller guarantees the list invariants. + return Ok( + unsafe { ListArray::new_unchecked(elements, offsets, validity) }.into_array(), + ); + }; + let len = offsets.len().saturating_sub(1); + let lists = names + .iter() + .map(|name| { + let field = elements.get_item(name.clone())?; + // SAFETY: every field of the packed projection has one value per element, so the + // caller's guarantee holds for each field. + Ok( + unsafe { ListArray::new_unchecked(field, offsets.clone(), validity.clone()) } + .into_array(), + ) + }) + .collect::>>()?; + Ok(StructArray::try_new(names.clone(), lists, len, Validity::NonNullable)?.into_array()) + } +} diff --git a/vortex-layout/src/layouts/list/expr/tests.rs b/vortex-layout/src/layouts/list/expr/tests.rs new file mode 100644 index 00000000000..74d3322ca38 --- /dev/null +++ b/vortex-layout/src/layouts/list/expr/tests.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::list::ListArrayExt; +use vortex_array::arrays::list::ListArraySlotsExt; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::and; +use vortex_array::expr::checked_add; +use vortex_array::expr::eq; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; + +use super::ElementProjection; +use crate::test::SESSION; + +/// `[{a, b}, {c, d}]`, `null` (hiding `[{e, i32::MAX}]`), `[]` and `[{null, 3}]`, as lists of +/// `{sku: utf8?, qty: i32}`. +fn items() -> VortexResult { + let elements = StructArray::from_fields(&[ + ( + "sku", + VarBinViewArray::from_iter_nullable_str([Some("a"), Some("c"), Some("e"), None]) + .into_array(), + ), + ("qty", buffer![1i32, 2, i32::MAX, 3].into_array()), + ])? + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 4].into_array(), + Validity::from_iter([true, false, true, true]), + &mut ctx, + ) +} + +fn sku(param: &str) -> VortexResult { + Lambda::new([param], get_item("sku", var(param))) +} + +fn qty(param: &str) -> VortexResult { + Lambda::new([param], get_item("qty", var(param))) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on the element of the null list. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// Rewrites `expr` over the lists of [`items`]. +fn push_down(expr: &Expression) -> VortexResult> { + ElementProjection::push_down(&expr.bind(items()?.dtype())?) +} + +/// Evaluates a projection the way the reader does, over the whole of `list`. +fn evaluate(projection: &ElementProjection, list: &ListArray) -> VortexResult { + let elements = list.elements().clone().apply_bound(projection.elements())?; + // SAFETY: the offsets and validity are those of a valid list over the projected elements. + let lists = + unsafe { projection.rebuild(elements, list.offsets().clone(), list.list_validity()) }?; + lists.apply_bound(projection.lists()) +} + +#[rstest] +#[case::one_field(list_transform(root(), sku("x")?), "$.sku", "$")] +#[case::param_name(list_transform(root(), sku("item")?), "$.sku", "$")] +#[case::predicate( + and( + is_not_null(root()), + list_contains(list_transform(root(), sku("x")?), lit("c")), + ), + "$.sku", + "(is_not_null($) and vortex.list.contains($, \"c\"))" +)] +#[case::length( + pack( + [("skus", list_transform(root(), sku("x")?)), ("len", list_length(root()))], + Nullability::NonNullable, + ), + "$.sku", + "pack(skus: $, len: vortex.list.length($))" +)] +#[case::repeated_lambda( + pack( + [("a", list_transform(root(), sku("x")?)), ("b", list_transform(root(), sku("x")?))], + Nullability::NonNullable, + ), + "$.sku", + "pack(a: $, b: $)" +)] +#[case::two_lambdas( + pack( + [ + ("skus", list_transform(root(), sku("x")?)), + ("qtys", list_transform(root(), qty("x")?)), + ("len", list_length(root())), + ], + Nullability::NonNullable, + ), + "pack(0: $.sku, 1: $.qty)", + "pack(skus: $.0, qtys: $.1, len: vortex.list.length($.0))" +)] +#[case::outer_lambda_in_memory( + list_transform( + list_transform(root(), qty("x")?), + Lambda::new(["y"], eq(var("y"), lit(1i32)))?, + ), + "$.qty", + "vortex.list.transform($, (y) -> ($.y = 1i32))" +)] +fn pushes_lambdas_into_elements( + #[case] expr: Expression, + #[case] elements: &str, + #[case] lists: &str, +) -> VortexResult<()> { + let projection = push_down(&expr)?.expect("reads the elements only through lambdas"); + assert_eq!(projection.elements().to_string(), elements); + assert_eq!(projection.lists().to_string(), lists); + assert!(!projection.is_fallible()); + + let list = items()?; + let expected = list.clone().into_array().apply(&expr)?; + let mut ctx = SESSION.create_execution_ctx(); + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} + +/// A lambda that can fail makes the projection fallible, so the reader runs it only on the +/// elements of valid lists. +#[test] +fn fallible_lambda_is_fallible() -> VortexResult<()> { + let projection = push_down(&qty_plus_one()?)?.expect("reads the elements through a lambda"); + assert_eq!(projection.elements().to_string(), "($.qty + 1i32)"); + assert!(projection.is_fallible()); + Ok(()) +} + +#[rstest] +#[case::root(root())] +#[case::no_lambda(list_length(root()))] +#[case::mixed(pack( + [("items", root()), ("skus", list_transform(root(), sku("x")?))], + Nullability::NonNullable, +))] +fn keeps_element_reads(#[case] expr: Expression) -> VortexResult<()> { + assert!(push_down(&expr)?.is_none()); + Ok(()) +} + +/// The identity projection reads the elements as stored and evaluates the expression over the +/// rebuilt list. +#[test] +fn identity_reads_stored_elements() -> VortexResult<()> { + let list = items()?; + let expr = list_contains(list_transform(root(), qty("x")?), lit(3i32)); + let projection = + ElementProjection::identity(&expr.bind(list.dtype())?, list.elements().dtype()); + assert!(projection.elements().is_root()); + assert!(!projection.is_fallible()); + + let expected = list.clone().into_array().apply(&expr)?; + let mut ctx = SESSION.create_execution_ctx(); + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} + +/// Lists of `i32` pushed into a flat elements child keep their shape. +#[test] +fn primitive_elements() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let list = ListArray::try_new( + PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), + buffer![0u32, 0, 2, 3].into_array(), + Validity::NonNullable, + &mut ctx, + )?; + let expr = list_transform(root(), Lambda::new(["x"], eq(var("x"), lit(3i32)))?); + let projection = ElementProjection::push_down(&expr.bind(list.dtype())?)? + .expect("reads the elements through a lambda"); + assert_eq!(projection.elements().to_string(), "($ = 3i32)"); + assert!(matches!(projection.lists().dtype(), DType::List(..))); + + let expected = list.clone().into_array().apply(&expr)?; + assert_arrays_eq!(evaluate(&projection, &list)?, expected, &mut ctx); + Ok(()) +} diff --git a/vortex-layout/src/layouts/list/reader.rs b/vortex-layout/src/layouts/list/reader.rs deleted file mode 100644 index 334a4f21efb..00000000000 --- a/vortex-layout/src/layouts/list/reader.rs +++ /dev/null @@ -1,1332 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::ops::Range; -use std::sync::Arc; - -use futures::FutureExt; -use futures::future::BoxFuture; -use futures::try_join; -use vortex_array::ArrayRef; -use vortex_array::Canonical; -use vortex_array::IntoArray; -use vortex_array::MaskFuture; -use vortex_array::VortexSessionExecute; -use vortex_array::arrays::ConstantArray; -use vortex_array::arrays::ListArray; -use vortex_array::builtins::ArrayBuiltins; -use vortex_array::dtype::DType; -use vortex_array::dtype::FieldMask; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::PType; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::root; -use vortex_array::scalar_fn::fns::operators::Operator; -use vortex_array::validity::Validity; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_mask::Mask; -use vortex_session::VortexSession; - -use crate::ArrayFuture; -use crate::LayoutReader; -use crate::LayoutReaderContext; -use crate::LayoutReaderRef; -use crate::RowSplits; -use crate::SplitRange; -use crate::layouts::list::ListLayout; -use crate::layouts::list::expr::ListChildrenNeeded; -use crate::layouts::list::expr::get_necessary_bound_list_children; -use crate::layouts::list::expr::rewrite_offsets_expr; -use crate::layouts::list::expr::rewrite_validity_expr; -use crate::segments::SegmentSource; - -type OptionalArrayFuture = BoxFuture<'static, VortexResult>>; - -/// The threshold of mask density below which we push the input mask into projection evaluation, -/// and above which we evaluate the expression over all rows and intersect afterward. -const EXPR_EVAL_THRESHOLD: f64 = 0.2; - -/// Minimum size of the outer-row split grid, so lists in small files still fan out. -const MIN_LIST_SPLIT_COUNT: u64 = 64; - -/// Outer rows per grid cell that the grid grows to stay under for large files. -const TARGET_LIST_SPLIT_ROWS: u64 = 8192; - -/// Number of cells in the outer-row split grid: at least [`MIN_LIST_SPLIT_COUNT`], and enough -/// that a cell covers at most about [`TARGET_LIST_SPLIT_ROWS`] outer rows. -fn list_split_grid_size(outer_row_count: u64) -> u64 { - outer_row_count - .div_ceil(TARGET_LIST_SPLIT_ROWS) - .next_power_of_two() - .max(MIN_LIST_SPLIT_COUNT) -} - -/// Reader for [`ListLayout`]. -#[derive(Clone)] -pub struct ListReader { - layout: ListLayout, - name: Arc, - session: VortexSession, - elements: LayoutReaderRef, - offsets: LayoutReaderRef, - validity: Option, -} - -impl ListReader { - pub(super) fn try_new( - layout: ListLayout, - name: Arc, - segment_source: Arc, - session: VortexSession, - ctx: &LayoutReaderContext, - ) -> VortexResult { - let elements = layout.elements()?.new_reader( - format!("{name}.elements").into(), - Arc::clone(&segment_source), - &session, - ctx, - )?; - let offsets = layout.offsets()?.new_reader( - format!("{name}.offsets").into(), - Arc::clone(&segment_source), - &session, - ctx, - )?; - let validity = layout - .validity()? - .map(|v| { - v.new_reader( - format!("{name}.validity").into(), - Arc::clone(&segment_source), - &session, - ctx, - ) - }) - .transpose()?; - - Ok(Self { - layout, - name, - session, - elements, - offsets, - validity, - }) - } - - /// Projection for [`ListChildrenNeeded::Validity`] expressions. Reads only the validity child, - /// synthesizing all-valid for a non-nullable list, and never touches the offsets or elements. - fn project_validity( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let validity_reader = self.validity.clone(); - let nullability = self.layout.dtype().nullability(); - let row_range = row_range.clone(); - // Evaluate the rewritten expression against the validity bool array (true == valid row). - let rewritten = rewrite_validity_expr(expr)?; - - Ok(async move { - let mask = mask.await?; - let row_count = usize::try_from(row_range.end - row_range.start)?; - let out_len = if mask.all_true() { - row_count - } else { - mask.true_count() - }; - - let validity_array = match validity_reader.as_ref() { - Some(v) => { - let root = root().bind(v.dtype())?; - Some( - v.projection_evaluation(&row_range, &root, MaskFuture::ready(mask))? - .await?, - ) - } - None => None, - }; - - let validity = create_validity(validity_array, nullability).to_array(out_len); - - validity.apply_bound(&rewritten) - } - .boxed()) - } - - /// Projection for [`ListChildrenNeeded::All`] expressions. - /// - /// An all-true mask over the full local range reads every child concurrently. Otherwise, the - /// read is bounded to the first and last selected list. - fn project_all( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let is_full_range = row_range.start == 0 && row_range.end == self.layout.row_count(); - let reader = self.clone(); - let row_range = row_range.clone(); - let expr = expr.clone(); - Ok(async move { - let mask = mask.await?; - if is_full_range && mask.all_true() { - reader.project_all_full(&expr)?.await - } else { - reader.project_all_bounded(&row_range, &expr, mask)?.await - } - } - .boxed()) - } - - /// Fetch the complete `elements`, `offsets`, and `validity` children concurrently. - fn project_all_full(&self, expr: &BoundExpression) -> VortexResult { - let row_count = self.layout.row_count(); - let elements_row_count = self.elements.row_count(); - let nullability = self.layout.dtype().nullability(); - let expr = expr.clone(); - - let offsets_fut = self.fetch_raw_offsets(&(0..row_count))?; - let elements_fut = self.fetch_raw_elements(&(0..elements_row_count))?; - let validity_fut = fetch_validity( - self.validity.as_ref(), - &(0..row_count), - MaskFuture::new_true(usize::try_from(row_count)?), - )?; - - Ok(async move { - let (offsets, elements, validity) = try_join!(offsets_fut, elements_fut, validity_fut)?; - // SAFETY: ListLayout is constructed from a valid ListArray and reading its children - // without transformation preserves the list invariants. - let list = unsafe { - ListArray::new_unchecked(elements, offsets, create_validity(validity, nullability)) - } - .into_array(); - list.apply_bound(&expr) - } - .boxed()) - } - - /// Bounded read for a sub-range or selective mask. - /// - /// Crops leading and trailing unselected lists, reads their offsets, and translates the first - /// and last offset into the element-row range to fetch. Any holes in the selection are filtered - /// after reconstructing the list array. - fn project_all_bounded( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: Mask, - ) -> VortexResult { - // Crop to the smallest contiguous row range containing every selected list. - let Some(selected_rows) = selected_row_range(&mask) else { - let empty = Canonical::empty(expr.dtype()).into_array(); - return Ok(async move { Ok(empty) }.boxed()); - }; - - let selected_mask = mask.slice(selected_rows.clone()); - let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) - ..(row_range.start + u64::try_from(selected_rows.end)?); - - let nullability = self.layout.dtype().nullability(); - let expr = expr.clone(); - let reader = self.clone(); - let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; - - Ok(async move { - let offsets = offsets_fut.await?; - - let elements_range = elements_range_from_offsets(&offsets, &reader.session)?; - let elements_fut = reader.fetch_raw_elements(&elements_range)?; - let validity_fut = fetch_validity( - reader.validity.as_ref(), - &selected_row_range, - MaskFuture::new_true(selected_mask.len()), - )?; - let (elements, validity) = try_join!(elements_fut, validity_fut)?; - - let offsets = rebase_offsets(offsets, elements_range.start)?; - // SAFETY: the selected offsets remain monotonically increasing, rebasing them against - // the selected element range preserves their lengths, and validity covers the same - // cropped list rows. - let list = unsafe { - ListArray::new_unchecked(elements, offsets, create_validity(validity, nullability)) - } - .into_array(); - let list = if selected_mask.all_true() { - list - } else { - list.filter(selected_mask)? - }; - list.apply_bound(&expr) - } - .boxed()) - } - - /// Projection for [`ListChildrenNeeded::OffsetsAndValidity`] expressions. Only reads offsets and validity children. - fn project_offsets_validity( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let offsets = self.fetch_raw_offsets(row_range)?; - let reader = self.clone(); - let row_range = row_range.clone(); - let lengths_dtype = DType::Primitive(PType::U64, self.layout.dtype().nullability()); - let rewritten = rewrite_offsets_expr(expr, &lengths_dtype)?; - - Ok(async move { - let mask = mask.await?; - let row_count = usize::try_from(row_range.end - row_range.start)?; - let nullability = reader.layout.dtype().nullability(); - - let validity_mask = if mask.all_true() { - MaskFuture::new_true(row_count) - } else { - MaskFuture::ready(mask.clone()) - }; - let validity_fut = fetch_validity(reader.validity.as_ref(), &row_range, validity_mask)?; - - let offsets = offsets.await?; - let lengths = list_lengths_from_offsets(offsets)?; - let lengths = if mask.all_true() { - lengths - } else { - lengths.filter(mask)? - }; - let validity = validity_fut.await?; - let lengths = apply_lengths_validity(lengths, validity, nullability)?; - - lengths.apply_bound(&rewritten) - } - .boxed()) - } - - /// Fire the offsets read for `row_range` in list row space. The offsets child has an extra entry, so reading - /// `row_range` maps to offsets in `[row_range.start..row_range.end + 1)`. - /// - /// No mask or expression is applied. - fn fetch_raw_offsets(&self, row_range: &Range) -> VortexResult { - let offsets_range = row_range.start..(row_range.end + 1); - let offsets_count = usize::try_from(offsets_range.end - offsets_range.start)?; - let root = root().bind(self.offsets.dtype())?; - self.offsets.projection_evaluation( - &offsets_range, - &root, - MaskFuture::new_true(offsets_count), - ) - } - - /// Fire the elements read for `row_range` in element space. - /// - /// No mask or expression is applied. - fn fetch_raw_elements(&self, row_range: &Range) -> VortexResult { - let row_count = usize::try_from(row_range.end - row_range.start)?; - let root = root().bind(self.elements.dtype())?; - self.elements - .projection_evaluation(row_range, &root, MaskFuture::new_true(row_count)) - } -} - -fn selected_row_range(mask: &Mask) -> Option> { - Some(mask.first()?..mask.last()? + 1) -} - -fn create_validity(validity_array: Option, nullability: Nullability) -> Validity { - match validity_array { - Some(arr) => Validity::Array(arr), - None => match nullability { - Nullability::Nullable => Validity::AllValid, - Nullability::NonNullable => Validity::NonNullable, - }, - } -} - -impl LayoutReader for ListReader { - fn name(&self) -> &Arc { - &self.name - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } - - fn dtype(&self) -> &DType { - self.layout.dtype() - } - - fn row_count(&self) -> u64 { - self.layout.row_count() - } - - fn register_splits( - &self, - _field_mask: &[FieldMask], - split_range: &SplitRange, - splits: &mut RowSplits, - ) -> VortexResult<()> { - split_range.check_bounds(self.layout.row_count())?; - - // Splits are difficult to calculate because all children live in different row coordinate spaces. - // List elements typically comprise the majority of the data in a list, and validity/offsets can be treated - // as metadata. We therefore want to parallelize the scan based on element work. - // - // Scan splits must be expressed in the list layout's outer-row space, but the elements child - // reports its natural boundaries in element-row space. So we translate the element splits using a - // heuristic to outer-row space. - - let element_row_count = self.elements.row_count(); - if element_row_count != 0 { - let mut element_splits = RowSplits::new_capacity(128); - self.elements.register_splits( - &[FieldMask::All], - &SplitRange::root(0..element_row_count)?, - &mut element_splits, - )?; - - let row_range = split_range.row_range(); - let grid_size = list_split_grid_size(self.layout.row_count()); - let mut last_split = None; - for element_split in element_splits.into_sorted_deduped() { - let Some(split) = map_element_split_to_outer_grid( - element_split, - element_row_count, - self.layout.row_count(), - grid_size, - ) else { - continue; - }; - if split <= row_range.start { - continue; - } - if split >= row_range.end { - break; - } - if last_split == Some(split) { - continue; - } - splits.push( - split_range - .row_offset() - .checked_add(split) - .vortex_expect("List layout split offset overflow"), - ); - last_split = Some(split); - } - } - splits.push(split_range.root_row_range().end); - Ok(()) - } - - // TODO(mk): handle zones for list elements - fn pruning_evaluation( - &self, - _row_range: &Range, - _expr: &BoundExpression, - mask: Mask, - ) -> VortexResult { - Ok(MaskFuture::ready(mask)) - } - - fn filter_evaluation( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - let len = mask.len(); - let reader = self.clone(); - let row_range = row_range.clone(); - let expr = expr.clone(); - let session = self.session.clone(); - - Ok(MaskFuture::new(len, async move { - let mask = mask.await?; - - if mask.all_false() { - return Ok(mask); - } - - let mut ctx = session.create_execution_ctx(); - if mask.density() < EXPR_EVAL_THRESHOLD { - let predicate = reader - .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? - .await?; - let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; - Ok(mask.intersect_by_rank(&predicate_mask)) - } else { - let predicate = reader - .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? - .await?; - let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; - Ok(mask & &predicate_mask) - } - })) - } - - /// Reads only the list children needed to evaluate `expr`. - /// - /// Validity-only expressions avoid offsets and elements, length expressions read offsets and - /// validity, and general expressions reconstruct a list from all applicable children. - fn projection_evaluation( - &self, - row_range: &Range, - expr: &BoundExpression, - mask: MaskFuture, - ) -> VortexResult { - // Read as little as possible based on which list children the expression needs. - match get_necessary_bound_list_children(expr) { - ListChildrenNeeded::Validity => self.project_validity(row_range, expr, mask), - ListChildrenNeeded::OffsetsAndValidity => { - self.project_offsets_validity(row_range, expr, mask) - } - ListChildrenNeeded::All => self.project_all(row_range, expr, mask), - } - } -} - -/// Converts a natural boundary from element-row space into an approximate outer-row scan split. -/// -/// Scan splits must be expressed in the list layout's outer-row space, but the elements child -/// reports its natural boundaries in element-row space. Translating a boundary exactly would -/// require consulting the list offsets, so this function instead preserves its relative position: -/// -/// ```text -/// element_split / element_row_count ≈ outer_split / outer_row_count -/// ``` -/// -/// The relative position is first rounded onto a grid containing at most `max_split_count` scan -/// ranges, then mapped into outer-row space. Multiple element boundaries may therefore map to the -/// same outer split and are deduplicated by the caller. With a grid size of 64, at most 63 interior -/// splits—and therefore 64 scan ranges—can be produced. -/// -/// The result is only a task-sizing hint. It is always between outer rows, but it is not guaranteed -/// to correspond exactly to the original physical element boundary. Endpoint boundaries are -/// omitted because they do not subdivide the scan -fn map_element_split_to_outer_grid( - element_split: u64, - element_row_count: u64, - outer_row_count: u64, - max_split_count: u64, -) -> Option { - if element_split == 0 - || element_split >= element_row_count - || outer_row_count == 0 - || max_split_count < 2 - { - return None; - } - debug_assert!(max_split_count.is_power_of_two()); - - let grid_index = (u128::from(element_split) * u128::from(max_split_count) - + u128::from(element_row_count / 2)) - / u128::from(element_row_count); - if grid_index == 0 || grid_index >= u128::from(max_split_count) { - return None; - } - - let outer_split = grid_index * u128::from(outer_row_count) / u128::from(max_split_count); - let outer_split = u64::try_from(outer_split) - .vortex_expect("Outer split is bounded by the list layout row count"); - (outer_split != 0 && outer_split < outer_row_count).then_some(outer_split) -} - -/// Fetch the validity child for `row_range` under `mask`, yielding `None` for a non-nullable list -/// (which has no validity child). -fn fetch_validity( - validity: Option<&LayoutReaderRef>, - row_range: &Range, - mask: MaskFuture, -) -> VortexResult { - let fut = validity - .map(|v| { - let root = root().bind(v.dtype())?; - v.projection_evaluation(row_range, &root, mask) - }) - .transpose()?; - Ok(async move { - match fut { - Some(f) => f.await.map(Some), - None => Ok(None), - } - } - .boxed()) -} - -/// Read `offsets[0]` and `offsets[-1]` and return the elements range they bound. -fn elements_range_from_offsets( - offsets: &ArrayRef, - session: &VortexSession, -) -> VortexResult> { - if offsets.is_empty() { - return Ok(0..0); - } - let mut exec_ctx = session.create_execution_ctx(); - let start = offsets - .execute_scalar(0, &mut exec_ctx)? - .as_primitive() - .as_::() - .vortex_expect("offset value fits in u64"); - let end = offsets - .execute_scalar(offsets.len() - 1, &mut exec_ctx)? - .as_primitive() - .as_::() - .vortex_expect("offset value fits in u64"); - Ok(start..end) -} - -/// Subtract `first` from every offset so they index into a sliced `elements[first..]` buffer that -/// starts at zero. -fn rebase_offsets(offsets: ArrayRef, first: u64) -> VortexResult { - if first == 0 { - return Ok(offsets); - } - let constant = ConstantArray::new(first, offsets.len()) - .into_array() - .cast(offsets.dtype().clone())?; - offsets.binary(constant, Operator::Sub) -} - -/// Compute `offsets[i + 1] - offsets[i]` as the unmasked list length values. -fn list_lengths_from_offsets(offsets: ArrayRef) -> VortexResult { - let len = offsets.len().saturating_sub(1); - offsets - .slice(1..offsets.len())? - .binary(offsets.slice(0..len)?, Operator::Sub) -} - -fn apply_lengths_validity( - lengths: ArrayRef, - validity: Option, - nullability: Nullability, -) -> VortexResult { - let len = lengths.len(); - let lengths = lengths.cast(DType::Primitive(PType::U64, nullability))?; - - if matches!(nullability, Nullability::Nullable) { - lengths.mask(create_validity(validity, nullability).to_array(len)) - } else { - Ok(lengths) - } -} - -#[cfg(test)] -mod tests { - use std::ops::Range; - - use rstest::rstest; - use vortex_array::ArrayContext; - use vortex_array::VortexSessionExecute; - use vortex_array::arrays::BoolArray; - use vortex_array::arrays::ChunkedArray; - use vortex_array::arrays::ListArray; - use vortex_array::arrays::ListViewArray; - use vortex_array::arrays::PrimitiveArray; - use vortex_array::assert_arrays_eq; - use vortex_array::expr::Expression; - use vortex_array::expr::cast; - use vortex_array::expr::gt; - use vortex_array::expr::is_not_null; - use vortex_array::expr::is_null; - use vortex_array::expr::list_length; - use vortex_array::expr::lit; - use vortex_buffer::buffer; - use vortex_io::session::RuntimeSession; - use vortex_io::session::RuntimeSessionExt; - use vortex_session::VortexSession; - - use super::*; - use crate::LayoutRef; - use crate::LayoutStrategy; - use crate::layouts::chunked::writer::ChunkedLayoutStrategy; - use crate::layouts::flat::writer::FlatLayoutStrategy; - use crate::layouts::list::writer::ListLayoutStrategy; - use crate::layouts::repartition::RepartitionStrategy; - use crate::layouts::repartition::RepartitionWriterOptions; - use crate::scan::split_by::SplitBy; - use crate::segments::CountingSegmentSource; - use crate::segments::SegmentSource; - use crate::segments::TestSegments; - use crate::sequence::SequenceId; - use crate::sequence::SequentialArrayStreamExt; - use crate::session::LayoutSession; - use crate::test::SESSION; - - /// Validity-class projections (`is_null` / `is_not_null` of the list) round-trip through the - /// validity-only read path, for both nullable and non-nullable lists. - #[rstest] - // `create_basic_list_array(true)` has validity `[true, false, true]`. - #[case::nullable(true, vec![true, false, true])] - #[case::non_nullable(false, vec![true, true, true])] - #[tokio::test] - async fn projection_validity_class( - #[case] nullable: bool, - #[case] valid: Vec, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let not_null_expr = is_not_null(root()).bind(reader.dtype())?; - let not_null = reader - .projection_evaluation(&(0..3), ¬_null_expr, MaskFuture::new_true(3))? - .await?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(not_null, BoolArray::from_iter(valid.clone()), &mut exec_ctx); - - let is_null_expr = is_null(root()).bind(reader.dtype())?; - let is_null_res = reader - .projection_evaluation(&(0..3), &is_null_expr, MaskFuture::new_true(3))? - .await?; - assert_arrays_eq!( - is_null_res, - BoolArray::from_iter(valid.iter().map(|v| !v).collect::>()), - &mut exec_ctx - ); - - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_reads_offsets() -> VortexResult<()> { - let list = create_basic_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, buffer![2u64, 2, 1].into_array(), &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_preserves_validity() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = - PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_list_length_applies_sparse_mask() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let mask = Mask::from_iter([false, true, true]); - let expr = list_length(root()).bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask))? - .await?; - - let expected = PrimitiveArray::from_option_iter::([None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_cast_list_length() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = cast( - list_length(root()), - DType::Primitive(PType::I64, Nullability::Nullable), - ) - .bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = - PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_list_length() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = gt(list_length(root()), lit(1u64)).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - assert_eq!(result, Mask::from_iter([true, false, false])); - Ok(()) - } - - #[rstest] - #[case::is_not_null_nullable(true, is_not_null(root()), Mask::from_iter([true, false, true]))] - #[case::is_not_null_non_nullable(false, is_not_null(root()), Mask::new_true(3))] - #[case::is_null_nullable(true, is_null(root()), Mask::from_iter([false, true, false]))] - #[case::is_null_non_nullable(false, is_null(root()), Mask::new_false(3))] - #[tokio::test] - async fn filter_evaluation_validity_class( - #[case] nullable: bool, - #[case] expr: Expression, - #[case] expected: Mask, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = expr.bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? - .await?; - - assert_eq!(result, expected); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_intersects_with_input_mask() -> VortexResult<()> { - let list = create_basic_list_array(true); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let input_mask = Mask::from_iter([true, true, false]); - let expr = is_not_null(root()).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..3), &expr, MaskFuture::ready(input_mask))? - .await?; - - assert_eq!(result, Mask::from_iter([true, false, false])); - Ok(()) - } - - #[tokio::test] - async fn filter_evaluation_sparse_mask_maps_by_rank() -> VortexResult<()> { - let list = create_six_list_array(); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let input_mask = Mask::from_iter([false, false, false, false, true, false]); - let expr = is_not_null(root()).bind(reader.dtype())?; - let result = reader - .filter_evaluation(&(0..6), &expr, MaskFuture::ready(input_mask))? - .await?; - - assert_eq!( - result, - Mask::from_iter([false, false, false, false, true, false]) - ); - Ok(()) - } - - fn flat_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default() - } - - fn layout_test_session() -> VortexSession { - VortexSession::empty() - .with::() - .with::() - } - - async fn write_layout( - strategy: &S, - array: ArrayRef, - ) -> VortexResult<(Arc, LayoutRef, VortexSession)> { - let session = layout_test_session().with_tokio(); - let segments = Arc::new(TestSegments::default()); - let segments_ref: Arc = Arc::::clone(&segments); - let (ptr, eof) = SequenceId::root().split(); - let stream = array.to_array_stream().sequenced(ptr); - let layout = strategy - .write_stream( - ArrayContext::empty().into(), - segments, - stream, - eof, - &session, - ) - .await?; - Ok((segments_ref, layout, session)) - } - - fn materialize_u64_array(array: ArrayRef) -> Vec { - let mut ctx = SESSION.create_execution_ctx(); - array - .execute::(&mut ctx) - .unwrap() - .as_slice::() - .to_vec() - } - - fn create_basic_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, false, true]).into_array()) - } else { - Validity::NonNullable - }; - - ListArray::try_new( - buffer![1i32, 2, 3, 4, 5].into_array(), - buffer![0u32, 2, 4, 5].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - fn create_six_list_array() -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = Validity::Array( - BoolArray::from_iter([true, false, true, false, true, true]).into_array(), - ); - - ListArray::try_new( - buffer![1i32, 2, 3, 4, 5, 6].into_array(), - buffer![0u32, 1, 2, 3, 4, 5, 6].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - #[tokio::test] - async fn fetch_offsets_includes_extra_endpoint() -> VortexResult<()> { - let list = create_basic_list_array(false); - - let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; - let ctx = LayoutReaderContext::new(); - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - let reader = reader - .as_any() - .downcast_ref::() - .expect("ListReader"); - - let offsets = reader.fetch_raw_offsets(&(1..3))?.await?; - assert_eq!(materialize_u64_array(offsets), vec![2u64, 4, 5]); - - Ok(()) - } - - #[rstest] - #[case::full_range(0..3, false)] - #[case::partial_start(0..2, false)] - #[case::partial_end(1..3, false)] - #[case::middle_single(1..2, false)] - #[case::empty_range(1..1, false)] - #[case::full_range_null(0..3, true)] - #[tokio::test] - async fn projection_evaluation_round_trips( - #[case] row_range: Range, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_basic_list_array(nullable); - let ctx = LayoutReaderContext::new(); - - let len = usize::try_from(row_range.end - row_range.start)?; - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? - .await?; - - let expected = - list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[tokio::test] - async fn projection_evaluation_applies_mask() -> VortexResult<()> { - let list = create_basic_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let mask = Mask::from_iter([true, false, true]); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// Build a list with 5 rows and lengths [2, 3, 0, 3, 2]. - fn create_wider_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) - } else { - Validity::NonNullable - }; - ListArray::try_new( - buffer![10i32, 11, 20, 21, 22, 30, 31, 32, 40, 41].into_array(), - buffer![0u32, 2, 5, 5, 8, 10].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - /// Sparse row masks over a whole chunk round-trip: the whole-chunk read is filtered by the - /// mask in memory. - #[rstest] - #[case::single_middle(Mask::from_iter([false, false, false, true, false]), false)] - #[case::two_far_apart(Mask::from_iter([true, false, false, true, false]), false)] - #[case::boundaries(Mask::from_iter([true, false, false, false, true]), false)] - #[case::kept_empty_row(Mask::from_iter([false, false, true, false, false]), false)] - #[case::sparse_nullable(Mask::from_iter([true, false, true, false, true]), true)] - #[case::all_false(Mask::new_false(5), false)] - #[tokio::test] - async fn projection_evaluation_sparse_mask_round_trips( - #[case] mask: Mask, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_wider_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// A partial range against a single flat elements segment takes the bounded path. The flat - /// reader may still fetch its whole segment, but the list reader reconstructs only the requested - /// element range. - #[tokio::test] - async fn projection_evaluation_partial_range_bounded() -> VortexResult<()> { - let list = create_wider_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(1..4), &expr, MaskFuture::new_true(3))? - .await?; - - let expected = list.slice(1..4)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[test] - fn maps_element_splits_to_outer_grid() { - assert_eq!(map_element_split_to_outer_grid(0, 100, 100, 8), None); - assert_eq!(map_element_split_to_outer_grid(20, 100, 100, 8), Some(25)); - assert_eq!(map_element_split_to_outer_grid(25, 100, 100, 8), Some(25)); - assert_eq!(map_element_split_to_outer_grid(50, 100, 100, 8), Some(50)); - assert_eq!(map_element_split_to_outer_grid(75, 100, 100, 8), Some(75)); - assert_eq!(map_element_split_to_outer_grid(100, 100, 100, 8), None); - - let mut splits = (1..1_000) - .filter_map(|split| { - map_element_split_to_outer_grid(split, 1_000, 100_000, MIN_LIST_SPLIT_COUNT) - }) - .collect::>(); - splits.dedup(); - - let expected = (1..MIN_LIST_SPLIT_COUNT) - .map(|grid_index| grid_index * 100_000 / MIN_LIST_SPLIT_COUNT) - .collect::>(); - assert_eq!(splits, expected); - } - - #[rstest] - #[case::empty(0, 64)] - #[case::small(100_000, 64)] - #[case::floor_boundary(64 * 8192, 64)] - #[case::past_floor(64 * 8192 + 1, 128)] - #[case::million(1_000_000, 128)] - #[case::ten_million(10_000_000, 2048)] - fn split_grid_grows_with_row_count(#[case] outer_row_count: u64, #[case] expected: u64) { - assert_eq!(list_split_grid_size(outer_row_count), expected); - } - - #[tokio::test] - async fn nested_list_propagates_element_splits() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let inner = ListArray::try_new( - PrimitiveArray::from_iter(0..128_i32).into_array(), - PrimitiveArray::from_iter((0..=8_u32).map(|idx| idx * 16)).into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let outer = ListArray::try_new( - inner, - buffer![0u32, 2, 4, 6, 8].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - - let inner_strategy = - ListLayoutStrategy::default().with_elements(chunked_elements_strategy()); - let strategy = ListLayoutStrategy::default().with_elements(Arc::new(inner_strategy)); - let (segments, layout, session) = write_layout(&strategy, outer).await?; - let reader = - layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; - - let splits = SplitBy::Layout.splits(reader.as_ref(), &(0..4), &[FieldMask::All])?; - assert_eq!(splits, vec![0, 1, 2, 3, 4]); - Ok(()) - } - - /// A list strategy whose `elements` child is repartitioned into two-element chunks, so the - /// reader takes the bounded (chunk-skipping) path for strict sub-ranges. Offsets stay flat. - fn chunked_elements_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default().with_elements(chunked_elements_strategy()) - } - - fn chunked_elements_strategy() -> Arc { - Arc::new(RepartitionStrategy::new( - ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), - RepartitionWriterOptions { - block_size_minimum: 0, - block_len_multiple: 2, - block_size_target: None, - canonicalize: true, - }, - )) - } - - /// The chunked-elements strategy must actually produce a chunked `elements` layout, otherwise - /// the reader would silently take the whole-chunk path and the bounded read would be untested. - #[tokio::test] - async fn chunked_elements_produces_chunked_layout() -> VortexResult<()> { - let list = create_wider_list_array(false); - let (_segments, layout, _session) = - write_layout(&chunked_elements_list_strategy(), list).await?; - let tree = layout.display_tree().to_string(); - assert!( - tree.contains("elements: vortex.chunked"), - "elements should be chunked:\n{tree}" - ); - Ok(()) - } - - /// A sparse mask must remain selective even when the requested row range covers the complete - /// local list layout. The selected first list touches one element chunk plus the offsets - /// segment; reading all five element chunks would make the count six. - #[tokio::test] - async fn full_range_sparse_mask_crops_element_read() -> VortexResult<()> { - let list = create_wider_list_array(false); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = - write_layout(&chunked_elements_list_strategy(), list.clone()).await?; - let source = Arc::new(CountingSegmentSource::new(segments)); - let reader = layout.new_reader("".into(), Arc::clone(&source) as _, &session, &ctx)?; - - let mask = Mask::from_iter([true, false, false, false, false]); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let expected = list.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - assert_eq!(source.requests(), 2); - Ok(()) - } - - /// With chunked elements, sub-range projections take the bounded read path. Every - /// range/mask/nullability combination must match the same projection over the ground-truth - /// array (`list.slice(range).filter(mask)`). - #[rstest] - #[case::full_all_true(0..5, Mask::new_true(5), false)] - #[case::subrange_all_true(1..4, Mask::new_true(3), false)] - #[case::subrange_sparse(1..4, Mask::from_iter([true, false, true]), false)] - #[case::partial_start(0..2, Mask::new_true(2), false)] - #[case::partial_end(2..5, Mask::new_true(3), false)] - #[case::single_non_empty(0..1, Mask::new_true(1), false)] - #[case::single_empty_row(2..3, Mask::from_iter([true]), false)] - #[case::empty_range(2..2, Mask::new_true(0), false)] - #[case::subrange_all_false(1..4, Mask::new_false(3), false)] - #[case::subrange_single_interior(0..4, Mask::from_iter([false, true, false, false]), false)] - #[case::subrange_sparse_nullable(1..4, Mask::from_iter([true, false, true]), true)] - #[case::partial_end_nullable(2..5, Mask::new_true(3), true)] - #[tokio::test] - async fn chunked_elements_round_trips( - #[case] row_range: Range, - #[case] mask: Mask, - #[case] nullable: bool, - ) -> VortexResult<()> { - let list = create_wider_list_array(nullable); - let ctx = LayoutReaderContext::new(); - let (segments, layout, session) = - write_layout(&chunked_elements_list_strategy(), list.clone()).await?; - let reader = layout.new_reader("".into(), segments, &session, &ctx)?; - - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? - .await?; - - let sliced = - list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; - let expected = sliced.filter(mask)?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - /// Lists `[0, 1, 2]`, `[]`, `[3, 4, 5]`, `[6, 7]`, `[8, 9]`. When nullable, the third is null - /// and keeps its elements. - fn create_ten_element_list_array(nullable: bool) -> ArrayRef { - let mut ctx = SESSION.create_execution_ctx(); - let validity = if nullable { - Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) - } else { - Validity::NonNullable - }; - ListArray::try_new( - PrimitiveArray::from_iter(0..10i32).into_array(), - buffer![0u32, 3, 3, 6, 8, 10].into_array(), - validity, - &mut ctx, - ) - .expect("array is valid") - .into_array() - } - - /// Slices of one list share its whole `elements`, so every chunk but the first starts at a - /// nonzero offset and every chunk but the last leaves trailing elements unreferenced. - fn sliced_chunks(array: &ArrayRef, cuts: &[usize]) -> VortexResult> { - let mut bounds = vec![0]; - bounds.extend_from_slice(cuts); - bounds.push(array.len()); - bounds - .windows(2) - .map(|range| array.slice(range[0]..range[1])) - .collect() - } - - fn chunked_flat() -> Arc { - Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())) - } - - /// A list strategy that keeps every chunk, so a multi-chunk stream reaches the list writer. - fn chunked_list_strategy() -> ListLayoutStrategy { - ListLayoutStrategy::default() - .with_elements(chunked_flat()) - .with_offsets(chunked_flat()) - .with_validity(chunked_flat()) - } - - async fn assert_round_trips( - strategy: &S, - chunks: Vec, - expected: ArrayRef, - ) -> VortexResult<()> { - let chunked = ChunkedArray::try_new(chunks, expected.dtype().clone())?.into_array(); - let (segments, layout, session) = write_layout(strategy, chunked).await?; - let reader = - layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; - - let len = expected.len(); - let expr = root().bind(reader.dtype())?; - let result = reader - .projection_evaluation(&(0..len as u64), &expr, MaskFuture::new_true(len))? - .await?; - let mut exec_ctx = session.create_execution_ctx(); - assert_arrays_eq!(result, expected, &mut exec_ctx); - Ok(()) - } - - #[rstest] - #[case::one_cut(&[2], false, false)] - #[case::two_cuts(&[1, 3], false, false)] - #[case::null_and_empty_at_cuts(&[1, 3], true, false)] - #[case::list_view_chunks(&[1, 3], true, true)] - #[case::non_nullable_list_view_chunks(&[1, 3], false, true)] - #[tokio::test] - async fn sliced_list_chunks_round_trip( - #[case] cuts: &[usize], - #[case] nullable: bool, - #[case] as_list_view: bool, - ) -> VortexResult<()> { - let list = create_ten_element_list_array(nullable); - let source = if as_list_view { - let mut ctx = SESSION.create_execution_ctx(); - list.clone() - .execute::(&mut ctx)? - .into_array() - } else { - list.clone() - }; - let chunks = sliced_chunks(&source, cuts)?; - assert_round_trips(&chunked_list_strategy(), chunks, list).await - } - - #[tokio::test] - async fn sliced_nested_list_chunks_round_trip() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let inner = ListArray::try_new( - PrimitiveArray::from_iter(0..12i32).into_array(), - buffer![0u32, 2, 2, 5, 7, 9, 12].into_array(), - Validity::NonNullable, - &mut ctx, - )? - .into_array(); - let outer = ListArray::try_new( - inner, - buffer![0u32, 2, 3, 5, 6].into_array(), - Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()), - &mut ctx, - )? - .into_array(); - - let strategy = chunked_list_strategy().with_elements(Arc::new(chunked_list_strategy())); - assert_round_trips(&strategy, sliced_chunks(&outer, &[1, 2])?, outer).await - } -} diff --git a/vortex-layout/src/layouts/list/reader/mod.rs b/vortex-layout/src/layouts/list/reader/mod.rs new file mode 100644 index 00000000000..a709b8aa5e0 --- /dev/null +++ b/vortex-layout/src/layouts/list/reader/mod.rs @@ -0,0 +1,785 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#[cfg(test)] +mod tests; + +use std::ops::Range; +use std::sync::Arc; +use std::sync::OnceLock; + +use futures::FutureExt; +use futures::future::BoxFuture; +use futures::try_join; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::IntoArray; +use vortex_array::MaskFuture; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldMask; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::ExactBoundExpr; +use vortex_array::expr::root; +use vortex_array::scalar_fn::fns::operators::Operator; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::BufferMut; +use vortex_error::VortexExpect; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_utils::aliases::dash_map::DashMap; + +use crate::ArrayFuture; +use crate::LayoutReader; +use crate::LayoutReaderContext; +use crate::LayoutReaderRef; +use crate::RowSplits; +use crate::SplitRange; +use crate::layouts::list::ListLayout; +use crate::layouts::list::expr::ElementProjection; +use crate::layouts::list::expr::ListChildrenNeeded; +use crate::layouts::list::expr::get_necessary_bound_list_children; +use crate::layouts::list::expr::rewrite_offsets_expr; +use crate::layouts::list::expr::rewrite_validity_expr; +use crate::segments::SegmentSource; + +type OptionalArrayFuture = BoxFuture<'static, VortexResult>>; + +/// The threshold of mask density below which we push the input mask into projection evaluation, +/// and above which we evaluate the expression over all rows and intersect afterward. +const EXPR_EVAL_THRESHOLD: f64 = 0.2; + +/// Minimum size of the outer-row split grid, so lists in small files still fan out. +const MIN_LIST_SPLIT_COUNT: u64 = 64; + +/// Outer rows per grid cell that the grid grows to stay under for large files. +const TARGET_LIST_SPLIT_ROWS: u64 = 8192; + +/// Number of cells in the outer-row split grid: at least [`MIN_LIST_SPLIT_COUNT`], and enough +/// that a cell covers at most about [`TARGET_LIST_SPLIT_ROWS`] outer rows. +fn list_split_grid_size(outer_row_count: u64) -> u64 { + outer_row_count + .div_ceil(TARGET_LIST_SPLIT_ROWS) + .next_power_of_two() + .max(MIN_LIST_SPLIT_COUNT) +} + +/// Reader for [`ListLayout`]. +/// +/// An expression that reads the list elements only through `list_transform(root, lambda)` runs +/// the lambda bodies over the elements child, so a lambda that reads one field of struct elements +/// reads only the column of that field. See [`ElementProjection`]. +#[derive(Clone)] +pub struct ListReader { + layout: ListLayout, + name: Arc, + session: VortexSession, + elements: LayoutReaderRef, + offsets: LayoutReaderRef, + validity: Option, + /// Element projections keyed by the identity of the expression they were derived from. + /// Cached so the elements reader sees the same tree on every split, keeping its own + /// identity-keyed caches warm. + projections: Arc, +} + +type ProjectionCache = DashMap>>>; + +impl ListReader { + pub(super) fn try_new( + layout: ListLayout, + name: Arc, + segment_source: Arc, + session: VortexSession, + ctx: &LayoutReaderContext, + ) -> VortexResult { + let elements = layout.elements()?.new_reader( + format!("{name}.elements").into(), + Arc::clone(&segment_source), + &session, + ctx, + )?; + let offsets = layout.offsets()?.new_reader( + format!("{name}.offsets").into(), + Arc::clone(&segment_source), + &session, + ctx, + )?; + let validity = layout + .validity()? + .map(|v| { + v.new_reader( + format!("{name}.validity").into(), + Arc::clone(&segment_source), + &session, + ctx, + ) + }) + .transpose()?; + + Ok(Self { + layout, + name, + session, + elements, + offsets, + validity, + projections: Arc::new(DashMap::with_hasher_and_shard_amount(Default::default(), 8)), + }) + } + + /// Returns how the [`ListChildrenNeeded::All`] expression `expr` reads the elements child: the + /// lambdas of its `list_transform(root, lambda)` nodes when it reads the elements only through + /// them, or the elements as stored. + fn element_projection(&self, expr: &BoundExpression) -> VortexResult> { + let key = ExactBoundExpr(expr.clone()); + let cell = match self.projections.get(&key) { + Some(entry) => Arc::clone(entry.value()), + None => Arc::clone( + self.projections + .entry(key) + .or_insert_with(|| Arc::new(OnceLock::new())) + .value(), + ), + }; + if let Some(projection) = cell.get() { + return Ok(Arc::clone(projection)); + } + let projection = match ElementProjection::push_down(expr)? { + Some(projection) => projection, + None => ElementProjection::identity(expr, self.layout.elements_dtype()), + }; + Ok(Arc::clone(cell.get_or_init(|| Arc::new(projection)))) + } + + /// Projection for [`ListChildrenNeeded::Validity`] expressions. Reads only the validity child, + /// synthesizing all-valid for a non-nullable list, and never touches the offsets or elements. + fn project_validity( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let validity_reader = self.validity.clone(); + let nullability = self.layout.dtype().nullability(); + let row_range = row_range.clone(); + // Evaluate the rewritten expression against the validity bool array (true == valid row). + let rewritten = rewrite_validity_expr(expr)?; + + Ok(async move { + let mask = mask.await?; + let row_count = usize::try_from(row_range.end - row_range.start)?; + let out_len = if mask.all_true() { + row_count + } else { + mask.true_count() + }; + + let validity_array = match validity_reader.as_ref() { + Some(v) => { + let root = root().bind(v.dtype())?; + Some( + v.projection_evaluation(&row_range, &root, MaskFuture::ready(mask))? + .await?, + ) + } + None => None, + }; + + let validity = create_validity(validity_array, nullability).to_array(out_len); + + validity.apply_bound(&rewritten) + } + .boxed()) + } + + /// Projection for [`ListChildrenNeeded::All`] expressions. + /// + /// The elements child is read through the [`ElementProjection`] of `expr`. A projection that + /// can fail reads only the elements of the selected valid lists. Otherwise, an all-true mask + /// over the full local range reads every child concurrently, and any other read is bounded to + /// the first and last selected list. + fn project_all( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let projection = self.element_projection(expr)?; + let is_full_range = row_range.start == 0 && row_range.end == self.layout.row_count(); + let reader = self.clone(); + let row_range = row_range.clone(); + Ok(async move { + let mask = mask.await?; + if projection.is_fallible() { + reader + .project_all_compacted(&row_range, projection, mask)? + .await + } else if is_full_range && mask.all_true() { + reader.project_all_full(projection)?.await + } else { + reader + .project_all_bounded(&row_range, projection, mask)? + .await + } + } + .boxed()) + } + + /// Fetch the complete `elements`, `offsets`, and `validity` children concurrently. + fn project_all_full(&self, projection: Arc) -> VortexResult { + let row_count = self.layout.row_count(); + let elements_row_count = self.elements.row_count(); + let nullability = self.layout.dtype().nullability(); + + let offsets_fut = self.fetch_raw_offsets(&(0..row_count))?; + let elements_fut = self.fetch_elements( + &(0..elements_row_count), + projection.elements(), + MaskFuture::new_true(usize::try_from(elements_row_count)?), + )?; + let validity_fut = fetch_validity( + self.validity.as_ref(), + &(0..row_count), + MaskFuture::new_true(usize::try_from(row_count)?), + )?; + + Ok(async move { + let (offsets, elements, validity) = try_join!(offsets_fut, elements_fut, validity_fut)?; + // SAFETY: ListLayout is constructed from a valid ListArray, and the element-wise + // projection keeps one value per element. + let lists = unsafe { + projection.rebuild(elements, offsets, create_validity(validity, nullability)) + }?; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Bounded read for a sub-range or selective mask. + /// + /// Crops leading and trailing unselected lists, reads their offsets, and translates the first + /// and last offset into the element-row range to fetch. Any holes in the selection are filtered + /// after reconstructing the lists. + fn project_all_bounded( + &self, + row_range: &Range, + projection: Arc, + mask: Mask, + ) -> VortexResult { + // Crop to the smallest contiguous row range containing every selected list. + let Some(selected_rows) = selected_row_range(&mask) else { + let empty = Canonical::empty(projection.lists().dtype()).into_array(); + return Ok(async move { Ok(empty) }.boxed()); + }; + + let selected_mask = mask.slice(selected_rows.clone()); + let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) + ..(row_range.start + u64::try_from(selected_rows.end)?); + + let nullability = self.layout.dtype().nullability(); + let reader = self.clone(); + let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; + + Ok(async move { + let offsets = offsets_fut.await?; + + let elements_range = elements_range_from_offsets(&offsets, &reader.session)?; + let elements_fut = reader.fetch_elements( + &elements_range, + projection.elements(), + MaskFuture::new_true(usize::try_from(elements_range.end - elements_range.start)?), + )?; + let validity_fut = fetch_validity( + reader.validity.as_ref(), + &selected_row_range, + MaskFuture::new_true(selected_mask.len()), + )?; + let (elements, validity) = try_join!(elements_fut, validity_fut)?; + + let offsets = rebase_offsets(offsets, elements_range.start)?; + // SAFETY: the selected offsets remain monotonically increasing, rebasing them against + // the selected element range preserves their lengths, the element-wise projection + // keeps one value per element, and validity covers the same cropped list rows. + let lists = unsafe { + projection.rebuild(elements, offsets, create_validity(validity, nullability)) + }?; + let lists = if selected_mask.all_true() { + lists + } else { + lists.filter(selected_mask)? + }; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Read for an element projection that can fail. + /// + /// `list_transform` runs a lambda that can fail only on the elements of valid lists, so this + /// read evaluates the projection only on the elements of the selected valid lists. It reads + /// the offsets and validity from the first to the last selected list, then the projected + /// elements under a mask of the elements of the selected valid lists, and rebuilds the + /// selected lists over just those elements. + fn project_all_compacted( + &self, + row_range: &Range, + projection: Arc, + mask: Mask, + ) -> VortexResult { + let Some(selected_rows) = selected_row_range(&mask) else { + let empty = Canonical::empty(projection.lists().dtype()).into_array(); + return Ok(async move { Ok(empty) }.boxed()); + }; + + let selected_mask = mask.slice(selected_rows.clone()); + let selected_row_range = (row_range.start + u64::try_from(selected_rows.start)?) + ..(row_range.start + u64::try_from(selected_rows.end)?); + + let nullability = self.layout.dtype().nullability(); + let reader = self.clone(); + let offsets_fut = self.fetch_raw_offsets(&selected_row_range)?; + let validity_fut = fetch_validity( + self.validity.as_ref(), + &selected_row_range, + MaskFuture::new_true(selected_mask.len()), + )?; + + Ok(async move { + let (offsets, validity) = try_join!(offsets_fut, validity_fut)?; + let mut ctx = reader.session.create_execution_ctx(); + let offsets = offsets + .cast(DType::Primitive(PType::U64, Nullability::NonNullable))? + .execute::(&mut ctx)?; + let valid = match &validity { + Some(validity) => validity.clone().execute::(&mut ctx)?, + None => Mask::new_true(selected_mask.len()), + }; + let compacted = compact_lists(offsets.as_slice::(), &selected_mask, &valid)?; + + let elements = reader + .fetch_elements( + &compacted.elements_range, + projection.elements(), + MaskFuture::ready(compacted.elements_mask), + )? + .await?; + let validity = validity + .map(|validity| validity.filter(selected_mask)) + .transpose()?; + // SAFETY: the compacted offsets index exactly the masked elements, the element-wise + // projection keeps one value per element, and validity is filtered to the same + // selected lists. + let lists = unsafe { + projection.rebuild( + elements, + compacted.offsets.into_array(), + create_validity(validity, nullability), + ) + }?; + lists.apply_bound(projection.lists()) + } + .boxed()) + } + + /// Projection for [`ListChildrenNeeded::OffsetsAndValidity`] expressions. Only reads offsets and validity children. + fn project_offsets_validity( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let offsets = self.fetch_raw_offsets(row_range)?; + let reader = self.clone(); + let row_range = row_range.clone(); + let lengths_dtype = DType::Primitive(PType::U64, self.layout.dtype().nullability()); + let rewritten = rewrite_offsets_expr(expr, &lengths_dtype)?; + + Ok(async move { + let mask = mask.await?; + let row_count = usize::try_from(row_range.end - row_range.start)?; + let nullability = reader.layout.dtype().nullability(); + + let validity_mask = if mask.all_true() { + MaskFuture::new_true(row_count) + } else { + MaskFuture::ready(mask.clone()) + }; + let validity_fut = fetch_validity(reader.validity.as_ref(), &row_range, validity_mask)?; + + let offsets = offsets.await?; + let lengths = list_lengths_from_offsets(offsets)?; + let lengths = if mask.all_true() { + lengths + } else { + lengths.filter(mask)? + }; + let validity = validity_fut.await?; + let lengths = apply_lengths_validity(lengths, validity, nullability)?; + + lengths.apply_bound(&rewritten) + } + .boxed()) + } + + /// Fire the offsets read for `row_range` in list row space. The offsets child has an extra entry, so reading + /// `row_range` maps to offsets in `[row_range.start..row_range.end + 1)`. + /// + /// No mask or expression is applied. + fn fetch_raw_offsets(&self, row_range: &Range) -> VortexResult { + let offsets_range = row_range.start..(row_range.end + 1); + let offsets_count = usize::try_from(offsets_range.end - offsets_range.start)?; + let root = root().bind(self.offsets.dtype())?; + self.offsets.projection_evaluation( + &offsets_range, + &root, + MaskFuture::new_true(offsets_count), + ) + } + + /// Fire the read of `expr` over the elements in `row_range`, in element space, under `mask`. + fn fetch_elements( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + self.elements.projection_evaluation(row_range, expr, mask) + } +} + +fn selected_row_range(mask: &Mask) -> Option> { + Some(mask.first()?..mask.last()? + 1) +} + +fn create_validity(validity_array: Option, nullability: Nullability) -> Validity { + match validity_array { + Some(arr) => Validity::Array(arr), + None => match nullability { + Nullability::Nullable => Validity::AllValid, + Nullability::NonNullable => Validity::NonNullable, + }, + } +} + +impl LayoutReader for ListReader { + fn name(&self) -> &Arc { + &self.name + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn dtype(&self) -> &DType { + self.layout.dtype() + } + + fn row_count(&self) -> u64 { + self.layout.row_count() + } + + fn register_splits( + &self, + _field_mask: &[FieldMask], + split_range: &SplitRange, + splits: &mut RowSplits, + ) -> VortexResult<()> { + split_range.check_bounds(self.layout.row_count())?; + + // Splits are difficult to calculate because all children live in different row coordinate spaces. + // List elements typically comprise the majority of the data in a list, and validity/offsets can be treated + // as metadata. We therefore want to parallelize the scan based on element work. + // + // Scan splits must be expressed in the list layout's outer-row space, but the elements child + // reports its natural boundaries in element-row space. So we translate the element splits using a + // heuristic to outer-row space. + + let element_row_count = self.elements.row_count(); + if element_row_count != 0 { + let mut element_splits = RowSplits::new_capacity(128); + self.elements.register_splits( + &[FieldMask::All], + &SplitRange::root(0..element_row_count)?, + &mut element_splits, + )?; + + let row_range = split_range.row_range(); + let grid_size = list_split_grid_size(self.layout.row_count()); + let mut last_split = None; + for element_split in element_splits.into_sorted_deduped() { + let Some(split) = map_element_split_to_outer_grid( + element_split, + element_row_count, + self.layout.row_count(), + grid_size, + ) else { + continue; + }; + if split <= row_range.start { + continue; + } + if split >= row_range.end { + break; + } + if last_split == Some(split) { + continue; + } + splits.push( + split_range + .row_offset() + .checked_add(split) + .vortex_expect("List layout split offset overflow"), + ); + last_split = Some(split); + } + } + splits.push(split_range.root_row_range().end); + Ok(()) + } + + // TODO(mk): handle zones for list elements + fn pruning_evaluation( + &self, + _row_range: &Range, + _expr: &BoundExpression, + mask: Mask, + ) -> VortexResult { + Ok(MaskFuture::ready(mask)) + } + + fn filter_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + let len = mask.len(); + let reader = self.clone(); + let row_range = row_range.clone(); + let expr = expr.clone(); + let session = self.session.clone(); + + Ok(MaskFuture::new(len, async move { + let mask = mask.await?; + + if mask.all_false() { + return Ok(mask); + } + + let mut ctx = session.create_execution_ctx(); + if mask.density() < EXPR_EVAL_THRESHOLD { + let predicate = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? + .await?; + let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; + Ok(mask.intersect_by_rank(&predicate_mask)) + } else { + let predicate = reader + .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? + .await?; + let predicate_mask = predicate.fill_null(false)?.execute::(&mut ctx)?; + Ok(mask & &predicate_mask) + } + })) + } + + /// Reads only the list children needed to evaluate `expr`. + /// + /// Validity-only expressions avoid offsets and elements, length expressions read offsets and + /// validity, and general expressions reconstruct a list from all applicable children. + fn projection_evaluation( + &self, + row_range: &Range, + expr: &BoundExpression, + mask: MaskFuture, + ) -> VortexResult { + // Read as little as possible based on which list children the expression needs. + match get_necessary_bound_list_children(expr) { + ListChildrenNeeded::Validity => self.project_validity(row_range, expr, mask), + ListChildrenNeeded::OffsetsAndValidity => { + self.project_offsets_validity(row_range, expr, mask) + } + ListChildrenNeeded::All => self.project_all(row_range, expr, mask), + } + } +} + +/// Converts a natural boundary from element-row space into an approximate outer-row scan split. +/// +/// Scan splits must be expressed in the list layout's outer-row space, but the elements child +/// reports its natural boundaries in element-row space. Translating a boundary exactly would +/// require consulting the list offsets, so this function instead preserves its relative position: +/// +/// ```text +/// element_split / element_row_count ≈ outer_split / outer_row_count +/// ``` +/// +/// The relative position is first rounded onto a grid containing at most `max_split_count` scan +/// ranges, then mapped into outer-row space. Multiple element boundaries may therefore map to the +/// same outer split and are deduplicated by the caller. With a grid size of 64, at most 63 interior +/// splits, and therefore 64 scan ranges, can be produced. +/// +/// The result is only a task-sizing hint. It is always between outer rows, but it is not guaranteed +/// to correspond exactly to the original physical element boundary. Endpoint boundaries are +/// omitted because they do not subdivide the scan +fn map_element_split_to_outer_grid( + element_split: u64, + element_row_count: u64, + outer_row_count: u64, + max_split_count: u64, +) -> Option { + if element_split == 0 + || element_split >= element_row_count + || outer_row_count == 0 + || max_split_count < 2 + { + return None; + } + debug_assert!(max_split_count.is_power_of_two()); + + let grid_index = (u128::from(element_split) * u128::from(max_split_count) + + u128::from(element_row_count / 2)) + / u128::from(element_row_count); + if grid_index == 0 || grid_index >= u128::from(max_split_count) { + return None; + } + + let outer_split = grid_index * u128::from(outer_row_count) / u128::from(max_split_count); + let outer_split = u64::try_from(outer_split) + .vortex_expect("Outer split is bounded by the list layout row count"); + (outer_split != 0 && outer_split < outer_row_count).then_some(outer_split) +} + +/// Fetch the validity child for `row_range` under `mask`, yielding `None` for a non-nullable list +/// (which has no validity child). +fn fetch_validity( + validity: Option<&LayoutReaderRef>, + row_range: &Range, + mask: MaskFuture, +) -> VortexResult { + let fut = validity + .map(|v| { + let root = root().bind(v.dtype())?; + v.projection_evaluation(row_range, &root, mask) + }) + .transpose()?; + Ok(async move { + match fut { + Some(f) => f.await.map(Some), + None => Ok(None), + } + } + .boxed()) +} + +/// Read `offsets[0]` and `offsets[-1]` and return the elements range they bound. +fn elements_range_from_offsets( + offsets: &ArrayRef, + session: &VortexSession, +) -> VortexResult> { + if offsets.is_empty() { + return Ok(0..0); + } + let mut exec_ctx = session.create_execution_ctx(); + let start = offsets + .execute_scalar(0, &mut exec_ctx)? + .as_primitive() + .as_::() + .vortex_expect("offset value fits in u64"); + let end = offsets + .execute_scalar(offsets.len() - 1, &mut exec_ctx)? + .as_primitive() + .as_::() + .vortex_expect("offset value fits in u64"); + Ok(start..end) +} + +/// The elements of the selected valid lists, and offsets that index them once the other elements +/// are dropped. +struct CompactedLists { + /// The element rows from the first to the last of the lists. + elements_range: Range, + /// The elements of the selected valid lists, relative to `elements_range`. + elements_mask: Mask, + /// The offsets of the selected lists into the masked elements. Null lists are empty. + offsets: Buffer, +} + +/// Compacts the lists that `offsets` describe to the `selected` ones, keeping only the elements +/// of the `valid` ones, as `list_transform` does before it runs a lambda that can fail. +fn compact_lists(offsets: &[u64], selected: &Mask, valid: &Mask) -> VortexResult { + let (Some(&first), Some(&last)) = (offsets.first(), offsets.last()) else { + vortex_bail!("List offsets must hold at least one entry"); + }; + let mut slices: Vec<(usize, usize)> = Vec::new(); + let mut compacted = BufferMut::::with_capacity(selected.true_count() + 1); + let mut kept = 0; + compacted.push(kept); + for (row, (selected, valid)) in selected.iter().zip(valid.iter()).enumerate() { + if !selected { + continue; + } + let (start, end) = (offsets[row], offsets[row + 1]); + if valid && start < end { + kept += end - start; + let slice = ( + usize::try_from(start - first)?, + usize::try_from(end - first)?, + ); + match slices.last_mut() { + Some((_, previous_end)) if *previous_end == slice.0 => *previous_end = slice.1, + _ => slices.push(slice), + } + } + compacted.push(kept); + } + Ok(CompactedLists { + elements_range: first..last, + elements_mask: Mask::from_slices(usize::try_from(last - first)?, slices), + offsets: compacted.freeze(), + }) +} + +/// Subtract `first` from every offset so they index into a sliced `elements[first..]` buffer that +/// starts at zero. +fn rebase_offsets(offsets: ArrayRef, first: u64) -> VortexResult { + if first == 0 { + return Ok(offsets); + } + let constant = ConstantArray::new(first, offsets.len()) + .into_array() + .cast(offsets.dtype().clone())?; + offsets.binary(constant, Operator::Sub) +} + +/// Compute `offsets[i + 1] - offsets[i]` as the unmasked list length values. +fn list_lengths_from_offsets(offsets: ArrayRef) -> VortexResult { + let len = offsets.len().saturating_sub(1); + offsets + .slice(1..offsets.len())? + .binary(offsets.slice(0..len)?, Operator::Sub) +} + +fn apply_lengths_validity( + lengths: ArrayRef, + validity: Option, + nullability: Nullability, +) -> VortexResult { + let len = lengths.len(); + let lengths = lengths.cast(DType::Primitive(PType::U64, nullability))?; + + if matches!(nullability, Nullability::Nullable) { + lengths.mask(create_validity(validity, nullability).to_array(len)) + } else { + Ok(lengths) + } +} diff --git a/vortex-layout/src/layouts/list/reader/tests.rs b/vortex-layout/src/layouts/list/reader/tests.rs new file mode 100644 index 00000000000..7b25d6faa1f --- /dev/null +++ b/vortex-layout/src/layouts/list/reader/tests.rs @@ -0,0 +1,989 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use rstest::rstest; +use vortex_array::ArrayContext; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::FieldNames; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::cast; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::gt; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::var; +use vortex_buffer::buffer; +use vortex_io::session::RuntimeSession; +use vortex_io::session::RuntimeSessionExt; +use vortex_session::VortexSession; + +use super::*; +use crate::LayoutRef; +use crate::LayoutStrategy; +use crate::layouts::chunked::writer::ChunkedLayoutStrategy; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::list::writer::ListLayoutStrategy; +use crate::layouts::repartition::RepartitionStrategy; +use crate::layouts::repartition::RepartitionWriterOptions; +use crate::layouts::struct_::writer::StructStrategy; +use crate::scan::split_by::SplitBy; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSource; +use crate::segments::TestSegments; +use crate::sequence::SequenceId; +use crate::sequence::SequentialArrayStreamExt; +use crate::session::LayoutSession; +use crate::test::SESSION; + +/// Validity-class projections (`is_null` / `is_not_null` of the list) round-trip through the +/// validity-only read path, for both nullable and non-nullable lists. +#[rstest] +// `create_basic_list_array(true)` has validity `[true, false, true]`. +#[case::nullable(true, vec![true, false, true])] +#[case::non_nullable(false, vec![true, true, true])] +#[tokio::test] +async fn projection_validity_class( + #[case] nullable: bool, + #[case] valid: Vec, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let not_null_expr = is_not_null(root()).bind(reader.dtype())?; + let not_null = reader + .projection_evaluation(&(0..3), ¬_null_expr, MaskFuture::new_true(3))? + .await?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(not_null, BoolArray::from_iter(valid.clone()), &mut exec_ctx); + + let is_null_expr = is_null(root()).bind(reader.dtype())?; + let is_null_res = reader + .projection_evaluation(&(0..3), &is_null_expr, MaskFuture::new_true(3))? + .await?; + assert_arrays_eq!( + is_null_res, + BoolArray::from_iter(valid.iter().map(|v| !v).collect::>()), + &mut exec_ctx + ); + + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_reads_offsets() -> VortexResult<()> { + let list = create_basic_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, buffer![2u64, 2, 1].into_array(), &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_preserves_validity() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = + PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_list_length_applies_sparse_mask() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let mask = Mask::from_iter([false, true, true]); + let expr = list_length(root()).bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask))? + .await?; + + let expected = PrimitiveArray::from_option_iter::([None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_cast_list_length() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = cast( + list_length(root()), + DType::Primitive(PType::I64, Nullability::Nullable), + ) + .bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = + PrimitiveArray::from_option_iter::([Some(2), None, Some(1)]).into_array(); + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_list_length() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = gt(list_length(root()), lit(1u64)).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + assert_eq!(result, Mask::from_iter([true, false, false])); + Ok(()) +} + +#[rstest] +#[case::is_not_null_nullable(true, is_not_null(root()), Mask::from_iter([true, false, true]))] +#[case::is_not_null_non_nullable(false, is_not_null(root()), Mask::new_true(3))] +#[case::is_null_nullable(true, is_null(root()), Mask::from_iter([false, true, false]))] +#[case::is_null_non_nullable(false, is_null(root()), Mask::new_false(3))] +#[tokio::test] +async fn filter_evaluation_validity_class( + #[case] nullable: bool, + #[case] expr: Expression, + #[case] expected: Mask, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = expr.bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::new_true(3))? + .await?; + + assert_eq!(result, expected); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_intersects_with_input_mask() -> VortexResult<()> { + let list = create_basic_list_array(true); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let input_mask = Mask::from_iter([true, true, false]); + let expr = is_not_null(root()).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..3), &expr, MaskFuture::ready(input_mask))? + .await?; + + assert_eq!(result, Mask::from_iter([true, false, false])); + Ok(()) +} + +#[tokio::test] +async fn filter_evaluation_sparse_mask_maps_by_rank() -> VortexResult<()> { + let list = create_six_list_array(); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let input_mask = Mask::from_iter([false, false, false, false, true, false]); + let expr = is_not_null(root()).bind(reader.dtype())?; + let result = reader + .filter_evaluation(&(0..6), &expr, MaskFuture::ready(input_mask))? + .await?; + + assert_eq!( + result, + Mask::from_iter([false, false, false, false, true, false]) + ); + Ok(()) +} + +fn flat_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default() +} + +fn layout_test_session() -> VortexSession { + VortexSession::empty() + .with::() + .with::() +} + +async fn write_layout( + strategy: &S, + array: ArrayRef, +) -> VortexResult<(Arc, LayoutRef, VortexSession)> { + let session = layout_test_session().with_tokio(); + let segments = Arc::new(TestSegments::default()); + let segments_ref: Arc = Arc::::clone(&segments); + let (ptr, eof) = SequenceId::root().split(); + let stream = array.to_array_stream().sequenced(ptr); + let layout = strategy + .write_stream( + ArrayContext::empty().into(), + segments, + stream, + eof, + &session, + ) + .await?; + Ok((segments_ref, layout, session)) +} + +fn materialize_u64_array(array: ArrayRef) -> Vec { + let mut ctx = SESSION.create_execution_ctx(); + array + .execute::(&mut ctx) + .unwrap() + .as_slice::() + .to_vec() +} + +fn create_basic_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, false, true]).into_array()) + } else { + Validity::NonNullable + }; + + ListArray::try_new( + buffer![1i32, 2, 3, 4, 5].into_array(), + buffer![0u32, 2, 4, 5].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +fn create_six_list_array() -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = + Validity::Array(BoolArray::from_iter([true, false, true, false, true, true]).into_array()); + + ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 1, 2, 3, 4, 5, 6].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +#[tokio::test] +async fn fetch_offsets_includes_extra_endpoint() -> VortexResult<()> { + let list = create_basic_list_array(false); + + let (segments, layout, session) = write_layout(&flat_list_strategy(), list).await?; + let ctx = LayoutReaderContext::new(); + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + let reader = reader + .as_any() + .downcast_ref::() + .expect("ListReader"); + + let offsets = reader.fetch_raw_offsets(&(1..3))?.await?; + assert_eq!(materialize_u64_array(offsets), vec![2u64, 4, 5]); + + Ok(()) +} + +#[rstest] +#[case::full_range(0..3, false)] +#[case::partial_start(0..2, false)] +#[case::partial_end(1..3, false)] +#[case::middle_single(1..2, false)] +#[case::empty_range(1..1, false)] +#[case::full_range_null(0..3, true)] +#[tokio::test] +async fn projection_evaluation_round_trips( + #[case] row_range: Range, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_basic_list_array(nullable); + let ctx = LayoutReaderContext::new(); + + let len = usize::try_from(row_range.end - row_range.start)?; + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::new_true(len))? + .await?; + + let expected = + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[tokio::test] +async fn projection_evaluation_applies_mask() -> VortexResult<()> { + let list = create_basic_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let mask = Mask::from_iter([true, false, true]); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..3), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// Build a list with 5 rows and lengths [2, 3, 0, 3, 2]. +fn create_wider_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) + } else { + Validity::NonNullable + }; + ListArray::try_new( + buffer![10i32, 11, 20, 21, 22, 30, 31, 32, 40, 41].into_array(), + buffer![0u32, 2, 5, 5, 8, 10].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +/// Sparse row masks over a whole chunk round-trip: the whole-chunk read is filtered by the +/// mask in memory. +#[rstest] +#[case::single_middle(Mask::from_iter([false, false, false, true, false]), false)] +#[case::two_far_apart(Mask::from_iter([true, false, false, true, false]), false)] +#[case::boundaries(Mask::from_iter([true, false, false, false, true]), false)] +#[case::kept_empty_row(Mask::from_iter([false, false, true, false, false]), false)] +#[case::sparse_nullable(Mask::from_iter([true, false, true, false, true]), true)] +#[case::all_false(Mask::new_false(5), false)] +#[tokio::test] +async fn projection_evaluation_sparse_mask_round_trips( + #[case] mask: Mask, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_wider_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// A partial range against a single flat elements segment takes the bounded path. The flat +/// reader may still fetch its whole segment, but the list reader reconstructs only the requested +/// element range. +#[tokio::test] +async fn projection_evaluation_partial_range_bounded() -> VortexResult<()> { + let list = create_wider_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = write_layout(&flat_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(1..4), &expr, MaskFuture::new_true(3))? + .await?; + + let expected = list.slice(1..4)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[test] +fn maps_element_splits_to_outer_grid() { + assert_eq!(map_element_split_to_outer_grid(0, 100, 100, 8), None); + assert_eq!(map_element_split_to_outer_grid(20, 100, 100, 8), Some(25)); + assert_eq!(map_element_split_to_outer_grid(25, 100, 100, 8), Some(25)); + assert_eq!(map_element_split_to_outer_grid(50, 100, 100, 8), Some(50)); + assert_eq!(map_element_split_to_outer_grid(75, 100, 100, 8), Some(75)); + assert_eq!(map_element_split_to_outer_grid(100, 100, 100, 8), None); + + let mut splits = (1..1_000) + .filter_map(|split| { + map_element_split_to_outer_grid(split, 1_000, 100_000, MIN_LIST_SPLIT_COUNT) + }) + .collect::>(); + splits.dedup(); + + let expected = (1..MIN_LIST_SPLIT_COUNT) + .map(|grid_index| grid_index * 100_000 / MIN_LIST_SPLIT_COUNT) + .collect::>(); + assert_eq!(splits, expected); +} + +#[rstest] +#[case::empty(0, 64)] +#[case::small(100_000, 64)] +#[case::floor_boundary(64 * 8192, 64)] +#[case::past_floor(64 * 8192 + 1, 128)] +#[case::million(1_000_000, 128)] +#[case::ten_million(10_000_000, 2048)] +fn split_grid_grows_with_row_count(#[case] outer_row_count: u64, #[case] expected: u64) { + assert_eq!(list_split_grid_size(outer_row_count), expected); +} + +#[tokio::test] +async fn nested_list_propagates_element_splits() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let inner = ListArray::try_new( + PrimitiveArray::from_iter(0..128_i32).into_array(), + PrimitiveArray::from_iter((0..=8_u32).map(|idx| idx * 16)).into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let outer = ListArray::try_new( + inner, + buffer![0u32, 2, 4, 6, 8].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + + let inner_strategy = ListLayoutStrategy::default().with_elements(chunked_elements_strategy()); + let strategy = ListLayoutStrategy::default().with_elements(Arc::new(inner_strategy)); + let (segments, layout, session) = write_layout(&strategy, outer).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + + let splits = SplitBy::Layout.splits(reader.as_ref(), &(0..4), &[FieldMask::All])?; + assert_eq!(splits, vec![0, 1, 2, 3, 4]); + Ok(()) +} + +/// A list strategy whose `elements` child is repartitioned into two-element chunks, so the +/// reader takes the bounded (chunk-skipping) path for strict sub-ranges. Offsets stay flat. +fn chunked_elements_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default().with_elements(chunked_elements_strategy()) +} + +fn chunked_elements_strategy() -> Arc { + Arc::new(RepartitionStrategy::new( + ChunkedLayoutStrategy::new(FlatLayoutStrategy::default()), + RepartitionWriterOptions { + block_size_minimum: 0, + block_len_multiple: 2, + block_size_target: None, + canonicalize: true, + }, + )) +} + +/// The chunked-elements strategy must actually produce a chunked `elements` layout, otherwise +/// the reader would silently take the whole-chunk path and the bounded read would be untested. +#[tokio::test] +async fn chunked_elements_produces_chunked_layout() -> VortexResult<()> { + let list = create_wider_list_array(false); + let (_segments, layout, _session) = + write_layout(&chunked_elements_list_strategy(), list).await?; + let tree = layout.display_tree().to_string(); + assert!( + tree.contains("elements: vortex.chunked"), + "elements should be chunked:\n{tree}" + ); + Ok(()) +} + +/// A sparse mask must remain selective even when the requested row range covers the complete +/// local list layout. The selected first list touches one element chunk plus the offsets +/// segment; reading all five element chunks would make the count six. +#[tokio::test] +async fn full_range_sparse_mask_crops_element_read() -> VortexResult<()> { + let list = create_wider_list_array(false); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = + write_layout(&chunked_elements_list_strategy(), list.clone()).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader("".into(), Arc::clone(&source) as _, &session, &ctx)?; + + let mask = Mask::from_iter([true, false, false, false, false]); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..5), &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let expected = list.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + assert_eq!(source.requests(), 2); + Ok(()) +} + +/// With chunked elements, sub-range projections take the bounded read path. Every +/// range/mask/nullability combination must match the same projection over the ground-truth +/// array (`list.slice(range).filter(mask)`). +#[rstest] +#[case::full_all_true(0..5, Mask::new_true(5), false)] +#[case::subrange_all_true(1..4, Mask::new_true(3), false)] +#[case::subrange_sparse(1..4, Mask::from_iter([true, false, true]), false)] +#[case::partial_start(0..2, Mask::new_true(2), false)] +#[case::partial_end(2..5, Mask::new_true(3), false)] +#[case::single_non_empty(0..1, Mask::new_true(1), false)] +#[case::single_empty_row(2..3, Mask::from_iter([true]), false)] +#[case::empty_range(2..2, Mask::new_true(0), false)] +#[case::subrange_all_false(1..4, Mask::new_false(3), false)] +#[case::subrange_single_interior(0..4, Mask::from_iter([false, true, false, false]), false)] +#[case::subrange_sparse_nullable(1..4, Mask::from_iter([true, false, true]), true)] +#[case::partial_end_nullable(2..5, Mask::new_true(3), true)] +#[tokio::test] +async fn chunked_elements_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[case] nullable: bool, +) -> VortexResult<()> { + let list = create_wider_list_array(nullable); + let ctx = LayoutReaderContext::new(); + let (segments, layout, session) = + write_layout(&chunked_elements_list_strategy(), list.clone()).await?; + let reader = layout.new_reader("".into(), segments, &session, &ctx)?; + + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask.clone()))? + .await?; + + let sliced = list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)?; + let expected = sliced.filter(mask)?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +/// Lists `[0, 1, 2]`, `[]`, `[3, 4, 5]`, `[6, 7]`, `[8, 9]`. When nullable, the third is null +/// and keeps its elements. +fn create_ten_element_list_array(nullable: bool) -> ArrayRef { + let mut ctx = SESSION.create_execution_ctx(); + let validity = if nullable { + Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()) + } else { + Validity::NonNullable + }; + ListArray::try_new( + PrimitiveArray::from_iter(0..10i32).into_array(), + buffer![0u32, 3, 3, 6, 8, 10].into_array(), + validity, + &mut ctx, + ) + .expect("array is valid") + .into_array() +} + +/// Slices of one list share its whole `elements`, so every chunk but the first starts at a +/// nonzero offset and every chunk but the last leaves trailing elements unreferenced. +fn sliced_chunks(array: &ArrayRef, cuts: &[usize]) -> VortexResult> { + let mut bounds = vec![0]; + bounds.extend_from_slice(cuts); + bounds.push(array.len()); + bounds + .windows(2) + .map(|range| array.slice(range[0]..range[1])) + .collect() +} + +fn chunked_flat() -> Arc { + Arc::new(ChunkedLayoutStrategy::new(FlatLayoutStrategy::default())) +} + +/// A list strategy that keeps every chunk, so a multi-chunk stream reaches the list writer. +fn chunked_list_strategy() -> ListLayoutStrategy { + ListLayoutStrategy::default() + .with_elements(chunked_flat()) + .with_offsets(chunked_flat()) + .with_validity(chunked_flat()) +} + +async fn assert_round_trips( + strategy: &S, + chunks: Vec, + expected: ArrayRef, +) -> VortexResult<()> { + let chunked = ChunkedArray::try_new(chunks, expected.dtype().clone())?.into_array(); + let (segments, layout, session) = write_layout(strategy, chunked).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + + let len = expected.len(); + let expr = root().bind(reader.dtype())?; + let result = reader + .projection_evaluation(&(0..len as u64), &expr, MaskFuture::new_true(len))? + .await?; + let mut exec_ctx = session.create_execution_ctx(); + assert_arrays_eq!(result, expected, &mut exec_ctx); + Ok(()) +} + +#[rstest] +#[case::one_cut(&[2], false, false)] +#[case::two_cuts(&[1, 3], false, false)] +#[case::null_and_empty_at_cuts(&[1, 3], true, false)] +#[case::list_view_chunks(&[1, 3], true, true)] +#[case::non_nullable_list_view_chunks(&[1, 3], false, true)] +#[tokio::test] +async fn sliced_list_chunks_round_trip( + #[case] cuts: &[usize], + #[case] nullable: bool, + #[case] as_list_view: bool, +) -> VortexResult<()> { + let list = create_ten_element_list_array(nullable); + let source = if as_list_view { + let mut ctx = SESSION.create_execution_ctx(); + list.clone() + .execute::(&mut ctx)? + .into_array() + } else { + list.clone() + }; + let chunks = sliced_chunks(&source, cuts)?; + assert_round_trips(&chunked_list_strategy(), chunks, list).await +} + +#[tokio::test] +async fn sliced_nested_list_chunks_round_trip() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let inner = ListArray::try_new( + PrimitiveArray::from_iter(0..12i32).into_array(), + buffer![0u32, 2, 2, 5, 7, 9, 12].into_array(), + Validity::NonNullable, + &mut ctx, + )? + .into_array(); + let outer = ListArray::try_new( + inner, + buffer![0u32, 2, 3, 5, 6].into_array(), + Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()), + &mut ctx, + )? + .into_array(); + + let strategy = chunked_list_strategy().with_elements(Arc::new(chunked_list_strategy())); + assert_round_trips(&strategy, sliced_chunks(&outer, &[1, 2])?, outer).await +} + +/// Lists `[{a, 1}, null]`, null (hiding `[{c, i32::MAX}]`), `[]`, `[{null, 3}, {e, 4}]` and +/// `[{f, i32::MAX}]`, of nullable `{sku: utf8?, qty: i32}` elements. +fn create_items_list_array() -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let elements = StructArray::try_new( + FieldNames::from(["sku", "qty"]), + vec![ + VarBinViewArray::from_iter_nullable_str([ + Some("a"), + Some("b"), + Some("c"), + None, + Some("e"), + Some("f"), + ]) + .into_array(), + buffer![1i32, 2, i32::MAX, 3, 4, i32::MAX].into_array(), + ], + 6, + Validity::from_iter([true, false, true, true, true, true]), + )? + .into_array(); + Ok(ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 5, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// A list strategy that writes struct elements as a struct layout, so each element field and the +/// element validity is a flat layout of one segment. +fn struct_elements_list_strategy() -> ListLayoutStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + ListLayoutStrategy::default() + .with_elements(Arc::new(StructStrategy::new(Arc::clone(&flat), flat))) +} + +fn sku_lambda() -> VortexResult { + Lambda::new(["x"], get_item("sku", var("x"))) +} + +fn qty_lambda() -> VortexResult { + Lambda::new(["x"], get_item("qty", var("x"))) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on `i32::MAX`. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// Projects `expr` over `row_range` under `mask` and counts the segments the read requests. +async fn project_counting( + list: ArrayRef, + expr: &Expression, + row_range: Range, + mask: Mask, +) -> VortexResult<(ArrayRef, usize)> { + let (segments, layout, session) = write_layout(&struct_elements_list_strategy(), list).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &session, + &LayoutReaderContext::new(), + )?; + let expr = expr.bind(reader.dtype())?; + let result = reader + .projection_evaluation(&row_range, &expr, MaskFuture::ready(mask))? + .await?; + // Execute so lazy results surface their errors before the count is read. + let result = result + .execute::(&mut session.create_execution_ctx())? + .0 + .into_array(); + Ok((result, source.requests())) +} + +/// The expected projection: `expr` over the rows of `list` in `row_range` that `mask` selects. +fn expected_projection( + list: &ArrayRef, + expr: &Expression, + row_range: &Range, + mask: Mask, +) -> VortexResult { + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)? + .filter(mask)? + .apply(expr) +} + +/// A projection that reads the elements only through `list_transform` lambdas reads the element +/// columns those lambdas read, plus the offsets, the list validity and the element validity. The +/// stored list has five segments: offsets, list validity, element validity, `sku` and `qty`. +#[rstest] +#[case::root(root(), 5)] +#[case::sku(list_transform(root(), sku_lambda()?), 4)] +#[case::qty(list_transform(root(), qty_lambda()?), 4)] +#[case::both( + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("qtys", list_transform(root(), qty_lambda()?)), + ], + Nullability::NonNullable, + ), + 5 +)] +#[case::with_length( + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("len", list_length(root())), + ], + Nullability::NonNullable, + ), + 4 +)] +#[case::predicate(list_contains(list_transform(root(), sku_lambda()?), lit("e")), 4)] +#[tokio::test] +async fn element_projection_reads_needed_fields( + #[case] expr: Expression, + #[case] segments: usize, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let (result, requests) = project_counting(list.clone(), &expr, 0..5, Mask::new_true(5)).await?; + let expected = list.apply(&expr)?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// Pushed-down lambdas keep the semantics of `list_transform` for null lists, empty lists and +/// null elements, over every read path: full, bounded and sparse. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(1..4, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, true, false, true]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[case::empty_list_only(2..3, Mask::new_true(1))] +#[case::none_selected(0..5, Mask::new_false(5))] +#[case::empty_range(2..2, Mask::new_true(0))] +#[tokio::test] +async fn element_projection_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + list_transform(root(), sku_lambda()?), + list_transform(root(), qty_lambda()?), + pack( + [ + ("skus", list_transform(root(), sku_lambda()?)), + ("valid", is_not_null(root())), + ], + Nullability::NonNullable, + ) + )] + expr: Expression, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let expected = expected_projection(&list, &expr, &row_range, mask.clone())?; + let (result, _) = project_counting(list, &expr, row_range, mask).await?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists, as in memory: +/// the `i32::MAX` under the null list never reaches it, nor does the one in the last list when the +/// mask leaves that list out. Only `qty` is read. +#[rstest] +#[case::full_without_last(0..4, Mask::new_true(4))] +#[case::masked_last(0..5, Mask::from_iter([true, true, true, true, false]))] +#[case::sparse(0..5, Mask::from_iter([false, true, false, true, false]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[tokio::test] +async fn fallible_lambda_runs_on_selected_valid_lists( + #[case] row_range: Range, + #[case] mask: Mask, +) -> VortexResult<()> { + let list = create_items_list_array()?; + let expr = qty_plus_one()?; + let expected = expected_projection(&list, &expr, &row_range, mask.clone())?; + let (result, requests) = project_counting(list, &expr, row_range, mask).await?; + assert_arrays_eq!(result, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(requests, 4); + Ok(()) +} + +/// The reader fails where the lambda fails in memory: on the `i32::MAX` of a selected valid list. +#[tokio::test] +async fn fallible_lambda_fails_on_selected_overflow() -> VortexResult<()> { + let list = create_items_list_array()?; + let expr = qty_plus_one()?; + let mut ctx = SESSION.create_execution_ctx(); + assert!( + list.clone() + .apply(&expr)? + .execute::(&mut ctx) + .is_err() + ); + assert!( + project_counting(list, &expr, 4..5, Mask::new_true(1)) + .await + .is_err() + ); + Ok(()) +} + +/// A filter through a pushed-down lambda reads only the element column it tests. +#[rstest] +#[case::dense(Mask::new_true(5))] +#[case::sparse(Mask::from_iter([false, false, false, true, false]))] +#[tokio::test] +async fn filter_evaluation_pushes_lambda(#[case] input: Mask) -> VortexResult<()> { + let list = create_items_list_array()?; + let (segments, layout, session) = + write_layout(&struct_elements_list_strategy(), list.clone()).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &session, + &LayoutReaderContext::new(), + )?; + + let filter = list_contains(list_transform(root(), sku_lambda()?), lit("e")); + let result = reader + .filter_evaluation( + &(0..5), + &filter.bind(reader.dtype())?, + MaskFuture::ready(input.clone()), + )? + .await?; + + let mut ctx = session.create_execution_ctx(); + let matches = list + .apply(&filter)? + .fill_null(false)? + .execute::(&mut ctx)?; + assert_eq!(result, &input & &matches); + assert_eq!(source.requests(), 4); + Ok(()) +} + +/// Every split sees the same element projection, so the elements reader's identity-keyed caches +/// stay warm. +#[tokio::test] +async fn element_projection_is_cached() -> VortexResult<()> { + let list = create_items_list_array()?; + let (segments, layout, session) = write_layout(&struct_elements_list_strategy(), list).await?; + let reader = layout.new_reader("".into(), segments, &session, &LayoutReaderContext::new())?; + let reader = reader + .as_any() + .downcast_ref::() + .expect("ListReader"); + + let expr = list_transform(root(), sku_lambda()?).bind(reader.dtype())?; + let first = reader.element_projection(&expr)?; + assert!(Arc::ptr_eq(&first, &reader.element_projection(&expr)?)); + Ok(()) +} diff --git a/vortex-layout/src/layouts/struct_/reader.rs b/vortex-layout/src/layouts/struct_/reader.rs index a7127f17301..8b42400176f 100644 --- a/vortex-layout/src/layouts/struct_/reader.rs +++ b/vortex-layout/src/layouts/struct_/reader.rs @@ -337,6 +337,21 @@ fn expand_struct_root( }); } + // A strict function of a field is null wherever the struct is, so it can run on the + // field inside the struct validity. It then stays with the field when the expression + // is partitioned, and the field reader can push it down, as a list reader pushes the + // lambda of `list_transform($.items, x -> x.sku)` into its elements. Only a function + // that cannot fail may run on the values that null structs hide. + if let Some(validity) = validity + && is_strict_field_function(&node) + { + return Ok(Transformed { + value: mask(node, validity.clone()), + changed: true, + order: TraversalOrder::Skip, + }); + } + let Some(scalar_fn) = node.as_scalar() else { return Ok(Transformed::no(node)); }; @@ -405,6 +420,20 @@ fn expand_struct_root( .into_inner()) } +/// Whether `expr` applies only strict functions of one argument that cannot fail to a field of the +/// root, as `list_transform($.items, x -> x.sku)` does. +fn is_strict_field_function(expr: &BoundExpression) -> bool { + let [child] = expr.children() else { + return false; + }; + let strict = expr.as_scalar().is_some_and(|scalar_fn| { + let signature = scalar_fn.signature(); + signature.is_strict() && signature.is_infallible() + }); + strict + && ((child.is::() && child.child(0).is_root()) || is_strict_field_function(child)) +} + // Same as make_bound_free_field_annotator, but handles is_not_null($) as the // struct's own validity coordinate fn make_struct_item_annotator( @@ -698,6 +727,7 @@ mod tests { use vortex_array::VortexSessionExecute; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; @@ -712,13 +742,17 @@ mod tests { use vortex_array::dtype::RESERVED_VALIDITY_FIELD_NAME; use vortex_array::dtype::StructFields; use vortex_array::expr::Expression; + use vortex_array::expr::Lambda; use vortex_array::expr::and; + use vortex_array::expr::checked_add; use vortex_array::expr::col; use vortex_array::expr::eq; use vortex_array::expr::get_item; use vortex_array::expr::gt; use vortex_array::expr::is_not_null; use vortex_array::expr::is_null; + use vortex_array::expr::list_length; + use vortex_array::expr::list_transform; use vortex_array::expr::lit; use vortex_array::expr::lt; use vortex_array::expr::mask; @@ -728,6 +762,7 @@ mod tests { use vortex_array::expr::root; use vortex_array::expr::select; use vortex_array::expr::select_exclude; + use vortex_array::expr::var; use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_buffer::buffer; @@ -2332,4 +2367,115 @@ mod tests { Ok(()) }) } + + /// Writes `{s: {inner: {x, y}, items: list<{sku, qty}>}?}` with the list layout, where `s` is + /// null in row 1, and returns the table too. The item of row 1 has the SKU `i32::MAX`, which + /// overflows when added to. + #[fixture] + fn nullable_struct_with_nested_columns() -> (Arc, LayoutRef, ArrayRef) { + let mut ctx = SESSION.create_execution_ctx(); + let inner = StructArray::try_from_iter([ + ("x", buffer![1i32, 2, 3].into_array()), + ("y", buffer![4i32, 5, 6].into_array()), + ]) + .unwrap(); + let elements = StructArray::try_from_iter([ + ("sku", buffer![10i32, 11, i32::MAX, 13].into_array()), + ("qty", buffer![20i32, 21, 22, 23].into_array()), + ]) + .unwrap(); + let items = ListArray::try_new( + elements.into_array(), + buffer![0u32, 2, 3, 4].into_array(), + Validity::NonNullable, + &mut ctx, + ) + .unwrap(); + let s = StructArray::try_from_iter_with_validity( + [("inner", inner.into_array()), ("items", items.into_array())], + Validity::Array(BoolArray::from_iter([true, false, true]).into_array()), + ) + .unwrap(); + let table = StructArray::try_from_iter([("s", s.into_array())]) + .unwrap() + .into_array(); + + let segments = Arc::new(TestSegments::default()); + let (ptr, eof) = SequenceId::root().split(); + let strategy = TableStrategy::new( + Arc::new(FlatLayoutStrategy::default()), + Arc::new(FlatLayoutStrategy::default()), + ) + .with_list_layout(); + let segments2 = Arc::::clone(&segments); + let stream = table.to_array_stream().sequenced(ptr); + let layout = block_on(|handle| async move { + let session = new_session().with_handle(handle); + strategy + .write_stream( + ArrayContext::empty().into(), + segments2, + stream, + eof, + &session, + ) + .await + }) + .unwrap(); + + (segments, layout, table) + } + + /// A strict function of a field of a nullable struct reaches the field reader inside the + /// struct validity, so the field reader reads only the columns the function needs. + #[rstest] + // The validity of `s` and `s.inner.x`, not `s.inner.y`. + #[case::nested_field(get_item("x", get_item("inner", get_item("s", root()))), 2)] + // The validity of `s`, the offsets of `s.items` and the `sku` elements, not the `qty` ones. + #[case::list_transform( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], get_item("sku", var("item")))?, + ), + 3 + )] + // The validity of `s` and the offsets of `s.items`, not their elements. + #[case::list_length(list_length(get_item("items", get_item("s", root()))), 2)] + // A lambda that can fail must not run on the items of null structs, where it would overflow, + // so it stays outside the struct validity and the items are read whole. + #[case::fallible_lambda( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], checked_add(get_item("sku", var("item")), lit(1i32)))?, + ), + 4 + )] + fn test_strict_function_of_nullable_struct_field_reads_needed_columns( + #[from(nullable_struct_with_nested_columns)] (segments, layout, table): ( + Arc, + LayoutRef, + ArrayRef, + ), + #[case] expr: Expression, + #[case] expected_requests: usize, + ) -> VortexResult<()> { + let source = Arc::new(CountingSegmentSource::new(segments)); + let reader = layout.new_reader( + "".into(), + Arc::clone(&source) as _, + &SESSION, + &Default::default(), + )?; + let bound = expr.bind(reader.dtype())?; + let project = reader.projection_evaluation(&(0..3), &bound, MaskFuture::new_true(3))?; + let result = block_on(move |_| project)?; + + assert_arrays_eq!( + result, + table.apply(&expr)?, + &mut SESSION.create_execution_ctx() + ); + assert_eq!(source.requests(), expected_requests); + Ok(()) + } } diff --git a/vortex-layout/src/scan/v2/tests/lists.rs b/vortex-layout/src/scan/v2/tests/lists.rs new file mode 100644 index 00000000000..3df254cdb7c --- /dev/null +++ b/vortex-layout/src/scan/v2/tests/lists.rs @@ -0,0 +1,456 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! List layouts on the planner-driven scan, mirroring the layout reader tests of the list layout +//! and of lists beneath a nullable struct. + +use std::ops::Range; +use std::sync::Arc; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_io::session::RuntimeSessionExt; +use vortex_mask::Mask; +use vortex_scan::strict_sorted_buffer::StrictSortedBuffer; + +use super::builder; +use super::chunked_flat; +use super::collect_scan; +use super::write_chunks; +use crate::LayoutStrategy; +use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::list::writer::ListLayoutStrategy; +use crate::layouts::struct_::writer::StructStrategy; +use crate::layouts::table::TableStrategy; +use crate::segments::CountingSegmentSource; +use crate::segments::SegmentSource; +use crate::test::new_session; + +/// Lists `[{a, 1}, null]`, null (hiding `[{c, i32::MAX}]`), `[]`, `[{null, 3}, {e, 4}]` and +/// `[{f, i32::MAX}]`, of nullable `{sku: utf8?, qty: i32}` elements. +fn items() -> VortexResult { + let mut ctx = new_session().create_execution_ctx(); + let elements = StructArray::try_new( + FieldNames::from(["sku", "qty"]), + vec![ + VarBinViewArray::from_iter_nullable_str([ + Some("a"), + Some("b"), + Some("c"), + None, + Some("e"), + Some("f"), + ]) + .into_array(), + buffer![1i32, 2, i32::MAX, 3, 4, i32::MAX].into_array(), + ], + 6, + Validity::from_iter([true, false, true, true, true, true]), + )? + .into_array(); + Ok(ListArray::try_new( + elements, + buffer![0u32, 2, 3, 3, 5, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// Writes struct elements as a struct layout, so the list has five segments: its offsets, its +/// validity, the element validity, `sku` and `qty`. +fn struct_elements_list_strategy() -> ListLayoutStrategy { + let flat: Arc = Arc::new(FlatLayoutStrategy::default()); + ListLayoutStrategy::default() + .with_elements(Arc::new(StructStrategy::new(Arc::clone(&flat), flat))) +} + +fn sku() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("sku", var("x")))?, + )) +} + +fn qty() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("qty", var("x")))?, + )) +} + +/// `list_transform(root, x -> x.qty + 1)`, which overflows on `i32::MAX`. +fn qty_plus_one() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + )) +} + +/// Writes `list` with `strategy`, then scans `expr` over the rows of `row_range` that `mask` +/// selects, filtered by `filter`, and counts the segments the scan requests. +async fn scan_counting( + strategy: &dyn LayoutStrategy, + list: &ArrayRef, + expr: &Expression, + filter: Option<&Expression>, + row_range: Range, + mask: &Mask, +) -> VortexResult<(ArrayRef, usize)> { + let session = new_session().with_tokio(); + let (segments, layout) = write_chunks(&session, strategy, vec![list.clone()]).await?; + let source = Arc::new(CountingSegmentSource::new(segments)); + let segments: Arc = Arc::::clone(&source); + let projection = expr.bind(layout.dtype())?; + let dtype = projection.dtype().clone(); + let start = row_range.start; + let rows = (0..mask.len()) + .filter(|&row| mask.value(row)) + .map(|row| start + row as u64); + let scan = builder(&session, &segments, &layout)? + .with_projection(projection) + .with_some_filter( + filter + .map(|filter| filter.bind(layout.dtype())) + .transpose()?, + ) + .with_row_range(row_range) + .with_row_indices(StrictSortedBuffer::try_new(Buffer::from_iter(rows))?); + let result = collect_scan(dtype, scan).await?; + // Execute so lazy results surface their errors before the count is read. + let result = result + .execute::(&mut session.create_execution_ctx())? + .0 + .into_array(); + Ok((result, source.requests())) +} + +/// `expr` over the rows of `list` in `row_range` that `mask` selects. +fn expected( + list: &ArrayRef, + expr: &Expression, + row_range: &Range, + mask: &Mask, +) -> VortexResult { + list.slice(usize::try_from(row_range.start)?..usize::try_from(row_range.end)?)? + .filter(mask.clone())? + .apply(expr) +} + +/// A projection reads only the list children it needs: the validity for a null check, the offsets +/// and the validity for the lengths, and for `list_transform` lambdas the element columns they +/// read, the element validity, the offsets and the validity. These are the reads of the layout +/// reader. +#[rstest] +#[case::root(root(), 5)] +#[case::is_null(is_null(root()), 1)] +#[case::length(list_length(root()), 2)] +#[case::sku(sku()?, 4)] +#[case::qty(qty()?, 4)] +#[case::both( + pack([("skus", sku()?), ("qtys", qty()?)], Nullability::NonNullable), + 5 +)] +#[case::with_length( + pack([("skus", sku()?), ("len", list_length(root()))], Nullability::NonNullable), + 4 +)] +#[case::predicate(list_contains(sku()?, lit("e")), 4)] +#[tokio::test] +async fn element_projection_reads_needed_fields( + #[case] expr: Expression, + #[case] segments: usize, +) -> VortexResult<()> { + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + &items()?, + &expr, + None, + 0..5, + &Mask::new_true(5), + ) + .await?; + let expected = items()?.apply(&expr)?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// Lists and their pushed-down lambdas keep the semantics of `list_transform` for null lists, +/// empty lists and null elements over any rows: whole, a range, or a selection. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(1..4, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, true, false, true]))] +#[case::null_list_only(1..2, Mask::new_true(1))] +#[case::empty_list_only(2..3, Mask::new_true(1))] +#[case::none_selected(0..5, Mask::new_false(5))] +#[case::empty_range(2..2, Mask::new_true(0))] +#[tokio::test] +async fn element_projection_round_trips( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + root(), + sku()?, + qty()?, + list_length(root()), + pack( + [("skus", sku()?), ("valid", is_not_null(root()))], + Nullability::NonNullable, + ) + )] + expr: Expression, +) -> VortexResult<()> { + let expected = expected(&items()?, &expr, &row_range, &mask)?; + let (result, _) = scan_counting( + &struct_elements_list_strategy(), + &items()?, + &expr, + None, + row_range, + &mask, + ) + .await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists, as in memory: +/// the `i32::MAX` under the null list never reaches it, nor does the one in the last list when the +/// selection leaves that list out. Only `qty`, the element validity, the offsets and the validity +/// are read, and no element at all when no selected list is valid. +#[rstest] +#[case::full_without_last(0..4, Mask::new_true(4), 4)] +#[case::unselected_last(0..5, Mask::from_iter([true, true, true, true, false]), 4)] +#[case::sparse(0..5, Mask::from_iter([false, true, false, true, false]), 4)] +#[case::null_list_only(1..2, Mask::new_true(1), 2)] +#[tokio::test] +async fn fallible_lambda_runs_on_selected_valid_lists( + #[case] row_range: Range, + #[case] mask: Mask, + #[case] segments: usize, +) -> VortexResult<()> { + let expr = qty_plus_one()?; + let expected = expected(&items()?, &expr, &row_range, &mask)?; + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + &items()?, + &expr, + None, + row_range, + &mask, + ) + .await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + assert_eq!(requests, segments); + Ok(()) +} + +/// The scan fails where the lambda fails in memory: on the `i32::MAX` of a selected valid list. +#[tokio::test] +async fn fallible_lambda_fails_on_selected_overflow() -> VortexResult<()> { + let expr = qty_plus_one()?; + let mut ctx = new_session().create_execution_ctx(); + assert!( + items()? + .apply(&expr)? + .execute::(&mut ctx) + .is_err() + ); + let scan = scan_counting( + &struct_elements_list_strategy(), + &items()?, + &expr, + None, + 4..5, + &Mask::new_true(1), + ) + .await; + assert!(scan.is_err()); + Ok(()) +} + +/// A filter through a pushed-down lambda reads the element column it tests and keeps the rows +/// the filter keeps in memory. The projection of the null checks shares the filter's read of the +/// validity. +#[rstest] +#[case::dense(Mask::new_true(5))] +#[case::sparse(Mask::from_iter([false, false, false, true, false]))] +#[tokio::test] +async fn filter_pushes_lambda(#[case] mask: Mask) -> VortexResult<()> { + let filter = list_contains(sku()?, lit("e")); + let projection = is_not_null(root()); + let (result, requests) = scan_counting( + &struct_elements_list_strategy(), + &items()?, + &projection, + Some(&filter), + 0..5, + &mask, + ) + .await?; + + let list = items()?.filter(mask)?; + let mut ctx = new_session().create_execution_ctx(); + let keep = list + .clone() + .apply(&filter)? + .fill_null(false)? + .execute::(&mut ctx)?; + assert_arrays_eq!(result, list.filter(keep)?.apply(&projection)?, &mut ctx); + assert_eq!(requests, 4); + Ok(()) +} + +/// `[[1, 2], null, []]`, `null`, `[[3]]`, `[]` and `[[], [4, 5, 6]]`, lists of nullable lists. +fn nested() -> VortexResult { + let mut ctx = new_session().create_execution_ctx(); + let inner = ListArray::try_new( + buffer![1i64, 2, 3, 4, 5, 6].into_array(), + buffer![0u32, 2, 2, 2, 3, 3, 6].into_array(), + Validity::from_iter([true, false, true, true, true, true]), + &mut ctx, + )? + .into_array(); + Ok(ListArray::try_new( + inner, + buffer![0u32, 3, 3, 4, 4, 6].into_array(), + Validity::from_iter([true, false, true, true, true]), + &mut ctx, + )? + .into_array()) +} + +/// A list of lists reads the inner lists of its selected lists, and their elements through their +/// own offsets. +#[rstest] +#[case::full(0..5, Mask::new_true(5))] +#[case::subrange(2..5, Mask::new_true(3))] +#[case::sparse(0..5, Mask::from_iter([true, false, false, false, true]))] +#[tokio::test] +async fn nested_lists_round_trip( + #[case] row_range: Range, + #[case] mask: Mask, + #[values( + root(), + list_transform(root(), Lambda::new(["x"], list_length(var("x")))?) + )] + expr: Expression, +) -> VortexResult<()> { + let chunked = chunked_flat(); + let strategy = ListLayoutStrategy::default() + .with_elements(Arc::new(ListLayoutStrategy::default())) + .with_offsets(Arc::clone(&chunked)) + .with_validity(chunked); + let expected = expected(&nested()?, &expr, &row_range, &mask)?; + let (result, _) = scan_counting(&strategy, &nested()?, &expr, None, row_range, &mask).await?; + assert_arrays_eq!(result, expected, &mut new_session().create_execution_ctx()); + Ok(()) +} + +/// `{s: {inner: {x, y}, items: list<{sku, qty}>}?}`, where `s` is null in row 1. The item of row 1 +/// has the SKU `i32::MAX`, which overflows when added to. +fn nullable_struct_with_nested_columns() -> VortexResult { + let mut ctx = new_session().create_execution_ctx(); + let inner = StructArray::try_new( + FieldNames::from(["x", "y"]), + vec![ + buffer![1i32, 2, 3].into_array(), + buffer![4i32, 5, 6].into_array(), + ], + 3, + Validity::NonNullable, + )?; + let elements = StructArray::try_new( + FieldNames::from(["sku", "qty"]), + vec![ + buffer![10i32, 11, i32::MAX, 13].into_array(), + buffer![20i32, 21, 22, 23].into_array(), + ], + 4, + Validity::NonNullable, + )?; + let items = ListArray::try_new( + elements.into_array(), + buffer![0u32, 2, 3, 4].into_array(), + Validity::NonNullable, + &mut ctx, + )?; + let s = StructArray::try_new( + FieldNames::from(["inner", "items"]), + vec![inner.into_array(), items.into_array()], + 3, + Validity::from_iter([true, false, true]), + )?; + Ok(StructArray::from_fields(&[("s", s.into_array())])?.into_array()) +} + +/// A strict function of a field of a nullable struct reaches the field's plan inside the struct +/// validity, so the field reads only the columns the function needs, as on the classic scan. +#[rstest] +// The validity of `s` and `s.inner.x`, not `s.inner.y`. +#[case::nested_field(get_item("x", get_item("inner", get_item("s", root()))), 2)] +// The validity of `s`, the offsets of `s.items` and the `sku` elements, not the `qty` ones. +#[case::list_transform( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], get_item("sku", var("item")))?, + ), + 3 +)] +// The validity of `s` and the offsets of `s.items`, not their elements. +#[case::list_length(list_length(get_item("items", get_item("s", root()))), 2)] +// A lambda that can fail must not run on the items of null structs, where it would overflow, so it +// stays outside the struct validity and the items are read whole. +#[case::fallible_lambda( + list_transform( + get_item("items", get_item("s", root())), + Lambda::new(["item"], checked_add(get_item("sku", var("item")), lit(1i32)))?, + ), + 4 +)] +#[tokio::test] +async fn strict_function_of_nullable_struct_field_reads_needed_columns( + #[case] expr: Expression, + #[case] segments: usize, +) -> VortexResult<()> { + let table = nullable_struct_with_nested_columns()?; + let strategy = TableStrategy::new(chunked_flat(), chunked_flat()).with_list_layout(); + let (result, requests) = + scan_counting(&strategy, &table, &expr, None, 0..3, &Mask::new_true(3)).await?; + assert_arrays_eq!( + result, + table.apply(&expr)?, + &mut new_session().create_execution_ctx() + ); + assert_eq!(requests, segments); + Ok(()) +} diff --git a/vortex-layout/src/scan/v2/tests.rs b/vortex-layout/src/scan/v2/tests/mod.rs similarity index 92% rename from vortex-layout/src/scan/v2/tests.rs rename to vortex-layout/src/scan/v2/tests/mod.rs index b09939511fa..773cac06033 100644 --- a/vortex-layout/src/scan/v2/tests.rs +++ b/vortex-layout/src/scan/v2/tests/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +mod lists; + use std::future::poll_fn; use std::num::NonZeroUsize; use std::ops::Range; @@ -42,6 +44,8 @@ use vortex_array::expr::gt; use vortex_array::expr::gt_eq; use vortex_array::expr::is_nan; use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; use vortex_array::expr::lit; use vortex_array::expr::lt; use vortex_array::expr::not; @@ -84,6 +88,8 @@ use crate::layouts::chunked::Chunked; use crate::layouts::chunked::writer::ChunkedLayoutStrategy; use crate::layouts::flat::Flat; use crate::layouts::flat::writer::FlatLayoutStrategy; +use crate::layouts::repartition::RepartitionStrategy; +use crate::layouts::repartition::RepartitionWriterOptions; use crate::layouts::row_idx::row_idx; use crate::layouts::table::TableStrategy; use crate::layouts::zoned::LegacyStats; @@ -201,6 +207,21 @@ fn zoned_table() -> Arc { Arc::new(TableStrategy::new(chunked_flat(), Arc::new(zoned_leaf()))) } +/// A [`zoned_leaf`] that first repartitions its input into chunks of `CHUNK_ROWS` rows, as the file +/// writer does. A list layout writes its elements in chunks as long as the lists they hold, and a +/// zoned leaf records one zone per chunk, so those zones would not match the zone length. +fn repartitioned_zoned_leaf() -> Arc { + Arc::new(RepartitionStrategy::new( + zoned_leaf(), + RepartitionWriterOptions { + block_size_minimum: 0, + block_len_multiple: CHUNK_ROWS, + block_size_target: None, + canonicalize: false, + }, + )) +} + /// A [`ScanFile`] over test segments. They have no byte offsets, and the scan fetches them by id, /// so each location is a placeholder whose offset is its id. fn scan_file(segments: &Arc, layout: &LayoutRef) -> VortexResult { @@ -508,17 +529,65 @@ async fn arrow_stream_projects_across_chunks() -> VortexResult<()> { Ok(()) } -/// V2 rejects list layouts: their element ranges are only known once their offsets are read. +/// List layouts scan the same on both executors, over row ranges, row indices and filters, whose +/// rows of lists map to the elements the offsets of those lists give. +#[rstest] +#[case::whole(root(), None, None, None)] +#[case::row_range(get_item("lists", root()), None, Some(250..3_100), None)] +#[case::row_indices( + get_item("lists", root()), + None, + None, + Some(&[0, 1, 999, 1000, 2500, 3999][..]) +)] +#[case::filter( + get_item("lists", root()), + Some(gt(get_item("ints", root()), lit(1500i32))), + Some(900..3_100), + None +)] +#[case::filter_on_lists( + get_item("ints", root()), + Some(list_contains(get_item("lists", root()), lit(1501i64))), + None, + None +)] +#[case::lengths(list_length(get_item("lists", root())), None, Some(10..20), None)] #[tokio::test] -async fn list_layouts_return_an_error() -> VortexResult<()> { +async fn list_layouts_match_v1( + #[values(false, true)] zoned: bool, + #[case] projection: Expression, + #[case] filter: Option, + #[case] row_range: Option>, + #[case] rows: Option<&'static [u64]>, +) -> VortexResult<()> { let session = new_session().with_tokio(); - let strategy = TableStrategy::new(chunked_flat(), chunked_flat()).with_list_layout(); + let leaf = if zoned { + repartitioned_zoned_leaf() + } else { + chunked_flat() + }; + let strategy = TableStrategy::new(chunked_flat(), leaf).with_list_layout(); let (segments, layout) = write(&session, &strategy).await?; - let error = run_scan(builder(&session, &segments, &layout)?) - .await - .expect_err("V2 must reject an unsupported layout"); - assert!(error.to_string().contains("vortex.plan.list_pack")); - Ok(()) + assert_same_as_v1(&session, || { + let mut builder = builder(&session, &segments, &layout)? + .with_projection(projection.bind(layout.dtype())?) + .with_some_filter( + filter + .as_ref() + .map(|filter| filter.bind(layout.dtype())) + .transpose()?, + ); + if let Some(row_range) = row_range.clone() { + builder = builder.with_row_range(row_range); + } + if let Some(rows) = rows { + builder = + builder.with_row_indices(StrictSortedBuffer::try_new(Buffer::copy_from(rows))?); + } + Ok(builder) + }) + .await } #[tokio::test] diff --git a/vortex-scan/src/plan/builtins/list_pack.rs b/vortex-scan/src/plan/builtins/list_pack.rs deleted file mode 100644 index f5f1369c167..00000000000 --- a/vortex-scan/src/plan/builtins/list_pack.rs +++ /dev/null @@ -1,180 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use std::borrow::Cow; -use std::sync::Arc; - -use vortex_array::EmptyMetadata; -use vortex_array::dtype::DType; -use vortex_array::dtype::Nullability; -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_error::vortex_err; -use vortex_session::registry::CachedId; - -use crate::plan::Plan; -use crate::plan::PlanId; -use crate::plan::PlanParts; -use crate::plan::PlanRef; -use crate::plan::PlanSlots; -use crate::plan::PlanVTable; - -const ELEMENTS: usize = 0; -const OFFSETS: usize = 1; -const VALIDITY: usize = 2; - -/// Assembles a list from slots `[elements, offsets, validity]`, with validity present exactly -/// when the list is nullable. -#[derive(Clone, Debug)] -pub struct ListPack; - -/// Operator-specific list assembly data. -#[derive(Clone, Debug)] -pub struct ListPackData; - -/// A plan that assembles a list from its children. -pub type ListPackPlan = Plan; - -impl ListPackPlan { - /// Creates a list assembly from potentially unbuilt slots without validation. - /// - /// # Safety - /// - /// `slots` must be `[elements, offsets, validity]`. `dtype` must be a list whose element - /// dtype matches the elements child. The offsets child must be a non-nullable integer with - /// `row_count + 1` rows. A non-nullable boolean validity child with `row_count` rows must be - /// present exactly when `dtype` is nullable. - pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { - PlanParts { - vtable: ListPack, - dtype, - row_count, - slots, - data: ListPackData, - } - .into_typed() - } - - /// Creates a list assembly from `elements` and `offsets`. - /// - /// `validity` is required exactly when `nullability` is [`Nullability::Nullable`]. The row - /// domain is one fewer than the number of offsets. - pub fn try_new( - nullability: Nullability, - row_count: u64, - elements: PlanRef, - offsets: PlanRef, - validity: Option, - ) -> VortexResult { - let dtype = DType::List(Arc::new(elements.dtype().clone()), nullability); - let slots = [Some(elements), Some(offsets), validity] - .into_iter() - .collect(); - validate_slots(&dtype, row_count, &slots)?; - - // SAFETY: All slot shape invariants were validated above. - Ok(unsafe { Self::from_slots_unchecked(dtype, row_count, slots) }) - } - - /// Returns the plan producing list elements. - pub fn elements(&self) -> VortexResult { - self.slot_required(ELEMENTS) - } - - /// Returns the plan producing list offsets. - pub fn offsets(&self) -> VortexResult { - self.slot_required(OFFSETS) - } - - /// Returns the plan producing list validity, if the list is nullable. - pub fn validity(&self) -> VortexResult> { - self.slot(VALIDITY) - } -} - -impl PlanVTable for ListPack { - type PlanData = ListPackData; - type Metadata = EmptyMetadata; - - fn id(&self) -> PlanId { - static ID: CachedId = CachedId::new("vortex.plan.list_pack"); - *ID - } - - fn metadata(_plan: &Plan) -> Option { - // Nullability is recoverable from the plan dtype. - Some(EmptyMetadata) - } - - fn with_slots( - plan: &Plan, - slots: &PlanSlots, - _data: &mut Self::PlanData, - ) -> VortexResult<()> { - validate_slots(plan.dtype(), plan.row_count(), slots) - } - - fn slot_name(_plan: &Plan, slot: usize) -> Cow<'_, str> { - match slot { - ELEMENTS => Cow::Borrowed("elements"), - OFFSETS => Cow::Borrowed("offsets"), - VALIDITY => Cow::Borrowed("validity"), - _ => Cow::Owned(format!("slot[{slot}]")), - } - } -} - -fn validate_slots(dtype: &DType, row_count: u64, slots: &PlanSlots) -> VortexResult<()> { - let elements_dtype = dtype - .as_list_element_opt() - .ok_or_else(|| vortex_err!("ListPack output dtype must be a list, got {dtype}"))?; - slots.check_len("ListPack", VALIDITY + 1)?; - - let elements = slots.required(ELEMENTS)?; - if elements.dtype() != elements_dtype.as_ref() { - vortex_bail!( - "ListPack elements child has dtype {} but the list element dtype is {}", - elements.dtype(), - elements_dtype - ); - } - - let offsets = slots.required(OFFSETS)?; - if !offsets.dtype().is_int() || offsets.dtype().is_nullable() { - vortex_bail!( - "ListPack offsets child must have a non-nullable integer dtype, got {}", - offsets.dtype() - ); - } - let offsets_row_count = row_count - .checked_add(1) - .ok_or_else(|| vortex_err!("ListPack offsets row count overflow"))?; - if offsets.row_count() != offsets_row_count { - vortex_bail!( - "ListPack offsets child has {} rows but must have {offsets_row_count}", - offsets.row_count() - ); - } - - match (dtype.is_nullable(), slots.get(VALIDITY)?) { - (true, Some(validity)) => { - let validity_dtype = DType::Bool(Nullability::NonNullable); - if validity.dtype() != &validity_dtype { - vortex_bail!( - "ListPack validity child has dtype {} but must have dtype {validity_dtype}", - validity.dtype() - ); - } - if validity.row_count() != row_count { - vortex_bail!( - "ListPack validity child has {} rows but the plan has {row_count}", - validity.row_count() - ); - } - } - (false, None) => {} - (true, None) => vortex_bail!("Nullable ListPack has no validity child"), - (false, Some(_)) => vortex_bail!("Non-nullable ListPack has a validity child"), - } - Ok(()) -} diff --git a/vortex-scan/src/plan/builtins/list_pack/execute.rs b/vortex-scan/src/plan/builtins/list_pack/execute.rs new file mode 100644 index 00000000000..87d3588ccb9 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/execute.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Assembling lists, reading their elements once their offsets give the element rows. + +use std::ops::Range; + +use rustc_hash::FxHashMap; +use smallvec::SmallVec; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::IntoArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::BufferMut; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; +use vortex_mask::Mask; +use vortex_session::VortexSession; + +use crate::execution::operator::Cx; +use crate::execution::operator::Input; +use crate::execution::operator::Operator; +use crate::execution::operator::Source; +use crate::execution::operator::SourceBlocked; +use crate::execution::operator::SourceReady; +use crate::execution::operator::Step; +use crate::execution::operators::join; +use crate::execution::operators::join_inlet; +use crate::execution::pipeline::ReadId; +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::execution::pipeline::Turn; +use crate::execution::pipeline::ValueCache; +use crate::plan::ListPackPlan; +use crate::source::SegmentId; + +const OFFSETS: usize = 0; +const VALIDITY: usize = 1; + +/// Assembles the selected lists of a row range from its inlets, the offsets of the range and the +/// validity of its selected lists, and from the elements those lists hold. +/// +/// The element rows of a list are known only once its offsets are read, so the elements cannot be +/// compiled with the lists. Once both inlets have closed, the source compiles the elements plan +/// over the elements of the selected valid lists as a scan of its own, which it runs within its +/// readiness checks: the reads that scan asks for are this source's reads, and their bytes go +/// back to it. The lists are emitted as one batch once every element has arrived. +pub(crate) struct ListSource { + plan: ListPackPlan, + /// The selected lists of the row range the offsets inlet covers. + selected: Mask, + session: VortexSession, + values: ValueCache, + state: State, +} + +enum State { + /// Waiting for the offsets and the validity. + Lists, + /// Reading the elements of the selected valid lists. + Elements(Box), + /// The lists, built and not yet emitted. + Built(ArrayRef), + Done, +} + +/// The scan of the elements of the selected valid lists. +struct ElementScan { + scan: Scan, + /// The scan's reads that have not arrived, by segment, oldest first. + reads: FxHashMap>, + /// What the scan produced, in element order. + elements: Vec, + dtype: DType, + lists: CompactedLists, +} + +impl ListSource { + /// A source of the `selected` lists of a row range, whose offsets inlet holds the offsets of + /// every list of the range, one more than `selected` is long, and whose validity inlet, present + /// exactly when the list is nullable, holds the validity of the selected lists. + pub(crate) fn new( + plan: ListPackPlan, + selected: Mask, + session: VortexSession, + values: ValueCache, + ) -> Self { + Self { + plan, + selected, + session, + values, + state: State::Lists, + } + } + + /// Compacts the lists once their offsets and validity have arrived, and starts the scan of + /// their elements. + fn read_lists(&mut self, cx: &mut Cx<'_>) -> VortexResult { + let offsets_dtype = self.plan.offsets()?.dtype().clone(); + let offsets = join_inlet(cx, OFFSETS, &offsets_dtype)? + .cast(DType::Primitive(PType::U64, Nullability::NonNullable))? + .execute::(cx.exec())?; + let validity = if self.plan.dtype().is_nullable() { + let validity = join_inlet(cx, VALIDITY, &DType::Bool(Nullability::NonNullable))?; + let valid = validity.clone().execute::(cx.exec())?; + Some((validity, valid)) + } else { + None + }; + let elements_plan = self.plan.elements()?; + let lists = CompactedLists::try_new( + offsets.as_slice::(), + &self.selected, + validity, + elements_plan.row_count(), + )?; + if lists.elements_mask.all_false() { + let elements = Canonical::empty(elements_plan.dtype()).into_array(); + return Ok(State::Built(lists.build(elements)?)); + } + let split = Split { + rows: lists.elements_range.clone(), + mask: lists.elements_mask.clone(), + }; + let dtype = elements_plan.dtype().clone(); + let scan = Scan::try_new(self.session.clone(), elements_plan, vec![split])? + .with_value_cache(self.values.clone()); + Ok(State::Elements(Box::new(ElementScan { + scan, + reads: FxHashMap::default(), + elements: Vec::new(), + dtype, + lists, + }))) + } +} + +impl ElementScan { + /// Hands the bytes that have arrived to the scan and runs it until it waits for more or has + /// finished, returning the lists once it has. + fn advance(&mut self, cx: &mut Cx<'_>) -> VortexResult> { + while let Some((segment, bytes)) = cx.take_segment() { + let read = self + .reads + .get_mut(&segment) + .filter(|reads| !reads.is_empty()) + .map(|reads| reads.remove(0)) + .ok_or_else(|| vortex_err!("List elements received {segment}, never asked for"))?; + self.scan.deliver(read, bytes)?; + } + loop { + match self.scan.step()? { + Turn::Read(read) => { + cx.request_read(read.segment_id); + self.reads.entry(read.segment_id).or_default().push(read.id); + } + Turn::Output(_, elements) => self.elements.push(elements), + Turn::Waiting => return Ok(None), + Turn::Done => { + let elements = join(&self.dtype, std::mem::take(&mut self.elements))?; + return self.lists.build(elements).map(Some); + } + } + } + } +} + +impl Source for ListSource { + fn ready(&mut self, cx: &mut Cx<'_>) -> VortexResult { + loop { + self.state = match &mut self.state { + State::Lists => { + if !cx.inlet(OFFSETS).closed() { + return Ok(SourceReady::Blocked(SourceBlocked::Inlet(OFFSETS))); + } + if self.plan.dtype().is_nullable() && !cx.inlet(VALIDITY).closed() { + return Ok(SourceReady::Blocked(SourceBlocked::Inlet(VALIDITY))); + } + self.read_lists(cx)? + } + State::Elements(scan) => match scan.advance(cx)? { + Some(lists) => State::Built(lists), + None => return Ok(SourceReady::Blocked(SourceBlocked::Io)), + }, + State::Built(_) | State::Done => return Ok(SourceReady::Ready), + }; + } + } +} + +impl Operator for ListSource { + fn compute(&mut self, _input: Input, _cx: &mut Cx<'_>) -> VortexResult { + Ok(match std::mem::replace(&mut self.state, State::Done) { + State::Built(lists) => Step::Final(lists), + State::Done => Step::End, + State::Lists | State::Elements(_) => { + vortex_bail!("List source computed before its lists were ready") + } + }) + } +} + +/// The selected lists of a row range, with only the elements of the valid ones. +/// +/// `list_transform` runs a lambda that can fail only on the elements of valid lists, and an +/// expression over the elements may be such a lambda's body, so the elements of a null or +/// unselected list are never read. +struct CompactedLists { + /// The element rows from the first list of the range to its last. + elements_range: Range, + /// The elements of the selected valid lists, relative to `elements_range`. + elements_mask: Mask, + /// The offsets of the selected lists into those elements. A null list is empty. + offsets: PrimitiveArray, + validity: Validity, +} + +impl CompactedLists { + /// Compacts the `selected` lists of a range whose lists start at `offsets`, one more offset than + /// `selected` is long, into an elements child of `elements_row_count` rows. `validity` holds + /// the validity of the selected lists of a nullable list, as an array and as a mask. + fn try_new( + offsets: &[u64], + selected: &Mask, + validity: Option<(ArrayRef, Mask)>, + elements_row_count: u64, + ) -> VortexResult { + vortex_ensure!( + offsets.len() == selected.len() + 1, + "{} list offsets cannot bound {} lists", + offsets.len(), + selected.len() + ); + let first = offsets[0]; + let last = offsets[selected.len()]; + vortex_ensure!( + first <= last && last <= elements_row_count, + "List offsets {first}..{last} exceed the {elements_row_count} elements" + ); + let mut slices: Vec<(usize, usize)> = Vec::new(); + let mut compacted = BufferMut::::with_capacity(selected.true_count() + 1); + let mut kept = 0; + compacted.push(kept); + let mut valid = validity.as_ref().map(|(_, valid)| valid.iter()); + for (row, is_selected) in selected.iter().enumerate() { + if !is_selected { + continue; + } + let is_valid = match valid.as_mut() { + Some(valid) => valid + .next() + .ok_or_else(|| vortex_err!("List validity is shorter than the selection"))?, + None => true, + }; + let (start, end) = (offsets[row], offsets[row + 1]); + vortex_ensure!( + first <= start && start <= end && end <= last, + "List offsets {start}..{end} are out of order" + ); + if is_valid && start < end { + kept += end - start; + let slice = ( + usize::try_from(start - first)?, + usize::try_from(end - first)?, + ); + match slices.last_mut() { + Some((_, previous_end)) if *previous_end == slice.0 => *previous_end = slice.1, + _ => slices.push(slice), + } + } + compacted.push(kept); + } + let len = usize::try_from(last - first)?; + let elements_mask = match slices.as_slice() { + [] => Mask::new_false(len), + [(0, end)] if *end == len => Mask::new_true(len), + _ => Mask::from_slices(len, slices), + }; + Ok(Self { + elements_range: first..last, + elements_mask, + offsets: PrimitiveArray::new(compacted.freeze(), Validity::NonNullable), + validity: validity.map_or(Validity::NonNullable, |(validity, _)| { + Validity::Array(validity) + }), + }) + } + + /// The lists over `elements`, the elements the mask keeps. + fn build(&self, elements: ArrayRef) -> VortexResult { + vortex_ensure!( + elements.len() == self.elements_mask.true_count(), + "List elements produced {} rows for {} elements", + elements.len(), + self.elements_mask.true_count() + ); + // SAFETY: the compacted offsets start at zero, never decrease and end at the number of + // elements the mask keeps, which the elements hold, and the validity covers one value per + // selected list. + let offsets = self.offsets.clone().into_array(); + Ok( + unsafe { ListArray::new_unchecked(elements, offsets, self.validity.clone()) } + .into_array(), + ) + } +} diff --git a/vortex-scan/src/plan/builtins/list_pack/expr.rs b/vortex-scan/src/plan/builtins/list_pack/expr.rs new file mode 100644 index 00000000000..9733cee8c79 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/expr.rs @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! What an expression over a list reads of the list. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::BoundLambda; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::expr::traversal::pre_order_visit_down; +use vortex_array::scalar_fn::ScalarFnVTable; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_array::scalar_fn::fns::is_not_null::IsNotNull; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_array::scalar_fn::fns::list_length::ListLength; +use vortex_array::scalar_fn::fns::list_transform::ListTransform; +use vortex_array::scalar_fn::fns::list_transform::ListTransformOptions; +use vortex_error::VortexResult; +use vortex_error::vortex_err; + +/// What an expression over a list reads of the list. +pub(crate) enum ListRead { + /// At most the validity, through `is_null($)` and `is_not_null($)`. + Validity, + /// At most the offsets and the validity, through these and `list_length($)`. + Lengths, + /// The elements, through the lambdas of `list_transform($, lambda)` nodes alone. + Transforms(ListTransforms), + /// The elements in any other way, such as the list itself. + Elements, +} + +impl ListRead { + /// What `expr`, an expression over a list, reads of the list. + pub(crate) fn of(expr: &BoundExpression) -> VortexResult { + let mut transforms: Vec = Vec::new(); + let mut reads_lengths = false; + let mut reads_elements = false; + pre_order_visit_down(expr, |node: &BoundExpression| { + if is_root_transform(node) { + if !transforms.contains(node) { + transforms.push(node.clone()); + } + return Ok(TraversalOrder::Skip); + } + if is_validity_read(node) { + return Ok(TraversalOrder::Skip); + } + if is_root_read::(node) { + reads_lengths = true; + return Ok(TraversalOrder::Skip); + } + if node.is_root() { + reads_elements = true; + return Ok(TraversalOrder::Stop); + } + Ok(TraversalOrder::Continue) + })?; + if reads_elements { + return Ok(Self::Elements); + } + if transforms.is_empty() { + return Ok(if reads_lengths { + Self::Lengths + } else { + Self::Validity + }); + } + Ok(ListTransforms::try_new(transforms)?.map_or(Self::Elements, Self::Transforms)) + } +} + +/// The `list_transform($, lambda)` nodes through which an expression over a list reads the list +/// elements, with the body of each lambda as an expression over the elements. +/// +/// A lambda that reads one field of struct elements, as in `list_transform($, x -> x.sku)`, has +/// the body `$.sku`, so a reader can evaluate it over the elements and read the column of that +/// field alone. +#[derive(Debug)] +pub struct ListTransforms { + transforms: Vec, + bodies: Vec, + fallible: bool, +} + +impl ListTransforms { + /// The `list_transform($, lambda)` nodes of `expr`, an expression over a list. + /// + /// Returns `None` when `expr` has no such node, or reads the list in another way than through + /// these nodes, `is_null($)`, `is_not_null($)` and `list_length($)`. The last three need only + /// the offsets and the validity of the list. + pub fn of(expr: &BoundExpression) -> VortexResult> { + Ok(match ListRead::of(expr)? { + ListRead::Transforms(transforms) => Some(transforms), + ListRead::Validity | ListRead::Lengths | ListRead::Elements => None, + }) + } + + fn try_new(transforms: Vec) -> VortexResult> { + let mut bodies = Vec::with_capacity(transforms.len()); + let mut fallible = false; + for transform in &transforms { + let ListTransformOptions::Bound(lambda) = transform.as_::() else { + return Ok(None); + }; + let Some(body) = body_over_elements(lambda)? else { + return Ok(None); + }; + fallible |= !lambda.is_infallible(); + bodies.push(body); + } + Ok(Some(Self { + transforms, + bodies, + fallible, + })) + } + + /// The distinct `list_transform($, lambda)` nodes, in the order they first occur. + pub fn transforms(&self) -> &[BoundExpression] { + &self.transforms + } + + /// The body of the lambda of each node, as an expression over the list elements. + pub fn bodies(&self) -> &[BoundExpression] { + &self.bodies + } + + /// Whether a lambda can fail. + /// + /// `list_transform` runs such a lambda only on the elements of valid lists, so a reader must + /// not evaluate its body over the elements of null or unselected lists either. + pub fn is_fallible(&self) -> bool { + self.fallible + } + + /// Rewrites `expr`, from which these nodes were taken, to read the results of the lambda + /// bodies instead of the elements. + /// + /// Node `i` becomes `transformed(i)`, and the list in `is_null($)`, `is_not_null($)` and + /// `list_length($)` becomes `list`, which must have the offsets and the validity of the list. + pub fn rewrite( + &self, + expr: &BoundExpression, + transformed: impl Fn(usize) -> VortexResult, + list: &BoundExpression, + ) -> VortexResult { + Ok(expr + .clone() + .transform_down(|node| { + let value = if is_root_transform(&node) { + let index = self + .transforms + .iter() + .position(|transform| *transform == node) + .ok_or_else(|| vortex_err!("{node} is not a transform of the list"))?; + transformed(index)? + } else if is_validity_read(&node) || is_root_read::(&node) { + node.with_children([list.clone()])? + } else { + return Ok(Transformed::no(node)); + }; + Ok(Transformed { + value, + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner()) + } +} + +/// Whether `expr` is `is_null($)` or `is_not_null($)`. +pub(crate) fn is_validity_read(expr: &BoundExpression) -> bool { + is_root_read::(expr) || is_root_read::(expr) +} + +/// Whether `expr` applies the function `F` to the root alone. +fn is_root_read(expr: &BoundExpression) -> bool { + expr.is::() && matches!(expr.children(), [child] if child.is_root()) +} + +fn is_root_transform(expr: &BoundExpression) -> bool { + is_root_read::(expr) +} + +/// The body of a `list_transform` lambda as an expression over the list elements. +/// +/// Binding made the lambda's parameter `x` the field `$.x` of the struct of its inputs, so every +/// `$.x` becomes the elements root. Returns `None` when the body reads the inputs in any other +/// way, which a lambda cannot do. +fn body_over_elements(lambda: &BoundLambda) -> VortexResult> { + let params = lambda.params(); + let ([param], Some(element_dtype)) = (params.names().as_ref(), params.field_by_index(0)) else { + return Ok(None); + }; + let elements_root = BoundExpression::new_root(element_dtype); + let mut reads_inputs = false; + let body = lambda + .body() + .clone() + .transform_down(|node| { + if node.as_opt::() == Some(param) && node.child(0).is_root() { + return Ok(Transformed { + value: elements_root.clone(), + changed: true, + order: TraversalOrder::Skip, + }); + } + reads_inputs |= node.is_root(); + Ok(Transformed::no(node)) + })? + .into_inner(); + Ok((!reads_inputs).then_some(body)) +} diff --git a/vortex-scan/src/plan/builtins/list_pack/mod.rs b/vortex-scan/src/plan/builtins/list_pack/mod.rs new file mode 100644 index 00000000000..0dfe7bee0b1 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/mod.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +pub(crate) mod execute; +mod expr; +#[cfg(test)] +mod tests; + +use std::borrow::Cow; +use std::ops::Range; +use std::sync::Arc; + +use vortex_array::EmptyMetadata; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Lambda; +use vortex_array::expr::bound; +use vortex_array::expr::get_item; +use vortex_array::expr::list_transform; +use vortex_array::expr::root; +use vortex_array::expr::traversal::NodeExt; +use vortex_array::expr::traversal::Transformed; +use vortex_array::expr::traversal::TraversalOrder; +use vortex_array::expr::var; +use vortex_array::scalar_fn::fns::get_item::GetItem; +use vortex_array::scalar_fn::fns::is_null::IsNull; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_error::vortex_err; +use vortex_mask::Mask; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use self::execute::ListSource; +use self::expr::ListRead; +pub use self::expr::ListTransforms; +use self::expr::is_validity_read; +use crate::execution::operators::UNBOUNDED; +use crate::execution::pipeline::Chain; +use crate::execution::pipeline::Compiler; +use crate::plan::Eval; +use crate::plan::EvalPlan; +use crate::plan::PackPlan; +use crate::plan::Plan; +use crate::plan::PlanId; +use crate::plan::PlanParts; +use crate::plan::PlanRef; +use crate::plan::PlanSlots; +use crate::plan::PlanVTable; +use crate::plan::optimizer::PlanParentReduceRule; +use crate::plan::selection::selected_slice; + +const ELEMENTS: usize = 0; +const OFFSETS: usize = 1; +const VALIDITY: usize = 2; + +/// Assembles a list from slots `[elements, offsets, validity]`, with validity present exactly +/// when the list is nullable. +/// +/// The elements live in a row domain of their own: list `i` holds the elements from +/// `offsets[i]` to `offsets[i + 1]`, so the element rows of a range of lists are known only once +/// their offsets are read. Compiled over a range of lists, a list reads the offsets of the range +/// and the validity of its selected lists, then compiles the elements plan over the elements of +/// the selected valid lists alone and reads them as a scan of their own. Compiling therefore +/// registers the segments of the offsets and the validity, but not those of the elements. +/// +/// An [`Eval`] above a list reads only the children its expression needs: the validity for +/// `is_null($)`, the offsets and the validity for `list_length($)`, and for the lambdas of +/// `list_transform($, lambda)` nodes the elements that the lambdas read. +#[derive(Clone, Debug)] +pub struct ListPack; + +/// Operator-specific list assembly data. +#[derive(Clone, Debug)] +pub struct ListPackData; + +/// A plan that assembles a list from its children. +pub type ListPackPlan = Plan; + +impl ListPackPlan { + /// Creates a list assembly from potentially unbuilt slots without validation. + /// + /// # Safety + /// + /// `slots` must be `[elements, offsets, validity]`. `dtype` must be a list whose element + /// dtype matches the elements child. The offsets child must be a non-nullable integer with + /// `row_count + 1` rows. A non-nullable boolean validity child with `row_count` rows must be + /// present exactly when `dtype` is nullable. + pub unsafe fn from_slots_unchecked(dtype: DType, row_count: u64, slots: PlanSlots) -> Self { + PlanParts { + vtable: ListPack, + dtype, + row_count, + slots, + data: ListPackData, + } + .into_typed() + } + + /// Creates a list assembly from `elements` and `offsets`. + /// + /// `validity` is required exactly when `nullability` is [`Nullability::Nullable`]. The row + /// domain is one fewer than the number of offsets. + pub fn try_new( + nullability: Nullability, + row_count: u64, + elements: PlanRef, + offsets: PlanRef, + validity: Option, + ) -> VortexResult { + let dtype = DType::List(Arc::new(elements.dtype().clone()), nullability); + let slots = [Some(elements), Some(offsets), validity] + .into_iter() + .collect(); + validate_slots(&dtype, row_count, &slots)?; + + // SAFETY: All slot shape invariants were validated above. + Ok(unsafe { Self::from_slots_unchecked(dtype, row_count, slots) }) + } + + /// Returns the plan producing list elements. + pub fn elements(&self) -> VortexResult { + self.slot_required(ELEMENTS) + } + + /// Returns the plan producing list offsets. + pub fn offsets(&self) -> VortexResult { + self.slot_required(OFFSETS) + } + + /// Returns the plan producing list validity, if the list is nullable. + pub fn validity(&self) -> VortexResult> { + self.slot(VALIDITY) + } +} + +impl PlanVTable for ListPack { + type PlanData = ListPackData; + type Metadata = EmptyMetadata; + + fn id(&self) -> PlanId { + static ID: CachedId = CachedId::new("vortex.plan.list_pack"); + *ID + } + + fn metadata(_plan: &Plan) -> Option { + // Nullability is recoverable from the plan dtype. + Some(EmptyMetadata) + } + + fn with_slots( + plan: &Plan, + slots: &PlanSlots, + _data: &mut Self::PlanData, + ) -> VortexResult<()> { + validate_slots(plan.dtype(), plan.row_count(), slots) + } + + fn slot_name(_plan: &Plan, slot: usize) -> Cow<'_, str> { + match slot { + ELEMENTS => Cow::Borrowed("elements"), + OFFSETS => Cow::Borrowed("offsets"), + VALIDITY => Cow::Borrowed("validity"), + _ => Cow::Owned(format!("slot[{slot}]")), + } + } + + /// Reads the offsets from the first selected list to the last and the validity of the + /// selected lists, as inlets `[offsets, validity]` of a source that reads the elements once + /// those have arrived. + fn compile( + plan: &Plan, + rows: Range, + mask: &Mask, + compiler: &mut Compiler<'_>, + ) -> VortexResult> { + let Some((span, selected)) = selected_slice(mask, 0..mask.len()) else { + return Ok(None); + }; + let lists = rows.start + u64::try_from(span.start)?..rows.start + u64::try_from(span.end)?; + let offsets = compiler + .compile( + &plan.offsets()?, + lists.start..lists.end + 1, + &Mask::new_true(span.len() + 1), + )? + .ok_or_else(|| vortex_err!("ListPack offsets produced no rows"))?; + let mut chains = vec![offsets]; + if let Some(validity) = plan.validity()? { + chains.push( + compiler + .compile(&validity, lists, &selected)? + .ok_or_else(|| vortex_err!("ListPack validity produced no rows"))?, + ); + } + let source = ListSource::new( + plan.clone(), + selected, + compiler.session().clone(), + compiler.values().clone(), + ); + Ok(Some(compiler.join_with(chains, |_| UNBOUNDED, source))) + } +} + +fn validate_slots(dtype: &DType, row_count: u64, slots: &PlanSlots) -> VortexResult<()> { + let elements_dtype = dtype + .as_list_element_opt() + .ok_or_else(|| vortex_err!("ListPack output dtype must be a list, got {dtype}"))?; + slots.check_len("ListPack", VALIDITY + 1)?; + + let elements = slots.required(ELEMENTS)?; + if elements.dtype() != elements_dtype.as_ref() { + vortex_bail!( + "ListPack elements child has dtype {} but the list element dtype is {}", + elements.dtype(), + elements_dtype + ); + } + + let offsets = slots.required(OFFSETS)?; + if !offsets.dtype().is_int() || offsets.dtype().is_nullable() { + vortex_bail!( + "ListPack offsets child must have a non-nullable integer dtype, got {}", + offsets.dtype() + ); + } + let offsets_row_count = row_count + .checked_add(1) + .ok_or_else(|| vortex_err!("ListPack offsets row count overflow"))?; + if offsets.row_count() != offsets_row_count { + vortex_bail!( + "ListPack offsets child has {} rows but must have {offsets_row_count}", + offsets.row_count() + ); + } + + match (dtype.is_nullable(), slots.get(VALIDITY)?) { + (true, Some(validity)) => { + let validity_dtype = DType::Bool(Nullability::NonNullable); + if validity.dtype() != &validity_dtype { + vortex_bail!( + "ListPack validity child has dtype {} but must have dtype {validity_dtype}", + validity.dtype() + ); + } + if validity.row_count() != row_count { + vortex_bail!( + "ListPack validity child has {} rows but the plan has {row_count}", + validity.row_count() + ); + } + } + (false, None) => {} + (true, None) => vortex_bail!("Nullable ListPack has no validity child"), + (false, Some(_)) => vortex_bail!("Non-nullable ListPack has a validity child"), + } + Ok(()) +} + +/// Reads only the children of a [`ListPack`] that the expression of an [`Eval`] above it needs. +/// +/// - An expression that reads at most the validity, through `is_null($)` and `is_not_null($)`, +/// evaluates over the validity child, or over no child at all for a non-nullable list. +/// - One that also reads the lengths, through `list_length($)`, evaluates over lists of empty +/// structs, which read only the offsets and the validity. +/// - One that reads the elements only through the lambdas of `list_transform($, lambda)` nodes +/// evaluates their bodies over the elements child, and the rest over the lists of the results. +/// So `list_transform($, x -> x.sku)` reads the column of `sku` alone. The bodies of several +/// lambdas are packed into one struct, so the lambdas share one read of the offsets and the +/// validity, and each node takes its field from the lists of those structs. +/// +/// A list reads only the elements of its selected valid lists, so a body runs on no element that +/// `list_transform` would not run it on, even when it can fail. +#[derive(Debug)] +pub(crate) struct ExpressionListPackRule; + +impl PlanParentReduceRule for ExpressionListPackRule { + type Parent = Eval; + + fn reduce_parent( + &self, + child: &ListPackPlan, + parent: &Plan, + _child_idx: usize, + _session: &VortexSession, + ) -> VortexResult> { + let expression = parent.expression(); + let rewritten = match ListRead::of(expression)? { + ListRead::Validity => read_validity(child, expression)?, + ListRead::Lengths => read_lengths(child, expression)?, + ListRead::Transforms(transforms) => read_transforms(child, expression, &transforms)?, + ListRead::Elements => None, + }; + Ok(rewritten.filter(|plan| plan.dtype() == parent.dtype())) + } +} + +/// Evaluates `expression`, which reads at most the validity of `list`, over the validity child. +fn read_validity( + list: &ListPackPlan, + expression: &BoundExpression, +) -> VortexResult> { + let Some(validity) = list.validity()? else { + let expression = replace_validity_reads(expression, |is_null| bound::lit(!is_null))?; + let empty = PackPlan::try_new( + StructFields::empty(), + Nullability::NonNullable, + list.row_count(), + Vec::new(), + None, + )?; + return Ok(Some( + EvalPlan::try_new(expression, empty.into_plan())?.into_plan(), + )); + }; + let valid = BoundExpression::new_root(validity.dtype().clone()); + let expression = replace_validity_reads(expression, |is_null| { + if is_null { + bound::not(valid.clone()) + } else { + valid.clone() + } + })?; + Ok(Some(EvalPlan::try_new(expression, validity)?.into_plan())) +} + +/// `expression` with each `is_null($)` and `is_not_null($)` replaced by `replacement`, which is +/// told whether it replaces `is_null($)`. +fn replace_validity_reads( + expression: &BoundExpression, + replacement: impl Fn(bool) -> BoundExpression, +) -> VortexResult { + Ok(expression + .clone() + .transform_down(|node| { + if !is_validity_read(&node) { + return Ok(Transformed::no(node)); + } + Ok(Transformed { + value: replacement(node.is::()), + changed: true, + order: TraversalOrder::Skip, + }) + })? + .into_inner()) +} + +/// Evaluates `expression`, which reads at most the lengths and the validity of `list`, over lists +/// of empty structs, which read no element. +fn read_lengths( + list: &ListPackPlan, + expression: &BoundExpression, +) -> VortexResult> { + let elements = list.elements()?; + if is_empty_struct(elements.dtype()) { + return Ok(None); + } + let empty = PackPlan::try_new( + StructFields::empty(), + Nullability::NonNullable, + elements.row_count(), + Vec::new(), + None, + )?; + let lengths = list.with_elements(empty.into_plan())?; + let expression = rebind_root(expression, lengths.dtype())?; + Ok(Some( + EvalPlan::try_new(expression, lengths.into_plan())?.into_plan(), + )) +} + +/// Evaluates the lambda bodies of `transforms` over the elements of `list`, and `expression` over +/// the lists of their results. +fn read_transforms( + list: &ListPackPlan, + expression: &BoundExpression, + transforms: &ListTransforms, +) -> VortexResult> { + let elements = list.elements()?; + if let [body] = transforms.bodies() { + let projected = list.with_elements(eval_unless_root(body, elements)?)?; + let lists = BoundExpression::new_root(projected.dtype().clone()); + let expression = transforms.rewrite(expression, |_| Ok(lists.clone()), &lists)?; + return Ok(Some( + EvalPlan::try_new(expression, projected.into_plan())?.into_plan(), + )); + } + if is_projection_of_every_field(transforms.bodies(), elements.dtype()) { + // Packing these bodies would only rename the fields of the elements. + return Ok(None); + } + let names: FieldNames = (0..transforms.bodies().len()) + .map(|index| index.to_string()) + .collect(); + let packed = bound::pack( + names + .iter() + .cloned() + .zip(transforms.bodies().iter().cloned()), + Nullability::NonNullable, + ); + let projected = list.with_elements(EvalPlan::try_new(packed, elements)?.into_plan())?; + let lists = BoundExpression::new_root(projected.dtype().clone()); + let expression = transforms.rewrite( + expression, + |index| { + let field = Lambda::new(["element"], get_item(names[index].clone(), var("element")))?; + list_transform(root(), field).bind(projected.dtype()) + }, + &lists, + )?; + Ok(Some( + EvalPlan::try_new(expression, projected.into_plan())?.into_plan(), + )) +} + +impl ListPackPlan { + /// This list over `elements` in place of its elements child, with the same offsets and + /// validity. + fn with_elements(&self, elements: PlanRef) -> VortexResult { + Self::try_new( + self.dtype().nullability(), + self.row_count(), + elements, + self.offsets()?, + self.validity()?, + ) + } +} + +/// `elements`, or an evaluation of `body` over them unless `body` is the root. +fn eval_unless_root(body: &BoundExpression, elements: PlanRef) -> VortexResult { + if body.is_root() { + return Ok(elements); + } + Ok(EvalPlan::try_new(body.clone(), elements)?.into_plan()) +} + +/// `expression` with every root bound to `dtype` instead. +fn rebind_root(expression: &BoundExpression, dtype: &DType) -> VortexResult { + Ok(expression + .clone() + .transform_down(|node| { + if !node.is_root() { + return Ok(Transformed::no(node)); + } + Ok(Transformed::yes(BoundExpression::new_root(dtype.clone()))) + })? + .into_inner()) +} + +/// Whether `dtype` is a non-nullable struct with no field. +fn is_empty_struct(dtype: &DType) -> bool { + !dtype.is_nullable() + && dtype + .as_struct_fields_opt() + .is_some_and(|fields| fields.nfields() == 0) +} + +/// Whether `bodies` read every field of non-nullable struct elements of `dtype`, one each and in +/// field order, and nothing else. +fn is_projection_of_every_field(bodies: &[BoundExpression], dtype: &DType) -> bool { + let Some(fields) = dtype.as_struct_fields_opt() else { + return false; + }; + !dtype.is_nullable() + && bodies.len() == fields.nfields() + && bodies + .iter() + .zip(fields.names().iter()) + .all(|(body, name)| body.as_opt::() == Some(name) && body.child(0).is_root()) +} diff --git a/vortex-scan/src/plan/builtins/list_pack/tests.rs b/vortex-scan/src/plan/builtins/list_pack/tests.rs new file mode 100644 index 00000000000..af88903f4d1 --- /dev/null +++ b/vortex-scan/src/plan/builtins/list_pack/tests.rs @@ -0,0 +1,368 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::ops::Range; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::expr::Expression; +use vortex_array::expr::Lambda; +use vortex_array::expr::checked_add; +use vortex_array::expr::get_item; +use vortex_array::expr::is_not_null; +use vortex_array::expr::is_null; +use vortex_array::expr::list_contains; +use vortex_array::expr::list_length; +use vortex_array::expr::list_transform; +use vortex_array::expr::lit; +use vortex_array::expr::pack; +use vortex_array::expr::root; +use vortex_array::expr::var; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use crate::execution::pipeline::Scan; +use crate::execution::pipeline::Split; +use crate::execution::pipeline::Turn; +use crate::plan::EvalPlan; +use crate::plan::ListPackPlan; +use crate::plan::PlanRef; +use crate::plan::optimize; +use crate::test::SESSION; +use crate::test::Store; +use crate::test::flat; +use crate::test::struct_plan; + +fn i32() -> DType { + DType::Primitive(PType::I32, Nullability::NonNullable) +} + +/// A non-nullable struct of `i32` fields named `names`. +fn struct_of(names: &[&str]) -> DType { + DType::Struct( + StructFields::from_iter(names.iter().map(|name| (*name, i32()))), + Nullability::NonNullable, + ) +} + +/// A shape-only list of `{sku: i32, qty: i32, price: i32}` elements whose fields are separate +/// sources, as a list layout with struct elements is lowered. +fn items_plan(nullability: Nullability) -> PlanRef { + let fields = (0..3).map(|segment| flat(6, i32(), segment)).collect(); + let elements = struct_plan(6, struct_of(&["sku", "qty", "price"]), fields); + let offsets = flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 3); + let validity = nullability + .is_nullable() + .then(|| flat(5, DType::Bool(Nullability::NonNullable), 4)); + ListPackPlan::try_new(nullability, 5, elements, offsets, validity) + .expect("valid test list") + .into_plan() +} + +fn sku() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("sku", var("x")))?, + )) +} + +fn qty() -> VortexResult { + Ok(list_transform( + root(), + Lambda::new(["x"], get_item("qty", var("x")))?, + )) +} + +fn optimized(expr: &Expression, plan: PlanRef) -> VortexResult { + let plan = EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(); + Ok(optimize(plan, &SESSION)?.display_tree().to_string()) +} + +#[test] +fn validity_reads_evaluate_over_the_validity() -> VortexResult<()> { + insta::assert_snapshot!(optimized(&is_null(root()), items_plan(Nullability::Nullable))?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.not($) + child: vortex.plan.filter(bool, rows=5) + child: vortex.test.source(bool, rows=5) + "); + insta::assert_snapshot!( + optimized(&is_not_null(root()), items_plan(Nullability::NonNullable))?, + @r" + root: vortex.plan.eval(bool, rows=5) expr=true + child: vortex.plan.pack({}, rows=5) + " + ); + Ok(()) +} + +#[test] +fn length_reads_assemble_lists_of_empty_structs() -> VortexResult<()> { + let expr = pack( + [("len", list_length(root())), ("valid", is_not_null(root()))], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::Nullable))?, @r" + root: vortex.plan.eval({len=u64?, valid=bool}, rows=5) expr=pack(len: vortex.list.length($), valid: is_not_null($)) + child: vortex.plan.list_pack(list({})?, rows=5) + elements: vortex.plan.pack({}, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + validity: vortex.plan.filter(bool, rows=5) + child: vortex.test.source(bool, rows=5) + "); + Ok(()) +} + +#[test] +fn lambda_bodies_push_into_the_elements() -> VortexResult<()> { + let expr = list_contains(sku()?, lit(3i32)); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::NonNullable))?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.list.contains($, 3i32) + child: vortex.plan.list_pack(list(i32), rows=5) + elements: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Two lambdas share one read of the offsets: their bodies are packed into one struct of results, +/// whose fields the transforms take, so `price` is never read. +#[test] +fn lambda_bodies_share_the_offsets() -> VortexResult<()> { + let expr = pack( + [("skus", sku()?), ("qtys", qty()?)], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, items_plan(Nullability::NonNullable))?, @r" + root: vortex.plan.eval({skus=list(i32), qtys=list(i32)}, rows=5) expr=pack(skus: vortex.list.transform($, (element) -> $.element.0), qtys: vortex.list.transform($, (element) -> $.element.1)) + child: vortex.plan.list_pack(list({0=i32, 1=i32}), rows=5) + elements: vortex.plan.eval({0=i32, 1=i32}, rows=6) expr=pack(0: $.0, 1: $.1) + child: vortex.plan.pack({0=i32, 1=i32}, rows=6) + 0: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + 1: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Lambdas that read every field of the elements in order read the elements as stored, as packing +/// their bodies would only rename the fields. +#[test] +fn lambda_bodies_reading_every_field_keep_the_elements() -> VortexResult<()> { + let elements = struct_plan( + 6, + struct_of(&["sku", "qty"]), + vec![flat(6, i32(), 0), flat(6, i32(), 1)], + ); + let offsets = flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 2); + let plan = ListPackPlan::try_new(Nullability::NonNullable, 5, elements, offsets, None)?; + let expr = pack( + [("skus", sku()?), ("qtys", qty()?)], + Nullability::NonNullable, + ); + insta::assert_snapshot!(optimized(&expr, plan.into_plan())?, @r" + root: vortex.plan.eval({skus=list(i32), qtys=list(i32)}, rows=5) expr=pack(skus: vortex.list.transform($, (x) -> $.x.sku), qtys: vortex.list.transform($, (x) -> $.x.qty)) + child: vortex.plan.list_pack(list({sku=i32, qty=i32}), rows=5) + elements: vortex.plan.pack({sku=i32, qty=i32}, rows=6) + sku: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + qty: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// An expression that reads the list itself reads every child. +#[test] +fn list_reads_keep_the_list() -> VortexResult<()> { + let expr = list_contains(root(), lit(3i32)); + let plan = ListPackPlan::try_new( + Nullability::NonNullable, + 5, + flat(6, i32(), 0), + flat(6, DType::Primitive(PType::U64, Nullability::NonNullable), 1), + None, + )? + .into_plan(); + insta::assert_snapshot!(optimized(&expr, plan)?, @r" + root: vortex.plan.eval(bool, rows=5) expr=vortex.list.contains($, 3i32) + child: vortex.plan.list_pack(list(i32), rows=5) + elements: vortex.plan.filter(i32, rows=6) + child: vortex.test.source(i32, rows=6) + offsets: vortex.plan.filter(u64, rows=6) + child: vortex.test.source(u64, rows=6) + "); + Ok(()) +} + +/// Lists `[{1, 10}, {2, 20}]`, null (hiding `[{3, i32::MAX}]`), `[]`, `[{4, 40}, {5, 50}]` and +/// `[{6, i32::MAX}]`, of `{sku: i32, qty: i32}` elements, stored with their element fields in two +/// chunks each, and a plan reading them. +fn stored_items(store: &Store) -> VortexResult<(ArrayRef, PlanRef)> { + let mut ctx = SESSION.create_execution_ctx(); + let skus = buffer![1i32, 2, 3, 4, 5, 6].into_array(); + let qtys = buffer![10i32, 20, i32::MAX, 40, 50, i32::MAX].into_array(); + let offsets = buffer![0u32, 2, 3, 3, 5, 6].into_array(); + let validity = Validity::from_iter([true, false, true, true, true]); + let elements = StructArray::from_fields(&[("sku", skus.clone()), ("qty", qtys.clone())])?; + let list = ListArray::try_new( + elements.into_array(), + offsets.clone(), + validity.clone(), + &mut ctx, + )? + .into_array(); + + let elements = struct_plan( + 6, + struct_of(&["sku", "qty"]), + vec![ + store.chunked(&skus, &[3, 3])?, + store.chunked(&qtys, &[3, 3])?, + ], + ); + let validity = validity.to_array(5); + let plan = ListPackPlan::try_new( + Nullability::Nullable, + 5, + elements, + store.flat(&offsets)?, + Some(store.flat(&validity)?), + )? + .into_plan(); + Ok((list, plan)) +} + +/// Runs `plan` over the rows of `rows` that `mask` selects, delivering the bytes of `store`, and +/// counts the segments it reads. +fn run( + store: &Store, + plan: PlanRef, + rows: Range, + mask: Mask, +) -> VortexResult<(ArrayRef, usize)> { + let dtype = plan.dtype().clone(); + let mut scan = Scan::try_new(SESSION.clone(), plan, vec![Split { rows, mask }])?; + let mut outputs = Vec::new(); + let mut reads = 0; + loop { + match scan.step()? { + Turn::Read(read) => { + reads += 1; + scan.deliver(read.id, store.read(read.segment_id))?; + } + Turn::Output(_, array) => outputs.push(array), + Turn::Waiting => unreachable!("every read is delivered at once"), + Turn::Done => break, + } + } + let array = ChunkedArray::try_new(outputs, dtype)?.into_array(); + let array = array + .execute::(&mut SESSION.create_execution_ctx())? + .0 + .into_array(); + Ok((array, reads)) +} + +/// A list reads the offsets of its selected rows, the validity of the selected lists and, of each +/// element field its expression reads, the chunks that hold the elements of the selected valid +/// lists: `chunks` of the two. A null or empty list reads no element. +#[rstest] +#[case::full(0..5, Mask::new_true(5), 2)] +#[case::first_chunk(0..1, Mask::new_true(1), 1)] +#[case::second_chunk(3..5, Mask::from_iter([true, false]), 1)] +#[case::spanning(0..4, Mask::from_iter([true, false, true, true]), 2)] +#[case::null_list(1..2, Mask::new_true(1), 0)] +#[case::empty_list(2..3, Mask::new_true(1), 0)] +fn lists_read_elements_of_selected_valid_lists( + #[case] rows: Range, + #[case] mask: Mask, + #[case] chunks: usize, + #[values((root(), 2), (sku()?, 1), (qty()?, 1))] read: (Expression, usize), +) -> VortexResult<()> { + let (expr, fields) = read; + let store = Store::default(); + let (list, plan) = stored_items(&store)?; + let plan = optimize( + EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(), + &SESSION, + )?; + let expected = list + .slice(usize::try_from(rows.start)?..usize::try_from(rows.end)?)? + .filter(mask.clone())? + .apply(&expr)?; + let (actual, reads) = run(&store, plan, rows, mask)?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + assert_eq!(reads, 2 + chunks * fields); + Ok(()) +} + +/// A lambda that can fail runs only on the elements of the selected valid lists. +#[rstest] +#[case::hidden_by_null(0..4, Mask::new_true(4), true)] +#[case::hidden_by_selection(3..5, Mask::from_iter([true, false]), true)] +#[case::selected(4..5, Mask::new_true(1), false)] +fn fallible_lambdas_run_on_selected_valid_lists( + #[case] rows: Range, + #[case] mask: Mask, + #[case] succeeds: bool, +) -> VortexResult<()> { + let expr = list_transform( + root(), + Lambda::new(["x"], checked_add(get_item("qty", var("x")), lit(1i32)))?, + ); + let store = Store::default(); + let (list, plan) = stored_items(&store)?; + let plan = optimize( + EvalPlan::try_new(expr.bind(plan.dtype())?, plan)?.into_plan(), + &SESSION, + )?; + let result = run(&store, plan, rows.clone(), mask.clone()); + assert_eq!(result.is_ok(), succeeds); + if let Ok((actual, _)) = result { + let expected = list + .slice(usize::try_from(rows.start)?..usize::try_from(rows.end)?)? + .filter(mask)? + .apply(&expr)?; + assert_arrays_eq!(actual, expected, &mut SESSION.create_execution_ctx()); + } + Ok(()) +} + +/// Offsets that decrease or run past the elements fail the read rather than build invalid lists. +#[rstest] +#[case::decreasing(buffer![0u32, 2, 1].into_array())] +#[case::past_the_elements(buffer![0u32, 2, 4].into_array())] +fn corrupt_offsets_fail(#[case] offsets: ArrayRef) -> VortexResult<()> { + let store = Store::default(); + let plan = ListPackPlan::try_new( + Nullability::NonNullable, + 2, + store.flat(&buffer![1i32, 2, 3].into_array())?, + store.flat(&offsets)?, + None, + )? + .into_plan(); + assert!(run(&store, plan, 0..2, Mask::new_true(2)).is_err()); + Ok(()) +} diff --git a/vortex-scan/src/plan/builtins/mod.rs b/vortex-scan/src/plan/builtins/mod.rs index 75c038e6eb1..1bcf1a4c763 100644 --- a/vortex-scan/src/plan/builtins/mod.rs +++ b/vortex-scan/src/plan/builtins/mod.rs @@ -24,9 +24,11 @@ pub use eval::EvalPlan; pub use filter::Filter; pub use filter::FilterData; pub use filter::FilterPlan; +pub(crate) use list_pack::ExpressionListPackRule; pub use list_pack::ListPack; pub use list_pack::ListPackData; pub use list_pack::ListPackPlan; +pub use list_pack::ListTransforms; pub(crate) use pack::ExpressionPackRule; pub use pack::Pack; pub use pack::PackData; diff --git a/vortex-scan/src/plan/builtins/pack/mod.rs b/vortex-scan/src/plan/builtins/pack/mod.rs index 06c319fdd0d..bb40ee8edab 100644 --- a/vortex-scan/src/plan/builtins/pack/mod.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -8,6 +8,7 @@ pub(crate) mod execute; mod pruning; +mod strict_functions; use std::borrow::Cow; use std::iter; @@ -43,6 +44,7 @@ use vortex_session::VortexSession; use vortex_session::registry::CachedId; use self::pruning::weaken_pruning_proof; +use self::strict_functions::ApplyStrictFunctionsInsideMasks; use crate::execution::operators::OnceSource; use crate::execution::operators::PackSource; use crate::execution::operators::WrapStage; @@ -355,6 +357,9 @@ impl PackPlan { /// /// The next pass pushes the lookup into the `address` child as `$.zip`. The scan can /// skip `city` and read just `zip` and the validity of each nullable ancestor. +/// +/// Strict functions that cannot fail move inside the masks the same way, so +/// `list_transform($.items, x -> x.sku)` reaches the `items` child and reads only `sku`. #[derive(Debug)] pub(crate) enum ExpressionPackRule { /// Preserves the value of the expression for every row. @@ -398,6 +403,9 @@ impl PlanParentReduceRule for ExpressionPackRule { let nullable = child.dtype().is_nullable(); if nullable { combiner = combiner.rewrite(&mut ProjectMaskedFields)?.into_inner(); + combiner = combiner + .rewrite(&mut ApplyStrictFunctionsInsideMasks)? + .into_inner(); // Stored statistics can weaken a proof. This rewrite is valid only when a true // result means the zone can be discarded. diff --git a/vortex-scan/src/plan/builtins/pack/strict_functions.rs b/vortex-scan/src/plan/builtins/pack/strict_functions.rs new file mode 100644 index 00000000000..da1a39293fc --- /dev/null +++ b/vortex-scan/src/plan/builtins/pack/strict_functions.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Moves strict functions that cannot fail inside the validity masks of a nullable struct's fields. +//! +//! The partition rules of a nullable [`Pack`](super::Pack) read a field as `mask(field, validity)`, +//! so a function of the field stays above the mask and the field's plan never sees it. For +//! `list_transform($.items, x -> x.sku)`, the list would then read every element column. Moving +//! the function inside the mask lets the next pass push it into the field's plan, where a list +//! reads only the `sku` elements. + +use vortex_array::expr::BoundExpression; +use vortex_array::expr::bound; +use vortex_array::expr::traversal::NodeRewriter; +use vortex_array::expr::traversal::Transformed; +use vortex_array::scalar_fn::fns::mask::Mask; +use vortex_error::VortexResult; + +/// Rewrites `f(mask(x, v))` as `mask(f(x), v)` for a function `f` of one argument that is strict +/// and cannot fail. +/// +/// A strict function is null wherever its argument is, so the mask keeps the same rows null. A +/// function that cannot fail may run on the values that `v` hides. A function that can fail, such +/// as a lambda that can overflow, stays above the mask, so it never runs on a hidden value. A +/// function that is not strict, such as `is_null`, also stays above it, because its result is not +/// null where the struct is. +/// +/// Field reads are strict and cannot fail, so this also moves a field read that a lifted function +/// exposes, as in `ext_storage(mask(p, v)).a`. +pub(super) struct ApplyStrictFunctionsInsideMasks; + +impl NodeRewriter for ApplyStrictFunctionsInsideMasks { + type NodeTy = BoundExpression; + + fn visit_up(&mut self, node: BoundExpression) -> VortexResult> { + let [input] = node.children() else { + return Ok(Transformed::no(node)); + }; + if !input.is::() || !is_strict_and_infallible(&node) { + return Ok(Transformed::no(node)); + } + + let applied = apply_inside_masks(&node, input)?; + // A strict function of a nullable input returns a nullable dtype, which the masks give the + // result too. Should a function break that contract, the expressions above it would change + // type, so it stays above the masks. + if applied.dtype() != node.dtype() { + return Ok(Transformed::no(node)); + } + + Ok(Transformed::yes(applied)) + } +} + +/// Whether `node` is a function that is null wherever its argument is, and cannot fail. +fn is_strict_and_infallible(node: &BoundExpression) -> bool { + node.as_scalar().is_some_and(|scalar_fn| { + let signature = scalar_fn.signature(); + signature.is_strict() && signature.is_infallible() + }) +} + +/// Applies the function of `node` to the input of the masks in `input`, beneath all of them. +fn apply_inside_masks( + node: &BoundExpression, + input: &BoundExpression, +) -> VortexResult { + if !input.is::() { + return node.clone().with_children([input.clone()]); + } + + let applied = apply_inside_masks(node, input.child(0))?; + Ok(bound::mask(applied, input.child(1).clone())) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use rstest::rstest; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::StructFields; + use vortex_array::expr::Expression; + use vortex_array::expr::Lambda; + use vortex_array::expr::checked_add; + use vortex_array::expr::eq; + use vortex_array::expr::get_item; + use vortex_array::expr::is_not_null; + use vortex_array::expr::is_null; + use vortex_array::expr::list_length; + use vortex_array::expr::list_transform; + use vortex_array::expr::lit; + use vortex_array::expr::mask; + use vortex_array::expr::not; + use vortex_array::expr::root; + use vortex_array::expr::traversal::NodeExt; + use vortex_array::expr::var; + use vortex_error::VortexResult; + + use super::ApplyStrictFunctionsInsideMasks; + + /// The list `l` of a nullable `{l: list(i64)}`, read through the struct's validity. + fn masked_list() -> Expression { + mask(get_item("l", root()), is_not_null(root())) + } + + /// Rewrites `expr` over a nullable `{l: list(i64)}`, returning the result in display form. + fn rewritten(expr: Expression) -> VortexResult { + let dtype = DType::Struct( + StructFields::from_iter([( + "l", + DType::List( + Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)), + Nullability::NonNullable, + ), + )]), + Nullability::Nullable, + ); + let expr = expr.bind(&dtype)?; + Ok(expr + .rewrite(&mut ApplyStrictFunctionsInsideMasks)? + .into_inner() + .to_string()) + } + + /// A strict function of one argument that cannot fail moves inside the masks, so the list's + /// plan can push it into the elements. A function that can fail would run on the lists that + /// the mask hides, and one that is not strict is not null where the struct is, so both stay + /// above it. + #[rstest] + #[case::transform( + list_transform(masked_list(), Lambda::new(["x"], not(eq(var("x"), lit(0i64))))?), + "vortex.mask(vortex.list.transform($.l, (x) -> vortex.not(($.x = 0i64))), is_not_null($))" + )] + #[case::length( + not(eq(list_length(masked_list()), lit(0u64))), + "vortex.not((vortex.mask(vortex.list.length($.l), is_not_null($)) = 0u64))" + )] + #[case::nested_masks( + list_length(mask(masked_list(), is_not_null(get_item("l", root())))), + "vortex.mask(vortex.mask(vortex.list.length($.l), is_not_null($)), is_not_null($.l))" + )] + #[case::fallible( + list_transform(masked_list(), Lambda::new(["x"], checked_add(var("x"), lit(1i64)))?), + "vortex.list.transform(vortex.mask($.l, is_not_null($)), (x) -> ($.x + 1i64))" + )] + #[case::not_strict( + is_null(masked_list()), + "vortex.is_null(vortex.mask($.l, is_not_null($)))" + )] + fn applies_strict_functions_that_cannot_fail_inside_masks( + #[case] expr: Expression, + #[case] expected: &str, + ) -> VortexResult<()> { + assert_eq!(rewritten(expr)?, expected); + Ok(()) + } +} diff --git a/vortex-scan/src/plan/mod.rs b/vortex-scan/src/plan/mod.rs index c65eab1a482..8c1671a3b22 100644 --- a/vortex-scan/src/plan/mod.rs +++ b/vortex-scan/src/plan/mod.rs @@ -36,6 +36,7 @@ pub use builtins::FilterPlan; pub use builtins::ListPack; pub use builtins::ListPackData; pub use builtins::ListPackPlan; +pub use builtins::ListTransforms; pub use builtins::Pack; pub use builtins::PackData; pub use builtins::PackPlan; diff --git a/vortex-scan/src/plan/optimize/registry.rs b/vortex-scan/src/plan/optimize/registry.rs index e6b256e49d6..0dd9f8ae7fc 100644 --- a/vortex-scan/src/plan/optimize/registry.rs +++ b/vortex-scan/src/plan/optimize/registry.rs @@ -10,6 +10,7 @@ use super::OptimizeMode; use super::rules::*; use crate::plan::Concat; use crate::plan::Eval; +use crate::plan::ListPack; use crate::plan::Pack; use crate::plan::PlanRef; use crate::plan::Take; @@ -18,6 +19,7 @@ use crate::plan::builtins::EvalEvalRule; use crate::plan::builtins::EvalIdentityRule; use crate::plan::builtins::EvalPackRule; use crate::plan::builtins::ExpressionConcatRule; +use crate::plan::builtins::ExpressionListPackRule; use crate::plan::builtins::ExpressionPackRule; use crate::plan::builtins::ExpressionTakeRule; use crate::plan::builtins::ExpressionZonedRule; @@ -47,21 +49,24 @@ static PRUNING_PACK_RULE: PlanParentReduceRuleAdapter PlanParentReduceRuleAdapter::new(ExpressionPackRule::Pruning); static EXPRESSION_ZONED_RULE: PlanParentReduceRuleAdapter = PlanParentReduceRuleAdapter::new(ExpressionZonedRule); +static EXPRESSION_LIST_PACK_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(ExpressionListPackRule); const fn parent_rules( pack_rule: &'static dyn DynPlanParentReduceRule, -) -> [&'static dyn DynPlanParentReduceRule; 5] { +) -> [&'static dyn DynPlanParentReduceRule; 6] { [ &EVAL_EVAL_RULE, &EXPRESSION_CONCAT_RULE, &EXPRESSION_TAKE_RULE, pack_rule, &EXPRESSION_ZONED_RULE, + &EXPRESSION_LIST_PACK_RULE, ] } -static EXACT_PARENT_RULES: [&dyn DynPlanParentReduceRule; 5] = parent_rules(&EXACT_PACK_RULE); -static PRUNING_PARENT_RULES: [&dyn DynPlanParentReduceRule; 5] = parent_rules(&PRUNING_PACK_RULE); +static EXACT_PARENT_RULES: [&dyn DynPlanParentReduceRule; 6] = parent_rules(&EXACT_PACK_RULE); +static PRUNING_PARENT_RULES: [&dyn DynPlanParentReduceRule; 6] = parent_rules(&PRUNING_PACK_RULE); /// Attempts a static rewrite for `plan`. pub(crate) fn reduce_plan(