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-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..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; @@ -51,6 +53,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; @@ -173,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( @@ -266,6 +277,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 +758,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 +802,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 @@ -926,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/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, 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?; 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..56c721b96bd 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests/mod.rs @@ -1,8 +1,15 @@ // 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 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/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/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/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/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..8b42400176f 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() @@ -313,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)); }; @@ -381,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( @@ -550,8 +603,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 +644,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 +684,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 @@ -677,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; @@ -691,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; @@ -707,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; @@ -2311,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/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/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/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/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 54% rename from vortex-layout/src/scan/v2/tests.rs rename to vortex-layout/src/scan/v2/tests/mod.rs index a8219d3014e..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; @@ -10,6 +12,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 +21,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 +30,31 @@ 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::list_contains; +use vortex_array::expr::list_length; 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 +72,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 +82,29 @@ 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::repartition::RepartitionStrategy; +use crate::layouts::repartition::RepartitionWriterOptions; 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 +190,36 @@ 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 [`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, @@ -479,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] @@ -568,6 +666,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-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-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/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/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 a76ed8d34ed..bb40ee8edab 100644 --- a/vortex-scan/src/plan/builtins/pack/mod.rs +++ b/vortex-scan/src/plan/builtins/pack/mod.rs @@ -7,6 +7,8 @@ //! expression that uses part of the struct can read the relevant children directly. pub(crate) mod execute; +mod pruning; +mod strict_functions; use std::borrow::Cow; use std::iter; @@ -41,6 +43,8 @@ use vortex_mask::Mask; 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; @@ -55,6 +59,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; @@ -352,8 +357,16 @@ 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) 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 +403,15 @@ 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. + 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/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/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..0dd9f8ae7fc 100644 --- a/vortex-scan/src/plan/optimize/registry.rs +++ b/vortex-scan/src/plan/optimize/registry.rs @@ -6,9 +6,11 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; +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; @@ -17,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; @@ -34,21 +37,36 @@ 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, -]); +static EXPRESSION_LIST_PACK_RULE: PlanParentReduceRuleAdapter = + PlanParentReduceRuleAdapter::new(ExpressionListPackRule); + +const fn parent_rules( + pack_rule: &'static dyn DynPlanParentReduceRule, +) -> [&'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; 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( @@ -62,13 +80,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), } 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 = []