diff --git a/AGENTS.md b/AGENTS.md index 003df93ec1f..f564de07b52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,8 @@ documentation in `docs/`, and benchmark tooling in `vortex-bench/` and `benchmar - `vortex-array` contains the core `Array` trait and the base encodings, including most Apache Arrow-style encodings. - `encodings/*` contains more specialized compressed encodings. +- `vortex-expr` contains expression trees, their optimizer, and the analyses and rewrites built on + them. `vortex-functions` contains the scalar functions that `vortex-array` itself is not built on. - `vortex-file` implements file IO. It uses `LayoutReader` from `vortex-layout`. - `vortex-io` holds the core async and blocking IO traits, plus the generic `object_store` adapters that implement them. diff --git a/Cargo.lock b/Cargo.lock index bd9b71f7542..dc783f5c7df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11162,6 +11162,7 @@ dependencies = [ "vortex-buffer", "vortex-decimal-byte-parts", "vortex-error", + "vortex-expr", "vortex-fsst", "vortex-functions", "vortex-mask", @@ -11653,14 +11654,20 @@ dependencies = [ name = "vortex-expr" version = "0.1.0" dependencies = [ + "arbitrary", + "codspeed-divan-compat", + "insta", "itertools 0.14.0", + "mimalloc", "parking_lot", + "prost 0.14.6", "rstest", + "smallvec", "tracing", "vortex-array", "vortex-buffer", "vortex-error", - "vortex-functions", + "vortex-mask", "vortex-session", "vortex-utils", ] @@ -11787,6 +11794,7 @@ dependencies = [ "vortex-array", "vortex-buffer", "vortex-error", + "vortex-expr", "vortex-functions", "vortex-mask", "vortex-session", @@ -11816,6 +11824,7 @@ dependencies = [ "vortex-buffer", "vortex-compute", "vortex-error", + "vortex-expr", "vortex-mask", "vortex-session", "vortex-utils", @@ -11842,6 +11851,7 @@ dependencies = [ "vortex-buffer", "vortex-cuda", "vortex-error", + "vortex-expr", "vortex-file", "vortex-fsst", "vortex-functions", @@ -11951,6 +11961,7 @@ dependencies = [ "vortex-arrow", "vortex-edition", "vortex-error", + "vortex-expr", "vortex-functions", "vortex-session", ] @@ -12085,6 +12096,7 @@ dependencies = [ "vortex-buffer", "vortex-edition", "vortex-error", + "vortex-expr", "vortex-file", "vortex-functions", "vortex-io", @@ -12225,6 +12237,7 @@ dependencies = [ "vortex-buffer", "vortex-compute", "vortex-error", + "vortex-expr", "vortex-functions", "vortex-mask", "vortex-session", diff --git a/docs/concepts/expressions.md b/docs/concepts/expressions.md index 81317a2b888..d6591ee80fb 100644 --- a/docs/concepts/expressions.md +++ b/docs/concepts/expressions.md @@ -9,8 +9,10 @@ to the returned data. Expressions are defined as abstract scalar functions. These vtables define the signature of the function, properties such as whether the function is strict, and the actual logic for executing the function over input arrays. -The built-in scalar functions can be found in the `vortex-array::expr` module, with additional use-case specific -functions provided by integration and plugin crates. +The scalar function framework and the handful of functions the array crate itself is built on live in +`vortex_array::scalar_fn`; expression trees, their optimizer and the analyses built on them live in the +`vortex-expr` crate; `vortex-functions` holds the rest of the built-in scalar functions, with additional +use-case specific functions provided by integration and plugin crates. In the future, we plan to add full support for spatial functions, date-time functions, and more. diff --git a/encodings/datetime-parts/src/compute/take.rs b/encodings/datetime-parts/src/compute/take.rs index 06e896508b4..6d33c4a0150 100644 --- a/encodings/datetime-parts/src/compute/take.rs +++ b/encodings/datetime-parts/src/compute/take.rs @@ -9,9 +9,9 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::dict::TakeExecute; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::Nullability; -use vortex_array::expr::stats::Stat; -use vortex_array::expr::stats::StatsProvider; use vortex_array::scalar::Scalar; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; use vortex_error::VortexResult; use vortex_error::vortex_panic; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs index 6058966737d..1efdb1718e9 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/mod.rs @@ -23,10 +23,10 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::WidenArray; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalType; -use vortex_array::expr::stats::Stat; use vortex_array::match_each_signed_integer_ptype; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; +use vortex_array::stats::Stat; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_mask::Mask; diff --git a/encodings/elias-fano/src/unary/tests.rs b/encodings/elias-fano/src/unary/tests.rs index 3ddba58729e..a5f4cffadd4 100644 --- a/encodings/elias-fano/src/unary/tests.rs +++ b/encodings/elias-fano/src/unary/tests.rs @@ -33,12 +33,12 @@ use vortex_array::compute::conformance::consistency::test_array_consistency; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; -use vortex_array::expr::stats::Precision; -use vortex_array::expr::stats::Stat; use vortex_array::match_each_unsigned_integer_ptype; use vortex_array::scalar::ScalarValue; use vortex_array::serde::SerializeOptions; use vortex_array::serde::SerializedArray; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; use vortex_array::test_harness::check_metadata; use vortex_array::validity::Validity; use vortex_array::vtable::VTable; diff --git a/encodings/fastlanes/src/for_/array/for_compress.rs b/encodings/fastlanes/src/for_/array/for_compress.rs index b133b97e436..348eefd3922 100644 --- a/encodings/fastlanes/src/for_/array/for_compress.rs +++ b/encodings/fastlanes/src/for_/array/for_compress.rs @@ -14,10 +14,10 @@ use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; -use vortex_array::expr::stats::Stat; use vortex_array::match_each_integer_ptype; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; +use vortex_array::stats::Stat; use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::BitBufferView; @@ -230,8 +230,8 @@ mod test { use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_array::assert_arrays_eq; use vortex_array::dtype::PType; - use vortex_array::expr::stats::StatsProvider; use vortex_array::scalar::Scalar; + use vortex_array::stats::StatsProvider; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; diff --git a/encodings/fsst/Cargo.toml b/encodings/fsst/Cargo.toml index 3d6313686dd..691842af042 100644 --- a/encodings/fsst/Cargo.toml +++ b/encodings/fsst/Cargo.toml @@ -22,6 +22,7 @@ rand = { workspace = true, optional = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } +vortex-expr = { workspace = true } vortex-functions = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } @@ -36,6 +37,7 @@ rand = { workspace = true } rstest = { workspace = true } test-with = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } +vortex-expr = { workspace = true } [[bench]] name = "fsst_compress" diff --git a/encodings/fsst/benches/fsst_url_compare.rs b/encodings/fsst/benches/fsst_url_compare.rs index 388477ac0b0..26e272cccb2 100644 --- a/encodings/fsst/benches/fsst_url_compare.rs +++ b/encodings/fsst/benches/fsst_url_compare.rs @@ -16,14 +16,15 @@ use vortex_array::arrays::VarBinArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::varbin::VarBinArrayExt; use vortex_array::builtins::ArrayBuiltins; -use vortex_array::expr::lit; -use vortex_array::expr::root; use vortex_array::memory::MemorySession; use vortex_array::optimizer::kernels::KernelSession; use vortex_array::scalar::Scalar; use vortex_array::scalar_fn::builtin::operators::Operator; use vortex_array::session::ArraySession; use vortex_array::test_harness::mark_optimized; +use vortex_expr::ArrayExprExt; +use vortex_expr::lit; +use vortex_expr::root; use vortex_fsst::fsst_compress; use vortex_fsst::fsst_train_compressor; use vortex_fsst::test_utils::HIGH_MATCH_DOMAIN; diff --git a/encodings/fsst/src/compress.rs b/encodings/fsst/src/compress.rs index c9cb16816f5..74c8e5ffd5b 100644 --- a/encodings/fsst/src/compress.rs +++ b/encodings/fsst/src/compress.rs @@ -26,9 +26,9 @@ use vortex_array::buffer::BufferHandle; use vortex_array::dtype::DType; use vortex_array::dtype::IntegerPType; use vortex_array::dtype::OffsetBuilderPType; -use vortex_array::expr::stats::Precision; -use vortex_array::expr::stats::Stat; use vortex_array::match_each_integer_ptype; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; use vortex_array::validity::Validity; use vortex_buffer::Alignment; use vortex_buffer::BufferAllocatorRef; diff --git a/encodings/fsst/src/compute/mod.rs b/encodings/fsst/src/compute/mod.rs index 41225acfc60..ddfc54b24ad 100644 --- a/encodings/fsst/src/compute/mod.rs +++ b/encodings/fsst/src/compute/mod.rs @@ -20,11 +20,11 @@ use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_array::arrays::varbin::take_varbin; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::IntegerPType; -use vortex_array::expr::stats::Stat; -use vortex_array::expr::stats::StatsProviderExt; use vortex_array::match_each_integer_ptype; use vortex_array::match_each_unsigned_integer_ptype; use vortex_array::scalar::Scalar; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProviderExt; use vortex_error::VortexResult; use vortex_mask::AllOr; @@ -174,9 +174,9 @@ mod tests { use vortex_array::compute::conformance::take::test_take_conformance; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; - use vortex_array::expr::stats::Precision; - use vortex_array::expr::stats::Stat; use vortex_array::optimizer::ArrayOptimizer; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; diff --git a/encodings/fsst/src/kernel.rs b/encodings/fsst/src/kernel.rs index 840594d7b17..c9184dc5eae 100644 --- a/encodings/fsst/src/kernel.rs +++ b/encodings/fsst/src/kernel.rs @@ -44,8 +44,9 @@ mod tests { use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; - use vortex_array::expr::root; use vortex_error::VortexResult; + use vortex_expr::ArrayExprExt; + use vortex_expr::root; use vortex_functions::expr::byte_length; use vortex_mask::Mask; use vortex_session::VortexSession; diff --git a/encodings/parquet-variant/Cargo.toml b/encodings/parquet-variant/Cargo.toml index ce8776645c7..acbe69151db 100644 --- a/encodings/parquet-variant/Cargo.toml +++ b/encodings/parquet-variant/Cargo.toml @@ -39,6 +39,7 @@ rstest = { workspace = true } tokio = { workspace = true, features = ["full"] } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } +vortex-expr = { workspace = true } vortex-file = { workspace = true, features = ["tokio"] } vortex-io = { workspace = true, features = ["tokio"] } vortex-layout = { workspace = true } diff --git a/encodings/parquet-variant/src/arrow.rs b/encodings/parquet-variant/src/arrow.rs index 041686f007b..36287bff2b0 100644 --- a/encodings/parquet-variant/src/arrow.rs +++ b/encodings/parquet-variant/src/arrow.rs @@ -53,6 +53,7 @@ use vortex_arrow::to_arrow_null_buffer; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; +use vortex_functions::builtins::ArrayFunctions; use vortex_session::registry::CachedId; use vortex_session::registry::Id; diff --git a/encodings/parquet-variant/src/json_to_variant_tests.rs b/encodings/parquet-variant/src/json_to_variant_tests.rs index 16febc9d8ce..0399a46aa72 100644 --- a/encodings/parquet-variant/src/json_to_variant_tests.rs +++ b/encodings/parquet-variant/src/json_to_variant_tests.rs @@ -26,10 +26,11 @@ use vortex_array::assert_nth_scalar_is_null; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; -use vortex_array::expr::root; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; +use vortex_expr::ArrayExprExt; +use vortex_expr::root; use vortex_functions::expr::variant_get; use vortex_functions::variant_get::VariantPath; use vortex_json::Json; diff --git a/encodings/parquet-variant/src/kernel.rs b/encodings/parquet-variant/src/kernel.rs index a550161e878..2f157c9d084 100644 --- a/encodings/parquet-variant/src/kernel.rs +++ b/encodings/parquet-variant/src/kernel.rs @@ -326,7 +326,6 @@ mod tests { use vortex_array::dtype::DType as VortexDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::expr::root; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::validity::Validity; use vortex_arrow::ArrowSessionExt; @@ -334,6 +333,8 @@ mod tests { use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_err; + use vortex_expr::ArrayExprExt; + use vortex_expr::root; use vortex_functions::expr::variant_get; use vortex_functions::variant_get::VariantPath; use vortex_functions::variant_get::VariantPathElement; diff --git a/encodings/sequence/Cargo.toml b/encodings/sequence/Cargo.toml index e8ce273483b..ce6ee9c1fb1 100644 --- a/encodings/sequence/Cargo.toml +++ b/encodings/sequence/Cargo.toml @@ -20,6 +20,7 @@ vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } vortex-error = { workspace = true } +vortex-expr = { workspace = true } vortex-functions = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } diff --git a/encodings/sequence/src/array/mod.rs b/encodings/sequence/src/array/mod.rs index daf9e37a7ad..8917ea754df 100644 --- a/encodings/sequence/src/array/mod.rs +++ b/encodings/sequence/src/array/mod.rs @@ -26,14 +26,14 @@ use vortex_array::dtype::DType; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; -use vortex_array::expr::stats::Precision as StatPrecision; -use vortex_array::expr::stats::Stat; use vortex_array::match_each_integer_ptype; use vortex_array::match_each_pvalue; use vortex_array::proto::scalar::ScalarValue as ProtoScalarValue; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; +use vortex_array::stats::Precision as StatPrecision; +use vortex_array::stats::Stat; use vortex_array::stats::StatsSet; use vortex_array::validity::Validity; use vortex_array::vtable::OperationsVTable; @@ -518,14 +518,14 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::expr::stats::Precision as StatPrecision; - use vortex_array::expr::stats::Stat; - use vortex_array::expr::stats::StatsProviderExt; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::serde::SerializeOptions; use vortex_array::serde::SerializedArray; + use vortex_array::stats::Precision as StatPrecision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProviderExt; use vortex_buffer::ByteBufferMut; use vortex_error::VortexResult; use vortex_error::vortex_err; diff --git a/encodings/sequence/src/compute/list_contains.rs b/encodings/sequence/src/compute/list_contains.rs index 926510981c1..881298a0008 100644 --- a/encodings/sequence/src/compute/list_contains.rs +++ b/encodings/sequence/src/compute/list_contains.rs @@ -97,11 +97,12 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType::I32; - use vortex_array::expr::lit; - use vortex_array::expr::root; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; + use vortex_expr::ArrayExprExt; + use vortex_expr::lit; + use vortex_expr::root; use vortex_functions::expr::list_contains; use vortex_functions::expr::list_contains_opts; use vortex_functions::list_contains::ListContainsOptions; diff --git a/encodings/zstd/src/zstd_buffers/mod.rs b/encodings/zstd/src/zstd_buffers/mod.rs index 49abfdad44a..ceca770c443 100644 --- a/encodings/zstd/src/zstd_buffers/mod.rs +++ b/encodings/zstd/src/zstd_buffers/mod.rs @@ -580,12 +580,12 @@ mod tests { use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::assert_arrays_eq; - use vortex_array::expr::stats::Precision; - use vortex_array::expr::stats::Stat; - use vortex_array::expr::stats::StatsProvider; use vortex_array::serde::SerializeOptions; use vortex_array::serde::SerializedArray; use vortex_array::session::ArraySessionExt; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProvider; use vortex_buffer::ByteBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index ec54202f0ac..c38d028f3c5 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -48,6 +48,7 @@ vortex-array = { workspace = true, features = ["arbitrary", "_test-harness"] } vortex-btrblocks = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } +vortex-expr = { workspace = true, features = ["arbitrary"] } vortex-fsst = { workspace = true, features = ["_test-harness"] } vortex-functions = { workspace = true } vortex-io = { workspace = true, features = ["wasm-bindgen"] } diff --git a/fuzz/fuzz_targets/file_io.rs b/fuzz/fuzz_targets/file_io.rs index 543ea76db0e..511755278a0 100644 --- a/fuzz/fuzz_targets/file_io.rs +++ b/fuzz/fuzz_targets/file_io.rs @@ -6,6 +6,8 @@ use itertools::Itertools; use libfuzzer_sys::Corpus; use libfuzzer_sys::fuzz_target; +use vortex::expr::lit; +use vortex::expr::root; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -15,10 +17,9 @@ use vortex_array::arrays::bool::BoolArrayExt; use vortex_array::assert_arrays_eq; use vortex_array::dtype::DType; use vortex_array::dtype::StructFields; -use vortex_array::expr::lit; -use vortex_array::expr::root; use vortex_btrblocks::BtrBlocksCompressorBuilder; use vortex_error::VortexExpect; +use vortex_expr::ArrayExprExt; use vortex_file::OpenOptionsSessionExt; use vortex_file::WriteOptionsSessionExt; use vortex_file::WriteStrategyBuilder; diff --git a/fuzz/src/array/sum/tests.rs b/fuzz/src/array/sum/tests.rs index 3e31e629887..0455c05bff9 100644 --- a/fuzz/src/array/sum/tests.rs +++ b/fuzz/src/array/sum/tests.rs @@ -20,11 +20,11 @@ use vortex_array::dtype::DecimalType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::i256; -use vortex_array::expr::stats::Precision; -use vortex_array::expr::stats::Stat; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; diff --git a/fuzz/src/file/mod.rs b/fuzz/src/file/mod.rs index f4fdc6d6ce1..f2254f99d7c 100644 --- a/fuzz/src/file/mod.rs +++ b/fuzz/src/file/mod.rs @@ -3,13 +3,13 @@ use arbitrary::Arbitrary; use arbitrary::Unstructured; +use vortex::expr::Expression; use vortex_array::ArrayRef; use vortex_array::arrays::arbitrary::ArbitraryArray; use vortex_array::arrays::arbitrary::ArbitraryArrayConfig; use vortex_array::arrays::arbitrary::ArbitraryWith; -use vortex_array::expr::Expression; -use vortex_array::expr::arbitrary::filter_expr; -use vortex_array::expr::arbitrary::projection_expr; +use vortex_expr::arbitrary::filter_expr; +use vortex_expr::arbitrary::projection_expr; use crate::FUZZ_FILE_ARRAY_MAX_LEN; use crate::array::CompressorStrategy; diff --git a/fuzz/src/fsst_like.rs b/fuzz/src/fsst_like.rs index 8ab863616a6..168c3d64615 100644 --- a/fuzz/src/fsst_like.rs +++ b/fuzz/src/fsst_like.rs @@ -9,6 +9,8 @@ use std::sync::LazyLock; use arbitrary::Arbitrary; use arbitrary::Unstructured; +use vortex::functions::like::Like; +use vortex::functions::like::LikeOptions; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -23,8 +25,6 @@ use vortex_error::VortexResult; use vortex_fsst::FSSTArray; use vortex_fsst::fsst_compress; use vortex_fsst::fsst_train_compressor; -use vortex_functions::like::Like; -use vortex_functions::like::LikeOptions; use vortex_session::VortexSession; use crate::error::Backtrace; diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index 45e4be04a61..8204f263cad 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -30,8 +30,6 @@ "dict_compress": 31, "dict_mask": 16, "dict_unreferenced_mask": 10, - "expr_large_struct_pack": 4, - "expr_optimize": 1, "filter_bool": 51, "filter_fixed_width": 30, "filter_fsl": 4, @@ -107,6 +105,10 @@ "vortex-elias-fano": { "unary": 20 }, + "vortex-expr": { + "expr_large_struct_pack": 4, + "expr_optimize": 1 + }, "vortex-fastlanes": { "bitpack_blocked": 0, "bitpack_blocked_decompress": 0, diff --git a/scripts/codspeed_bench_durations.json b/scripts/codspeed_bench_durations.json index fb7b6ddb336..2fc9523a973 100644 --- a/scripts/codspeed_bench_durations.json +++ b/scripts/codspeed_bench_durations.json @@ -28,8 +28,6 @@ "dict_compress": 4.688, "dict_mask": 4.854, "dict_unreferenced_mask": 2.816, - "expr_large_struct_pack": 2.408, - "expr_optimize": 2.377, "filter_bool": 5.51, "filter_fixed_width": 3.863, "filter_fsl": 2.687, @@ -99,6 +97,10 @@ "vortex-elias-fano": { "unary": 3.413 }, + "vortex-expr": { + "expr_large_struct_pack": 2.408, + "expr_optimize": 2.377 + }, "vortex-fastlanes": { "bitpack_blocked": 0.367, "bitpack_blocked_decompress": 0.369, diff --git a/vortex-array/Cargo.toml b/vortex-array/Cargo.toml index 2cab252bb47..549c97b600a 100644 --- a/vortex-array/Cargo.toml +++ b/vortex-array/Cargo.toml @@ -195,16 +195,6 @@ harness = false name = "varbinview_compact" harness = false -[[bench]] -name = "expr_large_struct_pack" -path = "benches/expr/large_struct_pack.rs" -harness = false - -[[bench]] -name = "expr_optimize" -path = "benches/expr/optimize_bench.rs" -harness = false - [[bench]] name = "chunked_dict_builder" harness = false diff --git a/vortex-array/benches/aggregate_sum.rs b/vortex-array/benches/aggregate_sum.rs index 50875aebe22..b40d29c7d4c 100644 --- a/vortex-array/benches/aggregate_sum.rs +++ b/vortex-array/benches/aggregate_sum.rs @@ -13,8 +13,8 @@ use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::fns::sum_v2::sum_v2; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::PrimitiveArray; -use vortex_array::expr::stats::Stat; use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::stats::Stat; use vortex_array::test_harness::mark_optimized; use vortex_session::VortexSession; diff --git a/vortex-array/benches/cast_primitive.rs b/vortex-array/benches/cast_primitive.rs index 79a45eaee06..7fbc6bdd5d7 100644 --- a/vortex-array/benches/cast_primitive.rs +++ b/vortex-array/benches/cast_primitive.rs @@ -19,8 +19,8 @@ use vortex_array::dtype::DecimalDType; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; -use vortex_array::expr::stats::Stat; use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::stats::Stat; use vortex_array::test_harness::mark_optimized; use vortex_session::VortexSession; diff --git a/vortex-array/benches/dict_compare.rs b/vortex-array/benches/dict_compare.rs index a0233fcd4e0..cdffa2e602c 100644 --- a/vortex-array/benches/dict_compare.rs +++ b/vortex-array/benches/dict_compare.rs @@ -19,9 +19,6 @@ use vortex_array::arrays::dict_test::gen_varbin_words; use vortex_array::arrays::varbin::VarBinArrayExt; use vortex_array::builders::dict::dict_encode; use vortex_array::builtins::ArrayBuiltins; -use vortex_array::expr::eq; -use vortex_array::expr::lit; -use vortex_array::expr::root; use vortex_array::memory::MemorySession; use vortex_array::optimizer::ArrayOptimizer; use vortex_array::optimizer::kernels::KernelSession; @@ -164,7 +161,10 @@ fn bench_compare_sliced_dict_primitive( .with_inputs(|| (&dict, SESSION.create_execution_ctx())) .bench_refs(|(dict, ctx)| { dict.clone() - .apply(&eq(root(), lit(value))) + .binary( + ConstantArray::new(value, codes_len).into_array(), + Operator::Eq, + ) .unwrap() .execute::(ctx) .unwrap() @@ -193,7 +193,10 @@ fn bench_compare_sliced_dict_varbinview( .with_inputs(|| (&dict, SESSION.create_execution_ctx())) .bench_refs(|(dict, ctx)| { dict.clone() - .apply(&eq(root(), lit(value))) + .binary( + ConstantArray::new(value, codes_len).into_array(), + Operator::Eq, + ) .unwrap() .execute::(ctx) .unwrap() diff --git a/vortex-array/benches/scalar_construction.rs b/vortex-array/benches/scalar_construction.rs index 31e2b34e63c..d274f41360b 100644 --- a/vortex-array/benches/scalar_construction.rs +++ b/vortex-array/benches/scalar_construction.rs @@ -24,13 +24,13 @@ use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; -use vortex_array::expr::stats::Precision; -use vortex_array::expr::stats::Stat; -use vortex_array::expr::stats::StatsProvider; use vortex_array::optimizer::kernels::KernelSession; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsSet; use vortex_buffer::Buffer; use vortex_buffer::BufferString; diff --git a/vortex-array/src/aggregate_fn/accumulator.rs b/vortex-array/src/aggregate_fn/accumulator.rs index 388d92ffd2f..3626d8e6c87 100644 --- a/vortex-array/src/aggregate_fn/accumulator.rs +++ b/vortex-array/src/aggregate_fn/accumulator.rs @@ -19,10 +19,10 @@ use crate::aggregate_fn::AggregateFnVTable; use crate::columnar::AnyColumnar; use crate::dtype::DType; use crate::executor::max_iterations; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// Reference-counted type-erased accumulator. pub type AccumulatorRef = Box; @@ -404,12 +404,12 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProvider; - use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProvider; + use crate::stats::StatsProviderExt; /// Mean partial sentinel `{sum: 42.0, count: 1}` — distinguishable from the /// natural fan-out result `{sum: 7.0, count: 1}` that `Combined::try_accumulate` diff --git a/vortex-array/src/aggregate_fn/fns/count/mod.rs b/vortex-array/src/aggregate_fn/fns/count/mod.rs index 05f4cd771f7..545a2a27281 100644 --- a/vortex-array/src/aggregate_fn/fns/count/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/count/mod.rs @@ -174,10 +174,10 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs index f6805518ad9..4f5d69ed11f 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs @@ -45,12 +45,12 @@ use crate::dtype::DType; use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::StructFields; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; use crate::scalar_fn::builtin::operators::Operator; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; /// Check if two arrays of the same length have equal values at every position (null-safe). /// @@ -518,8 +518,8 @@ mod tests { use crate::dtype::MapDType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Stat; use crate::scalar::Scalar; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs index 2fee938aceb..3e78bf186b8 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs @@ -40,10 +40,10 @@ use crate::dtype::DType; use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::StructFields; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; /// Options for the `is_sorted` aggregate function. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -649,9 +649,9 @@ mod tests { use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; use crate::scalar::Scalar; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/max/mod.rs b/vortex-array/src/aggregate_fn/fns/max/mod.rs index 863e40fedad..3072c72addc 100644 --- a/vortex-array/src/aggregate_fn/fns/max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/max/mod.rs @@ -22,12 +22,12 @@ use crate::aggregate_fn::fns::min_max::min_max; use crate::aggregate_fn::fns::min_max::nan_scalar; use crate::aggregate_fn::fns::min_max::scalar_is_nan; use crate::dtype::DType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::partial_ord::partial_max; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; /// Compute the maximum non-null value of an array. /// @@ -263,10 +263,10 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/min/mod.rs b/vortex-array/src/aggregate_fn/fns/min/mod.rs index 5dc08bf7afa..d1ecddc3875 100644 --- a/vortex-array/src/aggregate_fn/fns/min/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min/mod.rs @@ -22,12 +22,12 @@ use crate::aggregate_fn::fns::min_max::min_max; use crate::aggregate_fn::fns::min_max::nan_scalar; use crate::aggregate_fn::fns::min_max::scalar_is_nan; use crate::dtype::DType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::partial_ord::partial_min; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; /// Compute the minimum non-null value of an array. /// @@ -263,10 +263,10 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs index 8aa43cb9cc4..6b163df6681 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -41,13 +41,13 @@ use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::StructFields; use crate::dtype::half::f16; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::partial_ord::partial_max; use crate::partial_ord::partial_min; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; static NAMES: LazyLock = LazyLock::new(|| FieldNames::from(["min", "max"])); @@ -584,14 +584,14 @@ mod tests { use crate::dtype::extension::ExtDType; use crate::dtype::extension::ExtId; use crate::dtype::extension::ExtVTable; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProvider; use crate::extension::datetime::TimeUnit; use crate::match_each_decimal_value_type; use crate::scalar::DecimalValue; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProvider; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs b/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs index 1251db1616b..21f77ac57da 100644 --- a/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs @@ -24,10 +24,10 @@ use crate::aggregate_fn::EmptyOptions; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// Return the number of NaN values in an array. /// diff --git a/vortex-array/src/aggregate_fn/fns/null_count/mod.rs b/vortex-array/src/aggregate_fn/fns/null_count/mod.rs index d2876220f9a..2695bb134c7 100644 --- a/vortex-array/src/aggregate_fn/fns/null_count/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/null_count/mod.rs @@ -19,10 +19,10 @@ use crate::aggregate_fn::EmptyOptions; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// Return the number of null values in an array. pub fn null_count(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { @@ -188,9 +188,9 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProviderExt; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProviderExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/sum/constant.rs b/vortex-array/src/aggregate_fn/fns/sum/constant.rs index f1b21c8b0b2..0752b67dfcb 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/constant.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/constant.rs @@ -110,9 +110,9 @@ mod tests { use crate::dtype::Nullability::Nullable; use crate::dtype::PType; use crate::dtype::i256; - use crate::expr::stats::Stat; use crate::scalar::DecimalValue; use crate::scalar::Scalar; + use crate::stats::Stat; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/sum/mod.rs b/vortex-array/src/aggregate_fn/fns/sum/mod.rs index 325d285c253..21e6c9287f9 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/mod.rs @@ -37,12 +37,12 @@ use crate::dtype::DecimalDType; use crate::dtype::MAX_PRECISION; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::scalar::DecimalValue; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; /// Return the sum of an array. /// @@ -479,11 +479,11 @@ mod tests { use crate::dtype::Nullability::Nullable; use crate::dtype::PType; use crate::dtype::i256; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProvider; use crate::scalar::DecimalValue; use crate::scalar::Scalar; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProvider; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs b/vortex-array/src/aggregate_fn/fns/sum/primitive.rs index 243c4c48c23..caeacacd55a 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/primitive.rs @@ -195,10 +195,10 @@ mod tests { use crate::dtype::Nullability; use crate::dtype::Nullability::Nullable; use crate::dtype::PType; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs b/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs index f7a488f89e0..03b27a3454a 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs @@ -45,12 +45,12 @@ use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::StructFields; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; use crate::scalar::ScalarValue; use crate::scalar_fn::builtin::operators::Operator; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; use crate::validity::Validity; const SUM_FIELD: &str = "sum"; diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs b/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs index 79ff7b836ad..b10a11a3ad3 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs +++ b/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs @@ -39,11 +39,11 @@ use crate::dtype::FieldNames; use crate::dtype::Nullability; use crate::dtype::Nullability::Nullable; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::proto::expr as pb; use crate::scalar::Scalar; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs index de656de5e21..d82dd81590d 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs @@ -52,10 +52,10 @@ use crate::arrays::varbinview::BinaryView; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// Return the uncompressed size of an array in bytes. /// @@ -409,13 +409,13 @@ mod tests { use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::UnionVariants; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProvider; use crate::extension::datetime::Date; use crate::extension::datetime::TimeUnit; use crate::scalar::Scalar; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProvider; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index 320788b95cf..fdacd46327e 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -44,14 +44,14 @@ use crate::arrays::SliceArray; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProviderExt; use crate::matcher::Matcher; use crate::optimizer::ArrayOptimizer; use crate::optimizer::OptimizedState; use crate::scalar::Scalar; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; use crate::stats::StatsSetRef; use crate::validity::Validity; @@ -544,7 +544,7 @@ impl ArrayRef { /// # Safety /// The caller must put back a slot with the same logical dtype and length before exposing the /// parent array, and must only use this for physical rewrites. - pub(crate) unsafe fn take_slot_unchecked( + pub unsafe fn take_slot_unchecked( mut self, slot_idx: usize, ) -> VortexResult<(ArrayRef, ArrayRef)> { @@ -578,7 +578,7 @@ impl ArrayRef { /// # Safety /// The replacement must have the same logical dtype and length as the taken slot, and this /// must only be used for physical rewrites. - pub(crate) unsafe fn put_slot_unchecked( + pub unsafe fn put_slot_unchecked( mut self, slot_idx: usize, replacement: ArrayRef, diff --git a/vortex-array/src/arrays/constant/vtable/canonical.rs b/vortex-array/src/arrays/constant/vtable/canonical.rs index 3661ac90a41..8c2d4b851da 100644 --- a/vortex-array/src/arrays/constant/vtable/canonical.rs +++ b/vortex-array/src/arrays/constant/vtable/canonical.rs @@ -542,11 +542,11 @@ mod tests { use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::half::f16; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProvider; use crate::extension::datetime::Date; use crate::extension::datetime::TimeUnit; use crate::scalar::Scalar; + use crate::stats::Stat; + use crate::stats::StatsProvider; use crate::validity::Validity; /// A shared session for these constant-array tests, used to create execution contexts. diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs b/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs index b7d88a23859..98111beb438 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/mod.rs @@ -42,7 +42,7 @@ use crate::arrays::Widen; use crate::arrays::WidenArray; use crate::arrays::decimal::DecimalDataParts; use crate::dtype::DecimalType; -use crate::expr::stats::Precision; +use crate::stats::Precision; /// The metadata of a `vortex.decimal` node. #[derive(prost::Message)] diff --git a/vortex-array/src/arrays/dict/compute/filter.rs b/vortex-array/src/arrays/dict/compute/filter.rs index c015425965a..de32b090c5f 100644 --- a/vortex-array/src/arrays/dict/compute/filter.rs +++ b/vortex-array/src/arrays/dict/compute/filter.rs @@ -50,11 +50,11 @@ mod tests { use crate::arrays::PrimitiveArray; use crate::arrays::dict::DictArraySlotsExt; use crate::assert_arrays_eq; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProviderExt; use crate::optimizer::ArrayOptimizer; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProviderExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/dict/compute/slice.rs b/vortex-array/src/arrays/dict/compute/slice.rs index 7b12fa1700a..cb7e2f427b9 100644 --- a/vortex-array/src/arrays/dict/compute/slice.rs +++ b/vortex-array/src/arrays/dict/compute/slice.rs @@ -16,10 +16,10 @@ use crate::arrays::DictArray; use crate::arrays::Primitive; use crate::arrays::dict::DictArraySlotsExt; use crate::arrays::slice::SliceReduce; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::scalar::Scalar; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; impl SliceReduce for Dict { fn slice(array: ArrayView<'_, Self>, range: Range) -> VortexResult> { diff --git a/vortex-array/src/arrays/dict/take.rs b/vortex-array/src/arrays/dict/take.rs index 461d76617ce..c79e3e52970 100644 --- a/vortex-array/src/arrays/dict/take.rs +++ b/vortex-array/src/arrays/dict/take.rs @@ -14,14 +14,14 @@ use crate::array::VTable; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::dict::DictArraySlotsExt; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::kernel::ExecuteParentKernel; use crate::matcher::Matcher; use crate::optimizer::rules::ArrayParentReduceRule; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; use crate::stats::StatsSet; use crate::validity::Validity; diff --git a/vortex-array/src/arrays/extension/compute/cast.rs b/vortex-array/src/arrays/extension/compute/cast.rs index ce67e5d6d52..ef1a503b8d5 100644 --- a/vortex-array/src/arrays/extension/compute/cast.rs +++ b/vortex-array/src/arrays/extension/compute/cast.rs @@ -60,11 +60,11 @@ mod tests { use crate::dtype::PType; use crate::dtype::StructFields; use crate::executor::VortexSessionExecute; - use crate::expr::cast; - use crate::expr::root; use crate::extension::datetime::TimeUnit; use crate::extension::datetime::Timestamp; use crate::scalar::Scalar; + use crate::scalar_fn::ScalarFnVTableExt; + use crate::scalar_fn::builtin::cast::Cast; use crate::test_harness::ExpectedOutcome; use crate::test_harness::assert_execution_paths; use crate::validity::Validity; @@ -160,7 +160,11 @@ mod tests { list_dtype(DType::Primitive(PType::I64, Nullability::NonNullable), Nullability::NonNullable), )] fn cast_never_reinterprets_storage(#[case] input: ArrayRef, #[case] target: DType) { - assert!(cast(root(), target.clone()).bind(input.dtype()).is_err()); + assert!( + Cast.bind(target.clone()) + .return_dtype(std::slice::from_ref(input.dtype())) + .is_err() + ); assert!(input.cast(target.clone()).is_err()); assert_execution_paths( diff --git a/vortex-array/src/arrays/list/array.rs b/vortex-array/src/arrays/list/array.rs index 008a095f0da..86568037f57 100644 --- a/vortex-array/src/arrays/list/array.rs +++ b/vortex-array/src/arrays/list/array.rs @@ -31,13 +31,13 @@ use crate::arrays::PrimitiveArray; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::match_each_integer_ptype; use crate::match_each_native_ptype; use crate::optimizer::ArrayOptimizer; use crate::scalar::ScalarValue; use crate::scalar_fn::builtin::operators::Operator; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; #[array_slots(List)] diff --git a/vortex-array/src/arrays/list/tests.rs b/vortex-array/src/arrays/list/tests.rs index 58dd2e7e737..2e2bbe07a05 100644 --- a/vortex-array/src/arrays/list/tests.rs +++ b/vortex-array/src/arrays/list/tests.rs @@ -30,12 +30,12 @@ use crate::builders::ListBuilder; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType::I32; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::optimizer::ArrayOptimizer; use crate::scalar::Scalar; use crate::serde::SerializeOptions; use crate::serde::SerializedArray; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; /// A shared session for `List` tests, used to create execution contexts. diff --git a/vortex-array/src/arrays/listview/array.rs b/vortex-array/src/arrays/listview/array.rs index 5dae39eb7b5..09c92107486 100644 --- a/vortex-array/src/arrays/listview/array.rs +++ b/vortex-array/src/arrays/listview/array.rs @@ -34,11 +34,11 @@ use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; use crate::dtype::PType; -use crate::expr::stats::Stat; use crate::match_each_integer_ptype; use crate::match_each_unsigned_integer_ptype; use crate::optimizer::ArrayOptimizer; use crate::scalar_fn::builtin::operators::Operator; +use crate::stats::Stat; use crate::validity::Validity; #[array_slots(ListView)] diff --git a/vortex-array/src/arrays/listview/tests/density.rs b/vortex-array/src/arrays/listview/tests/density.rs index 12d21890be0..73e00e60c90 100644 --- a/vortex-array/src/arrays/listview/tests/density.rs +++ b/vortex-array/src/arrays/listview/tests/density.rs @@ -23,9 +23,9 @@ use crate::arrays::ListViewArray; use crate::arrays::listview::ListViewArrayExt; use crate::arrays::listview::ListViewArraySlotsExt; use crate::arrays::listview::tests::common::create_empty_elements_listview; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/primitive/compute/cast.rs b/vortex-array/src/arrays/primitive/compute/cast.rs index 53649d9d059..1b60b641d03 100644 --- a/vortex-array/src/arrays/primitive/compute/cast.rs +++ b/vortex-array/src/arrays/primitive/compute/cast.rs @@ -37,16 +37,16 @@ use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::half::f16; use crate::dtype::i256; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; -use crate::expr::stats::StatsProviderExt; use crate::match_each_float_ptype; use crate::match_each_integer_ptype; use crate::scalar::DecimalValue; use crate::scalar::Scalar; use crate::scalar_fn::builtin::cast::CastKernel; use crate::scalar_fn::builtin::cast::CastReduce; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; +use crate::stats::StatsProviderExt; use crate::validity::Validity; impl CastReduce for Primitive { @@ -488,10 +488,10 @@ mod test { use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::i256; - use crate::expr::stats::Stat; use crate::match_each_decimal_value_type; use crate::match_each_native_ptype; use crate::scalar_fn::builtin::cast::CastKernel; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/runend/compress.rs b/vortex-array/src/arrays/runend/compress.rs index 1aee6600cb1..6a3b3787fcd 100644 --- a/vortex-array/src/arrays/runend/compress.rs +++ b/vortex-array/src/arrays/runend/compress.rs @@ -33,12 +33,12 @@ use crate::arrays::runend::iter::slice_relative_ends; use crate::buffer::BufferHandle; use crate::dtype::NativePType; use crate::dtype::Nullability; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::match_each_decimal_value_type; use crate::match_each_native_ptype; use crate::match_each_unsigned_integer_ptype; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; /// Run-end encode a `PrimitiveArray`, returning a tuple of `(ends, values)`. diff --git a/vortex-array/src/arrays/scalar_fn/rules.rs b/vortex-array/src/arrays/scalar_fn/rules.rs index 3520b1dd7ce..8f987586c00 100644 --- a/vortex-array/src/arrays/scalar_fn/rules.rs +++ b/vortex-array/src/arrays/scalar_fn/rules.rs @@ -167,10 +167,6 @@ mod tests { use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; - use crate::expr::cast; - use crate::expr::is_not_null; - use crate::expr::is_null; - use crate::expr::root; use crate::optimizer::rules::ArrayParentReduceRule; use crate::scalar_fn::TypedScalarFnInstance; use crate::scalar_fn::builtin::binary::Binary; @@ -234,10 +230,7 @@ mod tests { ConstantArray::new(Some(1u64), 0).into_array(), PrimitiveArray::from_iter(vec![2u64]) .into_array() - .apply(&cast( - root(), - DType::Primitive(PType::U64, Nullability::Nullable), - )) + .cast(DType::Primitive(PType::U64, Nullability::Nullable)) .vortex_expect("casted"), ], DType::Primitive(PType::U64, Nullability::Nullable), @@ -245,36 +238,25 @@ mod tests { .vortex_expect("construction") .into_array(); - let expr = is_null(root()); - let result = array.apply(&expr).vortex_expect("expr evaluation"); + let result = array.is_not_null().vortex_expect("is_not_null"); assert_arrays_eq!( result, - BoolArray::from_iter([false]), + BoolArray::from_iter([true]), &mut SESSION.create_execution_ctx() ); } #[test] - fn test_reduce_isnull() -> VortexResult<()> { + fn test_reduce_is_not_null() -> VortexResult<()> { let ctx = &mut SESSION.create_execution_ctx(); let validity = BoolArray::from_iter([true, false, true]).into_array(); - assert_arrays_eq!( - validity.clone().apply(&is_null(root()))?, - ConstantArray::new(false, 3), - ctx - ); - assert_arrays_eq!( - validity.clone().apply(&is_not_null(root()))?, - ConstantArray::new(true, 3), - ctx - ); + assert_arrays_eq!(validity.is_not_null()?, ConstantArray::new(true, 3), ctx); let buffer = buffer![1, 2, 3]; let nullable = PrimitiveArray::new(buffer, Validity::Array(validity.clone())).into_array(); - assert_arrays_eq!(nullable.clone().apply(&is_not_null(root()))?, validity, ctx); - assert_arrays_eq!(nullable.apply(&is_null(root()))?, validity.not()?, ctx); + assert_arrays_eq!(nullable.is_not_null()?, validity, ctx); Ok(()) } diff --git a/vortex-array/src/arrays/varbin/array.rs b/vortex-array/src/arrays/varbin/array.rs index bf2a68636bc..0f1d8a97a6a 100644 --- a/vortex-array/src/arrays/varbin/array.rs +++ b/vortex-array/src/arrays/varbin/array.rs @@ -32,10 +32,10 @@ use crate::dtype::DType; use crate::dtype::IntegerPType; use crate::dtype::Nullability; use crate::dtype::OffsetBuilderPType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::match_each_integer_ptype; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; /// Returns `true` if `index` is the end of `bytes` or the start of a UTF-8 char in it. diff --git a/vortex-array/src/arrays/varbin/builder.rs b/vortex-array/src/arrays/varbin/builder.rs index 1594e9ae11d..700a105378c 100644 --- a/vortex-array/src/arrays/varbin/builder.rs +++ b/vortex-array/src/arrays/varbin/builder.rs @@ -35,10 +35,10 @@ use crate::arrays::varbinview::VarBinViewArrayExt; use crate::builders::ArrayBuilder; use crate::dtype::DType; use crate::dtype::OffsetBuilderPType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::match_each_integer_ptype; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; /// Builder for [`VarBinArray`] values with `O`-typed offsets. @@ -739,10 +739,10 @@ mod tests { use crate::builders::ArrayBuilder; use crate::dtype::DType; use crate::dtype::Nullability::Nullable; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProviderExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/varbin/compute/cast.rs b/vortex-array/src/arrays/varbin/compute/cast.rs index d7bf000db4c..524f3fe2f3d 100644 --- a/vortex-array/src/arrays/varbin/compute/cast.rs +++ b/vortex-array/src/arrays/varbin/compute/cast.rs @@ -110,8 +110,8 @@ mod tests { use crate::compute::conformance::cast::test_cast_conformance; use crate::dtype::DType; use crate::dtype::Nullability; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; + use crate::stats::Precision; + use crate::stats::Stat; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/varbin/tests.rs b/vortex-array/src/arrays/varbin/tests.rs index c20965d0f38..e8e586df47f 100644 --- a/vortex-array/src/arrays/varbin/tests.rs +++ b/vortex-array/src/arrays/varbin/tests.rs @@ -22,12 +22,12 @@ use crate::arrays::varbin::offsets_tile_utf8; use crate::assert_arrays_eq; use crate::dtype::DType; use crate::dtype::Nullability; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProviderExt; use crate::scalar::Scalar; use crate::serde::SerializeOptions; use crate::serde::SerializedArray; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/arrays/widen/compute/aggregate.rs b/vortex-array/src/arrays/widen/compute/aggregate.rs index 6552df57d0f..6aa15593430 100644 --- a/vortex-array/src/arrays/widen/compute/aggregate.rs +++ b/vortex-array/src/arrays/widen/compute/aggregate.rs @@ -28,8 +28,8 @@ use crate::aggregate_fn::kernels::DynAggregateKernel; use crate::arrays::Widen; use crate::arrays::widen::WidenArraySlotsExt; use crate::dtype::DType; -use crate::expr::stats::Stat; use crate::scalar::Scalar; +use crate::stats::Stat; /// Computes aggregate partials from a [`Widen`]'s child without materializing widened values. #[derive(Debug)] diff --git a/vortex-array/src/arrays/widen/encode/decimal.rs b/vortex-array/src/arrays/widen/encode/decimal.rs index bb239f9de89..ab1f3afc782 100644 --- a/vortex-array/src/arrays/widen/encode/decimal.rs +++ b/vortex-array/src/arrays/widen/encode/decimal.rs @@ -40,11 +40,11 @@ use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::NativeDecimalType; use crate::dtype::i256; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::match_each_decimal_value_type; use crate::scalar::DecimalValue; use crate::scalar::ScalarValue; +use crate::stats::Precision; +use crate::stats::Stat; use crate::validity::Validity; impl WidenArray { diff --git a/vortex-array/src/arrays/widen/tests/aggregates.rs b/vortex-array/src/arrays/widen/tests/aggregates.rs index 3ff601c4434..7b4d7b1ba72 100644 --- a/vortex-array/src/arrays/widen/tests/aggregates.rs +++ b/vortex-array/src/arrays/widen/tests/aggregates.rs @@ -56,10 +56,10 @@ use crate::dtype::Nullability; use crate::dtype::Nullability::NonNullable; use crate::dtype::Nullability::Nullable; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; use crate::scalar::DecimalValue; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; /// Every aggregate that applies to integers, and whether the `Widen` aggregate kernel serves it. fn aggregates() -> Vec<(AggregateFnRef, bool)> { diff --git a/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs b/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs index ad2e3bb764b..668258fefb1 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs @@ -41,12 +41,12 @@ use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::Nullability::NonNullable; use crate::dtype::Nullability::Nullable; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::match_each_decimal_value_type; use crate::scalar::DecimalValue; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// Decimal aggregates paired with whether the [`Widen`] kernel must return a partial. fn aggregates() -> Vec<(AggregateFnRef, bool)> { diff --git a/vortex-array/src/arrays/widen/tests/decimal_cast.rs b/vortex-array/src/arrays/widen/tests/decimal_cast.rs index bc3f3c817c2..84b8b83a8e1 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_cast.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_cast.rs @@ -27,14 +27,14 @@ use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::optimizer::ArrayOptimizer; use crate::scalar::DecimalValue; use crate::scalar::Scalar; use crate::scalar_fn::builtin::cast::CastKernel; use crate::scalar_fn::builtin::cast::CastReduce; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; use crate::validity::Validity; #[rstest] diff --git a/vortex-array/src/arrays/widen/tests/decimal_stored.rs b/vortex-array/src/arrays/widen/tests/decimal_stored.rs index 28cfbc02554..24fab701c7d 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_stored.rs +++ b/vortex-array/src/arrays/widen/tests/decimal_stored.rs @@ -31,12 +31,12 @@ use crate::dtype::BigCast; use crate::dtype::DecimalDType; use crate::dtype::DecimalType; use crate::dtype::i256; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::match_each_decimal_value_type; use crate::scalar::DecimalValue; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; use crate::validity::Validity; /// Returns `values` as a buffer of `values_type`, with zero in each null slot. diff --git a/vortex-array/src/arrays/widen/tests/serde.rs b/vortex-array/src/arrays/widen/tests/serde.rs index 7251095a8f7..5436ad1518a 100644 --- a/vortex-array/src/arrays/widen/tests/serde.rs +++ b/vortex-array/src/arrays/widen/tests/serde.rs @@ -43,13 +43,13 @@ use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::scalar::Scalar; use crate::serde::SerializeOptions; use crate::serde::SerializedArray; use crate::session::ArraySessionExt; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; use crate::validity::Validity; fn serialize_blob( diff --git a/vortex-array/src/builtins.rs b/vortex-array/src/builtins.rs index 0aacd73c88f..60bc534884c 100644 --- a/vortex-array/src/builtins.rs +++ b/vortex-array/src/builtins.rs @@ -17,85 +17,17 @@ use crate::arrays::ConstantArray; use crate::arrays::InterleaveArray; use crate::dtype::DType; use crate::dtype::FieldName; -use crate::expr::Expression; use crate::scalar::Scalar; -use crate::scalar_fn::EmptyOptions; -use crate::scalar_fn::ScalarFnVTableExt; use crate::scalar_fn::builtin::binary::Binary; use crate::scalar_fn::builtin::cast::Cast; use crate::scalar_fn::builtin::fill_null::FillNull; use crate::scalar_fn::builtin::get_item::GetItem; use crate::scalar_fn::builtin::is_not_null::IsNotNull; -use crate::scalar_fn::builtin::is_null::IsNull; use crate::scalar_fn::builtin::mask::Mask; use crate::scalar_fn::builtin::not::Not; use crate::scalar_fn::builtin::operators::Operator; /// A collection of built-in scalar functions that can be applied to expressions or arrays. -pub trait ExprBuiltins: Sized { - /// Cast to the given data type. - fn cast(&self, dtype: DType) -> VortexResult; - - /// Replace null values with the given fill value. - fn fill_null(&self, fill_value: Expression) -> VortexResult; - - /// Get item by field name (for struct types). - fn get_item(&self, field_name: impl Into) -> VortexResult; - - /// Is null check. - fn is_null(&self) -> VortexResult; - - /// Is not null check. - fn is_not_null(&self) -> VortexResult; - - /// Mask the expression using the given boolean mask. - /// The resulting expression's validity is the intersection of the original expression's - /// validity. - fn mask(&self, mask: Expression) -> VortexResult; - - /// Boolean negation. - fn not(&self) -> VortexResult; - - // TODO(joe): add an `interleave` expression builtin mirroring `ArrayBuiltins::interleave`. - - /// Apply a binary operator to this expression and another. - fn binary(&self, rhs: Expression, op: Operator) -> VortexResult; -} - -impl ExprBuiltins for Expression { - fn cast(&self, dtype: DType) -> VortexResult { - Cast.try_new_expr(dtype, [self.clone()]) - } - - fn fill_null(&self, fill_value: Expression) -> VortexResult { - FillNull.try_new_expr(EmptyOptions, [self.clone(), fill_value]) - } - - fn get_item(&self, field_name: impl Into) -> VortexResult { - GetItem.try_new_expr(field_name.into(), [self.clone()]) - } - - fn is_null(&self) -> VortexResult { - IsNull.try_new_expr(EmptyOptions, [self.clone()]) - } - - fn is_not_null(&self) -> VortexResult { - IsNotNull.try_new_expr(EmptyOptions, [self.clone()]) - } - - fn mask(&self, mask: Expression) -> VortexResult { - Mask.try_new_expr(EmptyOptions, [self.clone(), mask]) - } - - fn not(&self) -> VortexResult { - Not.try_new_expr(EmptyOptions, [self.clone()]) - } - - fn binary(&self, rhs: Expression, op: Operator) -> VortexResult { - Binary.try_new_expr(op, [self.clone(), rhs]) - } -} - pub trait ArrayBuiltins: Sized { /// Cast to the given data type. fn cast(&self, dtype: DType) -> VortexResult; @@ -106,9 +38,6 @@ pub trait ArrayBuiltins: Sized { /// Get item by field name (for struct types). fn get_item(&self, field_name: impl Into) -> VortexResult; - /// Is null check. - fn is_null(&self) -> VortexResult; - /// Is not null check. fn is_not_null(&self) -> VortexResult; @@ -158,10 +87,6 @@ impl ArrayBuiltins for ArrayRef { Ok(GetItem::try_new(self.clone(), field_name)?.into_array()) } - fn is_null(&self) -> VortexResult { - Ok(IsNull::new(self.clone()).into_array()) - } - fn is_not_null(&self) -> VortexResult { Ok(IsNotNull::new(self.clone()).into_array()) } diff --git a/vortex-array/src/display/extractors/stats.rs b/vortex-array/src/display/extractors/stats.rs index 7459daccc5c..d2b7be87ffe 100644 --- a/vortex-array/src/display/extractors/stats.rs +++ b/vortex-array/src/display/extractors/stats.rs @@ -7,8 +7,8 @@ use std::fmt::{self}; use crate::ArrayRef; use crate::display::extractor::TreeContext; use crate::display::extractor::TreeExtractor; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; +use crate::stats::Stat; +use crate::stats::StatsProvider; use crate::validity::Validity; /// Display wrapper for array statistics in compact format. diff --git a/vortex-array/src/expr/aliases.rs b/vortex-array/src/expr/aliases.rs deleted file mode 100644 index bf4694355d0..00000000000 --- a/vortex-array/src/expr/aliases.rs +++ /dev/null @@ -1,7 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -pub mod paste { - //! Re-export of [`paste`](https://docs.rs/paste/latest/paste/). - pub use paste::paste; -} diff --git a/vortex-array/src/expr/bound_expression.rs b/vortex-array/src/expr/bound_expression.rs index f6d6c2f78c0..b8f42bfb91a 100644 --- a/vortex-array/src/expr/bound_expression.rs +++ b/vortex-array/src/expr/bound_expression.rs @@ -16,12 +16,8 @@ use vortex_error::VortexResult; use vortex_error::vortex_ensure; use crate::dtype::DType; -use crate::expr::Expression; use crate::expr::display::DisplayTreeExpr; -use crate::expr::expression::unbound_variable; -use crate::expr::scope::Scope; -use crate::expr::traversal::TraversalOrder; -use crate::expr::traversal::pre_order_visit_down; +use crate::scalar::Scalar; use crate::scalar_fn::EmptyOptions; use crate::scalar_fn::ExpressionReduceNode; use crate::scalar_fn::ReduceNode; @@ -30,8 +26,10 @@ use crate::scalar_fn::ScalarFnRef; use crate::scalar_fn::ScalarFnVTable; use crate::scalar_fn::ScalarFnVTableExt; use crate::scalar_fn::builtin::is_not_null::IsNotNull; +use crate::scalar_fn::builtin::literal::Literal; +use crate::scalar_fn::display::ExprDisplay; -/// An [`Expression`] that has been type-checked against a [`Scope`]. +/// An expression that has been type-checked against a scope's root dtype. /// /// Every node carries its own dtype, so reading one is a field access rather than a walk of the /// subtree. Holding a `BoundExpression` is proof that the whole tree type-checked. @@ -379,15 +377,25 @@ impl BoundExpression { /// Return whether this expression tree contains a node using the given scalar-function vtable. pub fn contains(&self) -> VortexResult { - let mut contains = false; - pre_order_visit_down(self, |node| { - if node.is::() { - contains = true; - return Ok(TraversalOrder::Stop); + Ok(self.any_node(|node| node.is::())) + } + + /// Whether any node of this tree, visited depth-first, satisfies `predicate`. + fn any_node(&self, mut predicate: impl FnMut(&BoundExpression) -> bool) -> bool { + let mut stack = vec![self]; + while let Some(node) = stack.pop() { + if predicate(node) { + return true; } - Ok(TraversalOrder::Continue) - })?; - Ok(contains) + stack.extend(node.children().iter().rev()); + } + false + } + + /// Create a bound literal node. + pub fn literal(value: Scalar) -> Self { + Self::try_new(Literal.bind(value), []) + .vortex_expect("literal expressions are always well-typed") } /// Return the typed scalar-function options when this node uses the given vtable. @@ -414,16 +422,7 @@ impl BoundExpression { /// /// Expressions without a scope root, such as literals, match every dtype. pub fn is_root_bound_to(&self, dtype: &DType) -> bool { - let mut is_bound_to = true; - pre_order_visit_down(self, |node| { - if node.is_root() && node.dtype() != dtype { - is_bound_to = false; - return Ok(TraversalOrder::Stop); - } - Ok(TraversalOrder::Continue) - }) - .vortex_expect("bound expression traversal cannot not fail"); - is_bound_to + !self.any_node(|node| node.is_root() && node.dtype() != dtype) } /// Returns a new expression representing the validity mask output of this expression. @@ -442,7 +441,7 @@ impl BoundExpression { // IsNotNull(x) -> x.validity() symbolic reduction rule works only // when node's.validity is Reduced to avoid infinite recursion. ReduceNodeValidity::Irreducible => { - IsNotNull.try_new_bound_expr(EmptyOptions, [self.clone()])? + BoundExpression::try_new(IsNotNull.bind(EmptyOptions), [self.clone()])? } }) } @@ -464,37 +463,6 @@ impl Display for BoundExpression { } } -impl Expression { - /// Bind this expression against a root dtype, type-checking every node in a single walk. - /// - /// The returned tree carries a dtype on each node, so callers needing types at more than one - /// node should bind once and read fields rather than calling - /// [`return_dtype`](Expression::return_dtype) repeatedly. - pub fn bind(&self, dtype: &DType) -> VortexResult { - self.bind_scope(&Scope::new(dtype.clone())) - } - - /// Bind this expression against an explicit [`Scope`]. - pub fn bind_scope(&self, scope: &Scope) -> VortexResult { - if self.is_root() { - return Ok(BoundExpression::new_root(scope.root().clone())); - } - if let Expression::Variable(name) = self { - return Err(unbound_variable(name)); - } - - let children: Vec<_> = self - .children() - .iter() - .map(|child| child.bind_scope(scope)) - .try_collect()?; - let scalar_fn = self - .as_scalar() - .vortex_expect("leaves were handled above, so this is a scalar node"); - BoundExpression::try_new(scalar_fn.clone(), children) - } -} - /// Iterative drop to avoid stack overflows on deep trees. impl Drop for BoundExpression { fn drop(&mut self) { @@ -516,179 +484,12 @@ impl Drop for BoundExpression { } } -#[cfg(test)] -mod tests { - use vortex_error::VortexResult; - - use super::*; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::expr::col; - use crate::expr::eq; - use crate::expr::lit; - use crate::expr::root; - use crate::expr::test_harness::struct_dtype; - use crate::scalar_fn::builtin::literal::Literal; - - fn scope() -> Scope { - Scope::new(struct_dtype()) - } - - #[test] - fn root_binds_to_the_scope() -> VortexResult<()> { - let bound = root().bind_scope(&scope())?; - assert!(bound.is_root()); - assert_eq!(bound.dtype(), &struct_dtype()); - assert_eq!(bound, BoundExpression::new_root(struct_dtype())); - Ok(()) - } - - #[test] - fn every_node_carries_its_dtype() -> VortexResult<()> { - let expr = eq(col("a"), lit(1_i32)); - let bound = expr.bind_scope(&scope())?; - - assert_eq!(bound.dtype(), &DType::Bool(Nullability::NonNullable)); - - let lhs = &bound.children()[0]; - assert_eq!( - lhs.dtype(), - &DType::Primitive(PType::I32, Nullability::NonNullable) - ); - assert_eq!(lhs.children()[0].dtype(), &struct_dtype()); - Ok(()) - } - - #[test] - fn bind_agrees_with_return_dtype() -> VortexResult<()> { - for (expr, expected) in [ - (root(), struct_dtype()), - ( - col("a"), - DType::Primitive(PType::I32, Nullability::NonNullable), - ), - ( - eq(col("a"), lit(1_i32)), - DType::Bool(Nullability::NonNullable), - ), - (lit(true), DType::Bool(Nullability::NonNullable)), - ] { - assert_eq!( - expr.bind(&struct_dtype())?.dtype(), - &expected, - "binding {expr}" - ); - assert_eq!( - expr.return_dtype(&struct_dtype())?, - expected, - "return dtype of {expr}" - ); - } - Ok(()) - } - - #[test] - fn contains_scalar_function() -> VortexResult<()> { - let bound = eq(col("a"), lit(1_i32)).bind_scope(&scope())?; - assert!(bound.contains::()?); - assert!(!root().bind_scope(&scope())?.contains::()?); - Ok(()) - } - - #[test] - fn bound_to_checks_every_root() -> VortexResult<()> { - let dtype = struct_dtype(); - let bound = eq(col("a"), col("a")).bind(&dtype)?; - assert!(bound.is_root_bound_to(&dtype)); - assert!(!bound.is_root_bound_to(&DType::Bool(Nullability::NonNullable))); - assert!( - lit(true) - .bind(&dtype)? - .is_root_bound_to(&DType::Bool(Nullability::NonNullable)) - ); - Ok(()) - } - - #[test] - fn bound_display_matches_unbound() -> VortexResult<()> { - for expr in [root(), col("a"), eq(col("a"), lit(1_i32)), lit(true)] { - let bound = expr.bind_scope(&scope())?; - assert_eq!(bound.to_string(), expr.to_string()); - assert_eq!( - bound.display_tree().to_string(), - expr.display_tree().to_string() - ); - } - Ok(()) +impl ExprDisplay for BoundExpression { + fn display_child(&self, index: usize) -> &dyn ExprDisplay { + &self.children()[index] } - #[test] - fn clone_shares_children() -> VortexResult<()> { - let bound = eq(col("a"), lit(1_i32)).bind_scope(&scope())?; - let cloned = bound.clone(); - - let ( - BoundExpression::Scalar { children: a, .. }, - BoundExpression::Scalar { children: b, .. }, - ) = (&bound, &cloned) - else { - unreachable!("eq is a scalar node") - }; - assert!(Arc::ptr_eq(a, b)); - Ok(()) - } - - #[test] - fn repeated_subtree_is_bound_per_occurrence() -> VortexResult<()> { - let shared = col("a"); - let bound = eq(shared.clone(), shared).bind_scope(&scope())?; - let children = bound.children(); - assert_eq!(children.len(), 2); - for child in children { - assert_eq!( - child.dtype(), - &DType::Primitive(PType::I32, Nullability::NonNullable) - ); - } - Ok(()) - } - - #[test] - fn structural_and_exact_equality_are_distinct() -> VortexResult<()> { - let expr = eq(col("a"), lit(1_i32)); - let bound = expr.bind_scope(&scope())?; - let independently_bound = expr.bind_scope(&scope())?; - - assert_eq!(bound, independently_bound); - assert_eq!(ExactBoundExpr(bound.clone()), ExactBoundExpr(bound.clone())); - assert_ne!(ExactBoundExpr(bound), ExactBoundExpr(independently_bound)); - Ok(()) - } - - #[test] - fn weak_keys_match_only_their_live_expression() -> VortexResult<()> { - let expr = eq(col("a"), lit(1_i32)); - let bound = expr.bind_scope(&scope())?; - let independently_bound = expr.bind_scope(&scope())?; - let key = WeakBoundExprKey::new(&bound); - - assert!(key.is_live()); - assert!((&key as &dyn ExactKey) == (&bound as &dyn ExactKey)); - assert!((&key as &dyn ExactKey) != (&independently_bound as &dyn ExactKey)); - // A clone shares the children, so it is the same expression to the key. - let clone = bound.clone(); - assert_eq!(key, WeakBoundExprKey::new(&clone)); - - drop(bound); - assert!(key.is_live()); - drop(clone); - assert!(!key.is_live()); - Ok(()) - } - - #[test] - fn binding_reports_a_type_error() { - let expr = eq(col("a"), lit("nope")); - assert!(expr.bind_scope(&scope()).is_err()); + fn display_children_count(&self) -> usize { + self.children().len() } } diff --git a/vortex-array/src/expr/display.rs b/vortex-array/src/expr/display.rs index 74dcfd26a30..013b4d197ed 100644 --- a/vortex-array/src/expr/display.rs +++ b/vortex-array/src/expr/display.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +//! Tree rendering shared by bound and unbound expressions. + use std::fmt; use std::fmt::Display; use std::fmt::Formatter; @@ -9,78 +11,22 @@ use vortex_utils::tree::TreeDisplayAdapter; use vortex_utils::tree::write_branch_tree; use crate::expr::BoundExpression; -use crate::expr::Expression; use crate::scalar_fn::ChildName; -pub enum DisplayFormat { - Compact, - Tree, -} - -/// Read-only expression-tree interface used by scalar functions for SQL-style formatting. -/// -/// Both [`Expression`] and [`BoundExpression`] implement this interface, allowing scalar -/// functions to format either representation without converting between them. -pub trait ExprDisplay: Display { - /// Return the child at `index`. - fn display_child(&self, index: usize) -> &dyn ExprDisplay; - - /// Return the number of children in this node. - fn display_children_count(&self) -> usize; -} - -impl ExprDisplay for Expression { - fn display_child(&self, index: usize) -> &dyn ExprDisplay { - Expression::child(self, index) - } - - fn display_children_count(&self) -> usize { - self.children().len() - } -} - -impl ExprDisplay for BoundExpression { - fn display_child(&self, index: usize) -> &dyn ExprDisplay { - &self.children()[index] - } - - fn display_children_count(&self) -> usize { - self.children().len() - } -} - -trait DisplayTreeNode: Sized { +/// A node of an expression tree that [`DisplayTreeExpr`] can render. +pub trait DisplayTreeNode: Sized { + /// The children of this node, in argument order. fn tree_children(&self) -> &[Self]; + /// The display name of the child at `index`. fn tree_child_name(&self, index: usize) -> ChildName; + /// Write this node's own label. fn fmt_tree_node(&self, f: &mut Formatter<'_>) -> fmt::Result; } /// Tree-display label for the scope root. -const ROOT_DISPLAY: &str = "vortex.root()"; - -impl DisplayTreeNode for Expression { - fn tree_children(&self) -> &[Self] { - Expression::children(self) - } - - fn tree_child_name(&self, index: usize) -> ChildName { - match self { - Expression::Scalar { scalar_fn, .. } => scalar_fn.signature().child_name(index), - Expression::Root => unreachable!("the scope root has no children"), - Expression::Variable(_) => unreachable!("a variable has no children"), - } - } - - fn fmt_tree_node(&self, f: &mut Formatter<'_>) -> fmt::Result { - match self { - Expression::Scalar { scalar_fn, .. } => Display::fmt(scalar_fn, f), - Expression::Root => write!(f, "{ROOT_DISPLAY}"), - Expression::Variable(name) => write!(f, "@{name}"), - } - } -} +pub const ROOT_DISPLAY: &str = "vortex.root()"; impl DisplayTreeNode for BoundExpression { fn tree_children(&self) -> &[Self] { @@ -102,7 +48,8 @@ impl DisplayTreeNode for BoundExpression { } } -pub struct DisplayTreeExpr<'a, T: ?Sized = Expression>(pub &'a T); +/// Renders an expression tree with one node per line. +pub struct DisplayTreeExpr<'a, T: ?Sized>(pub &'a T); impl TreeDisplayAdapter for DisplayTreeExpr<'_, T> { type Context = (); @@ -136,101 +83,3 @@ impl Display for DisplayTreeExpr<'_, T> { write_branch_tree(self, self.0, &mut (), f) } } - -#[cfg(test)] -mod tests { - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::expr::and; - use crate::expr::cast; - use crate::expr::eq; - use crate::expr::get_item; - use crate::expr::gt; - use crate::expr::lit; - use crate::expr::not; - use crate::expr::root; - - #[test] - fn test_display_tree_root() { - use insta::assert_snapshot; - let root_expr = root(); - assert_snapshot!(root_expr.display_tree().to_string(), @"vortex.root()"); - } - - #[test] - fn test_display_tree_literal() { - use insta::assert_snapshot; - let lit_expr = lit(42); - assert_snapshot!(lit_expr.display_tree().to_string(), @"vortex.literal(42i32)"); - } - - #[test] - fn test_display_tree_get_item() { - use insta::assert_snapshot; - let get_item_expr = get_item("my_field", root()); - assert_snapshot!(get_item_expr.display_tree().to_string(), @r" - vortex.get_item(my_field) - └── input: vortex.root() - "); - } - - #[test] - fn test_display_tree_binary() { - use insta::assert_snapshot; - let binary_expr = gt(get_item("x", root()), lit(10)); - assert_snapshot!(binary_expr.display_tree().to_string(), @r" - vortex.binary(>) - ├── lhs: vortex.get_item(x) - │ └── input: vortex.root() - └── rhs: vortex.literal(10i32) - "); - } - - #[test] - fn test_display_tree_complex_binary() { - use insta::assert_snapshot; - let complex_binary = and( - eq(get_item("name", root()), lit("alice")), - gt(get_item("age", root()), lit(18)), - ); - assert_snapshot!(complex_binary.display_tree().to_string(), @r#" - vortex.binary(and) - ├── lhs: vortex.binary(=) - │ ├── lhs: vortex.get_item(name) - │ │ └── input: vortex.root() - │ └── rhs: vortex.literal("alice") - └── rhs: vortex.binary(>) - ├── lhs: vortex.get_item(age) - │ └── input: vortex.root() - └── rhs: vortex.literal(18i32) - "#); - } - - #[test] - fn test_display_tree_cast() { - use insta::assert_snapshot; - let cast_expr = cast( - get_item("value", root()), - DType::Primitive(PType::I64, Nullability::NonNullable), - ); - assert_snapshot!(cast_expr.display_tree().to_string(), @r" - vortex.cast(i64) - └── input: vortex.get_item(value) - └── input: vortex.root() - "); - } - - #[test] - fn test_display_tree_not() { - use insta::assert_snapshot; - let not_expr = not(eq(get_item("active", root()), lit(true))); - assert_snapshot!(not_expr.display_tree().to_string(), @r" - vortex.not() - └── input: vortex.binary(=) - ├── lhs: vortex.get_item(active) - │ └── input: vortex.root() - └── rhs: vortex.literal(true) - "); - } -} diff --git a/vortex-array/src/expr/mod.rs b/vortex-array/src/expr/mod.rs index bf8b427003f..e469c490589 100644 --- a/vortex-array/src/expr/mod.rs +++ b/vortex-array/src/expr/mod.rs @@ -1,130 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Vortex's expression language: scalar operations over [arrays](crate::ArrayRef). +//! Bound expression trees and their optimizer. //! -//! An [`Expression`] is a tree of scalar operations rooted at a scope (see [`root`]). Expressions -//! are the common currency of scans: a scan takes a *filter* expression that resolves to a boolean -//! and a *projection* expression that shapes the output. All expressions are serializable and own -//! their own wire format, so they can be pushed down to remote sources and reconstructed on workers. -//! -//! # Scalar functions -//! -//! Each node references a scalar function defined by a -//! [`ScalarFnVTable`](crate::scalar_fn::ScalarFnVTable). The vtable declares the function signature, -//! properties such as strictness, and the logic that executes it over input arrays. Built-in -//! functions live in [`crate::scalar_fn`]; integration and plugin crates supply additional, -//! use-case-specific functions. -//! -//! # Deferred execution -//! -//! Applying an expression to an array does not compute the result eagerly. Instead it builds a -//! [`ScalarFnArray`](crate::arrays::ScalarFnArray) representing the deferred application, letting -//! downstream encodings push the computation into compressed data, or fuse several expressions -//! together, before any data is materialized. The deferred tree is executed toward canonical form -//! only when a result is actually required. -//! -//! # Type checking -//! -//! Expressions are strictly typed: an input array's dtype must match the function signature exactly, -//! so callers perform any required casts themselves before building the expression. The one -//! relaxation is nullability—for example, equality may compare a `u32` against a `u32?`, but never -//! a `u32` against an `i32`. -//! -//! Scans decompose bound filter expressions into independent conjuncts so that they can evaluate -//! and reorder the most selective predicates first. -//! -//! The implementation takes inspiration from [Postgres] and [Apache Datafusion]. -//! -//! [Postgres]: https://www.postgresql.org/docs/current/sql-expressions.html -//! [Apache Datafusion]: https://github.com/apache/datafusion/tree/5fac581efbaffd0e6a9edf931182517524526afd/datafusion/expr +//! [`BoundExpression`] lives here because the scalar function vtable reduces over it: keeping it +//! next to [`ScalarFnVTable`](crate::scalar_fn::ScalarFnVTable) lets every reduction rule be +//! monomorphized for expression trees as well as array trees. Unbound expressions, binding, +//! constructors and the analyses built on them live in the `vortex-expr` crate. -pub mod aliases; -#[cfg(feature = "arbitrary")] -pub mod arbitrary; -pub mod bound_expression; +mod bound_expression; pub mod display; -pub(crate) mod expression; -mod exprs; -pub(crate) mod field; -pub mod lambda; mod optimize; -pub mod proto; -pub mod scope; -pub mod stats; -pub mod traversal; pub use bound_expression::*; -pub use expression::*; -pub use exprs::and; -pub use exprs::and_collect; -pub use exprs::binary; -pub use exprs::bound; -pub use exprs::bound_select; -pub use exprs::bound_select_exclude; -pub use exprs::cast; -pub use exprs::checked_add; -pub use exprs::col; -pub use exprs::eq; -pub use exprs::fill_null; -pub use exprs::get_item; -pub use exprs::gt; -pub use exprs::gt_eq; -pub use exprs::is_not_null; -pub use exprs::is_null; -pub use exprs::is_root; -pub use exprs::lit; -pub use exprs::lt; -pub use exprs::lt_eq; -pub use exprs::mask; -pub use exprs::not; -pub use exprs::not_eq; -pub use exprs::or; -pub use exprs::or_collect; -pub use exprs::pack; -pub use exprs::root; -pub use exprs::select; -pub use exprs::select_exclude; -pub use exprs::var; -pub use lambda::*; -pub use scope::*; - -#[cfg(feature = "_test-harness")] -pub mod test_harness { - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::dtype::StructFields; - - pub fn struct_dtype() -> DType { - DType::Struct( - StructFields::new( - ["a", "col1", "col2", "bool1", "bool2"].into(), - vec![ - DType::Primitive(PType::I32, Nullability::NonNullable), - DType::Primitive(PType::U16, Nullability::Nullable), - DType::Primitive(PType::U16, Nullability::Nullable), - DType::Bool(Nullability::NonNullable), - DType::Bool(Nullability::NonNullable), - ], - ), - Nullability::NonNullable, - ) - } -} - -#[cfg(test)] -mod tests { - use crate::expr::eq; - use crate::expr::lit; - use crate::expr::root; - use crate::scalar_fn::builtin::literal::Literal; - - #[test] - fn expr_contains() { - let expression = &eq(root(), lit(3u64)); - assert!(expression.contains::().unwrap()); - let expression = root(); - assert!(!expression.contains::().unwrap()); - } -} diff --git a/vortex-array/src/expr/optimize.rs b/vortex-array/src/expr/optimize.rs index a96b3e7af32..411a8bc01a0 100644 --- a/vortex-array/src/expr/optimize.rs +++ b/vortex-array/src/expr/optimize.rs @@ -10,7 +10,7 @@ impl BoundExpression { /// Optimize the root expression node only, iterating to convergence. /// /// This applies optimization rules repeatedly until no more changes occur: - /// 1. `simplify` - scalar-function simplifications over the bound node + /// 1. `simplify` - scalar-function simplifications over the node /// 2. `reduce` - abstract reduction rules via `ReduceNode` pub fn optimize(&self) -> VortexResult { Ok(self.try_optimize()?.unwrap_or_else(|| self.clone())) @@ -21,18 +21,19 @@ impl BoundExpression { /// Non-scalar nodes carry no rules, so they never simplify. fn simplify_node(&self) -> VortexResult> { match self { - BoundExpression::Scalar { scalar_fn, .. } => scalar_fn.simplify(self), + BoundExpression::Scalar { scalar_fn, .. } => Ok(scalar_fn + .simplify_expression(&ExpressionReduceNode::new(self))? + .map(ExpressionReduceNode::into_expression)), BoundExpression::Root { .. } => Ok(None), } } /// Apply this node's own abstract reduction rule, if it has one. - fn reduce_node<'a>( - &self, - node: &ExpressionReduceNode<'a>, - ) -> VortexResult>> { + fn reduce_node(&self) -> VortexResult> { match self { - BoundExpression::Scalar { scalar_fn, .. } => scalar_fn.reduce_expression(node), + BoundExpression::Scalar { scalar_fn, .. } => Ok(scalar_fn + .reduce_expression(&ExpressionReduceNode::new(self))? + .map(ExpressionReduceNode::into_expression)), BoundExpression::Root { .. } => Ok(None), } } @@ -60,15 +61,9 @@ impl BoundExpression { changed = true; } - // Try reduce via ReduceNode. The node borrows the expression, so constructing it is - // free; the block scopes the borrow so `current` can be updated. - let reduced = { - let expr = current.as_ref().unwrap_or(self); - expr.reduce_node(&ExpressionReduceNode::new(expr))? - .map(ExpressionReduceNode::into_expression) - }; - if let Some(reduced_expr) = reduced { - current = Some(reduced_expr); + let expr = current.as_ref().unwrap_or(self); + if let Some(reduced) = expr.reduce_node()? { + current = Some(reduced); changed = true; } @@ -79,7 +74,6 @@ impl BoundExpression { Ok(current) } - /// Optimize the entire expression tree recursively. /// /// Optimizes children first (bottom-up), then optimizes the root. @@ -119,113 +113,3 @@ impl BoundExpression { Ok(current) } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_error::vortex_err; - use vortex_session::VortexSession; - - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::arrays::BoolArray; - use crate::arrays::StructArray; - use crate::assert_arrays_eq; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::dtype::StructFields; - use crate::expr::Expression; - use crate::expr::and; - use crate::expr::cast; - use crate::expr::eq; - use crate::expr::get_item; - use crate::expr::lit; - use crate::expr::lt_eq; - use crate::expr::or; - use crate::expr::root; - use crate::scalar::Scalar; - use crate::scalar_fn::builtin::literal::Literal; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn optimize_or_chain_correctness() -> VortexResult<()> { - let expr = or( - eq(get_item("x", root()), lit(1i32)), - eq(get_item("x", root()), lit(2i32)), - ); - let scope = DType::Struct( - StructFields::new( - ["x"].into(), - vec![DType::Primitive(PType::I32, Nullability::NonNullable)], - ), - Nullability::NonNullable, - ); - let optimized = expr.bind(&scope)?.optimize_recursive()?; - - let data = - StructArray::from_fields(&[("x", buffer![0i32, 1, 2, 3].into_array())])?.into_array(); - let actual = data.apply_bound(&optimized)?; - assert_arrays_eq!( - actual, - BoolArray::from_iter([false, true, true, false]), - &mut SESSION.create_execution_ctx() - ); - Ok(()) - } - - #[test] - fn optimize_folds_cast_of_literal_in_comparison() -> VortexResult<()> { - let expr = lt_eq( - get_item("x", root()), - cast( - lit(3i32), - DType::Primitive(PType::F64, Nullability::NonNullable), - ), - ); - let scope = DType::Struct( - StructFields::new( - ["x"].into(), - vec![DType::Primitive(PType::F64, Nullability::NonNullable)], - ), - Nullability::NonNullable, - ); - let optimized = expr.bind(&scope)?.optimize_recursive()?; - - // Prune rules pattern-match a bare Literal on the comparison RHS; a cast wrapper - // silently disables pruning. - let rhs = optimized - .child(1) - .as_opt::() - .ok_or_else(|| vortex_err!("expected a bare literal RHS, got {optimized}"))?; - assert_eq!(rhs, &Scalar::primitive(3.0f64, Nullability::NonNullable)); - Ok(()) - } - - #[rstest] - #[case::and_annihilator(and(root(), lit(false)), DType::Bool(Nullability::Nullable))] - #[case::or_annihilator(or(root(), lit(true)), DType::Bool(Nullability::Nullable))] - #[case::and_nullable_identity( - and(root(), lit(Scalar::from(Some(true)))), - DType::Bool(Nullability::NonNullable) - )] - #[case::or_nullable_identity( - or(root(), lit(Scalar::from(Some(false)))), - DType::Bool(Nullability::NonNullable) - )] - fn literal_simplification_preserves_result_dtype( - #[case] expr: Expression, - #[case] scope: DType, - ) -> VortexResult<()> { - let original = expr.bind(&scope)?; - let optimized = expr.bind(&scope)?.optimize_recursive()?; - assert_eq!(optimized.dtype(), original.dtype()); - - Ok(()) - } -} diff --git a/vortex-array/src/lib.rs b/vortex-array/src/lib.rs index 331208c2e66..9f8046f35b4 100644 --- a/vortex-array/src/lib.rs +++ b/vortex-array/src/lib.rs @@ -115,7 +115,6 @@ pub mod display; pub mod dtype; mod executor; pub mod expr; -mod expression; pub mod extension; pub mod flatbuffers; mod hash; diff --git a/vortex-array/src/optimizer/mod.rs b/vortex-array/src/optimizer/mod.rs index 7b22214b438..669aec5a8c7 100644 --- a/vortex-array/src/optimizer/mod.rs +++ b/vortex-array/src/optimizer/mod.rs @@ -86,7 +86,7 @@ const MAX_OPTIMIZER_REWRITE_PASS: usize = 100; /// also sees that state. /// /// [`ArrayRef::inner_mut`]: crate::ArrayRef::inner_mut -/// [`Stat::IsConstant`]: crate::expr::stats::Stat::IsConstant +/// [`Stat::IsConstant`]: crate::stats::Stat::IsConstant #[derive(Debug, Default)] pub(crate) struct OptimizedState(pub(crate) AtomicBool); @@ -600,11 +600,11 @@ mod tests { use crate::IntoArray; use crate::arrays::Primitive; use crate::arrays::StructArray; - use crate::expr::stats::Precision; - use crate::expr::stats::Stat; - use crate::expr::stats::StatsProviderExt; use crate::optimizer::ArrayOptimizer; use crate::scalar::ScalarValue; + use crate::stats::Precision; + use crate::stats::Stat; + use crate::stats::StatsProviderExt; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/scalar_fn/builtin/binary/mod.rs b/vortex-array/src/scalar_fn/builtin/binary/mod.rs index fb51375253d..571c80a4d83 100644 --- a/vortex-array/src/scalar_fn/builtin/binary/mod.rs +++ b/vortex-array/src/scalar_fn/builtin/binary/mod.rs @@ -27,9 +27,6 @@ use crate::arrays::Constant; use crate::arrays::ScalarFnArray; use crate::dtype::DType; use crate::dtype::Nullability; -use crate::expr::BoundExpression; -use crate::expr::bound; -use crate::expr::display::ExprDisplay; use crate::matcher::Matcher; use crate::proto::expr as pb; use crate::require_input; @@ -41,9 +38,10 @@ use crate::scalar_fn::ScalarFnExecutionResult; use crate::scalar_fn::ScalarFnId; use crate::scalar_fn::ScalarFnVTable; use crate::scalar_fn::ScalarFnVTableExt; -use crate::scalar_fn::builtin::literal::Literal; +use crate::scalar_fn::builtin::cast::Cast; use crate::scalar_fn::builtin::operators::CompareOperator; use crate::scalar_fn::builtin::operators::Operator; +use crate::scalar_fn::display::ExprDisplay; pub mod boolean; pub use boolean::BooleanExecuteAdaptor; @@ -202,30 +200,25 @@ impl ScalarFnVTable for Binary { } } - fn simplify( - &self, - operator: &Operator, - expr: &BoundExpression, - ) -> VortexResult> { - let lhs = expr.child(0); - let rhs = expr.child(1); + fn simplify(&self, operator: &Operator, node: &T) -> VortexResult> { + let lhs = node.child(0); + let rhs = node.child(1); - let is_literal_null = - |expr: &BoundExpression| expr.as_opt::().is_some_and(Scalar::is_null); + let is_constant_null = |node: &T| node.as_constant().is_some_and(|s| s.is_null()); // Binding already rejected ill-typed comparisons such as `int_col = null_utf8`, so a - // comparison against a null literal always evaluates to null. - if operator.is_comparison() && (is_literal_null(lhs) || is_literal_null(rhs)) { - return Ok(Some(bound::lit(Scalar::null(DType::Bool( - Nullability::Nullable, - ))))); + // comparison against a null constant always evaluates to null. + if operator.is_comparison() && (is_constant_null(&lhs) || is_constant_null(&rhs)) { + return Ok(Some( + node.new_constant(Scalar::null(DType::Bool(Nullability::Nullable))), + )); } - let bool_literal = |expr: &BoundExpression| { - expr.as_opt::()? - .as_bool_opt() - .map(|value| value.value()) - }; + if !matches!(operator, Operator::And | Operator::Or) { + return Ok(None); + } + + let bool_constant = |node: &T| node.as_constant()?.as_bool_opt().map(|value| value.value()); // AND/OR use Kleene three-valued logic. `None` below is a boolean null. // @@ -240,34 +233,37 @@ impl ScalarFnVTable for Binary { // - null OR null => null // // Other null cases either fall out of the identity/annihilator rules - // above (`null AND true`, `null OR false`) or cannot be simplified under - // Kleene semantics (`null AND x`, `null OR x` for non-literal `x`). - // Simplification must keep the result nullability binding inferred: the annihilator - // literal and the identity child can both be less nullable than `lhs OP rhs`. - let result_nullable = lhs.dtype().is_nullable() || rhs.dtype().is_nullable(); + // above (`null AND true`, `null OR false`) or cannot be reduced under + // Kleene semantics (`null AND x`, `null OR x` for non-constant `x`). + // Reduction must keep the result nullability binding inferred: the annihilator + // constant and the identity child can both be less nullable than `lhs OP rhs`. + let result_nullable = lhs.node_dtype()?.is_nullable() || rhs.node_dtype()?.is_nullable(); let nullability = Nullability::from(result_nullable); - let bool_lit = |value: bool| bound::lit(Scalar::bool(value, nullability)); - let widen = |child: &BoundExpression| { - if child.dtype().is_nullable() == result_nullable { - child.clone() + let bool_constant_node = |value: bool| node.new_constant(Scalar::bool(value, nullability)); + let widen = |child: T| -> VortexResult { + if child.node_dtype()?.is_nullable() == result_nullable { + Ok(child) } else { - bound::cast(child.clone(), DType::Bool(nullability)) + child.new_node( + Cast.bind(DType::Bool(nullability)), + std::slice::from_ref(&child), + ) } }; Ok(match operator { - Operator::And => match (bool_literal(lhs), bool_literal(rhs)) { - (Some(Some(false)), _) | (_, Some(Some(false))) => Some(bool_lit(false)), - (Some(Some(true)), _) => Some(widen(rhs)), - (_, Some(Some(true))) => Some(widen(lhs)), - (Some(None), Some(None)) => Some(widen(lhs)), + Operator::And => match (bool_constant(&lhs), bool_constant(&rhs)) { + (Some(Some(false)), _) | (_, Some(Some(false))) => Some(bool_constant_node(false)), + (Some(Some(true)), _) => Some(widen(rhs)?), + (_, Some(Some(true))) => Some(widen(lhs)?), + (Some(None), Some(None)) => Some(widen(lhs)?), _ => None, }, - Operator::Or => match (bool_literal(lhs), bool_literal(rhs)) { - (Some(Some(true)), _) | (_, Some(Some(true))) => Some(bool_lit(true)), - (Some(Some(false)), _) => Some(widen(rhs)), - (_, Some(Some(false))) => Some(widen(lhs)), - (Some(None), Some(None)) => Some(widen(lhs)), + Operator::Or => match (bool_constant(&lhs), bool_constant(&rhs)) { + (Some(Some(true)), _) | (_, Some(Some(true))) => Some(bool_constant_node(true)), + (Some(Some(false)), _) => Some(widen(rhs)?), + (_, Some(Some(false))) => Some(widen(lhs)?), + (Some(None), Some(None)) => Some(widen(lhs)?), _ => None, }, _ => None, @@ -370,466 +366,3 @@ impl ScalarFnVTable for Binary { ) } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use vortex_error::VortexExpect; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use super::*; - use crate::Canonical; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::arrays::Bool; - use crate::arrays::BoolArray; - use crate::arrays::Constant; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::ScalarFn; - use crate::arrays::scalar_fn::ExactScalarFn; - use crate::arrays::scalar_fn::ScalarFnArrayExt; - use crate::assert_arrays_eq; - use crate::builtins::ArrayBuiltins; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::expr::Expression; - use crate::expr::and; - use crate::expr::and_collect; - use crate::expr::col; - use crate::expr::eq; - use crate::expr::gt; - use crate::expr::gt_eq; - use crate::expr::lit; - use crate::expr::lt; - use crate::expr::lt_eq; - use crate::expr::not_eq; - use crate::expr::or; - use crate::expr::or_collect; - use crate::expr::test_harness; - use crate::optimizer::ArrayOptimizer; - use crate::scalar::Scalar; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn and_collect_balanced() { - let values = vec![lit(1), lit(2), lit(3), lit(4), lit(5)]; - - insta::assert_snapshot!(and_collect(values.into_iter()).unwrap().display_tree(), @r" - vortex.binary(and) - ├── lhs: vortex.binary(and) - │ ├── lhs: vortex.literal(1i32) - │ └── rhs: vortex.literal(2i32) - └── rhs: vortex.binary(and) - ├── lhs: vortex.binary(and) - │ ├── lhs: vortex.literal(3i32) - │ └── rhs: vortex.literal(4i32) - └── rhs: vortex.literal(5i32) - "); - - // 4 elements: and(and(1, 2), and(3, 4)) - perfectly balanced - let values = vec![lit(1), lit(2), lit(3), lit(4)]; - insta::assert_snapshot!(and_collect(values.into_iter()).unwrap().display_tree(), @r" - vortex.binary(and) - ├── lhs: vortex.binary(and) - │ ├── lhs: vortex.literal(1i32) - │ └── rhs: vortex.literal(2i32) - └── rhs: vortex.binary(and) - ├── lhs: vortex.literal(3i32) - └── rhs: vortex.literal(4i32) - "); - - // 1 element: just the element - let values = vec![lit(1)]; - insta::assert_snapshot!(and_collect(values.into_iter()).unwrap().display_tree(), @"vortex.literal(1i32)"); - - // 0 elements: None - let values: Vec = vec![]; - assert!(and_collect(values.into_iter()).is_none()); - } - - #[test] - fn or_collect_balanced() { - // 4 elements: or(or(1, 2), or(3, 4)) - perfectly balanced - let values = vec![lit(1), lit(2), lit(3), lit(4)]; - insta::assert_snapshot!(or_collect(values.into_iter()).unwrap().display_tree(), @r" - vortex.binary(or) - ├── lhs: vortex.binary(or) - │ ├── lhs: vortex.literal(1i32) - │ └── rhs: vortex.literal(2i32) - └── rhs: vortex.binary(or) - ├── lhs: vortex.literal(3i32) - └── rhs: vortex.literal(4i32) - "); - } - - #[test] - fn dtype() { - let dtype = test_harness::struct_dtype(); - let bool1: Expression = col("bool1"); - let bool2: Expression = col("bool2"); - assert_eq!( - and(bool1.clone(), bool2.clone()) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::NonNullable) - ); - assert_eq!( - or(bool1, bool2).return_dtype(&dtype).unwrap(), - DType::Bool(Nullability::NonNullable) - ); - - let col1: Expression = col("col1"); - let col2: Expression = col("col2"); - - assert_eq!( - eq(col1.clone(), col2.clone()).return_dtype(&dtype).unwrap(), - DType::Bool(Nullability::Nullable) - ); - assert_eq!( - not_eq(col1.clone(), col2.clone()) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::Nullable) - ); - assert_eq!( - gt(col1.clone(), col2.clone()).return_dtype(&dtype).unwrap(), - DType::Bool(Nullability::Nullable) - ); - assert_eq!( - gt_eq(col1.clone(), col2.clone()) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::Nullable) - ); - assert_eq!( - lt(col1.clone(), col2.clone()).return_dtype(&dtype).unwrap(), - DType::Bool(Nullability::Nullable) - ); - assert_eq!( - lt_eq(col1.clone(), col2.clone()) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::Nullable) - ); - - assert_eq!( - or(lt(col1.clone(), col2.clone()), not_eq(col1, col2)) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::Nullable) - ); - } - - #[test] - fn comparison_with_typed_null_simplifies_after_type_check() -> VortexResult<()> { - let dtype = test_harness::struct_dtype(); - - let expr = eq( - col("col1"), - lit(Scalar::null(DType::Primitive( - PType::U16, - Nullability::Nullable, - ))), - ); - - assert_eq!( - expr.bind(&dtype)?.optimize_recursive()?, - lit(Scalar::null(DType::Bool(Nullability::Nullable))).bind(&dtype)? - ); - Ok(()) - } - - #[test] - fn comparison_with_incompatible_null_still_type_checks() { - let dtype = test_harness::struct_dtype(); - let expr = eq( - col("col1"), - lit(Scalar::null(DType::Utf8(Nullability::Nullable))), - ); - - assert!(expr.bind(&dtype).is_err()); - } - - #[test] - fn test_display_print() { - let expr = gt(lit(1), lit(2)); - assert_eq!(format!("{expr}"), "(1i32 > 2i32)"); - } - - /// Regression test for GitHub issue #5947: struct comparison in filter expressions should work - /// using `make_comparator` instead of Arrow's `cmp` functions which don't support nested types. - #[test] - fn test_struct_comparison() { - use crate::IntoArray; - use crate::arrays::StructArray; - - // Create a struct array with one element for testing. - let lhs_struct = StructArray::from_fields(&[ - ("a", PrimitiveArray::from_iter([1i32]).into_array()), - ("b", PrimitiveArray::from_iter([3i32]).into_array()), - ]) - .unwrap() - .into_array(); - - let rhs_struct_equal = StructArray::from_fields(&[ - ("a", PrimitiveArray::from_iter([1i32]).into_array()), - ("b", PrimitiveArray::from_iter([3i32]).into_array()), - ]) - .unwrap() - .into_array(); - - let rhs_struct_different = StructArray::from_fields(&[ - ("a", PrimitiveArray::from_iter([1i32]).into_array()), - ("b", PrimitiveArray::from_iter([4i32]).into_array()), - ]) - .unwrap() - .into_array(); - - // Test using binary method directly - let result_equal = lhs_struct.binary(rhs_struct_equal, Operator::Eq).unwrap(); - assert_eq!( - result_equal - .execute_scalar(0, &mut SESSION.create_execution_ctx()) - .vortex_expect("value"), - Scalar::bool(true, Nullability::NonNullable), - "Equal structs should be equal" - ); - - let result_different = lhs_struct - .binary(rhs_struct_different, Operator::Eq) - .unwrap(); - assert_eq!( - result_different - .execute_scalar(0, &mut SESSION.create_execution_ctx()) - .vortex_expect("value"), - Scalar::bool(false, Nullability::NonNullable), - "Different structs should not be equal" - ); - } - - #[test] - fn test_or_kleene_validity() { - let mut ctx = SESSION.create_execution_ctx(); - use crate::arrays::StructArray; - use crate::expr::col; - - let struct_arr = StructArray::from_fields(&[ - ("a", BoolArray::from_iter([Some(true)]).into_array()), - ( - "b", - BoolArray::from_iter([Option::::None]).into_array(), - ), - ]) - .unwrap() - .into_array(); - - let expr = or(col("a"), col("b")); - let result = struct_arr.apply(&expr).unwrap(); - - assert_arrays_eq!( - result, - BoolArray::from_iter([Some(true)]).into_array(), - &mut ctx - ) - } - - #[test] - fn test_and_reduce() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let left = BoolArray::from_iter([true, true, false]).into_array(); - let right = ConstantArray::new(true, 3).into_array(); - - let array = Binary::try_new(left.clone(), right.clone(), Operator::And)? - .into_array() - .optimize_ctx(&SESSION)?; // calls reduce() - assert!(array.is::()); // and(left, const) -> left - assert_arrays_eq!(array, left, &mut ctx); - - let array = Binary::try_new(right.clone(), left.clone(), Operator::And)? - .into_array() - .optimize_ctx(&SESSION)?; - assert!(array.is::()); // and(const, left) -> left - assert_arrays_eq!(array, left, &mut ctx); - - let array = Binary::try_new(left.clone(), right.clone(), Operator::Or)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(array.as_constant(), Some(&true.into())); // or(left, const) -> true - - let array = Binary::try_new(right.clone(), left, Operator::Or)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(array.as_constant(), Some(&true.into())); // or(const, left) -> true - - let array = Binary::try_new(right.clone(), right.clone(), Operator::Or)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(array.as_constant(), Some(&true.into())); // or(const, const) -> const - - let left_false = ConstantArray::new(false, 3).into_array(); - - let array = Binary::try_new(right.clone(), left_false.clone(), Operator::Or)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(array.as_constant(), Some(&true.into())); - let array = Binary::try_new(left_false, right, Operator::And)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(array.as_constant(), Some(&false.into())); - - Ok(()) - } - - #[test] - fn test_and_reduce_nullable() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let nullable_true = - ConstantArray::new(Scalar::bool(true, Nullability::Nullable), 3).into_array(); - let right = BoolArray::from_iter([true, false, true]).into_array(); - - let array = Binary::try_new(nullable_true, right, Operator::And)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_arrays_eq!( - array, - BoolArray::from_iter([Some(true), Some(false), Some(true)]), - &mut ctx - ); - Ok(()) - } - - /// Short-circuiting against a constant keeps the result's nullability: `x AND false` over a - /// nullable `x` is a nullable false, which a parent rebuilt around it requires. - #[test] - fn test_short_circuit_keeps_nullability() -> VortexResult<()> { - let nullable = BoolArray::from_iter([Some(true), None, Some(false)]).into_array(); - let non_nullable = BoolArray::from_iter([true, false, true]).into_array(); - let false_ = ConstantArray::new(false, 3).into_array(); - let nullable_false = - ConstantArray::new(Scalar::bool(false, Nullability::Nullable), 3).into_array(); - - let and_false = Binary::try_new(nullable, false_, Operator::And)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(and_false.dtype(), &DType::Bool(Nullability::Nullable)); - assert!(and_false.is::()); - - let or_false = Binary::try_new(non_nullable, nullable_false, Operator::Or)? - .into_array() - .optimize_ctx(&SESSION)?; - assert_eq!(or_false.dtype(), &DType::Bool(Nullability::Nullable)); - assert_arrays_eq!( - or_false, - BoolArray::from_iter([Some(true), Some(false), Some(true)]), - &mut SESSION.create_execution_ctx() - ); - Ok(()) - } - - #[test] - fn test_and_reject_non_bool() { - let lhs = ConstantArray::new(7i32, 3).into_array(); - let rhs = PrimitiveArray::from_iter([1i32, 2, 3]).into_array(); - assert!(Binary::try_new(lhs, rhs, Operator::And).is_err()); - } - - #[test] - fn test_isnull_and_reduce() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let left = BoolArray::from_iter([Some(true), Some(true), None]).into_array(); - let right = BoolArray::from_iter([true, false, true]).into_array(); - - // IsNull(and(x, y)) -> and(IsNull(x), y) -> and(not(x.validity), y) - // ^ nullable - for (lhs, rhs) in [(left.clone(), right.clone()), (right.clone(), left)] { - let array = lhs - .binary(rhs, Operator::And)? - .is_null()? - .optimize_ctx(&SESSION)?; - assert_eq!(*array.as_::>().options, Operator::And); - assert_arrays_eq!( - array.as_::().get_child(0), // not(left.validity()) - BoolArray::from_iter([false, false, true]), - &mut ctx - ); - assert_arrays_eq!(array.as_::().get_child(1), right, &mut ctx); - assert_arrays_eq!(array, BoolArray::from_iter([false, false, true]), &mut ctx); - } - Ok(()) - } - - #[test] - fn test_isnotnull_or_reduce() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let left = BoolArray::from_iter([Some(true), Some(true), None]).into_array(); - let right = BoolArray::from_iter([true, false, true]).into_array(); - - // IsNotNull(or(x, y)) -> or(IsNotNull(x), y) -> or(x.validity, y) - // ^ nullable - for (lhs, rhs) in [(left.clone(), right.clone()), (right.clone(), left)] { - let array = lhs - .binary(rhs, Operator::Or)? - .is_not_null()? - .optimize_ctx(&SESSION)?; - assert_eq!(*array.as_::>().options, Operator::Or); - assert_arrays_eq!( - array.as_::().get_child(0), // left.validity() - BoolArray::from_iter([true, true, false]), - &mut ctx - ); - assert_arrays_eq!(array.as_::().get_child(1), right, &mut ctx); - assert_arrays_eq!(array, BoolArray::from_iter([true, true, true]), &mut ctx); - } - Ok(()) - } - - /// Comparisons over arithmetic, joined by `AND`: every input is a scalar function, so each - /// operator executes its inputs through the executor. - #[test] - fn executes_non_columnar_inputs_iteratively() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let a = PrimitiveArray::from_iter([1i32, 5, 9, 12]).into_array(); - let b = PrimitiveArray::from_iter([2i32, 2, 2, 2]).into_array(); - let sum = a.binary(b.clone(), Operator::Add)?; - let difference = a.binary(b, Operator::Sub)?; - let ten = ConstantArray::new(10i32, 4).into_array(); - let result = sum - .binary(ten.clone(), Operator::Gt)? - .binary(difference.binary(ten, Operator::Lt)?, Operator::And)?; - - assert_arrays_eq!( - result, - BoolArray::from_iter([false, false, true, false]), - &mut ctx - ); - Ok(()) - } - - /// A constant `false` decides `AND` without executing the other operand, which here fails - /// when executed. - #[test] - fn deciding_constant_skips_other_operand() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let failing = PrimitiveArray::from_iter([1i32, 2, 3]) - .into_array() - .binary(ConstantArray::new(0i32, 3).into_array(), Operator::Div)? - .binary(ConstantArray::new(1i32, 3).into_array(), Operator::Gt)?; - assert!(failing.clone().execute::(&mut ctx).is_err()); - - let result = ConstantArray::new(false, 3) - .into_array() - .binary(failing, Operator::And)?; - - assert_arrays_eq!( - result, - BoolArray::from_iter([false, false, false]), - &mut ctx - ); - Ok(()) - } -} diff --git a/vortex-array/src/scalar_fn/builtin/binary/numeric/tests.rs b/vortex-array/src/scalar_fn/builtin/binary/numeric/tests.rs index 291d92cef54..490eaf54c6b 100644 --- a/vortex-array/src/scalar_fn/builtin/binary/numeric/tests.rs +++ b/vortex-array/src/scalar_fn/builtin/binary/numeric/tests.rs @@ -31,11 +31,11 @@ use crate::dtype::NativePType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::dtype::i256; -use crate::expr::stats::Precision; use crate::scalar::DecimalValue; use crate::scalar::NumericOperator; use crate::scalar::Scalar; use crate::scalar_fn::builtin::operators::Operator; +use crate::stats::Precision; use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/scalar_fn/builtin/cast/mod.rs b/vortex-array/src/scalar_fn/builtin/cast/mod.rs index 9efd9257759..cb05fa652d5 100644 --- a/vortex-array/src/scalar_fn/builtin/cast/mod.rs +++ b/vortex-array/src/scalar_fn/builtin/cast/mod.rs @@ -37,9 +37,6 @@ use crate::arrays::struct_::compute::cast::struct_cast; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::StructFields; -use crate::expr::BoundExpression; -use crate::expr::bound; -use crate::expr::display::ExprDisplay; use crate::proto::expr as pb; use crate::scalar_fn::Arity; use crate::scalar_fn::ChildName; @@ -49,7 +46,7 @@ use crate::scalar_fn::ReduceNodeValidity; use crate::scalar_fn::ScalarFnId; use crate::scalar_fn::ScalarFnVTable; use crate::scalar_fn::ScalarFnVTableExt; -use crate::scalar_fn::builtin::literal::Literal; +use crate::scalar_fn::display::ExprDisplay; use crate::scalar_fn::is_not_null_node; /// Checks that a cast involving an extension dtype changes only its top-level nullability or @@ -224,17 +221,21 @@ impl ScalarFnVTable for Cast { Ok(None) } - fn simplify( - &self, - target_dtype: &DType, - expr: &BoundExpression, - ) -> VortexResult> { - let Some(scalar) = expr.child(0).as_opt::() else { - return Ok(None); - }; - // A failing cast (e.g. null to a non-nullable dtype) is left in place so the error - // surfaces at execution time rather than during optimization. - Ok(scalar.cast(target_dtype).ok().map(bound::lit)) + fn simplify(&self, target_dtype: &DType, node: &T) -> VortexResult> { + let child = node.child(0); + if let Some(scalar) = child.as_constant() { + // A failing cast (e.g. null to a non-nullable dtype) is left in place so the error + // surfaces at execution time rather than during optimization. + return Ok(scalar + .cast(target_dtype) + .ok() + .map(|scalar| node.new_constant(scalar))); + } + // Collapse node if child is already the target type + if &child.node_dtype()? == target_dtype { + return Ok(Some(child)); + } + Ok(None) } fn validity( @@ -295,147 +296,3 @@ fn cast_canonical( fn cast_constant(array: ArrayView, dtype: &DType) -> VortexResult> { ::cast(array, dtype) } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_error::vortex_err; - use vortex_session::VortexSession; - - use super::Cast; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::arrays::StructArray; - use crate::assert_arrays_eq; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::expr::Expression; - use crate::expr::cast; - use crate::expr::get_item; - use crate::expr::lit; - use crate::expr::root; - use crate::expr::test_harness; - use crate::scalar::DecimalValue; - use crate::scalar::Scalar; - use crate::scalar_fn::builtin::literal::Literal; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn dtype() { - let dtype = test_harness::struct_dtype(); - assert_eq!( - cast(root(), DType::Bool(Nullability::NonNullable)) - .return_dtype(&dtype) - .unwrap(), - DType::Bool(Nullability::NonNullable) - ); - } - - #[test] - fn replace_children() -> VortexResult<()> { - let dtype = DType::Bool(Nullability::Nullable); - let expr = cast(root(), dtype.clone()); - let replaced = expr.with_children(vec![get_item("a", root())])?; - assert_eq!(replaced, cast(get_item("a", root()), dtype)); - Ok(()) - } - - #[test] - fn evaluate() { - let test_array = StructArray::from_fields(&[ - ("a", buffer![0i32, 1, 2].into_array()), - ("b", buffer![4i64, 5, 6].into_array()), - ]) - .unwrap() - .into_array(); - - let expr: Expression = cast( - get_item("a", root()), - DType::Primitive(PType::I64, Nullability::NonNullable), - ); - let result = test_array.apply(&expr).unwrap(); - - assert_eq!( - result.dtype(), - &DType::Primitive(PType::I64, Nullability::NonNullable) - ); - assert_arrays_eq!( - result, - buffer![0i64, 1, 2].into_array(), - &mut SESSION.create_execution_ctx() - ); - } - - #[test] - fn simplify_folds_cast_of_literal() -> VortexResult<()> { - let expr = cast( - lit(3i32), - DType::Primitive(PType::F64, Nullability::NonNullable), - ); - let optimized = expr.bind(&test_harness::struct_dtype())?.optimize()?; - - let scalar = optimized - .as_opt::() - .ok_or_else(|| vortex_err!("expected a bare literal, got {optimized}"))?; - assert_eq!(scalar, &Scalar::primitive(3.0f64, Nullability::NonNullable)); - Ok(()) - } - - #[test] - fn simplify_folds_cast_of_decimal_literal() -> VortexResult<()> { - let decimal = Scalar::decimal( - DecimalValue::I128(319), - DecimalDType::new(3, 2), - Nullability::NonNullable, - ); - let expr = cast( - lit(decimal), - DType::Primitive(PType::F64, Nullability::NonNullable), - ); - let optimized = expr.bind(&test_harness::struct_dtype())?.optimize()?; - - let scalar = optimized - .as_opt::() - .ok_or_else(|| vortex_err!("expected a bare literal, got {optimized}"))?; - assert_eq!( - scalar, - &Scalar::primitive(3.19f64, Nullability::NonNullable) - ); - Ok(()) - } - - #[test] - fn simplify_leaves_failing_cast_unchanged() -> VortexResult<()> { - let target = DType::Primitive(PType::F64, Nullability::NonNullable); - let expr = cast( - lit(Scalar::null(DType::Primitive( - PType::I32, - Nullability::Nullable, - ))), - target.clone(), - ); - let optimized = expr.bind(&test_harness::struct_dtype())?.optimize()?; - - assert!(optimized.as_opt::().is_none()); - assert_eq!(optimized.as_opt::(), Some(&target)); - Ok(()) - } - - #[test] - fn test_display() { - let expr = cast( - get_item("value", root()), - DType::Primitive(PType::I64, Nullability::NonNullable), - ); - assert_eq!(expr.to_string(), "cast($.value as i64)"); - - let expr2 = cast(root(), DType::Bool(Nullability::Nullable)); - assert_eq!(expr2.to_string(), "cast($ as bool?)"); - } -} diff --git a/vortex-array/src/scalar_fn/builtin/fill_null/mod.rs b/vortex-array/src/scalar_fn/builtin/fill_null/mod.rs index 4faae06f454..c9d15582795 100644 --- a/vortex-array/src/scalar_fn/builtin/fill_null/mod.rs +++ b/vortex-array/src/scalar_fn/builtin/fill_null/mod.rs @@ -26,7 +26,6 @@ use crate::arrays::Primitive; use crate::arrays::ScalarFnArray; use crate::arrays::VarBinView; use crate::dtype::DType; -use crate::expr::BoundExpression; use crate::optimizer::ArrayOptimizer; use crate::require_input; use crate::scalar::Scalar; @@ -184,15 +183,15 @@ impl ScalarFnVTable for FillNull { .map(ScalarFnExecutionResult::done) } - fn simplify( + fn simplify( &self, _options: &Self::Options, - expr: &BoundExpression, - ) -> VortexResult> { - if !expr.child(0).dtype().is_nullable() { - return Ok(Some(expr.child(0).clone())); + node: &T, + ) -> VortexResult> { + let child = node.child(0); + if !child.node_dtype()?.is_nullable() { + return Ok(Some(child)); } - Ok(None) } @@ -288,351 +287,3 @@ fn fill_null_canonical( } } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_buffer::buffer; - use vortex_error::VortexExpect; - use vortex_session::VortexSession; - - use super::*; - use crate::Canonical; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::arrays::BoolArray; - use crate::arrays::Chunked; - use crate::arrays::ChunkedArray; - use crate::arrays::Constant; - use crate::arrays::ConstantArray; - use crate::arrays::Primitive; - use crate::arrays::PrimitiveArray; - use crate::arrays::ScalarFnArray; - use crate::arrays::StructArray; - use crate::arrays::VariantArray; - use crate::arrays::scalar_fn::ExactScalarFn; - use crate::assert_arrays_eq; - use crate::builders::builder_with_capacity_in; - use crate::builtins::ArrayBuiltins; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::expr::fill_null; - use crate::expr::get_item; - use crate::expr::lit; - use crate::expr::root; - use crate::extension::datetime::Date; - use crate::extension::datetime::TimeUnit; - use crate::kernel::ExecuteParentKernel; - use crate::matcher::Matcher; - use crate::optimizer::rules::ArrayParentReduceRule; - use crate::scalar::Scalar; - use crate::scalar_fn::builtin::binary::Binary; - use crate::scalar_fn::builtin::operators::Operator; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn test_fill_null_rejects_other_base_type_for_non_nullable_input() -> VortexResult<()> { - let input = buffer![1i32].into_array(); - let fill = Scalar::from(0i64); - - let expression_error = fill_null(root(), lit(fill.clone())) - .bind(input.dtype()) - .expect_err("the input and fill have different base types"); - let array_error = input - .fill_null(fill) - .expect_err("the array shortcut must enforce the expression's dtype rule"); - - // Compare only the message, because the error text includes a backtrace when - // `RUST_BACKTRACE` is set, and the two paths fail at different call sites. - let rule = "fill_null requires input and fill value to have the same base type"; - assert!( - expression_error.to_string().contains(rule), - "{expression_error}" - ); - assert!(array_error.to_string().contains(rule), "{array_error}"); - Ok(()) - } - - /// A fill of `40 + 2` that is not a [`ConstantArray`] until it executes. - fn lazy_fill_42(len: usize) -> VortexResult { - Ok(ScalarFnArray::try_new( - Binary.bind(Operator::Add), - vec![ - ConstantArray::new(40i32, len).into_array(), - ConstantArray::new(2i32, len).into_array(), - ], - )? - .into_array()) - } - - #[test] - fn dtype() { - let dtype = DType::Primitive(PType::I32, Nullability::Nullable); - assert_eq!( - fill_null(root(), lit(0i32)).return_dtype(&dtype).unwrap(), - DType::Primitive(PType::I32, Nullability::NonNullable) - ); - } - - #[test] - fn replace_children() { - let expr = fill_null(root(), lit(0i32)); - let replaced = expr - .with_children(vec![get_item("a", root()), lit(42i32)]) - .vortex_expect("operation should succeed in test"); - assert_eq!(replaced, fill_null(get_item("a", root()), lit(42i32))); - } - - #[test] - fn evaluate() { - let mut ctx = SESSION.create_execution_ctx(); - let test_array = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), None, Some(5)]) - .into_array(); - - let expr = fill_null(root(), lit(42i32)); - let result = test_array.apply(&expr).unwrap(); - - assert_eq!( - result.dtype(), - &DType::Primitive(PType::I32, Nullability::NonNullable) - ); - assert_arrays_eq!( - result, - PrimitiveArray::from_iter([1i32, 42, 3, 42, 5]), - &mut ctx - ); - } - - #[test] - fn evaluate_lazy_constant_fill() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let input = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(); - let fill = lazy_fill_42(input.len())?; - assert!(fill.as_constant().is_none()); - - let result = FillNull::try_new(input, fill)? - .into_array() - .execute::(&mut ctx)?; - - assert_eq!( - result.dtype(), - &DType::Primitive(PType::I32, Nullability::NonNullable) - ); - assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 42, 3]), &mut ctx); - Ok(()) - } - - #[test] - fn evaluate_lazy_fill_preserves_chunked_input() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let input = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter([Some(1i32), None]).into_array(), - PrimitiveArray::from_option_iter([Some(3), None]).into_array(), - ], - DType::Primitive(PType::I32, Nullability::Nullable), - )? - .into_array(); - let fill = lazy_fill_42(input.len())?; - - let result = FillNull::try_new(input, fill)? - .into_array() - .execute::(&mut ctx)?; - - assert!(result.is::()); - assert_arrays_eq!( - result, - PrimitiveArray::from_iter([1i32, 42, 3, 42]), - &mut ctx - ); - Ok(()) - } - - #[test] - fn non_constant_fill_declines_and_errors() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let varying = PrimitiveArray::from_iter([1i32, 2, 3]).into_array(); - - let constant_input = ConstantArray::new(Scalar::null_native::(), 3).into_array(); - let constant_parent = - FillNull::try_new(constant_input.clone(), varying.clone())?.into_array(); - let reduced = FillNullReduceAdaptor(Constant).reduce_parent( - constant_input - .as_opt::() - .vortex_expect("constant input"), - ExactScalarFn::::try_match(&constant_parent) - .vortex_expect("fill_null parent"), - 0, - )?; - assert!(reduced.is_none()); - - let primitive_input = - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(); - let primitive_parent = FillNull::try_new(primitive_input.clone(), varying)?.into_array(); - let executed = FillNullExecuteAdaptor(Primitive).execute_parent( - primitive_input - .as_opt::() - .vortex_expect("primitive input"), - ExactScalarFn::::try_match(&primitive_parent) - .vortex_expect("fill_null parent"), - 0, - &mut ctx, - )?; - assert!(executed.is_none()); - - let err = primitive_parent.execute::(&mut ctx).unwrap_err(); - assert!( - err.to_string() - .contains("fill_null fill_value must be a constant/scalar") - ); - Ok(()) - } - - /// Filling a chunked array slices the constant fill per chunk, and an empty slice is a - /// canonical array rather than a constant. Stacked fills over an empty chunk must still run. - #[test] - fn repeated_fill_over_empty_chunk() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let input = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter(Vec::>::new()).into_array(), - PrimitiveArray::from_option_iter([Some(7u16), None]).into_array(), - ], - DType::Primitive(PType::U16, Nullability::Nullable), - )? - .into_array(); - - let result = input - .fill_null(Scalar::primitive(1u16, Nullability::Nullable))? - .fill_null(Scalar::primitive(2u16, Nullability::NonNullable))?; - - assert_arrays_eq!(result, PrimitiveArray::from_iter([7u16, 1]), &mut ctx); - Ok(()) - } - - #[test] - fn evaluate_struct_field() { - let mut ctx = SESSION.create_execution_ctx(); - let test_array = StructArray::from_fields(&[( - "a", - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), - )]) - .unwrap() - .into_array(); - - let expr = fill_null(get_item("a", root()), lit(0i32)); - let result = test_array.apply(&expr).unwrap(); - - assert_eq!( - result.dtype(), - &DType::Primitive(PType::I32, Nullability::NonNullable) - ); - assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 0, 3]), &mut ctx); - } - - #[test] - fn evaluate_non_nullable_input() { - let mut ctx = SESSION.create_execution_ctx(); - let test_array = buffer![1i32, 2, 3].into_array(); - let expr = fill_null(root(), lit(0i32)); - let result = test_array.apply(&expr).unwrap(); - assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 2, 3]), &mut ctx); - } - - /// Inputs with both valid and null rows execute for every non-zip dtype that `supports_dtype` - /// accepts, with a nullable or a non-nullable fill value. - #[rstest] - #[case::bool(DType::Bool(Nullability::Nullable))] - #[case::primitive(DType::Primitive(PType::I32, Nullability::Nullable))] - #[case::decimal(DType::Decimal(DecimalDType::new(19, 2), Nullability::Nullable))] - #[case::utf8(DType::Utf8(Nullability::Nullable))] - #[case::binary(DType::Binary(Nullability::Nullable))] - #[case::date(DType::Extension(Date::new(TimeUnit::Days, Nullability::Nullable).erased()))] - fn supported_dtypes_fill_mixed_validity( - #[case] dtype: DType, - #[values(Nullability::NonNullable, Nullability::Nullable)] fill_nullability: Nullability, - ) -> VortexResult<()> { - assert!(FillNull::supports_dtype(&dtype), "{dtype}"); - - let mut ctx = SESSION.create_execution_ctx(); - let fill = Scalar::default_value(&dtype.as_nonnullable()) - .cast(&dtype.with_nullability(fill_nullability))?; - let mut builder = builder_with_capacity_in(&dtype, 2, ctx.allocator()); - builder.append_scalar(&fill.cast(&dtype)?)?; - builder.append_null(); - let filled = builder - .finish() - .fill_null(fill.clone())? - .execute::(&mut ctx)? - .into_array(); - - assert_eq!(filled.dtype(), fill.dtype(), "{dtype}"); - assert_eq!(filled.execute_scalar(1, &mut ctx)?, fill, "{dtype}"); - assert_arrays_eq!(filled, ConstantArray::new(fill, 2), &mut ctx); - Ok(()) - } - - #[rstest] - #[case::null(DType::Null)] - #[case::variant(DType::Variant(Nullability::Nullable))] - #[case::nested_variant(DType::struct_( - [("value", DType::Variant(Nullability::Nullable))], - Nullability::Nullable, - ))] - fn unsupported_dtypes(#[case] dtype: DType) { - assert!(!FillNull::supports_dtype(&dtype), "{dtype}"); - } - - /// A variant input with mixed validity fails with an error instead of a panic. - #[test] - fn variant_with_mixed_validity_errors() -> VortexResult<()> { - let dtype = DType::Variant(Nullability::Nullable); - let value = Scalar::variant(Scalar::primitive(1i32, Nullability::NonNullable)); - let core_storage = ChunkedArray::try_new( - vec![ - ConstantArray::new(value.cast(&dtype)?, 1).into_array(), - ConstantArray::new(Scalar::null(dtype.clone()), 1).into_array(), - ], - dtype, - )? - .into_array(); - let input = VariantArray::try_new(core_storage, None)?.into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - let error = input - .fill_null(value)? - .execute::(&mut ctx) - .unwrap_err(); - assert!( - error.to_string().contains("fill_null is not supported"), - "{error}" - ); - Ok(()) - } - - #[test] - fn test_display() { - let expr = fill_null(get_item("value", root()), lit(0i32)); - assert_eq!(expr.to_string(), "vortex.fill_null($.value, 0i32)"); - } - - /// A scalar function input is executed through the executor before its nulls are filled. - #[test] - fn executes_non_columnar_input_iteratively() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let input = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]) - .into_array() - .binary(ConstantArray::new(2i32, 3).into_array(), Operator::Gt)?; - - let result = input.fill_null(Scalar::from(false))?; - - assert_arrays_eq!(result, BoolArray::from_iter([false, false, true]), &mut ctx); - Ok(()) - } -} diff --git a/vortex-array/src/scalar_fn/builtin/get_item.rs b/vortex-array/src/scalar_fn/builtin/get_item.rs index 67aaa96c571..38d2f3b8d69 100644 --- a/vortex-array/src/scalar_fn/builtin/get_item.rs +++ b/vortex-array/src/scalar_fn/builtin/get_item.rs @@ -22,7 +22,6 @@ use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::FieldName; use crate::dtype::Nullability; -use crate::expr::display::ExprDisplay; use crate::proto::expr as pb; use crate::scalar::Scalar; use crate::scalar_fn::Arity; @@ -35,8 +34,7 @@ use crate::scalar_fn::ScalarFnVTable; use crate::scalar_fn::ScalarFnVTableExt; use crate::scalar_fn::builtin::mask::Mask; use crate::scalar_fn::builtin::pack::Pack; -use crate::scalar_fn::builtin::select::FieldSelection; -use crate::scalar_fn::builtin::select::Select; +use crate::scalar_fn::display::ExprDisplay; #[derive(Clone)] pub struct GetItem; @@ -71,7 +69,8 @@ impl GetItem { ) } - /// Extract a constant field, bypass a selection, or read a field directly from a pack. + /// Extract a constant field, read through a function that forwards the field, or read a field + /// directly from a pack. fn maybe_apply_now( struct_node: &T, field_name: &FieldName, @@ -82,18 +81,11 @@ impl GetItem { )); } - if let Some(selection) = struct_node + if let Some(child_idx) = struct_node .scalar_fn() - .and_then(|scalar_fn| scalar_fn.as_opt::() - .normalize_to_included_fields(&field_names) - .unwrap(), - FieldNames::from(["a"]) - ); - } - } - - #[test] - fn execute_constant_struct_stays_constant() -> VortexResult<()> { - let field_count = 128usize; - let names = (0..field_count) - .map(|idx| FieldName::from(format!("f{idx}"))) - .collect::>(); - let dtypes = vec![I32.into(); field_count]; - let fields = StructFields::new(FieldNames::from(names), dtypes); - let scalar = Scalar::struct_( - DType::Struct(fields, Nullability::NonNullable), - (0..128).map(Scalar::from), - ); - let array = ConstantArray::new(scalar, 1_000_000).into_array(); - let mut ctx = SESSION.create_execution_ctx(); - - let item: ArrayRef = ScalarFnArray::try_new( - Select.bind(FieldSelection::Include(FieldNames::from(["f97", "f3"]))), - vec![array], - )? - .into_array() - .execute(&mut ctx)?; - - let constant = item.as_::(); - assert_eq!(constant.len(), 1_000_000); - assert_eq!( - constant.scalar(), - &Scalar::struct_( - DType::Struct( - StructFields::new( - FieldNames::from(["f97", "f3"]), - vec![I32.into(), I32.into()], - ), - Nullability::NonNullable, - ), - [Scalar::from(97), Scalar::from(3)], - ) - ); - Ok(()) - } - - #[test] - fn test_remove_select_rule() { - let dtype = DType::Struct( - StructFields::new(["a", "b"].into(), vec![I32.into(), I32.into()]), - Nullable, - ); - let e = select(["a", "b"], root()); - - let result = e.bind(&dtype).unwrap().optimize_recursive().unwrap(); - - assert_eq!(result.dtype(), &dtype); - } - - #[test] - fn test_remove_select_rule_exclude_fields() { - use crate::expr::select_exclude; - - let dtype = DType::Struct( - StructFields::new( - ["a", "b", "c"].into(), - vec![I32.into(), I32.into(), I32.into()], - ), - Nullable, - ); - let e = select_exclude(["c"], root()); - - let result = e.bind(&dtype).unwrap().optimize_recursive().unwrap(); - - // Should exclude "c" and include "a" and "b" - let result_dtype = result.dtype(); - assert!(result_dtype.is_nullable()); - let fields = result_dtype.as_struct_fields_opt().unwrap(); - assert_eq!(fields.names().as_ref(), &["a", "b"]); - assert_eq!( - result_dtype, - &DType::struct_([("a", I32), ("b", I32)], Nullable) - ); - } -} diff --git a/vortex-functions/src/strpos.rs b/vortex-functions/src/strpos.rs index 293f7fd2a25..232d52e568a 100644 --- a/vortex-functions/src/strpos.rs +++ b/vortex-functions/src/strpos.rs @@ -166,12 +166,13 @@ mod tests { use vortex_array::arrays::StructArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::assert_arrays_eq; - use vortex_array::expr::Expression; - use vortex_array::expr::get_item; - use vortex_array::expr::lit; - use vortex_array::expr::proto::ExprSerializeProtoExt; - use vortex_array::expr::root; use vortex_error::VortexResult; + use vortex_expr::ArrayExprExt; + use vortex_expr::Expression; + use vortex_expr::get_item; + use vortex_expr::lit; + use vortex_expr::proto::ExprSerializeProtoExt; + use vortex_expr::root; use vortex_session::VortexSession; use crate::expr::strpos; diff --git a/vortex-functions/src/tests/is_null.rs b/vortex-functions/src/tests/is_null.rs new file mode 100644 index 00000000000..fd03da508dc --- /dev/null +++ b/vortex-functions/src/tests/is_null.rs @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::LazyLock; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::ScalarFn; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::scalar_fn::ExactScalarFn; +use vortex_array::arrays::scalar_fn::ScalarFnArrayExt; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::expr::BoundExpression; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::binary::Binary; +use vortex_array::scalar_fn::builtin::operators::Operator; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_expr::ArrayExprExt; +use vortex_expr::Expression; +use vortex_expr::and; +use vortex_expr::col; +use vortex_expr::get_item; +use vortex_expr::lit; +use vortex_expr::not; +use vortex_expr::or; +use vortex_expr::root; +use vortex_expr::test_harness; +use vortex_session::VortexSession; + +use crate::builtins::ArrayFunctions; +use crate::expr::is_null; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[test] +fn dtype() { + let dtype = test_harness::struct_dtype(); + assert_eq!( + is_null(root()).return_dtype(&dtype).unwrap(), + DType::Bool(Nullability::NonNullable) + ); +} + +#[test] +fn evaluate_mask() { + let test_array = + PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)]).into_array(); + let expected = [false, true, false, true, false]; + + let result = test_array.clone().apply(&is_null(root())).unwrap(); + + assert_eq!(result.len(), test_array.len()); + assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable)); + + for (i, expected_value) in expected.iter().enumerate() { + assert_eq!( + result + .execute_scalar(i, &mut SESSION.create_execution_ctx()) + .unwrap(), + Scalar::bool(*expected_value, Nullability::NonNullable) + ); + } +} + +#[test] +fn evaluate_all_false() { + let test_array = buffer![1, 2, 3, 4, 5].into_array(); + + let result = test_array.clone().apply(&is_null(root())).unwrap(); + + assert_eq!(result.len(), test_array.len()); + // All values should be false (non-nullable input) + for i in 0..result.len() { + assert_eq!( + result + .execute_scalar(i, &mut SESSION.create_execution_ctx()) + .unwrap(), + Scalar::bool(false, Nullability::NonNullable) + ); + } +} + +#[test] +fn evaluate_all_true() { + let test_array = + PrimitiveArray::from_option_iter(vec![None::, None, None, None, None]).into_array(); + + let result = test_array.clone().apply(&is_null(root())).unwrap(); + + assert_eq!(result.len(), test_array.len()); + // All values should be true (all nulls) + for i in 0..result.len() { + assert_eq!( + result + .execute_scalar(i, &mut SESSION.create_execution_ctx()) + .unwrap(), + Scalar::bool(true, Nullability::NonNullable) + ); + } +} + +#[test] +fn evaluate_struct() { + let test_array = StructArray::from_fields(&[( + "a", + PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2), None, Some(3)]).into_array(), + )]) + .unwrap() + .into_array(); + let expected = [false, true, false, true, false]; + + let result = test_array + .clone() + .apply(&is_null(get_item("a", root()))) + .unwrap(); + + assert_eq!(result.len(), test_array.len()); + assert_eq!(result.dtype(), &DType::Bool(Nullability::NonNullable)); + + for (i, expected_value) in expected.iter().enumerate() { + assert_eq!( + result + .execute_scalar(i, &mut SESSION.create_execution_ctx()) + .unwrap(), + Scalar::bool(*expected_value, Nullability::NonNullable) + ); + } +} + +#[test] +fn test_display() { + let expr = is_null(get_item("name", root())); + assert_eq!(expr.to_string(), "vortex.is_null($.name)"); + + let expr2 = is_null(root()); + assert_eq!(expr2.to_string(), "vortex.is_null($)"); +} + +#[test] +fn test_is_null_is_not_strict() { + assert!( + !is_null(col("a")) + .as_scalar() + .is_some_and(|f| f.signature().is_strict()) + ); +} + +fn bool_dtype() -> DType { + let names = ["a", "b"].into(); + let fields = vec![ + DType::Bool(Nullability::Nullable), + DType::Bool(Nullability::NonNullable), + ]; + DType::Struct(StructFields::new(names, fields), Nullability::NonNullable) +} + +fn optimized(expr: Expression, scope: &DType) -> VortexResult { + expr.bind(scope)?.optimize() +} + +#[test] +fn reduce_to_constant() -> VortexResult<()> { + let dtype = bool_dtype(); + assert_eq!( + optimized(is_null(col("b")), &dtype)?, + lit(false).bind(&dtype)? + ); + Ok(()) +} + +/// Rules 1 and 2 of `reduce_null_check`: a null check of `and`/`or` with one non-nullable side. +#[test] +fn reduce_kleene() -> VortexResult<()> { + let dtype = bool_dtype(); + assert_eq!( + optimized(is_null(and(col("a"), col("b"))), &dtype)?, + and(is_null(col("a")), col("b")).bind(&dtype)? + ); + assert_eq!( + optimized(is_null(or(col("a"), col("b"))), &dtype)?, + and(is_null(col("a")), not(col("b"))).bind(&dtype)? + ); + Ok(()) +} + +#[test] +fn test_isnull_and_reduce() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let left = BoolArray::from_iter([Some(true), Some(true), None]).into_array(); + let right = BoolArray::from_iter([true, false, true]).into_array(); + + // IsNull(and(x, y)) -> and(IsNull(x), y) -> and(not(x.validity), y) + // ^ nullable + for (lhs, rhs) in [(left.clone(), right.clone()), (right.clone(), left)] { + let array = lhs + .binary(rhs, Operator::And)? + .is_null()? + .optimize_ctx(&SESSION)?; + assert_eq!(*array.as_::>().options, Operator::And); + assert_arrays_eq!( + array.as_::().get_child(0), // not(left.validity()) + BoolArray::from_iter([false, false, true]), + &mut ctx + ); + assert_arrays_eq!(array.as_::().get_child(1), right, &mut ctx); + assert_arrays_eq!(array, BoolArray::from_iter([false, false, true]), &mut ctx); + } + Ok(()) +} + +/// A non-nullable input is never null, and a nullable input is null where its validity is false. +#[test] +fn reduces_through_validity() -> VortexResult<()> { + let ctx = &mut SESSION.create_execution_ctx(); + let validity = BoolArray::from_iter([true, false, true]).into_array(); + assert_arrays_eq!(validity.is_null()?, ConstantArray::new(false, 3), ctx); + + let nullable = + PrimitiveArray::new(buffer![1, 2, 3], Validity::Array(validity.clone())).into_array(); + assert_arrays_eq!(nullable.is_null()?, validity.not()?, ctx); + Ok(()) +} + +#[test] +fn empty_constant_chunk_is_null() -> VortexResult<()> { + let array = ChunkedArray::try_new( + vec![ + ConstantArray::new(Some(1u64), 0).into_array(), + PrimitiveArray::from_iter(vec![2u64]) + .into_array() + .cast(DType::Primitive(PType::U64, Nullability::Nullable))?, + ], + DType::Primitive(PType::U64, Nullability::Nullable), + )? + .into_array(); + + let result = array.apply(&is_null(root()))?; + assert_arrays_eq!( + result, + BoolArray::from_iter([false]), + &mut SESSION.create_execution_ctx() + ); + Ok(()) +} diff --git a/vortex-functions/src/tests.rs b/vortex-functions/src/tests/mod.rs similarity index 94% rename from vortex-functions/src/tests.rs rename to vortex-functions/src/tests/mod.rs index 30ed7dd5b3d..beb454768c4 100644 --- a/vortex-functions/src/tests.rs +++ b/vortex-functions/src/tests/mod.rs @@ -3,33 +3,34 @@ //! Expression display, binding and optimizer tests that involve this crate's functions. +mod is_null; +mod select; + use vortex_array::dtype::DType; use vortex_array::dtype::FieldName; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; -use vortex_array::expr::Expression; -use vortex_array::expr::and; -use vortex_array::expr::bound; -use vortex_array::expr::cast; -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::gt_eq; -use vortex_array::expr::lit; -use vortex_array::expr::lt; -use vortex_array::expr::lt_eq; -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::expr::select; -use vortex_array::expr::select_exclude; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; +use vortex_expr::Expression; +use vortex_expr::and; +use vortex_expr::bound; +use vortex_expr::cast; +use vortex_expr::col; +use vortex_expr::eq; +use vortex_expr::get_item; +use vortex_expr::gt; +use vortex_expr::gt_eq; +use vortex_expr::lit; +use vortex_expr::lt; +use vortex_expr::lt_eq; +use vortex_expr::not; +use vortex_expr::not_eq; +use vortex_expr::or; +use vortex_expr::pack; +use vortex_expr::root; use crate::between::BetweenOptions; use crate::between::StrictComparison; @@ -37,6 +38,8 @@ use crate::expr::between; use crate::expr::bound::case_when as bound_case_when; use crate::expr::case_when; use crate::expr::merge; +use crate::expr::select; +use crate::expr::select_exclude; #[test] fn test_display_tree_select() { diff --git a/vortex-functions/src/tests/select.rs b/vortex-functions/src/tests/select.rs new file mode 100644 index 00000000000..37fba0789a1 --- /dev/null +++ b/vortex-functions/src/tests/select.rs @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::Constant; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ScalarFnArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldName; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::PType::I32; +use vortex_array::dtype::StructFields; +use vortex_array::optimizer::ArrayOptimizer; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::ScalarFnVTableExt; +use vortex_array::scalar_fn::builtin::get_item::GetItem; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_expr::ArrayExprExt; +use vortex_expr::Expression; +use vortex_expr::get_item; +use vortex_expr::proto::ExprSerializeProtoExt; +use vortex_expr::root; +use vortex_expr::test_harness; +use vortex_session::VortexSession; + +use crate::expr::select; +use crate::expr::select_exclude; +use crate::select::FieldSelection; +use crate::select::Select; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + + vortex_array::initialize(&session); + crate::initialize(&session); + session +}); + +fn test_array() -> StructArray { + StructArray::from_fields(&[ + ("a", buffer![0, 1, 2].into_array()), + ("b", buffer![4, 5, 6].into_array()), + ]) + .unwrap() +} + +#[test] +pub fn include_columns() { + let mut ctx = SESSION.create_execution_ctx(); + let st = test_array(); + let select = select(vec![FieldName::from("a")], root()); + let selected = st.into_array().apply(&select).unwrap(); + let selected_names = selected.dtype().as_struct_fields().names(); + assert_eq!(selected_names.as_ref(), &["a"]); + assert_arrays_eq!( + selected, + StructArray::from_fields(&[("a", buffer![0i32, 1, 2].into_array())]).unwrap(), + &mut ctx + ); +} + +#[test] +pub fn exclude_columns() { + let mut ctx = SESSION.create_execution_ctx(); + let st = test_array(); + let select = select_exclude(vec![FieldName::from("a")], root()); + let selected = st.into_array().apply(&select).unwrap(); + let selected_names = selected.dtype().as_struct_fields().names(); + assert_eq!(selected_names.as_ref(), &["b"]); + assert_arrays_eq!( + selected, + StructArray::from_fields(&[("b", buffer![4i32, 5, 6].into_array())]).unwrap(), + &mut ctx + ); +} + +#[test] +fn dtype() { + let dtype = test_harness::struct_dtype(); + + let select_expr = select(vec![FieldName::from("a")], root()); + let expected_dtype = DType::Struct( + dtype + .as_struct_fields_opt() + .unwrap() + .project(&["a".into()]) + .unwrap(), + Nullability::NonNullable, + ); + assert_eq!(select_expr.return_dtype(&dtype).unwrap(), expected_dtype); + + let select_expr_exclude = select_exclude( + vec![ + FieldName::from("col1"), + FieldName::from("col2"), + FieldName::from("bool1"), + FieldName::from("bool2"), + ], + root(), + ); + assert_eq!( + select_expr_exclude.return_dtype(&dtype).unwrap(), + expected_dtype + ); + + let select_expr_exclude = select_exclude( + vec![FieldName::from("col1"), FieldName::from("col2")], + root(), + ); + assert_eq!( + select_expr_exclude.return_dtype(&dtype).unwrap(), + DType::Struct( + dtype + .as_struct_fields_opt() + .unwrap() + .project(&["a".into(), "bool1".into(), "bool2".into()]) + .unwrap(), + Nullability::NonNullable + ) + ); +} + +#[test] +fn test_as_include_names() { + let field_names = FieldNames::from(["a", "b", "c"]); + for expr in [select(["a"], root()), select_exclude(["b", "c"], root())] { + assert_eq!( + expr.as_::