From 99ea4b41b6aa3f1a8c3792a4144f3b6c9d0db877 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Wed, 14 Oct 2026 01:31:27 +0000 Subject: [PATCH 01/27] Move non-statistics aggregate functions into vortex-aggregates vortex-array keeps the aggregate framework (vtables, accumulators, session registry, kernels) and the aggregates that back array statistics: min/max, sum, null/NaN counts, sortedness, constancy, uncompressed size, the all_* predicates and all_non_distinct. These are wired into `Stat`, `StatsSetRef::compute_stat` and array validation, so they cannot move up without first making statistics computation session-dispatched. Everything else moves to a new `vortex-aggregates` crate: `count`, `first`, `last`, `mean`, `bounded_min`, `bounded_max` and the `combined` adapter, together with the tests and benches that exercise them. `vortex_aggregates::initialize` registers BoundedMin/BoundedMax/First/Last and the Count grouped kernel, which `AggregateFnSession::default` used to do. It is called from `vortex_file::register_default_encodings` and from `VortexSessionDefault`, so sessions built through either keep writing the bounded string min/max zone stats. Sessions built only from `vortex_array::array_session()` no longer know these aggregates. `Min`/`Max::can_satisfy` now recognise the bounded variants by id instead of by type. A few helpers the moved code needs become public: `columnar_min_max`, `sum_decimal_dtype`, `DecimalValue::{rescale_i256, try_from_i256}`, `Accumulator::{dtypes, empty_partial, fold_partial}`, and the `partial_ord` module (doc-hidden). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- Cargo.lock | 17 ++ Cargo.toml | 2 + scripts/codspeed_bench_counts.json | 5 +- scripts/codspeed_bench_durations.json | 4 +- vortex-aggregates/Cargo.toml | 37 +++ .../benches/accumulator_construction.rs | 50 ++++ .../benches/aggregate_grouped.rs | 8 +- .../src}/bounded_max/mod.rs | 103 +++++--- .../src}/bounded_min/mod.rs | 87 ++++--- .../src}/combined.rs | 33 ++- vortex-aggregates/src/combined_tests.rs | 246 ++++++++++++++++++ .../src}/count/grouped.rs | 54 ++-- .../src}/count/mod.rs | 67 +++-- .../src}/first/mod.rs | 61 +++-- vortex-aggregates/src/grouped_tests.rs | 83 ++++++ .../fns => vortex-aggregates/src}/last/mod.rs | 61 +++-- vortex-aggregates/src/lib.rs | 49 ++++ .../fns => vortex-aggregates/src}/mean/mod.rs | 80 +++--- vortex-array/Cargo.toml | 4 - vortex-array/benches/scalar_construction.rs | 12 - vortex-array/src/aggregate_fn/accumulator.rs | 201 +------------- .../src/aggregate_fn/accumulator_grouped.rs | 64 +---- vortex-array/src/aggregate_fn/fns/max/mod.rs | 3 +- vortex-array/src/aggregate_fn/fns/min/mod.rs | 3 +- .../src/aggregate_fn/fns/min_max/mod.rs | 2 +- vortex-array/src/aggregate_fn/fns/mod.rs | 6 - vortex-array/src/aggregate_fn/fns/sum/mod.rs | 3 +- vortex-array/src/aggregate_fn/mod.rs | 1 - vortex-array/src/aggregate_fn/session.rs | 13 - vortex-array/src/lib.rs | 3 +- .../src/scalar/typed_view/decimal/dvalue.rs | 4 +- vortex-duckdb/src/convert/expr.rs | 8 +- vortex-file/Cargo.toml | 1 + vortex-file/src/lib.rs | 1 + vortex-layout/Cargo.toml | 1 + vortex-layout/src/layouts/zoned/mod.rs | 5 +- vortex-layout/src/layouts/zoned/writer.rs | 12 +- vortex-layout/src/layouts/zoned/zone_map.rs | 4 +- vortex/Cargo.toml | 1 + vortex/src/lib.rs | 2 + 40 files changed, 827 insertions(+), 574 deletions(-) create mode 100644 vortex-aggregates/Cargo.toml create mode 100644 vortex-aggregates/benches/accumulator_construction.rs rename {vortex-array => vortex-aggregates}/benches/aggregate_grouped.rs (98%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/bounded_max/mod.rs (86%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/bounded_min/mod.rs (84%) rename {vortex-array/src/aggregate_fn => vortex-aggregates/src}/combined.rs (95%) create mode 100644 vortex-aggregates/src/combined_tests.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/count/grouped.rs (87%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/count/mod.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/first/mod.rs (88%) create mode 100644 vortex-aggregates/src/grouped_tests.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/last/mod.rs (88%) create mode 100644 vortex-aggregates/src/lib.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/mean/mod.rs (90%) diff --git a/Cargo.lock b/Cargo.lock index 91c86751a26..a2a7744a366 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11049,6 +11049,7 @@ dependencies = [ "tracing", "tracing-subscriber", "vortex", + "vortex-aggregates", "vortex-alp", "vortex-array", "vortex-arrow", @@ -11083,6 +11084,20 @@ dependencies = [ "vortex-zstd", ] +[[package]] +name = "vortex-aggregates" +version = "0.1.0" +dependencies = [ + "codspeed-divan-compat", + "mimalloc", + "rand 0.10.3", + "vortex-array", + "vortex-buffer", + "vortex-error", + "vortex-mask", + "vortex-session", +] + [[package]] name = "vortex-alp" version = "0.1.0" @@ -11798,6 +11813,7 @@ dependencies = [ "tokio", "tracing", "url", + "vortex-aggregates", "vortex-alp", "vortex-array", "vortex-arrow", @@ -12059,6 +12075,7 @@ dependencies = [ "tracing", "twox-hash", "uuid", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-btrblocks", diff --git a/Cargo.toml b/Cargo.toml index 8ca2693d7d4..74daf70948a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "vortex-cloud", "vortex-array", "vortex-functions", + "vortex-aggregates", "vortex-expr", "vortex-arrow", "vortex-row", @@ -303,6 +304,7 @@ zstd = { version = "0.14.3", default-features = false, features = [ # BEGIN crates published by this project vortex = { version = "0.1.0", path = "./vortex" } +vortex-aggregates = { version = "0.1.0", path = "./vortex-aggregates", default-features = false } vortex-alp = { version = "0.1.0", path = "./encodings/alp", default-features = false } vortex-array = { version = "0.1.0", path = "./vortex-array", default-features = false } vortex-array-macros = { version = "0.1.0", path = "./vortex-array-macros" } diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index 37143ef18e5..e3853743655 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -7,6 +7,10 @@ "take_union": 4, "write_compression": 3 }, + "vortex-aggregates": { + "accumulator_construction": 1, + "aggregate_grouped": 18 + }, "vortex-alp": { "alp_chain_decode": 4, "alp_compress": 36, @@ -16,7 +20,6 @@ }, "vortex-array": { "aggregate_definedness": 6, - "aggregate_grouped": 18, "aggregate_max": 15, "aggregate_sum": 15, "binary_ops": 7, diff --git a/scripts/codspeed_bench_durations.json b/scripts/codspeed_bench_durations.json index 51a8a3f0342..2547c0cc520 100644 --- a/scripts/codspeed_bench_durations.json +++ b/scripts/codspeed_bench_durations.json @@ -8,11 +8,13 @@ "single_encoding_throughput": 5.819, "take_union": 3.473 }, + "vortex-aggregates": { + "aggregate_grouped": 3.823 + }, "vortex-alp": { "alp_compress": 5.189 }, "vortex-array": { - "aggregate_grouped": 3.823, "aggregate_max": 3.586, "aggregate_sum": 3.199, "binary_ops": 2.881, diff --git a/vortex-aggregates/Cargo.toml b/vortex-aggregates/Cargo.toml new file mode 100644 index 00000000000..37753072ff1 --- /dev/null +++ b/vortex-aggregates/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "vortex-aggregates" +authors = { workspace = true } +categories = { workspace = true } +description = "Vortex aggregate functions beyond those backing array statistics" +edition = { workspace = true } +include = { workspace = true } +keywords = { workspace = true } +license = { workspace = true } +readme = { workspace = true } +repository = { workspace = true } +rust-version = { workspace = true } +version = { workspace = true } + +[dependencies] +vortex-array = { workspace = true } +vortex-buffer = { workspace = true } +vortex-error = { workspace = true } +vortex-mask = { workspace = true } +vortex-session = { workspace = true } + +[lints] +workspace = true + +[dev-dependencies] +divan = { workspace = true } +mimalloc = { workspace = true } +rand = { workspace = true } +vortex-array = { workspace = true, features = ["_test-harness"] } + +[[bench]] +name = "aggregate_grouped" +harness = false + +[[bench]] +name = "accumulator_construction" +harness = false diff --git a/vortex-aggregates/benches/accumulator_construction.rs b/vortex-aggregates/benches/accumulator_construction.rs new file mode 100644 index 00000000000..1a0c00302b0 --- /dev/null +++ b/vortex-aggregates/benches/accumulator_construction.rs @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +#![expect(clippy::unwrap_used)] + +//! Accumulator creation for this crate's aggregate functions. + +use std::hint::black_box; + +use divan::Bencher; +use divan::counter::ItemsCount; +use mimalloc::MiMalloc; +use vortex_aggregates::count::Count; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; + +#[global_allocator] +static GLOBAL: MiMalloc = MiMalloc; + +fn main() { + divan::main(); +} + +const N: usize = 1024; + +fn struct8_dtype() -> DType { + DType::Struct( + StructFields::new( + FieldNames::from(["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8"]), + vec![DType::Primitive(PType::I64, Nullability::NonNullable); 8], + ), + Nullability::NonNullable, + ) +} + +#[divan::bench] +fn accumulator_count_struct8(bencher: Bencher) { + let dtype = struct8_dtype(); + let aggregate_fn = Count.bind(NumericalAggregateOpts::default()); + bencher.counter(ItemsCount::new(N)).bench_local(|| { + for _ in 0..N { + black_box(aggregate_fn.accumulator(black_box(&dtype)).unwrap()); + } + }); +} diff --git a/vortex-array/benches/aggregate_grouped.rs b/vortex-aggregates/benches/aggregate_grouped.rs similarity index 98% rename from vortex-array/benches/aggregate_grouped.rs rename to vortex-aggregates/benches/aggregate_grouped.rs index 8a7eb402f87..9056ec84ba4 100644 --- a/vortex-array/benches/aggregate_grouped.rs +++ b/vortex-aggregates/benches/aggregate_grouped.rs @@ -11,6 +11,7 @@ use mimalloc::MiMalloc; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; +use vortex_aggregates::count::Count; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -19,7 +20,6 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynGroupedAccumulator; use vortex_array::aggregate_fn::GroupedAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::count::Count; use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::aggregate_fn::session::AggregateFnSession; @@ -42,9 +42,11 @@ fn main() { } static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); const GROUP_COUNT: usize = 128; diff --git a/vortex-array/src/aggregate_fn/fns/bounded_max/mod.rs b/vortex-aggregates/src/bounded_max/mod.rs similarity index 86% rename from vortex-array/src/aggregate_fn/fns/bounded_max/mod.rs rename to vortex-aggregates/src/bounded_max/mod.rs index 4b041ea3028..ec139d6de26 100644 --- a/vortex-array/src/aggregate_fn/fns/bounded_max/mod.rs +++ b/vortex-aggregates/src/bounded_max/mod.rs @@ -6,6 +6,27 @@ use std::fmt::Formatter; use std::num::NonZeroUsize; use std::sync::LazyLock; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min_max::MinMax; +use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::partial_ord::partial_max; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarTruncation; +use vortex_array::scalar::upper_bound; use vortex_buffer::BufferString; use vortex_buffer::ByteBuffer; use vortex_error::VortexExpect; @@ -16,28 +37,28 @@ use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnSatisfaction; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::columnar_min_max; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::StructFields; -use crate::partial_ord::partial_max; -use crate::scalar::Scalar; -use crate::scalar::ScalarTruncation; -use crate::scalar::upper_bound; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::max::Max; +use vortex_array::aggregate_fn::fns::min_max::MinMax; +use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; +use vortex_array::aggregate_fn::fns::min_max::min_max; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::partial_ord::partial_max; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarTruncation; +use vortex_array::scalar::upper_bound; /// Field name for the bounded maximum upper-bound value in the partial state. pub const BOUNDED_MAX_BOUND: &str = "bound"; @@ -367,30 +388,30 @@ mod tests { use std::num::NonZeroUsize; use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateFnSatisfaction; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::aggregate_fn::fns::max::Max; + use vortex_array::aggregate_fn::fns::min::Min; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::dtype::Nullability; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateFnSatisfaction; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::bounded_max::BoundedMax; - use crate::aggregate_fn::fns::bounded_max::BoundedMaxOptions; - use crate::aggregate_fn::fns::bounded_max::BoundedMaxPartial; - use crate::aggregate_fn::fns::bounded_max::BoundedMaxState; - use crate::aggregate_fn::fns::max::Max; - use crate::aggregate_fn::fns::min::Min; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinViewArray; - use crate::dtype::Nullability; - use crate::scalar::Scalar; - use crate::validity::Validity; + use crate::bounded_max::BoundedMax; + use crate::bounded_max::BoundedMaxOptions; + use crate::bounded_max::BoundedMaxPartial; + use crate::bounded_max::BoundedMaxState; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/bounded_min/mod.rs b/vortex-aggregates/src/bounded_min/mod.rs similarity index 84% rename from vortex-array/src/aggregate_fn/fns/bounded_min/mod.rs rename to vortex-aggregates/src/bounded_min/mod.rs index e6b5af413a7..f7099f8d399 100644 --- a/vortex-array/src/aggregate_fn/fns/bounded_min/mod.rs +++ b/vortex-aggregates/src/bounded_min/mod.rs @@ -5,6 +5,23 @@ use std::fmt::Display; use std::fmt::Formatter; use std::num::NonZeroUsize; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::min_max::MinMax; +use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; +use vortex_array::dtype::DType; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarTruncation; +use vortex_array::scalar::lower_bound; use vortex_buffer::BufferString; use vortex_buffer::ByteBuffer; use vortex_error::VortexExpect; @@ -14,24 +31,24 @@ use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnSatisfaction; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::columnar_min_max; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::dtype::DType; -use crate::partial_ord::partial_min; -use crate::scalar::Scalar; -use crate::scalar::ScalarTruncation; -use crate::scalar::lower_bound; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::min::Min; +use vortex_array::aggregate_fn::fns::min_max::MinMax; +use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; +use vortex_array::aggregate_fn::fns::min_max::min_max; +use vortex_array::dtype::DType; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarTruncation; +use vortex_array::scalar::lower_bound; /// Options for [`BoundedMin`]. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -281,28 +298,28 @@ mod tests { use std::num::NonZeroUsize; use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateFnSatisfaction; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::aggregate_fn::fns::max::Max; + use vortex_array::aggregate_fn::fns::min::Min; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::dtype::Nullability; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateFnSatisfaction; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::bounded_min::BoundedMin; - use crate::aggregate_fn::fns::bounded_min::BoundedMinOptions; - use crate::aggregate_fn::fns::max::Max; - use crate::aggregate_fn::fns::min::Min; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinViewArray; - use crate::dtype::Nullability; - use crate::scalar::Scalar; - use crate::validity::Validity; + use crate::bounded_min::BoundedMin; + use crate::bounded_min::BoundedMinOptions; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/combined.rs b/vortex-aggregates/src/combined.rs similarity index 95% rename from vortex-array/src/aggregate_fn/combined.rs rename to vortex-aggregates/src/combined.rs index 842603c672e..2d9177c6c1a 100644 --- a/vortex-array/src/aggregate_fn/combined.rs +++ b/vortex-aggregates/src/combined.rs @@ -10,28 +10,27 @@ use std::fmt::Formatter; use std::fmt::{self}; use std::hash::Hash; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateDTypes; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +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::StructFields; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateDTypes; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::FieldName; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::StructFields; -use crate::scalar::Scalar; - /// Pair of options for the two children of a [`BinaryCombined`] aggregate. /// /// Wrapper around `(L, R)` because the [`AggregateFnVTable::Options`] bound diff --git a/vortex-aggregates/src/combined_tests.rs b/vortex-aggregates/src/combined_tests.rs new file mode 100644 index 00000000000..bd6000036a5 --- /dev/null +++ b/vortex-aggregates/src/combined_tests.rs @@ -0,0 +1,246 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Accumulator dispatch tests that exercise [`Combined`](crate::combined::Combined) through +//! [`Mean`](crate::mean::Mean). + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VTable; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AccumulatorRef; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::sum::Sum; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::Dict; +use vortex_array::arrays::DictArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::SessionExt; +use vortex_session::VortexSession; + +use crate::combined::Combined; +use crate::combined::PairOptions; +use crate::mean::Mean; + +fn fresh_session() -> VortexSession { + crate::test_session() +} + +fn dict_of_seven() -> ArrayRef { + DictArray::try_new(buffer![0u32].into_array(), buffer![7.0f64].into_array()) + .expect("valid dictionary") + .into_array() +} + +/// Mean partial sentinel `{sum: 42.0, count: 1}` — distinguishable from the +/// natural fan-out result `{sum: 7.0, count: 1}` that `Combined::try_accumulate` +/// would produce for `dict_of_seven()`. +#[derive(Debug)] +struct SentinelMeanPartialKernel; +impl DynAggregateKernel for SentinelMeanPartialKernel { + fn aggregate( + &self, + _aggregate_fn: &AggregateFnRef, + _batch: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some(sentinel_partial())) + } +} + +/// Returns `Ok(None)` => kernel declined, dispatch falls through. +#[derive(Debug)] +struct DeclineKernel; +impl DynAggregateKernel for DeclineKernel { + fn aggregate( + &self, + _aggregate_fn: &AggregateFnRef, + _batch: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(None) + } +} + +/// A sentinel sum of `42.0`, distinguishable from `dict_of_seven()`'s natural sum of `7.0`. +#[derive(Debug)] +struct SentinelSumPartialKernel; +impl DynAggregateKernel for SentinelSumPartialKernel { + fn aggregate( + &self, + _aggregate_fn: &AggregateFnRef, + _batch: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some(Scalar::primitive(42.0f64, Nullability::Nullable))) + } +} + +fn mean_f64_accumulator() -> VortexResult>> { + let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); + Accumulator::try_new( + Mean::combined(), + PairOptions( + NumericalAggregateOpts::default(), + NumericalAggregateOpts::default(), + ), + dtype, + ) +} + +fn sentinel_partial() -> Scalar { + let acc = mean_f64_accumulator().expect("build accumulator"); + let sum = Scalar::primitive(42.0f64, Nullability::Nullable); + let count = Scalar::primitive(1u64, Nullability::NonNullable); + Scalar::struct_(acc.dtypes().partial_dtype.clone(), vec![sum, count]) +} + +/// Kernel registered for `(Dict, Combined)` fires in preference to +/// `Combined::try_accumulate`'s fan-out path — proves the dispatch reorder. +#[test] +fn combined_kernel_fires() -> VortexResult<()> { + static KERNEL: SentinelMeanPartialKernel = SentinelMeanPartialKernel; + let session = fresh_session(); + session + .get::() + .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); + let mut ctx = session.create_execution_ctx(); + + let mut acc = mean_f64_accumulator()?; + acc.accumulate(&dict_of_seven(), &mut ctx)?; + let partial = acc.flush()?; + + let s = partial.as_struct(); + assert_eq!( + s.field("sum").unwrap().as_primitive().as_::(), + Some(42.0) + ); + assert_eq!( + s.field("count").unwrap().as_primitive().as_::(), + Some(1) + ); + Ok(()) +} + +/// An execution context snapshots the aggregate kernels on first use, so a kernel registered +/// afterwards only fires through a new context. +#[test] +fn execution_ctx_snapshots_aggregate_kernels_on_first_use() -> VortexResult<()> { + static KERNEL: SentinelMeanPartialKernel = SentinelMeanPartialKernel; + let session = fresh_session(); + let mut ctx = session.create_execution_ctx(); + + let mut acc = mean_f64_accumulator()?; + acc.accumulate(&dict_of_seven(), &mut ctx)?; + assert_eq!( + acc.flush()? + .as_struct() + .field("sum") + .unwrap() + .as_primitive() + .as_::(), + Some(7.0) + ); + + session + .get::() + .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); + + acc.accumulate(&dict_of_seven(), &mut ctx)?; + assert_eq!( + acc.flush()? + .as_struct() + .field("sum") + .unwrap() + .as_primitive() + .as_::(), + Some(7.0) + ); + + acc.accumulate(&dict_of_seven(), &mut session.create_execution_ctx())?; + assert_eq!(acc.flush()?, sentinel_partial()); + Ok(()) +} + +/// Kernel returns `Ok(None)` => dispatch falls through to `Combined::try_accumulate`'s +/// natural fan-out. The natural partial is `{sum: 7.0, count: 1}`. +#[test] +fn fallback_when_kernel_declines() -> VortexResult<()> { + static KERNEL: DeclineKernel = DeclineKernel; + let session = fresh_session(); + session + .get::() + .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); + let mut ctx = session.create_execution_ctx(); + + let mut acc = mean_f64_accumulator()?; + acc.accumulate(&dict_of_seven(), &mut ctx)?; + let partial = acc.flush()?; + + let s = partial.as_struct(); + assert_eq!( + s.field("sum").unwrap().as_primitive().as_::(), + Some(7.0) + ); + assert_eq!( + s.field("count").unwrap().as_primitive().as_::(), + Some(1) + ); + Ok(()) +} + +/// A kernel registered for the inner `(Dict, Sum)` child fires when accumulating a +/// Dict batch through `Combined`. This is the reusable-primitive case the +/// refactor enables: no `(Dict, Combined)` kernel is needed. +#[test] +fn child_kernel_fires_through_combined() -> VortexResult<()> { + static KERNEL: SentinelSumPartialKernel = SentinelSumPartialKernel; + let session = fresh_session(); + session + .get::() + .register_aggregate_kernel(Dict.id(), Some(Sum.id()), &KERNEL); + let mut ctx = session.create_execution_ctx(); + + let mut acc = mean_f64_accumulator()?; + acc.accumulate(&dict_of_seven(), &mut ctx)?; + let partial = acc.flush()?; + + let s = partial.as_struct(); + // `Sum` child returned the sentinel 42.0 — proves the (Dict, Sum) kernel fired + // via `Combined`'s fan-out. `Count`'s native `try_accumulate` reads the + // batch's valid_count, so count is the real 1. + assert_eq!( + s.field("sum").unwrap().as_primitive().as_::(), + Some(42.0) + ); + assert_eq!( + s.field("count").unwrap().as_primitive().as_::(), + Some(1) + ); + Ok(()) +} + +#[test] +fn merge_from_combines_child_accumulators() -> VortexResult<()> { + let mut ctx = fresh_session().create_execution_ctx(); + let mut global: AccumulatorRef = Box::new(mean_f64_accumulator()?); + let mut local: AccumulatorRef = Box::new(mean_f64_accumulator()?); + + global.accumulate(&buffer![1.0f64, 2.0].into_array(), &mut ctx)?; + local.accumulate(&buffer![6.0f64].into_array(), &mut ctx)?; + global.merge_from(local.as_mut())?; + + assert_eq!(global.finish()?.as_primitive().as_::(), Some(3.0)); + Ok(()) +} diff --git a/vortex-array/src/aggregate_fn/fns/count/grouped.rs b/vortex-aggregates/src/count/grouped.rs similarity index 87% rename from vortex-array/src/aggregate_fn/fns/count/grouped.rs rename to vortex-aggregates/src/count/grouped.rs index 94bc8513a91..d612c336f8e 100644 --- a/vortex-array/src/aggregate_fn/fns/count/grouped.rs +++ b/vortex-aggregates/src/count/grouped.rs @@ -1,20 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::GroupRanges; +use vortex_array::aggregate_fn::GroupedArray; +use vortex_array::aggregate_fn::kernels::DynGroupedAggregateKernel; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_error::VortexResult; use vortex_mask::Mask; use super::Count; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::GroupRanges; -use crate::aggregate_fn::GroupedArray; -use crate::aggregate_fn::kernels::DynGroupedAggregateKernel; -use crate::arrays::PrimitiveArray; -use crate::validity::Validity; /// Encoding-independent grouped [`Count`] kernel. #[derive(Debug)] @@ -88,28 +88,28 @@ mod tests { use std::sync::LazyLock; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability::NonNullable; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::count::Count; - use crate::arrays::FixedSizeListArray; - use crate::arrays::ListViewArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinViewArray; - use crate::assert_arrays_eq; - use crate::dtype::DType; - use crate::dtype::Nullability::NonNullable; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::validity::Validity; + use crate::count::Count; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/count/mod.rs b/vortex-aggregates/src/count/mod.rs similarity index 89% rename from vortex-array/src/aggregate_fn/fns/count/mod.rs rename to vortex-aggregates/src/count/mod.rs index 545a2a27281..333e2f082bd 100644 --- a/vortex-array/src/aggregate_fn/fns/count/mod.rs +++ b/vortex-aggregates/src/count/mod.rs @@ -3,24 +3,23 @@ mod grouped; pub(crate) use grouped::CountGroupedKernel; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::nan_count::nan_count; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::nan_count::nan_count; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; -use crate::scalar::Scalar; - /// Count the number of non-null elements in an array. /// /// Applies to all types. Returns a `u64` count. @@ -153,32 +152,32 @@ impl AggregateFnVTable for Count { mod tests { use std::sync::LazyLock; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::count::Count; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::scalar::ScalarValue; - use crate::stats::Precision; - use crate::stats::Stat; - use crate::validity::Validity; + use crate::count::Count; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/first/mod.rs b/vortex-aggregates/src/first/mod.rs similarity index 88% rename from vortex-array/src/aggregate_fn/fns/first/mod.rs rename to vortex-aggregates/src/first/mod.rs index bf8e5162946..a2ab11362f7 100644 --- a/vortex-array/src/aggregate_fn/fns/first/mod.rs +++ b/vortex-aggregates/src/first/mod.rs @@ -1,22 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::dtype::DType; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::EmptyOptions; -use crate::dtype::DType; -use crate::scalar::Scalar; - /// Return the first non-null value of an array. /// /// See [`First`] for details. @@ -163,29 +162,29 @@ impl AggregateFnVTable for First { mod tests { use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::first::First; - use crate::aggregate_fn::fns::first::first; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::validity::Validity; + use crate::first::First; + use crate::first::first; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-aggregates/src/grouped_tests.rs b/vortex-aggregates/src/grouped_tests.rs new file mode 100644 index 00000000000..685723f52c9 --- /dev/null +++ b/vortex-aggregates/src/grouped_tests.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Grouped accumulation of the aggregates in this crate. + +use std::sync::LazyLock; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::GroupedAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::null_count::NullCount; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::PType; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::combined::PairOptions; +use crate::count::Count; +use crate::mean::Mean; + +static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + +#[test] +fn test_accumulate_list_with_null_group_non_nullable_partials() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // Groups: [[1.0, null, 3.0], null, [4.0]] + let elements = PrimitiveArray::from_option_iter([Some(1.0f64), None, Some(3.0), Some(4.0)]) + .into_array(); + let groups = ListViewArray::try_new( + elements, + buffer![0u32, 3, 3].into_array(), + buffer![3u32, 0, 1].into_array(), + Validity::from_iter([true, false, true]), + &mut ctx, + )? + .into_array(); + let elem_dtype = DType::Primitive(PType::F64, Nullable); + + let mut count_acc = GroupedAccumulator::try_new( + Count, + NumericalAggregateOpts::default(), + elem_dtype.clone(), + )?; + count_acc.accumulate_list(&groups, &mut ctx)?; + assert_arrays_eq!( + count_acc.finish()?, + PrimitiveArray::new(buffer![2u64, 0, 1], Validity::NonNullable), + &mut ctx + ); + + let mut null_count_acc = + GroupedAccumulator::try_new(NullCount, EmptyOptions, elem_dtype.clone())?; + null_count_acc.accumulate_list(&groups, &mut ctx)?; + assert_arrays_eq!( + null_count_acc.finish()?, + PrimitiveArray::new(buffer![1u64, 0, 0], Validity::NonNullable), + &mut ctx + ); + + let mut mean_acc = GroupedAccumulator::try_new( + Mean::combined(), + PairOptions( + NumericalAggregateOpts::default(), + NumericalAggregateOpts::default(), + ), + elem_dtype, + )?; + mean_acc.accumulate_list(&groups, &mut ctx)?; + assert_arrays_eq!( + mean_acc.finish()?, + PrimitiveArray::from_option_iter([Some(2.0f64), None, Some(4.0)]), + &mut ctx + ); + Ok(()) +} diff --git a/vortex-array/src/aggregate_fn/fns/last/mod.rs b/vortex-aggregates/src/last/mod.rs similarity index 88% rename from vortex-array/src/aggregate_fn/fns/last/mod.rs rename to vortex-aggregates/src/last/mod.rs index 052abb51a5a..e8ed09d2437 100644 --- a/vortex-array/src/aggregate_fn/fns/last/mod.rs +++ b/vortex-aggregates/src/last/mod.rs @@ -1,22 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::dtype::DType; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::EmptyOptions; -use crate::dtype::DType; -use crate::scalar::Scalar; - /// Return the last non-null value of an array. /// /// See [`Last`] for details. @@ -161,29 +160,29 @@ impl AggregateFnVTable for Last { mod tests { use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::last::Last; - use crate::aggregate_fn::fns::last::last; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::validity::Validity; + use crate::last::Last; + use crate::last::last; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-aggregates/src/lib.rs b/vortex-aggregates/src/lib.rs new file mode 100644 index 00000000000..d7a94648c6a --- /dev/null +++ b/vortex-aggregates/src/lib.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Aggregate functions built on the vortex-array aggregate framework that the core array crate +//! does not itself depend on. +//! +//! The aggregates backing array statistics (min/max, sum, null and NaN counts, sortedness, +//! constancy, uncompressed size) live in `vortex_array::aggregate_fn::fns`. This crate holds the +//! remaining built-ins: [`count`], [`first`], [`last`], [`mean`], the byte-bounded +//! [`bounded_min`]/[`bounded_max`] used by zone maps, and the [`combined`] adapter that composes +//! two aggregates into one. +//! +//! Call [`initialize`] to register them with a session. + +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_session::VortexSession; + +pub mod bounded_max; +pub mod bounded_min; +pub mod combined; +pub mod count; +pub mod first; +pub mod last; +pub mod mean; + +#[cfg(test)] +mod combined_tests; +#[cfg(test)] +mod grouped_tests; + +/// Register this crate's aggregate functions and grouped kernels with the given session. +pub fn initialize(session: &VortexSession) { + let aggregate_fns = session.aggregate_fns(); + aggregate_fns.register(bounded_max::BoundedMax); + aggregate_fns.register(bounded_min::BoundedMin); + aggregate_fns.register(count::Count); + aggregate_fns.register(first::First); + aggregate_fns.register(last::Last); + aggregate_fns.register(mean::Mean::combined()); + aggregate_fns.register_grouped_kernel(count::Count.id(), &count::CountGroupedKernel); +} + +#[cfg(test)] +fn test_session() -> VortexSession { + let session = VortexSession::empty(); + initialize(&session); + session +} diff --git a/vortex-array/src/aggregate_fn/fns/mean/mod.rs b/vortex-aggregates/src/mean/mod.rs similarity index 90% rename from vortex-array/src/aggregate_fn/fns/mean/mod.rs rename to vortex-aggregates/src/mean/mod.rs index 0758299debe..1c13cc0f3b3 100644 --- a/vortex-array/src/aggregate_fn/fns/mean/mod.rs +++ b/vortex-aggregates/src/mean/mod.rs @@ -1,41 +1,41 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::fns::sum::Sum; +use vortex_array::aggregate_fn::fns::sum::sum_decimal_dtype; +use vortex_array::arrays::ConstantArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::MAX_PRECISION; +use vortex_array::dtype::MAX_SCALE; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::combined::BinaryCombined; -use crate::aggregate_fn::combined::Combined; -use crate::aggregate_fn::combined::CombinedOptions; -use crate::aggregate_fn::combined::PairOptions; -use crate::aggregate_fn::fns::count::Count; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum::sum_decimal_dtype; -use crate::arrays::ConstantArray; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::MAX_PRECISION; -use crate::dtype::MAX_SCALE; -use crate::dtype::Nullability; -use crate::dtype::PType; -use crate::dtype::i256; -use crate::scalar::DecimalValue; -use crate::scalar::NumericOperator; -use crate::scalar::Scalar; -use crate::scalar_fn::builtin::operators::CompareMode; -use crate::scalar_fn::builtin::operators::CompareOperator; +use crate::combined::BinaryCombined; +use crate::combined::Combined; +use crate::combined::CombinedOptions; +use crate::combined::PairOptions; +use crate::count::Count; +use vortex_array::scalar::NumericOperator; +use vortex_array::scalar_fn::builtin::operators::CompareMode; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; /// Compute the arithmetic mean of an array. /// @@ -244,22 +244,22 @@ fn finalize_decimal_scalar( mod tests { use std::sync::LazyLock; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DecimalDType; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; use super::*; - use crate::VortexSessionExecute; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::GroupedAccumulator; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::DecimalArray; - use crate::arrays::FixedSizeListArray; - use crate::arrays::PrimitiveArray; - use crate::assert_arrays_eq; - use crate::dtype::DecimalDType; - use crate::validity::Validity; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/Cargo.toml b/vortex-array/Cargo.toml index fec3b56d6eb..55538b37b4d 100644 --- a/vortex-array/Cargo.toml +++ b/vortex-array/Cargo.toml @@ -114,10 +114,6 @@ harness = false name = "aggregate_sum" harness = false -[[bench]] -name = "aggregate_grouped" -harness = false - [[bench]] name = "aggregate_definedness" harness = false diff --git a/vortex-array/benches/scalar_construction.rs b/vortex-array/benches/scalar_construction.rs index d274f41360b..a39a0c7579f 100644 --- a/vortex-array/benches/scalar_construction.rs +++ b/vortex-array/benches/scalar_construction.rs @@ -17,7 +17,6 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::count::Count; use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; @@ -199,14 +198,3 @@ fn accumulator_sum_v2(bencher: Bencher) { } }); } - -#[divan::bench] -fn accumulator_count_struct8(bencher: Bencher) { - let dtype = struct8_dtype(); - let aggregate_fn = Count.bind(NumericalAggregateOpts::default()); - bencher.counter(ItemsCount::new(N)).bench_local(|| { - for _ in 0..N { - black_box(aggregate_fn.accumulator(black_box(&dtype)).unwrap()); - } - }); -} diff --git a/vortex-array/src/aggregate_fn/accumulator.rs b/vortex-array/src/aggregate_fn/accumulator.rs index 597e1ed2857..f88dfc1b1c9 100644 --- a/vortex-array/src/aggregate_fn/accumulator.rs +++ b/vortex-array/src/aggregate_fn/accumulator.rs @@ -63,8 +63,13 @@ impl Accumulator { } } + /// The input, partial, and result dtypes this accumulator was resolved with. + pub fn dtypes(&self) -> &AggregateDTypes { + &self.dtypes + } + /// The state of a group with no accumulated values. - pub(crate) fn empty_partial(&self) -> VortexResult { + pub fn empty_partial(&self) -> VortexResult { self.vtable.empty_partial(self.dtypes.args(&self.options)) } @@ -82,7 +87,8 @@ impl Accumulator { Ok(()) } - pub(crate) fn fold_partial(&mut self, other: V::Partial) -> VortexResult<()> { + /// Merge a typed partial state into this accumulator. + pub fn fold_partial(&mut self, other: V::Partial) -> VortexResult<()> { self.partial = Some(match self.partial.take() { // The empty state is the identity of the merge. None => other, @@ -390,9 +396,6 @@ mod tests { use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::combined::Combined; - use crate::aggregate_fn::combined::PairOptions; - use crate::aggregate_fn::fns::mean::Mean; use crate::aggregate_fn::fns::min::Min; use crate::aggregate_fn::fns::sum::Sum; use crate::aggregate_fn::kernels::DynAggregateKernel; @@ -410,36 +413,6 @@ mod tests { 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` - /// would produce for `dict_of_seven()`. - #[derive(Debug)] - struct SentinelMeanPartialKernel; - impl DynAggregateKernel for SentinelMeanPartialKernel { - fn aggregate( - &self, - _aggregate_fn: &AggregateFnRef, - _batch: &ArrayRef, - _ctx: &mut ExecutionCtx, - ) -> VortexResult> { - Ok(Some(sentinel_partial())) - } - } - - /// Returns `Ok(None)` => kernel declined, dispatch falls through. - #[derive(Debug)] - struct DeclineKernel; - impl DynAggregateKernel for DeclineKernel { - fn aggregate( - &self, - _aggregate_fn: &AggregateFnRef, - _batch: &ArrayRef, - _ctx: &mut ExecutionCtx, - ) -> VortexResult> { - Ok(None) - } - } - /// A sentinel sum of `42.0`, distinguishable from `dict_of_seven()`'s natural sum of `7.0`. #[derive(Debug)] struct SentinelSumPartialKernel; @@ -464,150 +437,6 @@ mod tests { .into_array() } - fn mean_f64_accumulator() -> VortexResult>> { - let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); - Accumulator::try_new( - Mean::combined(), - PairOptions( - NumericalAggregateOpts::default(), - NumericalAggregateOpts::default(), - ), - dtype, - ) - } - - fn sentinel_partial() -> Scalar { - let acc = mean_f64_accumulator().expect("build accumulator"); - let sum = Scalar::primitive(42.0f64, Nullability::Nullable); - let count = Scalar::primitive(1u64, Nullability::NonNullable); - Scalar::struct_(acc.dtypes.partial_dtype, vec![sum, count]) - } - - /// Kernel registered for `(Dict, Combined)` fires in preference to - /// `Combined::try_accumulate`'s fan-out path — proves the dispatch reorder. - #[test] - fn combined_kernel_fires() -> VortexResult<()> { - static KERNEL: SentinelMeanPartialKernel = SentinelMeanPartialKernel; - let session = fresh_session(); - session - .get::() - .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); - let mut ctx = session.create_execution_ctx(); - - let mut acc = mean_f64_accumulator()?; - acc.accumulate(&dict_of_seven(), &mut ctx)?; - let partial = acc.flush()?; - - let s = partial.as_struct(); - assert_eq!( - s.field("sum").unwrap().as_primitive().as_::(), - Some(42.0) - ); - assert_eq!( - s.field("count").unwrap().as_primitive().as_::(), - Some(1) - ); - Ok(()) - } - - /// An execution context snapshots the aggregate kernels on first use, so a kernel registered - /// afterwards only fires through a new context. - #[test] - fn execution_ctx_snapshots_aggregate_kernels_on_first_use() -> VortexResult<()> { - static KERNEL: SentinelMeanPartialKernel = SentinelMeanPartialKernel; - let session = fresh_session(); - let mut ctx = session.create_execution_ctx(); - - let mut acc = mean_f64_accumulator()?; - acc.accumulate(&dict_of_seven(), &mut ctx)?; - assert_eq!( - acc.flush()? - .as_struct() - .field("sum") - .unwrap() - .as_primitive() - .as_::(), - Some(7.0) - ); - - session - .get::() - .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); - - acc.accumulate(&dict_of_seven(), &mut ctx)?; - assert_eq!( - acc.flush()? - .as_struct() - .field("sum") - .unwrap() - .as_primitive() - .as_::(), - Some(7.0) - ); - - acc.accumulate(&dict_of_seven(), &mut session.create_execution_ctx())?; - assert_eq!(acc.flush()?, sentinel_partial()); - Ok(()) - } - - /// Kernel returns `Ok(None)` => dispatch falls through to `Combined::try_accumulate`'s - /// natural fan-out. The natural partial is `{sum: 7.0, count: 1}`. - #[test] - fn fallback_when_kernel_declines() -> VortexResult<()> { - static KERNEL: DeclineKernel = DeclineKernel; - let session = fresh_session(); - session - .get::() - .register_aggregate_kernel(Dict.id(), Some(Mean::combined().id()), &KERNEL); - let mut ctx = session.create_execution_ctx(); - - let mut acc = mean_f64_accumulator()?; - acc.accumulate(&dict_of_seven(), &mut ctx)?; - let partial = acc.flush()?; - - let s = partial.as_struct(); - assert_eq!( - s.field("sum").unwrap().as_primitive().as_::(), - Some(7.0) - ); - assert_eq!( - s.field("count").unwrap().as_primitive().as_::(), - Some(1) - ); - Ok(()) - } - - /// A kernel registered for the inner `(Dict, Sum)` child fires when accumulating a - /// Dict batch through `Combined`. This is the reusable-primitive case the - /// refactor enables: no `(Dict, Combined)` kernel is needed. - #[test] - fn child_kernel_fires_through_combined() -> VortexResult<()> { - static KERNEL: SentinelSumPartialKernel = SentinelSumPartialKernel; - let session = fresh_session(); - session - .get::() - .register_aggregate_kernel(Dict.id(), Some(Sum.id()), &KERNEL); - let mut ctx = session.create_execution_ctx(); - - let mut acc = mean_f64_accumulator()?; - acc.accumulate(&dict_of_seven(), &mut ctx)?; - let partial = acc.flush()?; - - let s = partial.as_struct(); - // `Sum` child returned the sentinel 42.0 — proves the (Dict, Sum) kernel fired - // via `Combined`'s fan-out. `Count`'s native `try_accumulate` reads the - // batch's valid_count, so count is the real 1. - assert_eq!( - s.field("sum").unwrap().as_primitive().as_::(), - Some(42.0) - ); - assert_eq!( - s.field("count").unwrap().as_primitive().as_::(), - Some(1) - ); - Ok(()) - } - #[test] fn cached_sum_precedes_encoding_kernel() -> VortexResult<()> { static KERNEL: SentinelSumPartialKernel = SentinelSumPartialKernel; @@ -724,18 +553,4 @@ mod tests { assert!(skipping.merge_from(including.as_mut()).is_err()); Ok(()) } - - #[test] - fn merge_from_combines_child_accumulators() -> VortexResult<()> { - let mut ctx = fresh_session().create_execution_ctx(); - let mut global: AccumulatorRef = Box::new(mean_f64_accumulator()?); - let mut local: AccumulatorRef = Box::new(mean_f64_accumulator()?); - - global.accumulate(&buffer![1.0f64, 2.0].into_array(), &mut ctx)?; - local.accumulate(&buffer![6.0f64].into_array(), &mut ctx)?; - global.merge_from(local.as_mut())?; - - assert_eq!(global.finish()?.as_primitive().as_::(), Some(3.0)); - Ok(()) - } } diff --git a/vortex-array/src/aggregate_fn/accumulator_grouped.rs b/vortex-array/src/aggregate_fn/accumulator_grouped.rs index c31c3bc454c..1b22b98f3da 100644 --- a/vortex-array/src/aggregate_fn/accumulator_grouped.rs +++ b/vortex-array/src/aggregate_fn/accumulator_grouped.rs @@ -444,10 +444,6 @@ mod tests { use crate::aggregate_fn::DynGroupedAccumulator; use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::combined::PairOptions; - use crate::aggregate_fn::fns::count::Count; - use crate::aggregate_fn::fns::mean::Mean; use crate::aggregate_fn::fns::null_count::NullCount; use crate::arrays::Chunked; use crate::arrays::ListViewArray; @@ -461,10 +457,10 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - fn accumulator() -> VortexResult> { + fn accumulator() -> VortexResult> { GroupedAccumulator::try_new( - Count, - NumericalAggregateOpts::default(), + NullCount, + EmptyOptions, DType::Primitive(PType::I32, NonNullable), ) } @@ -515,58 +511,4 @@ mod tests { assert_eq!(flushed.dtype(), &DType::Primitive(PType::U64, NonNullable)); Ok(()) } - - #[test] - fn test_accumulate_list_with_null_group_non_nullable_partials() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - // Groups: [[1.0, null, 3.0], null, [4.0]] - let elements = PrimitiveArray::from_option_iter([Some(1.0f64), None, Some(3.0), Some(4.0)]) - .into_array(); - let groups = ListViewArray::try_new( - elements, - buffer![0u32, 3, 3].into_array(), - buffer![3u32, 0, 1].into_array(), - Validity::from_iter([true, false, true]), - &mut ctx, - )? - .into_array(); - let elem_dtype = DType::Primitive(PType::F64, Nullable); - - let mut count_acc = GroupedAccumulator::try_new( - Count, - NumericalAggregateOpts::default(), - elem_dtype.clone(), - )?; - count_acc.accumulate_list(&groups, &mut ctx)?; - assert_arrays_eq!( - count_acc.finish()?, - PrimitiveArray::new(buffer![2u64, 0, 1], Validity::NonNullable), - &mut ctx - ); - - let mut null_count_acc = - GroupedAccumulator::try_new(NullCount, EmptyOptions, elem_dtype.clone())?; - null_count_acc.accumulate_list(&groups, &mut ctx)?; - assert_arrays_eq!( - null_count_acc.finish()?, - PrimitiveArray::new(buffer![1u64, 0, 0], Validity::NonNullable), - &mut ctx - ); - - let mut mean_acc = GroupedAccumulator::try_new( - Mean::combined(), - PairOptions( - NumericalAggregateOpts::default(), - NumericalAggregateOpts::default(), - ), - elem_dtype, - )?; - mean_acc.accumulate_list(&groups, &mut ctx)?; - assert_arrays_eq!( - mean_acc.finish()?, - PrimitiveArray::from_option_iter([Some(2.0f64), None, Some(4.0)]), - &mut ctx - ); - Ok(()) - } } diff --git a/vortex-array/src/aggregate_fn/fns/max/mod.rs b/vortex-array/src/aggregate_fn/fns/max/mod.rs index 3072c72addc..43f50d7f2b1 100644 --- a/vortex-array/src/aggregate_fn/fns/max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/max/mod.rs @@ -15,7 +15,6 @@ use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::AggregateFnSatisfaction; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::bounded_max::BoundedMax; use crate::aggregate_fn::fns::min_max::MinMax; use crate::aggregate_fn::fns::min_max::columnar_min_max; use crate::aggregate_fn::fns::min_max::min_max; @@ -116,7 +115,7 @@ impl AggregateFnVTable for Max { .is_some_and(|other| other == options) { AggregateFnSatisfaction::Exact - } else if requested.is::() && options.skip_nans { + } else if requested.id().as_str() == "vortex.bounded_max" && options.skip_nans { // A NaN-including maximum may be NaN, which is not a usable upper bound. AggregateFnSatisfaction::Approximate } else { diff --git a/vortex-array/src/aggregate_fn/fns/min/mod.rs b/vortex-array/src/aggregate_fn/fns/min/mod.rs index d1ecddc3875..af06518aaf4 100644 --- a/vortex-array/src/aggregate_fn/fns/min/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min/mod.rs @@ -15,7 +15,6 @@ use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::AggregateFnSatisfaction; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::bounded_min::BoundedMin; use crate::aggregate_fn::fns::min_max::MinMax; use crate::aggregate_fn::fns::min_max::columnar_min_max; use crate::aggregate_fn::fns::min_max::min_max; @@ -116,7 +115,7 @@ impl AggregateFnVTable for Min { .is_some_and(|other| other == options) { AggregateFnSatisfaction::Exact - } else if requested.is::() && options.skip_nans { + } else if requested.id().as_str() == "vortex.bounded_min" && options.skip_nans { // A NaN-including minimum may be NaN, which is not a usable lower bound. AggregateFnSatisfaction::Approximate } else { 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 1d81d714a90..5e3f38dfa61 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min_max/mod.rs @@ -141,7 +141,7 @@ pub fn min_max( /// Aggregates that delegate to [`MinMax`] use this on the columnar form of their input, so that /// results are only ever cached on the array the aggregate was requested for, never on a /// temporary canonical array. -pub(crate) fn columnar_min_max( +pub fn columnar_min_max( batch: &Columnar, options: NumericalAggregateOpts, ctx: &mut ExecutionCtx, diff --git a/vortex-array/src/aggregate_fn/fns/mod.rs b/vortex-array/src/aggregate_fn/fns/mod.rs index 2a0119820b1..7d5684d5a3d 100644 --- a/vortex-array/src/aggregate_fn/fns/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/mod.rs @@ -6,16 +6,10 @@ pub mod all_non_distinct; pub mod all_non_nan; pub mod all_non_null; pub mod all_null; -pub mod bounded_max; -pub mod bounded_min; -pub mod count; -pub mod first; mod fixed_size_bytes; pub mod is_constant; pub mod is_sorted; -pub mod last; pub mod max; -pub mod mean; pub mod min; pub mod min_max; pub mod nan_count; diff --git a/vortex-array/src/aggregate_fn/fns/sum/mod.rs b/vortex-array/src/aggregate_fn/fns/sum/mod.rs index 21e6c9287f9..b81bb1c26a5 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/mod.rs @@ -78,7 +78,8 @@ pub struct Sum; // Both Spark and DataFusion use this heuristic. // - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 // - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 -pub(crate) fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { +/// Returns the decimal dtype a sum over `input` widens to. +pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { DecimalDType::new( u8::min(MAX_PRECISION, input.precision() + 10), input.scale(), diff --git a/vortex-array/src/aggregate_fn/mod.rs b/vortex-array/src/aggregate_fn/mod.rs index a6610b010da..0d99dd36e22 100644 --- a/vortex-array/src/aggregate_fn/mod.rs +++ b/vortex-array/src/aggregate_fn/mod.rs @@ -38,7 +38,6 @@ pub use storage_pushdown::*; mod options; pub use options::*; -pub mod combined; pub mod fns; pub mod kernels; pub mod proto; diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 98bb8855e2e..03a9526ee4a 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -19,14 +19,8 @@ use crate::aggregate_fn::fns::all_non_distinct::AllNonDistinct; use crate::aggregate_fn::fns::all_non_nan::AllNonNan; use crate::aggregate_fn::fns::all_non_null::AllNonNull; use crate::aggregate_fn::fns::all_null::AllNull; -use crate::aggregate_fn::fns::bounded_max::BoundedMax; -use crate::aggregate_fn::fns::bounded_min::BoundedMin; -use crate::aggregate_fn::fns::count::Count; -use crate::aggregate_fn::fns::count::CountGroupedKernel; -use crate::aggregate_fn::fns::first::First; use crate::aggregate_fn::fns::is_constant::IsConstant; use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::last::Last; use crate::aggregate_fn::fns::max::Max; use crate::aggregate_fn::fns::mean::Mean; use crate::aggregate_fn::fns::min::Min; @@ -116,15 +110,9 @@ impl Default for AggregateFnSession { this.register(AllNonNull); this.register(AllNan); this.register(AllNull); - this.register(BoundedMax); - this.register(BoundedMin); - this.register(Count); - this.register(First); this.register(IsConstant); this.register(IsSorted); - this.register(Last); this.register(Max); - this.register(Mean::combined()); this.register(Min); this.register(MinMax); this.register(NanCount); @@ -158,7 +146,6 @@ impl Default for AggregateFnSession { this.register_aggregate_kernel(Widen.id(), Some(Sum.id()), &WidenArrayAggregate); // Register the built-in grouped aggregate kernels. - this.register_grouped_kernel(Count.id(), &CountGroupedKernel); this.register_grouped_encoding_kernel( Primitive.id(), Sum.id(), diff --git a/vortex-array/src/lib.rs b/vortex-array/src/lib.rs index 0152a3d643b..93d7d9c3ceb 100644 --- a/vortex-array/src/lib.rs +++ b/vortex-array/src/lib.rs @@ -128,7 +128,8 @@ pub mod memory; mod metadata; pub mod normalize; pub mod optimizer; -mod partial_ord; +#[doc(hidden)] +pub mod partial_ord; pub mod patches; pub mod proto; pub mod scalar; diff --git a/vortex-array/src/scalar/typed_view/decimal/dvalue.rs b/vortex-array/src/scalar/typed_view/decimal/dvalue.rs index 7525bd4aaad..9bfa87732f1 100644 --- a/vortex-array/src/scalar/typed_view/decimal/dvalue.rs +++ b/vortex-array/src/scalar/typed_view/decimal/dvalue.rs @@ -123,7 +123,7 @@ impl DecimalValue { /// /// This preserves the represented numeric value exactly. Reducing scale fails if doing so /// would discard non-zero fractional digits. - pub(crate) fn rescale_i256(value: i256, from_scale: i8, to_scale: i8) -> VortexResult { + pub fn rescale_i256(value: i256, from_scale: i8, to_scale: i8) -> VortexResult { if from_scale == to_scale || value == i256::ZERO { return Ok(value); } @@ -170,7 +170,7 @@ impl DecimalValue { /// Converts an untyped stored decimal integer into the physical value type selected by /// `decimal_dtype`, after enforcing the dtype precision. - pub(crate) fn try_from_i256(value: i256, decimal_dtype: DecimalDType) -> VortexResult { + pub fn try_from_i256(value: i256, decimal_dtype: DecimalDType) -> VortexResult { let decimal_value = Self::I256(value); decimal_value.normalize(decimal_dtype).ok_or_else(|| { vortex_err!( diff --git a/vortex-duckdb/src/convert/expr.rs b/vortex-duckdb/src/convert/expr.rs index c608d5429ed..d3279eae930 100644 --- a/vortex-duckdb/src/convert/expr.rs +++ b/vortex-duckdb/src/convert/expr.rs @@ -11,13 +11,13 @@ use vortex::aggregate_fn::Accumulator; use vortex::aggregate_fn::DynAccumulator; use vortex::aggregate_fn::EmptyOptions as AggregateEmptyOptions; use vortex::aggregate_fn::NumericalAggregateOpts; -use vortex::aggregate_fn::combined::PairOptions; -use vortex::aggregate_fn::fns::count::Count; -use vortex::aggregate_fn::fns::first::First; use vortex::aggregate_fn::fns::max::Max; -use vortex::aggregate_fn::fns::mean::Mean; use vortex::aggregate_fn::fns::min::Min; use vortex::aggregate_fn::fns::sum_v2::SumV2; +use vortex::aggregates::combined::PairOptions; +use vortex::aggregates::count::Count; +use vortex::aggregates::first::First; +use vortex::aggregates::mean::Mean; use vortex::dtype::DType; use vortex::dtype::Nullability; use vortex::dtype::PType; diff --git a/vortex-file/Cargo.toml b/vortex-file/Cargo.toml index e7b2e7aa70a..0e13790fb20 100644 --- a/vortex-file/Cargo.toml +++ b/vortex-file/Cargo.toml @@ -31,6 +31,7 @@ prost = { workspace = true } tokio = { workspace = true, features = ["rt"], optional = true } tracing = { workspace = true } url = { workspace = true } +vortex-aggregates = { workspace = true } vortex-alp = { workspace = true } vortex-array = { workspace = true } vortex-arrow = { workspace = true } diff --git a/vortex-file/src/lib.rs b/vortex-file/src/lib.rs index 6bf6a35bc5d..e30037f1150 100644 --- a/vortex-file/src/lib.rs +++ b/vortex-file/src/lib.rs @@ -187,6 +187,7 @@ mod forever_constant { /// Registration covers reading: a session can decode every encoding registered here. The /// writer is gated separately by the editions enabled on its session. pub fn register_default_encodings(session: &VortexSession) { + vortex_aggregates::initialize(session); vortex_bytebool::initialize(session); vortex_fsst::initialize(session); vortex_onpair::initialize(session); diff --git a/vortex-layout/Cargo.toml b/vortex-layout/Cargo.toml index 56e67ec215d..d3e04dfd3e9 100644 --- a/vortex-layout/Cargo.toml +++ b/vortex-layout/Cargo.toml @@ -41,6 +41,7 @@ termtree = { workspace = true } tokio = { workspace = true, features = ["rt"], optional = true } tracing = { workspace = true } twox-hash = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-arrow = { workspace = true } vortex-btrblocks = { workspace = true } diff --git a/vortex-layout/src/layouts/zoned/mod.rs b/vortex-layout/src/layouts/zoned/mod.rs index a895001cd04..122bacd72c2 100644 --- a/vortex-layout/src/layouts/zoned/mod.rs +++ b/vortex-layout/src/layouts/zoned/mod.rs @@ -604,11 +604,11 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::bounded_max::BoundedMax; + use vortex_aggregates::bounded_max::BoundedMaxOptions; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::aggregate_fn::fns::sum::Sum; @@ -673,6 +673,7 @@ mod tests { let deserialized = ZonedMetadata::deserialize(&metadata.serialize())?; let session = VortexSession::empty().with::(); + vortex_aggregates::initialize(&session); let aggregate_fns = try_aggregate_fns_from_specs(&deserialized.aggregate_specs, &session)? .expect("known aggregates resolve"); diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index af716b42123..1b55ae4cb73 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -9,16 +9,16 @@ use std::sync::Arc; use async_trait::async_trait; use futures::StreamExt as _; use parking_lot::Mutex; +use vortex_aggregates::bounded_max::BoundedMax; +use vortex_aggregates::bounded_max::BoundedMaxOptions; +use vortex_aggregates::bounded_min::BoundedMin; +use vortex_aggregates::bounded_min::BoundedMinOptions; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMinOptions; use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::aggregate_fn::fns::nan_count::NanCount; @@ -410,11 +410,11 @@ fn default_zoned_aggregate_fns(dtype: &DType) -> Arc<[AggregateFnRef]> { mod tests { use futures::stream; use rstest::rstest; + use vortex_aggregates::bounded_max::BoundedMax; + use vortex_aggregates::bounded_min::BoundedMin; use vortex_array::ArrayContext; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnVTable; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; - use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::aggregate_fn::fns::sum::Sum; diff --git a/vortex-layout/src/layouts/zoned/zone_map.rs b/vortex-layout/src/layouts/zoned/zone_map.rs index 4b4c0b9c8d3..e05302e3ed6 100644 --- a/vortex-layout/src/layouts/zoned/zone_map.rs +++ b/vortex-layout/src/layouts/zoned/zone_map.rs @@ -5,6 +5,8 @@ use std::sync::Arc; +use vortex_aggregates::bounded_max::BOUNDED_MAX_BOUND; +use vortex_aggregates::bounded_max::BoundedMax; use vortex_array::ArrayRef; use vortex_array::Columnar; use vortex_array::ExecutionCtx; @@ -16,8 +18,6 @@ use vortex_array::aggregate_fn::fns::all_nan::AllNan; use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/vortex/Cargo.toml b/vortex/Cargo.toml index 9e4eaec0781..168e43d42c0 100644 --- a/vortex/Cargo.toml +++ b/vortex/Cargo.toml @@ -19,6 +19,7 @@ all-features = true workspace = true [dependencies] +vortex-aggregates = { workspace = true } vortex-alp = { workspace = true } vortex-array = { workspace = true } vortex-arrow = { workspace = true } diff --git a/vortex/src/lib.rs b/vortex/src/lib.rs index 9635b361f9d..6b36f235656 100644 --- a/vortex/src/lib.rs +++ b/vortex/src/lib.rs @@ -101,6 +101,7 @@ //! ``` // vortex::compute is deprecated and will be ported over to expressions. +pub use vortex_aggregates as aggregates; pub use vortex_array::aggregate_fn; use vortex_array::aggregate_fn::session::AggregateFnSession; pub use vortex_array::compute; @@ -415,6 +416,7 @@ impl VortexSessionDefault for VortexSession { .with::() .with::(); vortex_expr::initialize(&session); + vortex_aggregates::initialize(&session); vortex_functions::initialize(&session); #[cfg(feature = "parquet-variant")] vortex_parquet_variant::initialize(&session); From c38a622f2561843a5c585a86f6a0dbe0738b912c Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Sat, 24 Oct 2026 13:39:56 +0000 Subject: [PATCH 02/27] Validate offsets and narrow integers through statistics with a scan fallback Offset validation (List, ListView, VarBin), `PrimitiveArray::narrow`, the same-width integer cast range check, ListView's referenced element bounds, and the debug sortedness checks in `Patches` called the `min_max` and `is_sorted` aggregates directly, often through `legacy_session()`. That ties core array construction to aggregates being available in core, so they could not be resolved by session. They now go through `arrays::primitive::{integer_bounds, integer_is_sorted, integer_is_strict_sorted}`, which read the `Min`, `Max`, `IsSorted` and `IsStrictSorted` statistics: cached when present, otherwise computed by the session's aggregates and any kernel the encoding provides. Only when a statistic has no answer, because the session registers no aggregate for it, is the array executed to a `PrimitiveArray` and scanned once, caching `Min`, `Max` and `NullCount`. Validation therefore works in every session, and still benefits from statistics where they exist. Valid counts come from the validity bitmap and ListView sizes are summed directly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- vortex-array/src/aggregate_fn/session.rs | 1 - vortex-array/src/array/erased.rs | 12 +- vortex-array/src/arrays/listview/array.rs | 51 ++-- .../src/arrays/primitive/array/mod.rs | 17 +- .../src/arrays/primitive/integer_bounds.rs | 277 ++++++++++++++++++ vortex-array/src/arrays/primitive/mod.rs | 5 + vortex-array/src/arrays/varbin/builder.rs | 1 + vortex-array/src/patches.rs | 5 +- 8 files changed, 322 insertions(+), 47 deletions(-) create mode 100644 vortex-array/src/arrays/primitive/integer_bounds.rs diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 03a9526ee4a..20a3c8087e0 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -22,7 +22,6 @@ use crate::aggregate_fn::fns::all_null::AllNull; use crate::aggregate_fn::fns::is_constant::IsConstant; use crate::aggregate_fn::fns::is_sorted::IsSorted; use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::mean::Mean; use crate::aggregate_fn::fns::min::Min; use crate::aggregate_fn::fns::min_max::MinMax; use crate::aggregate_fn::fns::nan_count::NanCount; diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index 35033939a3d..8a317d1ffb4 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -15,7 +15,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_error::vortex_ensure_eq; -use vortex_error::vortex_err; use vortex_error::vortex_panic; use vortex_mask::Mask; @@ -30,7 +29,6 @@ use crate::ExecutionResult; use crate::ExecutionStep; use crate::IntoArray; use crate::VTable; -use crate::aggregate_fn::fns::sum::sum; use crate::array::ArrayData; use crate::array::ArrayDataRef; use crate::array::ArrayId; @@ -39,12 +37,14 @@ use crate::array::ArraySlots; use crate::array::DynArrayData; use crate::array::probe::ArrayProbe; use crate::array::probe::RepeatedArrayProbe; +use crate::arrays::BoolArray; use crate::arrays::Constant; use crate::arrays::DictArray; use crate::arrays::FilterArray; use crate::arrays::SliceArray; use crate::block::BlockOp; use crate::block::BlockSource; +use crate::arrays::bool::BoolArrayExt; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; @@ -383,13 +383,7 @@ impl ArrayRef { let count = match self.validity()? { Validity::NonNullable | Validity::AllValid => len, Validity::AllInvalid => 0, - Validity::Array(a) => { - let array_sum = sum(&a, ctx)?; - array_sum - .as_primitive() - .as_::() - .ok_or_else(|| vortex_err!("sum of validity array is null"))? - } + Validity::Array(a) => a.execute::(ctx)?.to_bit_buffer().true_count(), }; vortex_ensure!(count <= len, "Valid count exceeds array length"); diff --git a/vortex-array/src/arrays/listview/array.rs b/vortex-array/src/arrays/listview/array.rs index b738eb394c3..62e1f85ac75 100644 --- a/vortex-array/src/arrays/listview/array.rs +++ b/vortex-array/src/arrays/listview/array.rs @@ -6,6 +6,7 @@ use std::fmt::Formatter; use std::sync::Arc; use num_traits::AsPrimitive; +use num_traits::ToPrimitive; use vortex_buffer::BitBufferMut; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -17,8 +18,6 @@ use vortex_mask::Mask; use crate::ArrayRef; use crate::ArraySlots; use crate::ExecutionCtx; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::min_max; use crate::array::Array; use crate::array::ArrayParts; use crate::array::TypedArrayRef; @@ -30,6 +29,7 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::bool; use crate::arrays::primitive::PrimitiveArrayExt; +use crate::arrays::primitive::integer_bounds; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; @@ -487,14 +487,24 @@ pub trait ListViewArrayExt: TypedArrayRef { return Ok(0.0); } - // compute_stat short-circuits on a cached exact Sum and otherwise computes - let sizes_sum = sizes + let sizes_sum = match sizes .statistics() .compute_stat(Stat::Sum, ctx)? - .vortex_expect("sizes array has integer ptype elements") - .as_primitive() - .as_::() - .vortex_expect("integer ptypes can be upcast to u64"); + .and_then(|sum| sum.as_primitive().as_::()) + { + Some(sum) => sum, + // The session registers no `Sum` aggregate, so sum the sizes directly. + None => { + let sizes = sizes.clone().execute::(ctx)?; + match_each_integer_ptype!(sizes.ptype(), |P| { + sizes + .as_slice::

() + .iter() + .map(|size| size.to_u64().vortex_expect("sizes are non-negative")) + .sum::() + }) + } + }; // if the same elements are referenced more than once the estimate may be // greater than 1.0, so clamp @@ -530,11 +540,12 @@ pub trait ListViewArrayExt: TypedArrayRef { return Ok((start, end)); } - let start = self - .offsets() - .statistics() - .compute_min::(ctx) - .vortex_expect("offsets must report a usize min statistic"); + let start = usize::try_from( + integer_bounds(self.offsets(), ctx)? + .vortex_expect("non-empty offsets have a minimum") + .min, + ) + .vortex_expect("offsets are non-negative"); // Cast offsets and sizes to the widest integer type so that `offset + size` cannot overflow // the narrower input width. @@ -545,15 +556,11 @@ pub trait ListViewArrayExt: TypedArrayRef { }); let offsets = self.offsets().cast(wide_dtype.clone())?; let sizes = self.sizes().cast(wide_dtype)?; - let end = min_max( - &offsets.numeric(sizes, NumericOperator::Add)?, - ctx, - NumericalAggregateOpts::default(), - )? - .vortex_expect("non-empty array must report a min/max") - .max - .as_primitive() - .as_::() + let end = usize::try_from( + integer_bounds(&offsets.numeric(sizes, NumericOperator::Add)?, ctx)? + .vortex_expect("non-empty array has a maximum") + .max, + ) .vortex_expect("max `offset + size` must fit in a usize"); Ok((start, end)) diff --git a/vortex-array/src/arrays/primitive/array/mod.rs b/vortex-array/src/arrays/primitive/array/mod.rs index 9d937c65435..b10ee906ece 100644 --- a/vortex-array/src/arrays/primitive/array/mod.rs +++ b/vortex-array/src/arrays/primitive/array/mod.rs @@ -24,6 +24,7 @@ use crate::array::TypedArrayRef; use crate::arrays::BoolArray; use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; +use crate::arrays::primitive::integer_bounds; use crate::dtype::DType; use crate::dtype::NativePType; use crate::dtype::Nullability; @@ -40,8 +41,6 @@ pub use patch::chunk_range; pub use patch::patch_chunk; use crate::ArrayRef; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::min_max; use crate::array::child_to_validity; use crate::array::validity_to_child; use crate::array_slots; @@ -154,7 +153,7 @@ pub trait PrimitiveArrayExt: TypedArrayRef { return Ok(self.to_owned()); } - let Some(min_max) = min_max(self.as_ref(), ctx, NumericalAggregateOpts::default())? else { + let Some(bounds) = integer_bounds(self.as_ref(), ctx)? else { return Ok(PrimitiveArray::new( Buffer::::zeroed(self.len()), PrimitiveArrayExt::validity(self), @@ -163,18 +162,10 @@ pub trait PrimitiveArrayExt: TypedArrayRef { // If we can't cast to i64, then leave the array as its original type. // It's too big to downcast anyway. - let Ok(min) = min_max - .min - .cast(&PType::I64.into()) - .and_then(|s| i64::try_from(&s)) - else { + let Ok(min) = i64::try_from(bounds.min) else { return Ok(self.to_owned()); }; - let Ok(max) = min_max - .max - .cast(&PType::I64.into()) - .and_then(|s| i64::try_from(&s)) - else { + let Ok(max) = i64::try_from(bounds.max) else { return Ok(self.to_owned()); }; diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs new file mode 100644 index 00000000000..3478ed46647 --- /dev/null +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Integer bounds and sortedness for array validation and integer narrowing. +//! +//! These read the array's `Min`, `Max`, `IsSorted` and `IsStrictSorted` statistics, which are +//! cached and computed by the aggregate functions the session registers, using any kernel the +//! encoding provides. When a statistic has no answer, because the session registers no aggregate +//! for it, the array is executed to a [`PrimitiveArray`] and scanned once instead, and the scanned +//! `Min`, `Max` and `NullCount` are cached. Validation therefore works in every session. + +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_mask::Mask; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::arrays::PrimitiveArray; +use crate::arrays::primitive::PrimitiveArrayExt; +use crate::expr::stats::Precision; +use crate::expr::stats::Stat; +use crate::match_each_integer_ptype; +use crate::scalar::Scalar; + +/// The minimum and maximum of the valid values of an integer array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IntegerBounds { + /// The smallest valid value. + pub min: i128, + /// The largest valid value. + pub max: i128, +} + +/// Returns the [`IntegerBounds`] of the valid values of `array`, or `None` if it has no valid +/// values. +/// +/// # Errors +/// +/// Fails if `array` is not an integer array, or if computing its statistics or executing it to a +/// [`PrimitiveArray`] fails. +pub fn integer_bounds( + array: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + ensure_int(array)?; + let stats = array.statistics(); + if let Some(min) = stats + .compute_stat(Stat::Min, ctx)? + .and_then(|s| as_i128(array, &s)) + && let Some(max) = stats + .compute_stat(Stat::Max, ctx)? + .and_then(|s| as_i128(array, &s)) + { + return Ok(Some(IntegerBounds { min, max })); + } + Ok(scan_array(array, ctx)?.map(|scanned| IntegerBounds { + min: scanned.min, + max: scanned.max, + })) +} + +/// Returns whether the valid values of `array` are in non-decreasing order. +/// +/// # Errors +/// +/// Fails if `array` is not an integer array, or if computing its statistics or executing it to a +/// [`PrimitiveArray`] fails. +pub fn integer_is_sorted(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + sortedness(array, Stat::IsSorted, ctx) +} + +/// Returns whether the valid values of `array` are in strictly increasing order. +/// +/// # Errors +/// +/// Fails if `array` is not an integer array, or if computing its statistics or executing it to a +/// [`PrimitiveArray`] fails. +pub fn integer_is_strict_sorted(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + sortedness(array, Stat::IsStrictSorted, ctx) +} + +fn sortedness(array: &ArrayRef, stat: Stat, ctx: &mut ExecutionCtx) -> VortexResult { + ensure_int(array)?; + if let Some(sorted) = array + .statistics() + .compute_stat(stat, ctx)? + .and_then(|s| s.as_bool().value()) + { + return Ok(sorted); + } + // An array without valid values is trivially sorted. + Ok(scan_array(array, ctx)?.is_none_or(|scanned| match stat { + Stat::IsStrictSorted => scanned.is_strict_sorted, + _ => scanned.is_sorted, + })) +} + +fn ensure_int(array: &ArrayRef) -> VortexResult<()> { + vortex_ensure!( + array.dtype().is_int(), + "integer bounds require an integer array, got {}", + array.dtype() + ); + Ok(()) +} + +fn as_i128(array: &ArrayRef, scalar: &Scalar) -> Option { + match_each_integer_ptype!(array.dtype().as_ptype(), |P| { + scalar.as_primitive().as_::

().map(i128::from) + }) +} + +/// The bounds and sortedness of the valid values of an integer array, widened to `i128`. +struct ScannedBounds { + min: i128, + max: i128, + is_sorted: bool, + is_strict_sorted: bool, +} + +/// Executes `array` to a [`PrimitiveArray`] and scans its valid values once, caching `Min`, `Max` +/// and `NullCount`. Returns `None` if `array` has no valid values. +fn scan_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { + let primitive = array.clone().execute::(ctx)?; + let mask = PrimitiveArrayExt::validity(&primitive).execute_mask(primitive.len(), ctx)?; + + let stats = array.statistics(); + stats.set( + Stat::NullCount, + Precision::exact(primitive.len() - mask.true_count()), + ); + + match_each_integer_ptype!(array.dtype().as_ptype(), |P| { + let Some(scanned) = scan(primitive.as_slice::

(), &mask) else { + return Ok(None); + }; + stats.set(Stat::Min, Precision::exact(scanned.min)); + stats.set(Stat::Max, Precision::exact(scanned.max)); + Ok(Some(ScannedBounds { + min: i128::from(scanned.min), + max: i128::from(scanned.max), + is_sorted: scanned.is_sorted, + is_strict_sorted: scanned.is_strict_sorted, + })) + }) +} + +/// The bounds of the values selected by a mask, in the values' own type. +struct Scanned

{ + min: P, + max: P, + is_sorted: bool, + is_strict_sorted: bool, +} + +/// Returns the minimum, maximum and sortedness of the values selected by `mask`. +fn scan(values: &[P], mask: &Mask) -> Option> { + let mut valid = values + .iter() + .enumerate() + .filter(|(idx, _)| match mask { + Mask::AllTrue(_) => true, + Mask::AllFalse(_) => false, + Mask::Values(values) => values.value(*idx), + }) + .map(|(_, value)| *value); + + let first = valid.next()?; + let mut scanned = Scanned { + min: first, + max: first, + is_sorted: true, + is_strict_sorted: true, + }; + let mut prev = first; + for value in valid { + if value < scanned.min { + scanned.min = value; + } + if value > scanned.max { + scanned.max = value; + } + scanned.is_sorted &= prev <= value; + scanned.is_strict_sorted &= prev < value; + prev = value; + } + Some(scanned) +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use super::IntegerBounds; + use super::integer_bounds; + use super::integer_is_sorted; + use super::integer_is_strict_sorted; + use crate::IntoArray; + use crate::VortexSessionExecute; + use crate::arrays::PrimitiveArray; + use crate::expr::stats::Precision; + use crate::expr::stats::Stat; + use crate::expr::stats::StatsProviderExt; + + /// A session registering no aggregate functions, so statistics fall back to scanning. + static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + + #[test] + fn scans_sorted_values() -> VortexResult<()> { + let array = PrimitiveArray::from_iter([0u32, 2, 2, 7]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + integer_bounds(&array, &mut ctx)?, + Some(IntegerBounds { min: 0, max: 7 }) + ); + assert!(integer_is_sorted(&array, &mut ctx)?); + assert!(!integer_is_strict_sorted(&array, &mut ctx)?); + assert_eq!( + array.statistics().get_as::(Stat::Max), + Precision::exact(7u32) + ); + assert_eq!( + array.statistics().get_as::(Stat::IsSorted), + Precision::Absent + ); + Ok(()) + } + + #[test] + fn scan_skips_nulls() -> VortexResult<()> { + let array = + PrimitiveArray::from_option_iter([Some(5i64), None, Some(-3), None]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + integer_bounds(&array, &mut ctx)?, + Some(IntegerBounds { min: -3, max: 5 }) + ); + assert!(!integer_is_sorted(&array, &mut ctx)?); + assert_eq!( + array.statistics().get_as::(Stat::NullCount), + Precision::exact(2usize) + ); + Ok(()) + } + + #[test] + fn all_null_array_has_no_bounds_and_is_sorted() -> VortexResult<()> { + let array = PrimitiveArray::from_option_iter([None::, None]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!(integer_bounds(&array, &mut ctx)?, None); + assert!(integer_is_strict_sorted(&array, &mut ctx)?); + Ok(()) + } + + /// Exact statistics are read instead of scanning. They deliberately disagree with the values, + /// which a scan would report. + #[test] + fn reads_exact_statistics() -> VortexResult<()> { + let array = PrimitiveArray::from_iter([3i32, 1, 2]).into_array(); + let stats = array.statistics(); + stats.set(Stat::Min, Precision::exact(-10i32)); + stats.set(Stat::Max, Precision::exact(10i32)); + stats.set(Stat::IsSorted, Precision::exact(true)); + stats.set(Stat::IsStrictSorted, Precision::exact(true)); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + integer_bounds(&array, &mut ctx)?, + Some(IntegerBounds { min: -10, max: 10 }) + ); + assert!(integer_is_sorted(&array, &mut ctx)?); + assert!(integer_is_strict_sorted(&array, &mut ctx)?); + Ok(()) + } +} diff --git a/vortex-array/src/arrays/primitive/mod.rs b/vortex-array/src/arrays/primitive/mod.rs index 8eab0f756ef..59f36ec8495 100644 --- a/vortex-array/src/arrays/primitive/mod.rs +++ b/vortex-array/src/arrays/primitive/mod.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod array; +mod integer_bounds; pub use array::PrimitiveArrayExt; pub use array::PrimitiveArraySlotsExt; pub use array::PrimitiveData; @@ -9,6 +10,10 @@ pub use array::PrimitiveDataParts; pub use array::PrimitiveSlots; pub use array::chunk_range; pub use array::patch_chunk; +pub use integer_bounds::IntegerBounds; +pub use integer_bounds::integer_bounds; +pub use integer_bounds::integer_is_sorted; +pub use integer_bounds::integer_is_strict_sorted; pub use vtable::PrimitiveArray; pub(crate) mod compute; diff --git a/vortex-array/src/arrays/varbin/builder.rs b/vortex-array/src/arrays/varbin/builder.rs index 700a105378c..820f521ef42 100644 --- a/vortex-array/src/arrays/varbin/builder.rs +++ b/vortex-array/src/arrays/varbin/builder.rs @@ -29,6 +29,7 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::VarBinView; +#[cfg(debug_assertions)] use crate::arrays::varbin::VarBinArrayExt; use crate::arrays::varbin::VarBinArraySlotsExt; use crate::arrays::varbinview::VarBinViewArrayExt; diff --git a/vortex-array/src/patches.rs b/vortex-array/src/patches.rs index 81ab1e69b9e..3eb092e2fe1 100644 --- a/vortex-array/src/patches.rs +++ b/vortex-array/src/patches.rs @@ -42,6 +42,8 @@ use crate::arrays::piecewise_sequence::constant_unsigned_usize; use crate::arrays::piecewise_sequence::contiguous_runs; use crate::arrays::piecewise_sequence::maybe_contiguous_slices; use crate::arrays::primitive::PrimitiveArrayExt; +#[cfg(debug_assertions)] +use crate::arrays::primitive::integer_is_strict_sorted; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::IntegerPType; @@ -340,9 +342,8 @@ impl Patches { #[cfg(debug_assertions)] { - use crate::aggregate_fn::fns::is_sorted::is_strict_sorted; assert!( - is_strict_sorted(&indices, ctx).unwrap_or(false), + integer_is_strict_sorted(&indices, ctx).unwrap_or(false), "Patch indices must be strictly increasing" ); } From feeb1ef81d5f13a46edef09888ce65168f6a9ba2 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Sat, 24 Oct 2026 13:39:56 +0000 Subject: [PATCH 03/27] Compute array statistics through the aggregate function registry `StatsSetRef::compute_stat` called the `min_max`, `sum`, `is_sorted`, `is_constant`, `nan_count` and `uncompressed_size_in_bytes` functions directly. It now resolves the aggregate backing each statistic from `ctx.session()`'s `AggregateFnSession` and runs its accumulator, so the aggregate implementations can be registered from any crate. A session with no aggregate registered for a statistic cannot compute it. - New `aggregate_fn::stat_aggregates` holds the IDs of the aggregates backing statistics, the options types those statistics bind (`UncompressedSizeOpts`, `IsSortedOptions`), and the dtype rules (`sum_return_dtype`, `supports_uncompressed_size_in_bytes`) that both the aggregates and `Stat::dtype` use. The old paths re-export them. - `Stat` gains `aggregate_fn_id`, `aggregate_fn_options` and `resolve_aggregate_fn`. `Stat::from_aggregate_fn` matches by ID and serialized options instead of by vtable type, and `StatFn` compares IDs. - `IsSorted` and `IsConstant` are now serializable, so they can be resolved by ID. - The whole-array shortcuts of `is_sorted` and `is_constant` (cached statistics, validity-only answers, cached `min == max`) move into each aggregate's `try_accumulate`, so every caller of the aggregate gets them. - NaN-skipping `Min` and `Max` accumulate through `min_max`, which caches both extrema on the batch, as `compute_stat` did before. `compute_stat` caches sortedness and constancy, which have no stat slot of their own, the same way `is_sorted`/`is_constant` did. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- .../fastlanes/src/for_/compute/compare.rs | 1 + .../src/aggregate_fn/fns/all_nan/mod.rs | 5 +- .../src/aggregate_fn/fns/all_non_nan/mod.rs | 5 +- .../src/aggregate_fn/fns/all_non_null/mod.rs | 5 +- .../src/aggregate_fn/fns/all_null/mod.rs | 5 +- .../src/aggregate_fn/fns/is_constant/mod.rs | 113 ++++----- .../src/aggregate_fn/fns/is_sorted/mod.rs | 120 +++++----- vortex-array/src/aggregate_fn/fns/max/mod.rs | 5 +- vortex-array/src/aggregate_fn/fns/min/mod.rs | 5 +- .../src/aggregate_fn/fns/nan_count/mod.rs | 5 +- .../src/aggregate_fn/fns/null_count/mod.rs | 5 +- vortex-array/src/aggregate_fn/fns/sum/mod.rs | 43 +--- .../fns/uncompressed_size_in_bytes/mod.rs | 40 +--- vortex-array/src/aggregate_fn/mod.rs | 1 + .../src/aggregate_fn/stat_aggregates.rs | 215 ++++++++++++++++++ vortex-array/src/stats/array.rs | 86 +++---- vortex-array/src/stats/stat.rs | 111 ++++++--- vortex-expr/src/stats/stat_fn.rs | 13 +- 18 files changed, 484 insertions(+), 299 deletions(-) create mode 100644 vortex-array/src/aggregate_fn/stat_aggregates.rs diff --git a/encodings/fastlanes/src/for_/compute/compare.rs b/encodings/fastlanes/src/for_/compute/compare.rs index ba3032fbe4a..684d6d45267 100644 --- a/encodings/fastlanes/src/for_/compute/compare.rs +++ b/encodings/fastlanes/src/for_/compute/compare.rs @@ -211,6 +211,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); crate::initialize(&session); session }); diff --git a/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs b/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs index 884e161d23f..9b82e818e32 100644 --- a/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs @@ -3,7 +3,6 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -14,6 +13,7 @@ use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::fns::nan_count::columnar_nan_count; use crate::aggregate_fn::fns::nan_count::nan_count; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability; use crate::scalar::Scalar; @@ -36,8 +36,7 @@ impl AggregateFnVTable for AllNan { type Partial = bool; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.all_nan"); - *ID + *stat_aggregates::ALL_NAN_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs b/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs index 244dcd221ce..fe1e704b7a2 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs @@ -3,7 +3,6 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -14,6 +13,7 @@ use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::fns::nan_count::columnar_nan_count; use crate::aggregate_fn::fns::nan_count::nan_count; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability; use crate::scalar::Scalar; @@ -36,8 +36,7 @@ impl AggregateFnVTable for AllNonNan { type Partial = bool; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.all_non_nan"); - *ID + *stat_aggregates::ALL_NON_NAN_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs b/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs index 6f10f2ce442..044d9f42d79 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs @@ -3,7 +3,6 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -13,6 +12,7 @@ use crate::aggregate_fn::AggregateArgs; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability; use crate::scalar::Scalar; @@ -28,8 +28,7 @@ impl AggregateFnVTable for AllNonNull { type Partial = bool; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.all_non_null"); - *ID + *stat_aggregates::ALL_NON_NULL_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-array/src/aggregate_fn/fns/all_null/mod.rs b/vortex-array/src/aggregate_fn/fns/all_null/mod.rs index aae98e0f5bd..cba4b6c10e3 100644 --- a/vortex-array/src/aggregate_fn/fns/all_null/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/all_null/mod.rs @@ -3,7 +3,6 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -13,6 +12,7 @@ use crate::aggregate_fn::AggregateArgs; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability; use crate::scalar::Scalar; @@ -28,8 +28,7 @@ impl AggregateFnVTable for AllNull { type Partial = bool; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.all_null"); - *ID + *stat_aggregates::ALL_NULL_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { 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 b40e3efb2e0..9829ec3a362 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs @@ -11,6 +11,8 @@ pub mod primitive; mod struct_; mod varbin; +use std::mem; + use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -38,8 +40,8 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::stat_aggregates; use crate::arrays::Constant; -use crate::arrays::Null; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::FieldNames; @@ -103,63 +105,13 @@ pub fn is_constant(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult() || array.is::() { - array - .statistics() - .set(Stat::IsConstant, Precision::Exact(true.into())); - return Ok(true); - } - - let all_invalid = array.all_invalid(ctx)?; - if all_invalid { - array - .statistics() - .set(Stat::IsConstant, Precision::Exact(true.into())); - return Ok(true); - } - - let all_valid = array.all_valid(ctx)?; - - // If we have some nulls but not all nulls, array can't be constant. - if !all_valid && !all_invalid { - array - .statistics() - .set(Stat::IsConstant, Precision::Exact(false.into())); - return Ok(false); - } - - // We already know here that the array is all valid, so we check for min/max stats. - let min_stat = array.statistics().get(Stat::Min); - let max_stat = array.statistics().get(Stat::Max); - - if let Precision::Exact(min) = min_stat.as_ref() - && let Precision::Exact(max) = max_stat.as_ref() - && min == max - && (Stat::NaNCount.dtype(array.dtype()).is_none() - || array.statistics().get_as::(Stat::NaNCount) == Precision::exact(0u64)) - { - array - .statistics() - .set(Stat::IsConstant, Precision::Exact(true.into())); - return Ok(true); - } - - // Short-circuit for unsupported dtypes. + // The aggregate does not support null and variant dtypes. A null array is all null, so + // constant, as is a constant-encoded variant array. if IsConstant .return_dtype(&EmptyOptions, array.dtype()) .is_none() { - // Null dtype - vacuously false for empty - return Ok(false); + return Ok(matches!(array.dtype(), DType::Null) || array.is::()); } // Compute using Accumulator. @@ -177,6 +129,32 @@ pub fn is_constant(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult VortexResult> { + if let Precision::Exact(value) = batch.statistics().get_as::(Stat::IsConstant) { + return Ok(Some(value)); + } + if batch.len() == 1 || batch.all_invalid(ctx)? { + return Ok(Some(true)); + } + // Some values are null and some are not. + if !batch.all_valid(ctx)? { + return Ok(Some(false)); + } + + let stats = batch.statistics(); + if let Precision::Exact(min) = stats.get(Stat::Min) + && let Precision::Exact(max) = stats.get(Stat::Max) + && min == max + && (Stat::NaNCount.dtype(batch.dtype()).is_none() + || stats.get_as::(Stat::NaNCount) == Precision::exact(0u64)) + { + return Ok(Some(true)); + } + Ok(None) +} + /// Compute whether an array is constant. /// /// Returns a `Bool(NonNullable)` scalar. @@ -273,8 +251,7 @@ impl AggregateFnVTable for IsConstant { type Partial = IsConstantPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.is_constant"); - *ID + *stat_aggregates::IS_CONSTANT_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { @@ -378,6 +355,30 @@ impl AggregateFnVTable for IsConstant { !partial.is_constant } + fn try_accumulate( + &self, + args: AggregateArgs<'_, Self::Options>, + state: &mut Self::Partial, + batch: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !state.is_constant || batch.is_empty() { + return Ok(true); + } + + let Some(is_constant) = batch_is_constant(batch, ctx)? else { + return Ok(false); + }; + let partial = IsConstant::make_partial(batch, is_constant, ctx)?; + let partial = self.partial_from_scalar(args, &partial)?; + *state = self.merge_partials( + args, + mem::replace(state, IsConstantPartial::empty()), + partial, + )?; + Ok(true) + } + fn accumulate( &self, args: AggregateArgs<'_, Self::Options>, 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 e6c5976fcc6..def2e2fd092 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs @@ -7,14 +7,12 @@ mod fixed_size_list; mod primitive; mod varbin; -use std::fmt; -use std::fmt::Display; -use std::fmt::Formatter; +use std::mem; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use vortex_error::vortex_bail; use vortex_session::VortexSession; +use vortex_error::vortex_bail; use vortex_session::registry::CachedId; use self::bool::check_bool_sorted; @@ -33,8 +31,8 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::fns::fixed_size_bytes::is_fixed_size_bytes; -use crate::arrays::Constant; -use crate::arrays::Null; +use crate::aggregate_fn::stat_aggregates; +pub use crate::aggregate_fn::stat_aggregates::IsSortedOptions; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::FieldNames; @@ -45,19 +43,6 @@ 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)] -pub struct IsSortedOptions { - /// If true, check for strictly ascending order (no duplicates). - pub strict: bool, -} - -impl Display for IsSortedOptions { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "strict={}", self.strict) - } -} - /// Compute whether an array is sorted in non-decreasing order. /// /// Returns `true` for empty arrays and arrays of length 1. @@ -94,19 +79,7 @@ fn is_sorted_impl(array: &ArrayRef, strict: bool, ctx: &mut ExecutionCtx) -> Vor return Ok(value); } - // Constant and null arrays are always sorted, but not strict sorted. - if array.is::() || array.is::() { - let result = !strict; - cache_is_sorted(array, strict, result); - return Ok(result); - } - - // We don't support sorting struct arrays. - if array.dtype().is_struct() { - return Ok(false); - } - - // Short-circuit for unsupported dtypes. + // Unsupported dtypes, such as structs and lists, are reported as unsorted. if IsSorted .return_dtype(&IsSortedOptions { strict }, array.dtype()) .is_none() @@ -114,26 +87,6 @@ fn is_sorted_impl(array: &ArrayRef, strict: bool, ctx: &mut ExecutionCtx) -> Vor return Ok(false); } - // Enforce strictness before we even try to check if the array is sorted. - if strict { - let invalid_count = array.invalid_count(ctx)?; - match invalid_count { - // We can keep going - 0 => {} - // If we have a potential null value - it has to be the first one. - 1 => { - if !array.is_invalid(0, ctx)? { - cache_is_sorted(array, strict, false); - return Ok(false); - } - } - _ => { - cache_is_sorted(array, strict, false); - return Ok(false); - } - } - } - // Compute using Accumulator. let mut acc = Accumulator::try_new(IsSorted, IsSortedOptions { strict }, array.dtype().clone())?; @@ -148,6 +101,36 @@ fn is_sorted_impl(array: &ArrayRef, strict: bool, ctx: &mut ExecutionCtx) -> Vor Ok(result) } +/// Decides whether a non-empty `batch` is sorted from its statistics and validity alone, without +/// decoding its values. Returns `None` when the values must be inspected. +fn batch_is_sorted( + batch: &ArrayRef, + strict: bool, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + let stat = if strict { + Stat::IsStrictSorted + } else { + Stat::IsSorted + }; + if let Precision::Exact(value) = batch.statistics().get_as::(stat) { + return Ok(Some(value)); + } + + // Nulls sort first, and a strictly sorted array holds at most one of them, at its start. + if strict { + let unsorted = match batch.invalid_count(ctx)? { + 0 => false, + 1 => !batch.is_invalid(0, ctx)?, + _ => true, + }; + if unsorted { + return Ok(Some(false)); + } + } + Ok(None) +} + fn cache_is_sorted(array: &ArrayRef, strict: bool, result: bool) { let array_stats = array.statistics(); if strict { @@ -249,12 +232,11 @@ impl AggregateFnVTable for IsSorted { type Partial = IsSortedPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.is_sorted"); - *ID + *stat_aggregates::IS_SORTED_ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { - Ok(Some(vec![u8::from(options.strict)])) + Ok(Some(options.serialize())) } fn deserialize( @@ -262,11 +244,7 @@ impl AggregateFnVTable for IsSorted { metadata: &[u8], _session: &VortexSession, ) -> VortexResult { - match metadata { - [0] => Ok(IsSortedOptions { strict: false }), - [1] => Ok(IsSortedOptions { strict: true }), - _ => vortex_bail!("Invalid IsSorted options: expected a single boolean byte"), - } + IsSortedOptions::deserialize(metadata) } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { @@ -440,6 +418,28 @@ impl AggregateFnVTable for IsSorted { !partial.is_sorted } + fn try_accumulate( + &self, + args: AggregateArgs<'_, Self::Options>, + state: &mut Self::Partial, + batch: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + if !state.is_sorted || batch.is_empty() { + return Ok(true); + } + + let strict = args.options.strict; + let Some(is_sorted) = batch_is_sorted(batch, strict, ctx)? else { + return Ok(false); + }; + let partial = IsSorted::make_partial(batch, is_sorted, strict, ctx)?; + let partial = self.partial_from_scalar(args, &partial)?; + *state = + self.merge_partials(args, mem::replace(state, IsSortedPartial::empty()), partial)?; + Ok(true) + } + fn accumulate( &self, args: AggregateArgs<'_, Self::Options>, diff --git a/vortex-array/src/aggregate_fn/fns/max/mod.rs b/vortex-array/src/aggregate_fn/fns/max/mod.rs index 43f50d7f2b1..68bfbdce78e 100644 --- a/vortex-array/src/aggregate_fn/fns/max/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/max/mod.rs @@ -4,7 +4,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -20,6 +19,7 @@ use crate::aggregate_fn::fns::min_max::columnar_min_max; 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::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::partial_ord::partial_max; use crate::scalar::Scalar; @@ -83,8 +83,7 @@ impl AggregateFnVTable for Max { type Partial = MaxPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.max"); - *ID + *stat_aggregates::MAX_ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { diff --git a/vortex-array/src/aggregate_fn/fns/min/mod.rs b/vortex-array/src/aggregate_fn/fns/min/mod.rs index af06518aaf4..136d1e7c70b 100644 --- a/vortex-array/src/aggregate_fn/fns/min/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/min/mod.rs @@ -4,7 +4,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -20,6 +19,7 @@ use crate::aggregate_fn::fns::min_max::columnar_min_max; 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::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::partial_ord::partial_min; use crate::scalar::Scalar; @@ -83,8 +83,7 @@ impl AggregateFnVTable for Min { type Partial = MinPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.min"); - *ID + *stat_aggregates::MIN_ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { 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 21f77ac57da..78bd7b7c001 100644 --- a/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs @@ -7,7 +7,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use self::primitive::accumulate_primitive; use crate::ArrayRef; @@ -21,6 +20,7 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; use crate::dtype::PType; @@ -100,8 +100,7 @@ impl AggregateFnVTable for NanCount { type Partial = u64; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.nan_count"); - *ID + *stat_aggregates::NAN_COUNT_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { 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 2695bb134c7..4aa3416012d 100644 --- a/vortex-array/src/aggregate_fn/fns/null_count/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/null_count/mod.rs @@ -4,7 +4,6 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Columnar; @@ -16,6 +15,7 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::EmptyOptions; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; use crate::dtype::PType; @@ -54,8 +54,7 @@ impl AggregateFnVTable for NullCount { type Partial = u64; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.null_count"); - *ID + *stat_aggregates::NULL_COUNT_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-array/src/aggregate_fn/fns/sum/mod.rs b/vortex-array/src/aggregate_fn/fns/sum/mod.rs index b81bb1c26a5..c042ce34ac9 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/sum/mod.rs @@ -13,7 +13,6 @@ use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_panic; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; pub(crate) use self::bool::accumulate_bool; pub(crate) use self::constant::multiply_constant; @@ -32,9 +31,8 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::stat_aggregates; use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::MAX_PRECISION; use crate::dtype::Nullability; use crate::dtype::PType; use crate::scalar::DecimalValue; @@ -75,24 +73,14 @@ pub fn sum(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { #[derive(Clone, Debug)] pub struct Sum; -// Both Spark and DataFusion use this heuristic. -// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 -// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 -/// Returns the decimal dtype a sum over `input` widens to. -pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { - DecimalDType::new( - u8::min(MAX_PRECISION, input.precision() + 10), - input.scale(), - ) -} +pub use crate::aggregate_fn::stat_aggregates::sum_decimal_dtype; impl AggregateFnVTable for Sum { type Options = NumericalAggregateOpts; type Partial = SumPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.sum"); - *ID + *stat_aggregates::SUM_ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { @@ -108,30 +96,7 @@ impl AggregateFnVTable for Sum { } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - // When a sum overflows, we return a sum _value_ of null. Therefore, we all return dtypes - // are nullable. - use Nullability::Nullable; - - Some(match input_dtype { - DType::Bool(_) => DType::Primitive(PType::U64, Nullable), - DType::Primitive(ptype, _) => match ptype { - PType::U8 | PType::U16 | PType::U32 | PType::U64 => { - DType::Primitive(PType::U64, Nullable) - } - PType::I8 | PType::I16 | PType::I32 | PType::I64 => { - DType::Primitive(PType::I64, Nullable) - } - PType::F16 | PType::F32 | PType::F64 => { - // Float sums cannot overflow, but all null floats still end up as null - DType::Primitive(PType::F64, Nullable) - } - }, - DType::Decimal(decimal_dtype, _) => { - DType::Decimal(sum_decimal_dtype(decimal_dtype), Nullable) - } - // Unsupported types - _ => return None, - }) + stat_aggregates::sum_return_dtype(input_dtype) } fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { 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 2d26c28c553..d8cabcd1192 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 @@ -30,7 +30,6 @@ use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_mask::Mask; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::Canonical; @@ -42,6 +41,9 @@ use crate::aggregate_fn::AggregateArgs; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynAccumulator; +use crate::aggregate_fn::stat_aggregates; +pub use crate::aggregate_fn::stat_aggregates::UncompressedSizeOpts; +pub use crate::aggregate_fn::stat_aggregates::UncompressedSizePrecision; use crate::aggregate_fn::EmptyOptions; use crate::array::ArrayView; use crate::arrays::Constant; @@ -103,7 +105,7 @@ pub struct UncompressedSizeInBytes; impl UncompressedSizeInBytes { /// Whether arrays of `dtype` can be measured. Variant arrays cannot. pub fn supports_dtype(dtype: &DType) -> bool { - supports_uncompressed_size_in_bytes(dtype) + stat_aggregates::supports_uncompressed_size_in_bytes(dtype) } } @@ -112,8 +114,7 @@ impl AggregateFnVTable for UncompressedSizeInBytes { type Partial = u64; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.uncompressed_size_in_bytes"); - *ID + *stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { @@ -129,7 +130,7 @@ impl AggregateFnVTable for UncompressedSizeInBytes { } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - supports_uncompressed_size_in_bytes(input_dtype) + stat_aggregates::supports_uncompressed_size_in_bytes(input_dtype) .then_some(DType::Primitive(PType::U64, NonNullable)) } @@ -322,35 +323,6 @@ fn checked_len_mul(len: usize, width: usize, name: &str) -> VortexResult { .ok_or_else(|| vortex_err!("uncompressed size in bytes overflowed u64")) } -fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { - match dtype { - DType::FixedSizeBinary(..) => false, - DType::Null - | DType::Bool(_) - | DType::Primitive(..) - | DType::Decimal(..) - | DType::Utf8(_) - | DType::Binary(_) => true, - DType::List(element_dtype, _) | DType::FixedSizeList(element_dtype, ..) => { - supports_uncompressed_size_in_bytes(element_dtype) - } - DType::Map(map_dtype, _) => { - supports_uncompressed_size_in_bytes(&map_dtype.key_dtype()) - && supports_uncompressed_size_in_bytes(&map_dtype.value_dtype()) - } - DType::Struct(fields, _) => fields - .fields() - .all(|field| supports_uncompressed_size_in_bytes(&field)), - DType::Union(variants, _) => variants - .variants() - .all(|variant| supports_uncompressed_size_in_bytes(&variant)), - DType::Variant(_) => false, - DType::Extension(ext_dtype) => { - supports_uncompressed_size_in_bytes(ext_dtype.storage_dtype()) - } - } -} - pub(crate) fn validity_uncompressed_size_in_bytes(validity: Mask) -> VortexResult { match validity { Mask::AllTrue(_) => Ok(0), diff --git a/vortex-array/src/aggregate_fn/mod.rs b/vortex-array/src/aggregate_fn/mod.rs index 0d99dd36e22..781092d917f 100644 --- a/vortex-array/src/aggregate_fn/mod.rs +++ b/vortex-array/src/aggregate_fn/mod.rs @@ -42,6 +42,7 @@ pub mod fns; pub mod kernels; pub mod proto; pub mod session; +pub mod stat_aggregates; /// A unique identifier for an aggregate function. pub type AggregateFnId = Id; diff --git a/vortex-array/src/aggregate_fn/stat_aggregates.rs b/vortex-array/src/aggregate_fn/stat_aggregates.rs new file mode 100644 index 00000000000..1ac6fc8afd1 --- /dev/null +++ b/vortex-array/src/aggregate_fn/stat_aggregates.rs @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Identifiers and options of the aggregate functions that back array statistics. +//! +//! [`Stat`](crate::expr::stats::Stat) names each of these aggregates by ID and options, and +//! array statistics are computed by resolving them through the session's +//! [`AggregateFnSession`](crate::aggregate_fn::session::AggregateFnSession). The +//! implementations themselves can therefore be registered from any crate. + +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; + +use prost::Message; +use vortex_error::VortexResult; +use vortex_error::vortex_bail; +use vortex_session::registry::CachedId; + +use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::MAX_PRECISION; +use crate::dtype::Nullability; +use crate::dtype::PType; +use crate::proto::expr as pb; + +/// ID of the aggregate computing the minimum, the `Min` statistic. +pub static MIN_ID: CachedId = CachedId::new("vortex.min"); +/// ID of the aggregate computing the maximum, the `Max` statistic. +pub static MAX_ID: CachedId = CachedId::new("vortex.max"); +/// ID of the aggregate computing the sum, the `Sum` statistic. +pub static SUM_ID: CachedId = CachedId::new("vortex.sum"); +/// ID of the aggregate counting nulls, the `NullCount` statistic. +pub static NULL_COUNT_ID: CachedId = CachedId::new("vortex.null_count"); +/// ID of the aggregate counting NaN values, the `NaNCount` statistic. +pub static NAN_COUNT_ID: CachedId = CachedId::new("vortex.nan_count"); +/// ID of the aggregate measuring uncompressed size, the `UncompressedSizeInBytes` statistic. +pub static UNCOMPRESSED_SIZE_IN_BYTES_ID: CachedId = + CachedId::new("vortex.uncompressed_size_in_bytes"); +/// ID of the aggregate checking constancy, the `IsConstant` statistic. +pub static IS_CONSTANT_ID: CachedId = CachedId::new("vortex.is_constant"); +/// ID of the aggregate checking sortedness, the `IsSorted` and `IsStrictSorted` statistics. +pub static IS_SORTED_ID: CachedId = CachedId::new("vortex.is_sorted"); +/// ID of the aggregate checking that every value is null. +pub static ALL_NULL_ID: CachedId = CachedId::new("vortex.all_null"); +/// ID of the aggregate checking that no value is null. +pub static ALL_NON_NULL_ID: CachedId = CachedId::new("vortex.all_non_null"); +/// ID of the aggregate checking that every value is NaN. +pub static ALL_NAN_ID: CachedId = CachedId::new("vortex.all_nan"); +/// ID of the aggregate checking that no value is NaN. +pub static ALL_NON_NAN_ID: CachedId = CachedId::new("vortex.all_non_nan"); + +/// Whether the `vortex.uncompressed_size_in_bytes` aggregate approximates the bytes an array uses or counts them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum UncompressedSizePrecision { + /// An approximation: every byte of every buffer the canonical array holds, whether or not a + /// row uses it. Cheap, but a view array sharing or sliced from a larger buffer reports the + /// whole buffer. + #[default] + Inexact, + /// The actual number of bytes the array's rows use, which costs a pass over view and list + /// arrays. + Exact, +} + +/// Options for the `vortex.uncompressed_size_in_bytes` aggregate. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct UncompressedSizeOpts { + pub precision: UncompressedSizePrecision, +} + +impl UncompressedSizeOpts { + /// Approximate the bytes the array uses by the buffers it holds. This is the default. + pub const fn inexact() -> Self { + Self { + precision: UncompressedSizePrecision::Inexact, + } + } + + /// Count the actual bytes the array's rows use. + pub const fn exact() -> Self { + Self { + precision: UncompressedSizePrecision::Exact, + } + } + + pub const fn is_exact(&self) -> bool { + matches!(self.precision, UncompressedSizePrecision::Exact) + } + + /// Serialize these options to protobuf-encoded metadata bytes. + pub fn serialize(&self) -> Vec { + pb::UncompressedSizeInBytesOpts { + exact: self.is_exact(), + } + .encode_to_vec() + } + + /// Deserialize these options from protobuf-encoded metadata bytes. + pub fn deserialize(metadata: &[u8]) -> VortexResult { + let opts = pb::UncompressedSizeInBytesOpts::decode(metadata)?; + Ok(if opts.exact { + Self::exact() + } else { + Self::inexact() + }) + } +} + +impl Display for UncompressedSizeOpts { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + // Only the non-default configuration is displayed, so the default renders as + // `vortex.uncompressed_size_in_bytes()`. + if self.is_exact() { + write!(f, "precision=exact")?; + } + Ok(()) + } +} + +/// Options for the `is_sorted` aggregate function. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct IsSortedOptions { + /// If true, check for strictly ascending order (no duplicates). + pub strict: bool, +} + +impl IsSortedOptions { + /// Serialize these options to metadata bytes: one byte, `1` for strict and `0` otherwise. + pub fn serialize(&self) -> Vec { + vec![u8::from(self.strict)] + } + + /// Deserialize these options from metadata bytes written by [`IsSortedOptions::serialize`]. + pub fn deserialize(metadata: &[u8]) -> VortexResult { + match metadata { + [0] => Ok(Self { strict: false }), + [1] => Ok(Self { strict: true }), + _ => vortex_bail!("invalid is_sorted options metadata {metadata:?}"), + } + } +} + +impl Display for IsSortedOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "strict={}", self.strict) + } +} + +/// The return dtype of the `vortex.sum` aggregate over `input_dtype`, or `None` if summing that +/// dtype is unsupported. +/// +/// A sum that overflows is null, so every result dtype is nullable. +pub fn sum_return_dtype(input_dtype: &DType) -> Option { + use Nullability::Nullable; + + Some(match input_dtype { + DType::Bool(_) => DType::Primitive(PType::U64, Nullable), + DType::Primitive(ptype, _) => match ptype { + PType::U8 | PType::U16 | PType::U32 | PType::U64 => { + DType::Primitive(PType::U64, Nullable) + } + PType::I8 | PType::I16 | PType::I32 | PType::I64 => { + DType::Primitive(PType::I64, Nullable) + } + // Float sums cannot overflow, but all-null floats still sum to null. + PType::F16 | PType::F32 | PType::F64 => DType::Primitive(PType::F64, Nullable), + }, + DType::Decimal(decimal_dtype, _) => { + DType::Decimal(sum_decimal_dtype(decimal_dtype), Nullable) + } + _ => return None, + }) +} + +// Both Spark and DataFusion use this heuristic. +// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 +// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 +/// Returns the decimal dtype a sum over `input` widens to. +pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { + DecimalDType::new( + u8::min(MAX_PRECISION, input.precision() + 10), + input.scale(), + ) +} + +/// Whether the uncompressed size of an array of `dtype` can be measured. +pub fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { + match dtype { + DType::FixedSizeBinary(..) => false, + DType::Null + | DType::Bool(_) + | DType::Primitive(..) + | DType::Decimal(..) + | DType::Utf8(_) + | DType::Binary(_) => true, + DType::List(element_dtype, _) | DType::FixedSizeList(element_dtype, ..) => { + supports_uncompressed_size_in_bytes(element_dtype) + } + DType::Map(map_dtype, _) => { + supports_uncompressed_size_in_bytes(&map_dtype.key_dtype()) + && supports_uncompressed_size_in_bytes(&map_dtype.value_dtype()) + } + DType::Struct(fields, _) => fields + .fields() + .all(|field| supports_uncompressed_size_in_bytes(&field)), + DType::Union(variants, _) => variants + .variants() + .all(|variant| supports_uncompressed_size_in_bytes(&variant)), + DType::Variant(_) => false, + DType::Extension(ext_dtype) => { + supports_uncompressed_size_in_bytes(ext_dtype.storage_dtype()) + } + } +} diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 20909573968..3cf01ffa170 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -261,49 +261,53 @@ impl StatsSetRef<'_> { return Ok(None); } - Ok(match stat { - Stat::Min => min_max(self.dyn_array_ref, ctx, NumericalAggregateOpts::default())? - .map(|MinMaxResult { min, max: _ }| min), - Stat::Max => min_max(self.dyn_array_ref, ctx, NumericalAggregateOpts::default())? - .map(|MinMaxResult { min: _, max }| max), - Stat::Sum => { - Stat::Sum - .dtype(self.dyn_array_ref.dtype()) - .is_some() - .then(|| { - // Sum is supported for this dtype. - sum(self.dyn_array_ref, ctx) - }) - .transpose()? - } - Stat::NullCount => self.dyn_array_ref.invalid_count(ctx).ok().map(Into::into), - Stat::IsConstant => { - if self.dyn_array_ref.is_empty() { - None - } else { - Some(is_constant(self.dyn_array_ref, ctx)?.into()) + let array = self.dyn_array_ref; + match stat { + // Null counts come from validity, which every array exposes directly. + Stat::NullCount => return Ok(array.invalid_count(ctx).ok().map(Into::into)), + Stat::IsConstant if array.is_empty() => return Ok(None), + _ => {} + } + if stat.dtype(array.dtype()).is_none() { + return Ok(None); + } + + // Statistics are computed by the aggregate function registered for them in the session, + // so a session without one cannot compute the statistic. + let Some(aggregate_fn) = stat.resolve_aggregate_fn(ctx.session())? else { + return Ok(None); + }; + if aggregate_fn.return_dtype(array.dtype()).is_none() { + return Ok(None); + } + let mut accumulator = aggregate_fn.accumulator(array.dtype())?; + accumulator.accumulate(array, ctx)?; + let result = accumulator.finish()?; + if result.is_null() { + return Ok(None); + } + + // Aggregates with a stat slot cache their own result. Sortedness and constancy have + // none, so cache them here, along with what each implies about the other sortedness. + if let Some(value) = result.as_bool_opt().and_then(|b| b.value()) { + match (stat, value) { + (Stat::IsConstant, _) => self.set(stat, Precision::exact(value)), + (Stat::IsSorted, false) | (Stat::IsStrictSorted, false) => { + self.set(Stat::IsStrictSorted, Precision::exact(false)); + if stat == Stat::IsSorted { + self.set(Stat::IsSorted, Precision::exact(false)); + } } + (Stat::IsSorted, true) | (Stat::IsStrictSorted, true) => { + self.set(Stat::IsSorted, Precision::exact(true)); + if stat == Stat::IsStrictSorted { + self.set(Stat::IsStrictSorted, Precision::exact(true)); + } + } + _ => {} } - Stat::IsSorted => Some(is_sorted(self.dyn_array_ref, ctx)?.into()), - Stat::IsStrictSorted => Some(is_strict_sorted(self.dyn_array_ref, ctx)?.into()), - Stat::UncompressedSizeInBytes => Stat::UncompressedSizeInBytes - .dtype(self.dyn_array_ref.dtype()) - .is_some() - .then(|| uncompressed_size_in_bytes(self.dyn_array_ref, ctx)) - .transpose()? - .map(|s| s.into()), - Stat::NaNCount => { - Stat::NaNCount - .dtype(self.dyn_array_ref.dtype()) - .is_some() - .then(|| { - // NaNCount is supported for this dtype. - nan_count(self.dyn_array_ref, ctx) - }) - .transpose()? - .map(|s| s.into()) - } - }) + } + Ok(Some(result)) } pub fn compute_all(&self, stats: &[Stat], ctx: &mut ExecutionCtx) -> VortexResult { diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index a9beae852fc..fa4299d75aa 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -10,9 +10,12 @@ use enum_iterator::all; use num_enum::IntoPrimitive; use num_enum::TryFromPrimitive; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + use crate::aggregate_fn; +use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::AggregateFnVTableExt; use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::NumericalAggregateOpts; @@ -22,6 +25,11 @@ use crate::stats::LowerBound; use crate::stats::Precision; use crate::stats::StatType; use crate::stats::UpperBound; +use crate::aggregate_fn::session::AggregateFnSessionExt; +use crate::aggregate_fn::stat_aggregates; +use crate::aggregate_fn::stat_aggregates::IsSortedOptions; +use crate::aggregate_fn::stat_aggregates::UncompressedSizeOpts; +use crate::dtype::PType; #[derive( Debug, @@ -167,26 +175,61 @@ impl Stat { Self::Max => data_type.clone(), Self::Min if matches!(data_type, DType::Null) => return None, Self::Min => data_type.clone(), - Self::NullCount => { - return aggregate_fn::fns::null_count::NullCount - .return_dtype(&EmptyOptions, data_type); - } + Self::NullCount => DType::Primitive(PType::U64, NonNullable), Self::UncompressedSizeInBytes => { - return aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes - .return_dtype(&EmptyOptions, data_type); + return stat_aggregates::supports_uncompressed_size_in_bytes(data_type) + .then_some(DType::Primitive(PType::U64, NonNullable)); } Self::NaNCount => { - return aggregate_fn::fns::nan_count::NanCount - .return_dtype(&EmptyOptions, data_type); - } - Self::Sum => { - // Statistics follow NaN-skipping semantics; request it explicitly. - return aggregate_fn::fns::sum::Sum - .return_dtype(&NumericalAggregateOpts::skip_nans(), data_type); + return matches!(data_type, DType::Primitive(ptype, _) if ptype.is_float()) + .then_some(DType::Primitive(PType::U64, NonNullable)); } + Self::Sum => return stat_aggregates::sum_return_dtype(data_type), }) } + /// The ID of the aggregate function that computes this statistic. + pub fn aggregate_fn_id(&self) -> AggregateFnId { + **match self { + Self::IsConstant => &stat_aggregates::IS_CONSTANT_ID, + Self::IsSorted | Self::IsStrictSorted => &stat_aggregates::IS_SORTED_ID, + Self::Max => &stat_aggregates::MAX_ID, + Self::Min => &stat_aggregates::MIN_ID, + Self::NullCount => &stat_aggregates::NULL_COUNT_ID, + Self::UncompressedSizeInBytes => &stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID, + Self::Sum => &stat_aggregates::SUM_ID, + Self::NaNCount => &stat_aggregates::NAN_COUNT_ID, + } + } + + /// The serialized options the aggregate function computing this statistic is bound to. + /// + /// Min/max/sum statistics skip NaN values, and the uncompressed size statistic is exact. + pub fn aggregate_fn_options(&self) -> Vec { + match self { + Self::Max | Self::Min | Self::Sum => NumericalAggregateOpts::skip_nans().serialize(), + Self::UncompressedSizeInBytes => UncompressedSizeOpts::exact().serialize(), + Self::IsSorted => IsSortedOptions { strict: false }.serialize(), + Self::IsStrictSorted => IsSortedOptions { strict: true }.serialize(), + Self::IsConstant | Self::NullCount | Self::NaNCount => vec![], + } + } + + /// Resolve the aggregate function computing this statistic from the session's registry. + /// + /// Returns `None` if no aggregate function with this statistic's ID is registered. + pub fn resolve_aggregate_fn( + &self, + session: &VortexSession, + ) -> VortexResult> { + let Some(plugin) = session.aggregate_fns().find_plugin(&self.aggregate_fn_id()) else { + return Ok(None); + }; + plugin + .deserialize(&self.aggregate_fn_options(), session) + .map(Some) + } + /// Return the built-in aggregate function corresponding to this statistic, if one exists. pub fn aggregate_fn(&self) -> Option { // Statistics follow NaN-skipping semantics; request it explicitly rather than the default. @@ -206,30 +249,24 @@ impl Stat { /// Return the statistic represented by `aggregate_fn`, if it has a legacy stat slot. /// - /// Min/max/sum statistics skip NaN values, so NaN-including configurations of those - /// aggregates have no stat slot. + /// The aggregate must have this statistic's ID and options. Min/max/sum statistics skip NaN + /// values, so NaN-including configurations of those aggregates have no stat slot. The + /// uncompressed size statistic is exact, so the inexact configuration of that aggregate has + /// no stat slot either. Sortedness and constancy have no stat slot. pub fn from_aggregate_fn(aggregate_fn: &AggregateFnRef) -> Option { - if let Some(options) = aggregate_fn.as_opt::() { - return options.skip_nans.then_some(Self::Sum); - } - if aggregate_fn.is::() { - return Some(Self::NaNCount); - } - if aggregate_fn.is::() { - return Some(Self::NullCount); - } - if let Some(options) = aggregate_fn.as_opt::() { - return options.skip_nans.then_some(Self::Min); - } - if let Some(options) = aggregate_fn.as_opt::() { - return options.skip_nans.then_some(Self::Max); - } - if aggregate_fn - .is::() - { - return Some(Self::UncompressedSizeInBytes); - } - None + let id = aggregate_fn.id(); + let stat = [ + Self::Min, + Self::Max, + Self::Sum, + Self::NullCount, + Self::NaNCount, + Self::UncompressedSizeInBytes, + ] + .into_iter() + .find(|stat| stat.aggregate_fn_id() == id)?; + let options = aggregate_fn.options().serialize().ok()??; + (options == stat.aggregate_fn_options()).then_some(stat) } pub fn name(&self) -> &str { diff --git a/vortex-expr/src/stats/stat_fn.rs b/vortex-expr/src/stats/stat_fn.rs index ef4a3b1b532..add234a33f1 100644 --- a/vortex-expr/src/stats/stat_fn.rs +++ b/vortex-expr/src/stats/stat_fn.rs @@ -10,10 +10,7 @@ use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; +use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; use vortex_array::kernel::SupportsFn; @@ -153,7 +150,7 @@ fn stat_array( dtype: DType, len: usize, ) -> VortexResult { - let value = if aggregate_fn.is::() { + let value = if aggregate_fn.id() == *stat_aggregates::ALL_NULL_ID { let len = u64::try_from(len)?; match array.statistics().get_as::(Stat::NullCount) { Precision::Exact(count) => Some(count == len), @@ -161,14 +158,14 @@ fn stat_array( Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.is::() { + } else if aggregate_fn.id() == *stat_aggregates::ALL_NON_NULL_ID { match array.statistics().get_as::(Stat::NullCount) { Precision::Exact(count) => Some(count == 0), Precision::Inexact(0) => Some(true), Precision::Inexact(_) | Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.is::() { + } else if aggregate_fn.id() == *stat_aggregates::ALL_NAN_ID { let len = u64::try_from(len)?; match array.statistics().get_as::(Stat::NaNCount) { Precision::Exact(count) => Some(count == len), @@ -176,7 +173,7 @@ fn stat_array( Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.is::() { + } else if aggregate_fn.id() == *stat_aggregates::ALL_NON_NAN_ID { match array.statistics().get_as::(Stat::NaNCount) { Precision::Exact(count) => Some(count == 0), Precision::Inexact(0) => Some(true), From 2ed68bfb420113d4d87b61c3c54dcb507f6b2999 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Sat, 24 Oct 2026 13:39:56 +0000 Subject: [PATCH 04/27] Move the remaining aggregate functions into vortex-aggregates vortex-array now keeps only the aggregate function framework and `all_non_distinct`, which `assert_arrays_eq!` uses to compare arrays. The other concrete aggregates (min/max, sum, counts, sortedness, constancy, uncompressed size and the rest), their Dict kernels, the grouped encoding kernels and their benches move to vortex-aggregates, whose `initialize` registers them on a session. `Stat::aggregate_fn` is replaced by `vortex_aggregates::stat_aggregate_fn`. `ExtensionStoragePushdown` stays in vortex-array. Pushing `is_sorted` and `min_max` down into extension storage becomes `vortex_aggregates::register_storage_ordered`, which `initialize` calls for the temporal types and `vortex_uuid::initialize` calls for UUIDs. Validation and encoding paths that must work with any session no longer go through the registry: integer arrays use `integer_bounds` (which now also reports strict sortedness and caches Min, Max and NullCount), and boolean arrays use the new `bool_bounds`. This covers validity, RunEnd ends, bit-packing, FoR, datetime-parts comparison and the compressor's integer statistics. Tests of aggregate behaviour move alongside the aggregates. Core tests use a test-only row-count aggregate and run the aggregate consistency checks only when aggregates are registered. Test sessions that compute statistics register the aggregates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- Cargo.lock | 22 ++ benchmarks/string-bench/src/lib.rs | 2 +- encodings/alp/Cargo.toml | 1 + encodings/alp/src/alp/compute/nan_count.rs | 4 +- encodings/alp/src/lib.rs | 2 +- encodings/datetime-parts/Cargo.toml | 1 + encodings/datetime-parts/src/compress.rs | 4 +- .../datetime-parts/src/compute/compare.rs | 2 +- .../datetime-parts/src/compute/is_constant.rs | 4 +- encodings/datetime-parts/src/lib.rs | 2 +- encodings/decimal-byte-parts/Cargo.toml | 1 + .../decimal-byte-parts/benches/dbp_compute.rs | 4 +- .../compute/aggregate/mod.rs | 18 +- .../compute/aggregate/tests.rs | 14 +- .../decimal_byte_parts/compute/is_constant.rs | 4 +- encodings/decimal-byte-parts/src/lib.rs | 12 +- encodings/elias-fano/Cargo.toml | 1 + encodings/elias-fano/src/unary/compress.rs | 2 +- encodings/fastlanes/Cargo.toml | 1 + .../bitpacking/array/bitpack_compress/mod.rs | 15 +- .../src/bitpacking/compute/is_constant.rs | 10 +- .../src/delta/compute/is_constant.rs | 8 +- encodings/fastlanes/src/delta/tests.rs | 3 +- .../fastlanes/src/for_/array/for_compress.rs | 12 +- .../fastlanes/src/for_/compute/is_constant.rs | 4 +- .../fastlanes/src/for_/compute/is_sorted.rs | 8 +- encodings/fastlanes/src/for_/tests.rs | 4 +- encodings/fastlanes/src/lib.rs | 4 +- encodings/fastlanes/tests/widen.rs | 10 +- encodings/fsst/Cargo.toml | 1 + .../src/compute/uncompressed_size_in_bytes.rs | 8 +- encodings/fsst/src/lib.rs | 5 +- encodings/onpair/Cargo.toml | 1 + encodings/onpair/tests/big_data.rs | 2 +- encodings/sequence/Cargo.toml | 1 + encodings/sequence/src/compute/is_sorted.rs | 10 +- encodings/sequence/src/compute/min_max.rs | 8 +- encodings/sequence/src/lib.rs | 4 +- encodings/sequence/src/model_tests.rs | 4 +- encodings/sparse/Cargo.toml | 1 + encodings/sparse/benches/sparse_pushdown.rs | 8 +- encodings/sparse/src/compute/is_constant.rs | 6 +- encodings/sparse/src/compute/min_max.rs | 6 +- encodings/sparse/src/compute/nan_count.rs | 4 +- encodings/sparse/src/compute/null_count.rs | 6 +- encodings/sparse/src/compute/sum.rs | 10 +- encodings/sparse/src/lib.rs | 12 +- encodings/zstd/src/editions.rs | 4 +- fuzz/Cargo.toml | 1 + fuzz/array.rs | 6 +- fuzz/error.rs | 2 +- lang/java/vortex-jni-native/src/statistics.rs | 6 +- scripts/codspeed_bench_counts.json | 8 +- scripts/codspeed_bench_durations.json | 6 +- vortex-aggregates/Cargo.toml | 18 ++ .../benches/aggregate_definedness.rs | 10 +- .../benches/aggregate_grouped.rs | 4 +- .../benches/aggregate_max.rs | 8 +- .../benches/aggregate_sum.rs | 39 ++- .../src}/all_nan/mod.rs | 59 ++-- .../src}/all_non_nan/mod.rs | 59 ++-- .../src}/all_non_null/mod.rs | 54 ++-- .../src}/all_null/mod.rs | 54 ++-- vortex-aggregates/src/bounded_max/mod.rs | 35 +- vortex-aggregates/src/bounded_min/mod.rs | 31 +- vortex-aggregates/src/combined_tests.rs | 7 +- vortex-aggregates/src/count/grouped.rs | 6 +- vortex-aggregates/src/count/mod.rs | 3 +- .../src/dict}/is_constant.rs | 20 +- .../src/dict}/is_sorted.rs | 24 +- .../src/dict}/min_max.rs | 38 +-- vortex-aggregates/src/dict/mod.rs | 8 + vortex-aggregates/src/first/mod.rs | 7 +- .../src}/fixed_size_bytes.rs | 17 +- .../src/framework_tests/accumulator.rs | 183 +++++++++++ .../src/framework_tests/chunked_kernel.rs | 217 +++++++++++++ .../src/framework_tests/core_consistency.rs | 53 +++ .../framework_tests/extension_validation.rs | 157 +++++++++ .../framework_tests/listview_is_constant.rs | 150 +++++++++ vortex-aggregates/src/framework_tests/mod.rs | 15 + .../src/framework_tests/proto.rs | 301 ++++++++++++++++++ .../src/framework_tests/stats.rs | 93 ++++++ .../src/framework_tests/storage_pushdown.rs | 231 ++++++++++++++ .../src/framework_tests/struct_is_constant.rs | 29 ++ .../union_uncompressed_size.rs | 49 +++ .../src}/is_constant/bool.rs | 4 +- .../src}/is_constant/decimal.rs | 5 +- .../src}/is_constant/extension.rs | 6 +- .../src}/is_constant/fixed_size_list.rs | 12 +- .../src}/is_constant/list.rs | 12 +- .../src}/is_constant/map.rs | 8 +- .../src}/is_constant/mod.rs | 131 ++++---- .../src}/is_constant/primitive.rs | 7 +- .../src}/is_constant/struct_.rs | 6 +- .../src}/is_constant/varbin.rs | 5 +- .../src}/is_sorted/bool.rs | 6 +- .../src}/is_sorted/decimal.rs | 8 +- .../src}/is_sorted/fixed_size_list.rs | 6 +- .../src}/is_sorted/mod.rs | 122 +++---- .../src}/is_sorted/primitive.rs | 10 +- .../src}/is_sorted/varbin.rs | 4 +- vortex-aggregates/src/last/mod.rs | 7 +- vortex-aggregates/src/lib.rs | 232 +++++++++++++- .../fns => vortex-aggregates/src}/max/mod.rs | 83 ++--- vortex-aggregates/src/mean/mod.rs | 11 +- .../fns => vortex-aggregates/src}/min/mod.rs | 83 ++--- .../src}/min_max/bool.rs | 14 +- vortex-aggregates/src/min_max/decimal.rs | 64 ++++ .../src}/min_max/extension.rs | 14 +- .../src}/min_max/fixed_size_list.rs | 16 +- .../src}/min_max/mod.rs | 139 ++++---- .../src}/min_max/primitive.rs | 19 +- .../src}/min_max/varbinview.rs | 28 +- .../src}/nan_count/mod.rs | 79 ++--- .../src}/nan_count/primitive.rs | 26 +- .../src}/null_count/mod.rs | 74 +++-- .../src/runend}/is_constant.rs | 19 +- .../src/runend}/is_sorted.rs | 44 +-- .../src/runend}/min_max.rs | 21 +- vortex-aggregates/src/runend/mod.rs | 42 +++ .../src/runend}/sum/kernel.rs | 38 +-- .../src/runend}/sum/mod.rs | 4 +- .../src/runend}/sum/runs.rs | 5 +- .../src/runend}/sum/tests.rs | 43 +-- .../fns => vortex-aggregates/src}/sum/bool.rs | 39 ++- .../src}/sum/constant.rs | 46 +-- .../src}/sum/decimal.rs | 69 ++-- .../src}/sum/grouped.rs | 68 ++-- .../fns => vortex-aggregates/src}/sum/mod.rs | 119 +++---- .../src}/sum/primitive.rs | 57 ++-- .../src}/sum_v2/grouped.rs | 40 +-- .../src}/sum_v2/mod.rs | 73 ++--- .../src}/sum_v2/tests.rs | 76 ++--- .../src}/uncompressed_size_in_bytes/bool.rs | 4 +- .../constant_tests.rs | 34 +- .../uncompressed_size_in_bytes/decimal.rs | 6 +- .../uncompressed_size_in_bytes/extension.rs | 6 +- .../fixed_size_list.rs | 6 +- .../uncompressed_size_in_bytes/list_view.rs | 18 +- .../src}/uncompressed_size_in_bytes/mod.rs | 150 ++++----- .../src}/uncompressed_size_in_bytes/null.rs | 2 +- .../uncompressed_size_in_bytes/primitive.rs | 6 +- .../uncompressed_size_in_bytes/struct_.rs | 6 +- .../src}/uncompressed_size_in_bytes/union.rs | 8 +- .../uncompressed_size_in_bytes/varbinview.rs | 6 +- .../src/widen/mod.rs | 45 +-- .../src}/widen/tests/aggregates.rs | 97 +++--- .../src}/widen/tests/decimal_aggregates.rs | 70 ++-- vortex-aggregates/src/widen/tests/mod.rs | 29 ++ vortex-array/Cargo.toml | 13 +- vortex-array/benches/run_end_sum.rs | 2 +- vortex-array/benches/scalar_construction.rs | 14 - vortex-array/benches/widen.rs | 5 +- vortex-array/src/aggregate_fn/accumulator.rs | 176 ---------- .../src/aggregate_fn/accumulator_grouped.rs | 110 ++++++- .../src/aggregate_fn/fns/min_max/decimal.rs | 132 -------- vortex-array/src/aggregate_fn/fns/mod.rs | 15 - vortex-array/src/aggregate_fn/proto.rs | 297 ----------------- vortex-array/src/aggregate_fn/session.rs | 101 +----- .../src/aggregate_fn/stat_aggregates.rs | 72 +---- .../src/aggregate_fn/storage_pushdown.rs | 272 +--------------- vortex-array/src/array/erased.rs | 5 +- vortex-array/src/arrays/bool/array.rs | 3 +- vortex-array/src/arrays/bool/bounds.rs | 123 +++++++ vortex-array/src/arrays/bool/mod.rs | 3 + .../src/arrays/chunked/compute/aggregate.rs | 214 ------------- .../src/arrays/constant/compute/mod.rs | 1 - vortex-array/src/arrays/decimal/utils.rs | 70 +++- vortex-array/src/arrays/dict/compute/mod.rs | 3 - .../src/arrays/dict/compute/select.rs | 2 +- vortex-array/src/arrays/dict/mod.rs | 1 + vortex-array/src/arrays/extension/tests.rs | 48 --- .../src/arrays/listview/tests/operations.rs | 132 -------- vortex-array/src/arrays/runend/array/mod.rs | 8 +- vortex-array/src/arrays/runend/compute/mod.rs | 41 --- vortex-array/src/arrays/runend/ops.rs | 2 - .../src/arrays/struct_/compute/mod.rs | 11 - vortex-array/src/arrays/struct_/tests.rs | 26 -- vortex-array/src/arrays/union/tests/mod.rs | 14 - vortex-array/src/arrays/widen/compute/mod.rs | 7 +- .../src/arrays/widen/compute/numeric.rs | 7 +- .../src/arrays/widen/encode/integer.rs | 25 +- vortex-array/src/arrays/widen/tests/mod.rs | 2 - vortex-array/src/compute/conformance/cast.rs | 23 +- .../src/compute/conformance/consistency.rs | 64 ++-- vortex-array/src/compute/conformance/mod.rs | 34 ++ .../src/scalar/typed_view/decimal/dvalue.rs | 2 +- vortex-array/src/stats/array.rs | 13 +- vortex-array/src/stats/stat.rs | 33 +- vortex-array/src/stats/stats_set.rs | 44 +-- vortex-array/src/validity.rs | 15 +- vortex-btrblocks/Cargo.toml | 1 + vortex-btrblocks/src/lib.rs | 6 +- vortex-btrblocks/src/schemes/string/sparse.rs | 2 +- vortex-btrblocks/src/tests.rs | 3 +- vortex-btrblocks/tests/golden.rs | 6 +- vortex-compressor/Cargo.toml | 1 + vortex-compressor/src/compressor/cascade.rs | 5 +- .../src/compressor/constant/mod.rs | 2 +- vortex-compressor/src/compressor/tests.rs | 2 +- vortex-datafusion/src/persistent/format.rs | 2 +- vortex-duckdb/src/column_statistics.rs | 10 +- vortex-duckdb/src/convert/expr.rs | 6 +- vortex-duckdb/src/copy.rs | 10 +- vortex-expr/Cargo.toml | 1 + vortex-expr/src/stats/expr.rs | 47 +-- vortex-expr/src/stats/rewrite/builtins.rs | 23 +- vortex-extensions/vortex-spatial/Cargo.toml | 1 + vortex-extensions/vortex-spatial/README.md | 4 +- .../vortex-spatial/src/tests/mod.rs | 2 +- vortex-extensions/vortex-uuid/Cargo.toml | 1 + vortex-extensions/vortex-uuid/src/lib.rs | 11 +- vortex-file/src/footer/file_statistics.rs | 26 +- vortex-file/src/tests.rs | 10 +- vortex-file/src/v2/file_stats_reader.rs | 6 +- vortex-file/src/writer.rs | 2 +- vortex-functions/Cargo.toml | 1 + vortex-functions/src/list_sum.rs | 2 +- .../src/pruning/dynamic_expression.rs | 10 +- .../benches/aggregate_partial_merge.rs | 2 +- vortex-layout/benches/zone_map_prune.rs | 16 +- vortex-layout/src/layouts/compressed.rs | 4 +- vortex-layout/src/layouts/file_stats.rs | 28 +- vortex-layout/src/layouts/repartition.rs | 4 +- .../aggregates/bloom_filter/canonical/bool.rs | 2 +- vortex-layout/src/layouts/zoned/mod.rs | 11 +- vortex-layout/src/layouts/zoned/schema.rs | 9 +- vortex-layout/src/layouts/zoned/writer.rs | 15 +- vortex-layout/src/layouts/zoned/zone_map.rs | 11 +- vortex-layout/src/test.rs | 1 + vortex-scan/src/plan/tests.rs | 2 +- 231 files changed, 4002 insertions(+), 3316 deletions(-) rename {vortex-array => vortex-aggregates}/benches/aggregate_definedness.rs (97%) rename {vortex-array => vortex-aggregates}/benches/aggregate_max.rs (98%) rename {vortex-array => vortex-aggregates}/benches/aggregate_sum.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/all_nan/mod.rs (83%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/all_non_nan/mod.rs (81%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/all_non_null/mod.rs (82%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/all_null/mod.rs (82%) rename {vortex-array/src/arrays/dict/compute => vortex-aggregates/src/dict}/is_constant.rs (93%) rename {vortex-array/src/arrays/dict/compute => vortex-aggregates/src/dict}/is_sorted.rs (74%) rename {vortex-array/src/arrays/dict/compute => vortex-aggregates/src/dict}/min_max.rs (88%) create mode 100644 vortex-aggregates/src/dict/mod.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/fixed_size_bytes.rs (81%) create mode 100644 vortex-aggregates/src/framework_tests/accumulator.rs create mode 100644 vortex-aggregates/src/framework_tests/chunked_kernel.rs create mode 100644 vortex-aggregates/src/framework_tests/core_consistency.rs create mode 100644 vortex-aggregates/src/framework_tests/extension_validation.rs create mode 100644 vortex-aggregates/src/framework_tests/listview_is_constant.rs create mode 100644 vortex-aggregates/src/framework_tests/mod.rs create mode 100644 vortex-aggregates/src/framework_tests/proto.rs create mode 100644 vortex-aggregates/src/framework_tests/stats.rs create mode 100644 vortex-aggregates/src/framework_tests/storage_pushdown.rs create mode 100644 vortex-aggregates/src/framework_tests/struct_is_constant.rs create mode 100644 vortex-aggregates/src/framework_tests/union_uncompressed_size.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/bool.rs (76%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/decimal.rs (82%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/extension.rs (75%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/fixed_size_list.rs (82%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/list.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/map.rs (69%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/mod.rs (91%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/primitive.rs (94%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/struct_.rs (79%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_constant/varbin.rs (93%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/bool.rs (91%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/decimal.rs (90%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/fixed_size_list.rs (86%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/mod.rs (93%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/primitive.rs (87%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/is_sorted/varbin.rs (93%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/max/mod.rs (87%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min/mod.rs (87%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/bool.rs (80%) create mode 100644 vortex-aggregates/src/min_max/decimal.rs rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/extension.rs (75%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/fixed_size_list.rs (80%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/mod.rs (94%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/primitive.rs (95%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/min_max/varbinview.rs (94%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/nan_count/mod.rs (85%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/nan_count/primitive.rs (81%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/null_count/mod.rs (78%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/is_constant.rs (91%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/is_sorted.rs (88%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/min_max.rs (91%) create mode 100644 vortex-aggregates/src/runend/mod.rs rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/sum/kernel.rs (84%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/sum/mod.rs (83%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/sum/runs.rs (98%) rename {vortex-array/src/arrays/runend/compute => vortex-aggregates/src/runend}/sum/tests.rs (90%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/bool.rs (84%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/constant.rs (90%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/decimal.rs (92%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/grouped.rs (90%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/mod.rs (92%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum/primitive.rs (96%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum_v2/grouped.rs (91%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum_v2/mod.rs (92%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/sum_v2/tests.rs (91%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/bool.rs (91%) rename vortex-array/src/arrays/constant/compute/uncompressed_size.rs => vortex-aggregates/src/uncompressed_size_in_bytes/constant_tests.rs (83%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/decimal.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/extension.rs (74%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/fixed_size_list.rs (84%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/list_view.rs (93%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/mod.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/null.rs (83%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/primitive.rs (89%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/struct_.rs (88%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/union.rs (79%) rename {vortex-array/src/aggregate_fn/fns => vortex-aggregates/src}/uncompressed_size_in_bytes/varbinview.rs (94%) rename vortex-array/src/arrays/widen/compute/aggregate.rs => vortex-aggregates/src/widen/mod.rs (89%) rename {vortex-array/src/arrays => vortex-aggregates/src}/widen/tests/aggregates.rs (85%) rename {vortex-array/src/arrays => vortex-aggregates/src}/widen/tests/decimal_aggregates.rs (87%) create mode 100644 vortex-aggregates/src/widen/tests/mod.rs delete mode 100644 vortex-array/src/aggregate_fn/fns/min_max/decimal.rs create mode 100644 vortex-array/src/arrays/bool/bounds.rs diff --git a/Cargo.lock b/Cargo.lock index a2a7744a366..80b3300a930 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11088,9 +11088,15 @@ dependencies = [ name = "vortex-aggregates" version = "0.1.0" dependencies = [ + "cfg-if", "codspeed-divan-compat", + "enum-iterator", + "itertools 0.14.0", "mimalloc", + "num-traits", + "prost 0.14.4", "rand 0.10.3", + "rstest", "vortex-array", "vortex-buffer", "vortex-error", @@ -11113,6 +11119,7 @@ dependencies = [ "prost 0.14.6", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", @@ -11170,6 +11177,7 @@ dependencies = [ "tabled", "test-with", "tracing", + "vortex-aggregates", "vortex-array", "vortex-array-macros", "vortex-bench-support", @@ -11314,6 +11322,7 @@ dependencies = [ "pco", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-alp", "vortex-array", "vortex-buffer", @@ -11442,6 +11451,7 @@ dependencies = [ "rstest", "rustc-hash", "tracing", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -11600,6 +11610,7 @@ dependencies = [ "prost 0.14.6", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -11623,6 +11634,7 @@ dependencies = [ "rand 0.10.4", "rstest", "smallvec", + "vortex-aggregates", "vortex-array", "vortex-bench-support", "vortex-buffer", @@ -11691,6 +11703,7 @@ dependencies = [ "prost 0.14.6", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", @@ -11726,6 +11739,7 @@ dependencies = [ "rstest", "smallvec", "tracing", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", @@ -11748,6 +11762,7 @@ dependencies = [ "prost 0.14.6", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-alp", "vortex-array", "vortex-bench-support", @@ -11857,6 +11872,7 @@ dependencies = [ "rand 0.10.4", "rstest", "simdutf8", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", @@ -11887,6 +11903,7 @@ dependencies = [ "rstest", "rustc-hash", "tracing", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -11917,6 +11934,7 @@ dependencies = [ "tracing", "tracing-subscriber", "vortex", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-btrblocks", @@ -12141,6 +12159,7 @@ dependencies = [ "onpair", "prost 0.14.6", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", @@ -12311,6 +12330,7 @@ dependencies = [ "prost 0.14.6", "rstest", "smallvec", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -12342,6 +12362,7 @@ dependencies = [ "num-traits", "prost 0.14.6", "rstest", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-buffer", @@ -12519,6 +12540,7 @@ dependencies = [ "hegeltest", "rstest", "uuid", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-buffer", diff --git a/benchmarks/string-bench/src/lib.rs b/benchmarks/string-bench/src/lib.rs index d33e530d0eb..607e468a6e4 100644 --- a/benchmarks/string-bench/src/lib.rs +++ b/benchmarks/string-bench/src/lib.rs @@ -37,7 +37,7 @@ use parquet::arrow::async_reader; use tokio::fs::File; use url::Url; use vortex::VortexSessionDefault; -use vortex::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; +use vortex::aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex::array::ArrayRef; use vortex::array::ExecutionCtx; use vortex::array::IntoArray; diff --git a/encodings/alp/Cargo.toml b/encodings/alp/Cargo.toml index fef068bd044..ff82da99eab 100644 --- a/encodings/alp/Cargo.toml +++ b/encodings/alp/Cargo.toml @@ -22,6 +22,7 @@ fearless_simd_macros = { workspace = true } itertools = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } diff --git a/encodings/alp/src/alp/compute/nan_count.rs b/encodings/alp/src/alp/compute/nan_count.rs index b76dd6e7a97..49806bf8be2 100644 --- a/encodings/alp/src/alp/compute/nan_count.rs +++ b/encodings/alp/src/alp/compute/nan_count.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::nan_count::nan_count; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::nan_count::nan_count; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; diff --git a/encodings/alp/src/lib.rs b/encodings/alp/src/lib.rs index 160ab568cd4..c55f5ee0206 100644 --- a/encodings/alp/src/lib.rs +++ b/encodings/alp/src/lib.rs @@ -16,9 +16,9 @@ //! //! [paper]: https://ir.cwi.nl/pub/33334/33334.pdf +use vortex_aggregates::nan_count::NanCount; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::patched::use_experimental_patches; use vortex_array::session::ArraySessionExt; diff --git a/encodings/datetime-parts/Cargo.toml b/encodings/datetime-parts/Cargo.toml index baf13d17ac1..e2673a89b5e 100644 --- a/encodings/datetime-parts/Cargo.toml +++ b/encodings/datetime-parts/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [dependencies] num-traits = { workspace = true } prost = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/encodings/datetime-parts/src/compress.rs b/encodings/datetime-parts/src/compress.rs index 81d22925652..f04c341cb3c 100644 --- a/encodings/datetime-parts/src/compress.rs +++ b/encodings/datetime-parts/src/compress.rs @@ -11,12 +11,12 @@ use std::mem::MaybeUninit; use num_traits::AsPrimitive; +use vortex_aggregates::min_max::MinMaxResult; +use vortex_aggregates::min_max::min_max; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; -use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::TemporalArray; diff --git a/encodings/datetime-parts/src/compute/compare.rs b/encodings/datetime-parts/src/compute/compare.rs index e49e70db6b3..41a0f41e035 100644 --- a/encodings/datetime-parts/src/compute/compare.rs +++ b/encodings/datetime-parts/src/compute/compare.rs @@ -319,10 +319,10 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::sum::sum; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::VortexSessionExecute; - use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/datetime-parts/src/compute/is_constant.rs b/encodings/datetime-parts/src/compute/is_constant.rs index cd4ecf2752a..e813028b5e7 100644 --- a/encodings/datetime-parts/src/compute/is_constant.rs +++ b/encodings/datetime-parts/src/compute/is_constant.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; diff --git a/encodings/datetime-parts/src/lib.rs b/encodings/datetime-parts/src/lib.rs index 541032feac1..7dfff6e4e01 100644 --- a/encodings/datetime-parts/src/lib.rs +++ b/encodings/datetime-parts/src/lib.rs @@ -12,9 +12,9 @@ mod compute; mod ops; mod timestamp; +use vortex_aggregates::is_constant::IsConstant; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; diff --git a/encodings/decimal-byte-parts/Cargo.toml b/encodings/decimal-byte-parts/Cargo.toml index 9df011804c7..0b5b5613821 100644 --- a/encodings/decimal-byte-parts/Cargo.toml +++ b/encodings/decimal-byte-parts/Cargo.toml @@ -19,6 +19,7 @@ workspace = true num-traits = { workspace = true } prost = { workspace = true } smallvec = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/encodings/decimal-byte-parts/benches/dbp_compute.rs b/encodings/decimal-byte-parts/benches/dbp_compute.rs index 8012eb8392c..b24807c493a 100644 --- a/encodings/decimal-byte-parts/benches/dbp_compute.rs +++ b/encodings/decimal-byte-parts/benches/dbp_compute.rs @@ -19,13 +19,13 @@ use rand::SeedableRng; use rand::distr::uniform::SampleRange; use rand::distr::uniform::SampleUniform; use rand::rngs::StdRng; +use vortex_aggregates::min_max; +use vortex_aggregates::sum; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min_max; -use vortex_array::aggregate_fn::fns::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DecimalArray; 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 1efdb1718e9..5ad72d542e0 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 @@ -6,18 +6,18 @@ //! With no lower parts, the MSP holds the unscaled decimal values. Integer aggregates can reuse //! child kernels, but their results must preserve decimal scale, precision, and state nullability. +use vortex_aggregates::is_sorted::IsSorted; +use vortex_aggregates::is_sorted::is_sorted; +use vortex_aggregates::is_sorted::is_strict_sorted; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::min_max::min_max; +use vortex_aggregates::sum::Sum; +use vortex_aggregates::sum::sum; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; -use vortex_array::aggregate_fn::fns::is_sorted::is_strict_sorted; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::aggregate_fn::fns::sum::Sum; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::WidenArray; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs index 372b37ec375..bee6000a95d 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/aggregate/tests.rs @@ -4,6 +4,13 @@ //! Kernel selection, decimal partials, and fallback equivalence. use rstest::rstest; +use vortex_aggregates::first::First; +use vortex_aggregates::is_sorted::IsSorted; +use vortex_aggregates::is_sorted::IsSortedOptions; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::sum::Sum; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -11,13 +18,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::first::First; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::DecimalArray; diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/is_constant.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/is_constant.rs index 3fe59111f6e..2ad5fdfdee4 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/is_constant.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/is_constant.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; diff --git a/encodings/decimal-byte-parts/src/lib.rs b/encodings/decimal-byte-parts/src/lib.rs index cb536bbe00a..bbedc69d2d5 100644 --- a/encodings/decimal-byte-parts/src/lib.rs +++ b/encodings/decimal-byte-parts/src/lib.rs @@ -23,14 +23,14 @@ //! //! [`Widen`]: vortex_array::arrays::Widen +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_sorted::IsSorted; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::sum::Sum; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; diff --git a/encodings/elias-fano/Cargo.toml b/encodings/elias-fano/Cargo.toml index d044651693f..d3fa6541dad 100644 --- a/encodings/elias-fano/Cargo.toml +++ b/encodings/elias-fano/Cargo.toml @@ -15,6 +15,7 @@ version = { workspace = true } [dependencies] num-traits = { workspace = true } prost = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } diff --git a/encodings/elias-fano/src/unary/compress.rs b/encodings/elias-fano/src/unary/compress.rs index a8a95e7d833..f5a179885db 100644 --- a/encodings/elias-fano/src/unary/compress.rs +++ b/encodings/elias-fano/src/unary/compress.rs @@ -2,9 +2,9 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use num_traits::AsPrimitive; +use vortex_aggregates::sum::sum; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::Primitive; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; diff --git a/encodings/fastlanes/Cargo.toml b/encodings/fastlanes/Cargo.toml index 1f2ab9ca314..726c178aebc 100644 --- a/encodings/fastlanes/Cargo.toml +++ b/encodings/fastlanes/Cargo.toml @@ -25,6 +25,7 @@ itertools = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } rand = { workspace = true, optional = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs index 4e67a617881..8f9265cccb1 100644 --- a/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs +++ b/encodings/fastlanes/src/bitpacking/array/bitpack_compress/mod.rs @@ -19,10 +19,7 @@ pub use global::gather_patches; pub use global::test_harness; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; -use vortex_array::dtype::NativePType; -use vortex_array::match_each_integer_ptype; -use vortex_array::scalar::Scalar; -use vortex_error::VortexError; +use vortex_array::arrays::primitive::integer_bounds; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_ensure; @@ -40,18 +37,10 @@ fn ensure_non_negative_integers( ); if array.ptype().is_signed_int() { let has_negative_values = - match_each_integer_ptype!(array.ptype(), |P| { has_negative_min::

(array, ctx) }); + integer_bounds(array.as_ref(), ctx)?.is_some_and(|bounds| bounds.min < 0); if has_negative_values { vortex_bail!("cannot bitpack array containing negative integers") } } Ok(()) } - -/// Whether the minimum of `array` as `P` is negative, treating an unknown minimum as zero. -fn has_negative_min

(array: &PrimitiveArray, ctx: &mut ExecutionCtx) -> bool -where - P: NativePType + PartialOrd + for<'a> TryFrom<&'a Scalar, Error = VortexError>, -{ - array.statistics().compute_min::

(ctx).unwrap_or_default() < P::zero() -} diff --git a/encodings/fastlanes/src/bitpacking/compute/is_constant.rs b/encodings/fastlanes/src/bitpacking/compute/is_constant.rs index 74b0267470b..3d83ecf6258 100644 --- a/encodings/fastlanes/src/bitpacking/compute/is_constant.rs +++ b/encodings/fastlanes/src/bitpacking/compute/is_constant.rs @@ -5,13 +5,13 @@ use std::mem::MaybeUninit; use std::ops::Range; use itertools::Itertools; +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::primitive::IS_CONST_LANE_WIDTH; +use vortex_aggregates::is_constant::primitive::compute_is_constant; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::primitive::IS_CONST_LANE_WIDTH; -use vortex_array::aggregate_fn::fns::is_constant::primitive::compute_is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::IntegerPType; @@ -199,13 +199,13 @@ mod tests { use std::ops::Range; use rstest::rstest; + use vortex_aggregates::is_constant::IsConstant; + use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; - use vortex_array::aggregate_fn::fns::is_constant::IsConstant; - use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/fastlanes/src/delta/compute/is_constant.rs b/encodings/fastlanes/src/delta/compute/is_constant.rs index 21309b5c8a2..7e687f49d58 100644 --- a/encodings/fastlanes/src/delta/compute/is_constant.rs +++ b/encodings/fastlanes/src/delta/compute/is_constant.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::PrimitiveArray; use vortex_array::match_each_integer_ptype; @@ -125,13 +125,13 @@ fn deltas_are_zero(deltas: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult VortexSession { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session } diff --git a/encodings/fastlanes/src/for_/array/for_compress.rs b/encodings/fastlanes/src/for_/array/for_compress.rs index e277541c0c3..0a59dfeec57 100644 --- a/encodings/fastlanes/src/for_/array/for_compress.rs +++ b/encodings/fastlanes/src/for_/array/for_compress.rs @@ -12,12 +12,14 @@ use vortex_array::IntoArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::arrays::primitive::integer_bounds; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; 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; @@ -26,6 +28,7 @@ use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedSourceExt; use vortex_compute::lane_kernels::for_each_mask_word; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_mask::AllOr; use vortex_mask::Mask; @@ -38,9 +41,14 @@ use crate::FoRData; impl FoRData { pub fn encode(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult { let array_ref = array.clone().into_array(); + // `integer_bounds` caches the exact minimum, which is then read back as a scalar. + if integer_bounds(&array_ref, ctx)?.is_none() { + vortex_bail!("cannot frame-of-reference encode an array with no valid values"); + } let min = array_ref .statistics() - .compute_stat(Stat::Min, ctx)? + .get(Stat::Min) + .as_exact() .ok_or_else(|| vortex_err!("Min stat not found"))?; Self::encode_with_reference(array, min, ctx) } diff --git a/encodings/fastlanes/src/for_/compute/is_constant.rs b/encodings/fastlanes/src/for_/compute/is_constant.rs index 704ce82ece7..d25ca3505a8 100644 --- a/encodings/fastlanes/src/for_/compute/is_constant.rs +++ b/encodings/fastlanes/src/for_/compute/is_constant.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; diff --git a/encodings/fastlanes/src/for_/compute/is_sorted.rs b/encodings/fastlanes/src/for_/compute/is_sorted.rs index 2c784e526a6..6ebcba28106 100644 --- a/encodings/fastlanes/src/for_/compute/is_sorted.rs +++ b/encodings/fastlanes/src/for_/compute/is_sorted.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_sorted::IsSorted; +use vortex_aggregates::is_sorted::is_sorted; +use vortex_aggregates::is_sorted::is_strict_sorted; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; -use vortex_array::aggregate_fn::fns::is_sorted::is_strict_sorted; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::PrimitiveArray; use vortex_array::scalar::Scalar; @@ -66,9 +66,9 @@ impl DynAggregateKernel for FoRIsSortedKernel { mod test { use std::sync::LazyLock; + use vortex_aggregates::is_sorted::is_sorted; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; - use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; use vortex_array::arrays::PrimitiveArray; use vortex_array::validity::Validity; use vortex_buffer::buffer; diff --git a/encodings/fastlanes/src/for_/tests.rs b/encodings/fastlanes/src/for_/tests.rs index 3ae294895cb..2a945ffc084 100644 --- a/encodings/fastlanes/src/for_/tests.rs +++ b/encodings/fastlanes/src/for_/tests.rs @@ -8,6 +8,8 @@ use hegel::generators as gs; use num_traits::PrimInt; use num_traits::WrappingAdd; use rstest::rstest; +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::Array; use vortex_array::ArrayParts; use vortex_array::ArrayRef; @@ -16,8 +18,6 @@ use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::Accumulator; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::arrays::Constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/fastlanes/src/lib.rs b/encodings/fastlanes/src/lib.rs index 938b00f1aa8..1c54f90134b 100644 --- a/encodings/fastlanes/src/lib.rs +++ b/encodings/fastlanes/src/lib.rs @@ -53,10 +53,10 @@ use bitpacking::compute::is_constant::BitPackedIsConstantKernel; use delta::compute::is_constant::DeltaIsConstantKernel; use for_::compute::is_constant::FoRIsConstantKernel; use for_::compute::is_sorted::FoRIsSortedKernel; +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_sorted::IsSorted; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::patched::use_experimental_patches; use vortex_array::session::ArraySessionExt; diff --git a/encodings/fastlanes/tests/widen.rs b/encodings/fastlanes/tests/widen.rs index 24585b034ec..2b43b0ad3dc 100644 --- a/encodings/fastlanes/tests/widen.rs +++ b/encodings/fastlanes/tests/widen.rs @@ -11,15 +11,15 @@ use std::sync::LazyLock; use rstest::rstest; +use vortex_aggregates::is_constant::is_constant; +use vortex_aggregates::is_sorted::is_sorted; +use vortex_aggregates::is_sorted::is_strict_sorted; +use vortex_aggregates::min_max::min_max; +use vortex_aggregates::sum::sum; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; -use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; -use vortex_array::aggregate_fn::fns::is_sorted::is_strict_sorted; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/fsst/Cargo.toml b/encodings/fsst/Cargo.toml index 48ba85a0090..410ebbc8a2f 100644 --- a/encodings/fsst/Cargo.toml +++ b/encodings/fsst/Cargo.toml @@ -37,6 +37,7 @@ hegeltest = { workspace = true } mimalloc = { workspace = true } rand = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-expr = { workspace = true } diff --git a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs index 685df395b11..d9a2fca7886 100644 --- a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs +++ b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs @@ -9,8 +9,8 @@ use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::aggregate_fn::stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::varbinview::BinaryView; @@ -36,7 +36,7 @@ impl DynAggregateKernel for FsstUncompressedSizeKernel { batch: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - if !aggregate_fn.is::() { + if aggregate_fn.id() != *UNCOMPRESSED_SIZE_IN_BYTES_ID { return Ok(None); } @@ -108,13 +108,13 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; + use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::ArrayVTable; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTable; - use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; - use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinArray; diff --git a/encodings/fsst/src/lib.rs b/encodings/fsst/src/lib.rs index ecf10e73164..e2c9f0fc696 100644 --- a/encodings/fsst/src/lib.rs +++ b/encodings/fsst/src/lib.rs @@ -28,9 +28,8 @@ mod tests; pub use array::*; pub use compress::*; use vortex_array::ArrayVTable; -use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::aggregate_fn::stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; @@ -40,7 +39,7 @@ pub fn initialize(session: &VortexSession) { kernel::initialize(session); session.aggregate_fns().register_aggregate_kernel( FSST.id(), - Some(UncompressedSizeInBytes.id()), + Some(*UNCOMPRESSED_SIZE_IN_BYTES_ID), &compute::uncompressed_size_in_bytes::FsstUncompressedSizeKernel, ); rules::register_parent_rules(session); diff --git a/encodings/onpair/Cargo.toml b/encodings/onpair/Cargo.toml index b8f95012efb..f91b9e0aec7 100644 --- a/encodings/onpair/Cargo.toml +++ b/encodings/onpair/Cargo.toml @@ -32,6 +32,7 @@ _test-harness = ["vortex-array/_test-harness"] divan = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } [[bench]] diff --git a/encodings/onpair/tests/big_data.rs b/encodings/onpair/tests/big_data.rs index 42b24367a66..ab27b0b329e 100644 --- a/encodings/onpair/tests/big_data.rs +++ b/encodings/onpair/tests/big_data.rs @@ -15,9 +15,9 @@ use std::sync::LazyLock; use std::time::Instant; +use vortex_aggregates::sum::sum; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::VarBinArray; diff --git a/encodings/sequence/Cargo.toml b/encodings/sequence/Cargo.toml index fad14176db0..e6ba51f05e1 100644 --- a/encodings/sequence/Cargo.toml +++ b/encodings/sequence/Cargo.toml @@ -16,6 +16,7 @@ version = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } smallvec = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/encodings/sequence/src/compute/is_sorted.rs b/encodings/sequence/src/compute/is_sorted.rs index b3f18d8c701..afdecc921c1 100644 --- a/encodings/sequence/src/compute/is_sorted.rs +++ b/encodings/sequence/src/compute/is_sorted.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_sorted::IsSorted; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; @@ -50,13 +50,13 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::is_sorted::IsSorted; + use vortex_aggregates::is_sorted::IsSortedOptions; + use vortex_aggregates::is_sorted::is_sorted; + use vortex_aggregates::is_sorted::is_strict_sorted; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; - use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; - use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; - use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; - use vortex_array::aggregate_fn::fns::is_sorted::is_strict_sorted; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::ChunkedArray; use vortex_array::dtype::DType; diff --git a/encodings/sequence/src/compute/min_max.rs b/encodings/sequence/src/compute/min_max.rs index adb0781657f..93516121887 100644 --- a/encodings/sequence/src/compute/min_max.rs +++ b/encodings/sequence/src/compute/min_max.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::min_max::make_minmax_dtype; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::make_minmax_dtype; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; @@ -78,11 +78,11 @@ impl DynAggregateKernel for SequenceMinMaxKernel { mod tests { use std::sync::LazyLock; + use vortex_aggregates::min_max::MinMaxResult; + use vortex_aggregates::min_max::min_max; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; - use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; diff --git a/encodings/sequence/src/lib.rs b/encodings/sequence/src/lib.rs index d882e78523c..86b1f35784b 100644 --- a/encodings/sequence/src/lib.rs +++ b/encodings/sequence/src/lib.rs @@ -19,10 +19,10 @@ pub use array::SequenceArray; pub use array::SequenceData; pub use array::SequenceDataParts; pub use compress::sequence_encode; +use vortex_aggregates::is_sorted::IsSorted; +use vortex_aggregates::min_max::MinMax; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -use vortex_array::aggregate_fn::fns::min_max::MinMax; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; diff --git a/encodings/sequence/src/model_tests.rs b/encodings/sequence/src/model_tests.rs index 051174f1778..6a9d5580bf3 100644 --- a/encodings/sequence/src/model_tests.rs +++ b/encodings/sequence/src/model_tests.rs @@ -9,13 +9,13 @@ use hegel::TestCase; use hegel::generators as gs; use num_traits::Bounded; use num_traits::ToPrimitive; +use vortex_aggregates::min_max::MinMaxResult; +use vortex_aggregates::min_max::min_max; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; -use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/sparse/Cargo.toml b/encodings/sparse/Cargo.toml index ba5f267f660..b8d1e4343ec 100644 --- a/encodings/sparse/Cargo.toml +++ b/encodings/sparse/Cargo.toml @@ -19,6 +19,7 @@ workspace = true itertools = { workspace = true } num-traits = { workspace = true } prost = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/encodings/sparse/benches/sparse_pushdown.rs b/encodings/sparse/benches/sparse_pushdown.rs index 57da439a9fd..05008592ccf 100644 --- a/encodings/sparse/benches/sparse_pushdown.rs +++ b/encodings/sparse/benches/sparse_pushdown.rs @@ -15,15 +15,15 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; +use vortex_aggregates::is_constant::is_constant; +use vortex_aggregates::min_max::min_max; +use vortex_aggregates::null_count::null_count; +use vortex_aggregates::sum::sum; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::aggregate_fn::fns::null_count::null_count; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; diff --git a/encodings/sparse/src/compute/is_constant.rs b/encodings/sparse/src/compute/is_constant.rs index 950865c9874..c1c0dbffc79 100644 --- a/encodings/sparse/src/compute/is_constant.rs +++ b/encodings/sparse/src/compute/is_constant.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; @@ -69,9 +69,9 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::is_constant::is_constant; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; - use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::scalar::Scalar; use vortex_array::session::ArraySessionExt; use vortex_buffer::buffer; diff --git a/encodings/sparse/src/compute/min_max.rs b/encodings/sparse/src/compute/min_max.rs index a4a59a70277..29850b4d251 100644 --- a/encodings/sparse/src/compute/min_max.rs +++ b/encodings/sparse/src/compute/min_max.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::min_max::MinMax; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::Accumulator; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::DynAccumulator; -use vortex_array::aggregate_fn::fns::min_max::MinMax; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::ConstantArray; use vortex_array::scalar::Scalar; @@ -63,11 +63,11 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::min_max::MinMaxResult; + use vortex_aggregates::min_max::min_max; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; - use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::scalar::Scalar; use vortex_array::session::ArraySessionExt; use vortex_buffer::buffer; diff --git a/encodings/sparse/src/compute/nan_count.rs b/encodings/sparse/src/compute/nan_count.rs index c891927dd57..80fd6c65224 100644 --- a/encodings/sparse/src/compute/nan_count.rs +++ b/encodings/sparse/src/compute/nan_count.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::nan_count::NanCount; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -9,7 +10,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTable as _; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::ConstantArray; use vortex_array::scalar::Scalar; @@ -73,9 +73,9 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::nan_count::nan_count; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; - use vortex_array::aggregate_fn::fns::nan_count::nan_count; use vortex_array::scalar::Scalar; use vortex_array::session::ArraySessionExt; use vortex_buffer::buffer; diff --git a/encodings/sparse/src/compute/null_count.rs b/encodings/sparse/src/compute/null_count.rs index fa035f485d4..af68b8d697d 100644 --- a/encodings/sparse/src/compute/null_count.rs +++ b/encodings/sparse/src/compute/null_count.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::null_count::null_count; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::null_count::NullCount; -use vortex_array::aggregate_fn::fns::null_count::null_count; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::scalar::Scalar; @@ -58,9 +58,9 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::null_count::null_count; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; - use vortex_array::aggregate_fn::fns::null_count::null_count; use vortex_array::arrays::PrimitiveArray; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; diff --git a/encodings/sparse/src/compute/sum.rs b/encodings/sparse/src/compute/sum.rs index c02e3e04e44..8ccc82687a4 100644 --- a/encodings/sparse/src/compute/sum.rs +++ b/encodings/sparse/src/compute/sum.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::sum::Sum; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::sum::Sum; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::ConstantArray; use vortex_array::scalar::Scalar; @@ -65,6 +65,9 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::sum::sum; + use vortex_aggregates::sum_v2::SumV2; + use vortex_aggregates::sum_v2::sum_v2; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -72,9 +75,6 @@ mod tests { use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::sum::sum; - use vortex_array::aggregate_fn::fns::sum_v2::SumV2; - use vortex_array::aggregate_fn::fns::sum_v2::sum_v2; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::scalar::Scalar; use vortex_array::session::ArraySessionExt; diff --git a/encodings/sparse/src/lib.rs b/encodings/sparse/src/lib.rs index 5ea2b0f2cd7..fa73487fb91 100644 --- a/encodings/sparse/src/lib.rs +++ b/encodings/sparse/src/lib.rs @@ -73,13 +73,13 @@ mod plugin; mod rules; mod slice; +use vortex_aggregates::is_constant::IsConstant; +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::sum::Sum; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::aggregate_fn::AggregateFnVTable as _; -use vortex_array::aggregate_fn::fns::is_constant::IsConstant; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; -use vortex_array::aggregate_fn::fns::sum::Sum; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; diff --git a/encodings/zstd/src/editions.rs b/encodings/zstd/src/editions.rs index 2af1865d6d8..86ffe97e668 100644 --- a/encodings/zstd/src/editions.rs +++ b/encodings/zstd/src/editions.rs @@ -57,10 +57,8 @@ mod tests { #[test] fn initialize_does_not_enable_zstd_edition() { - let session = VortexSession::empty(); - crate::initialize(&session); assert!( - !session + !SESSION .enabled_editions() .editions() .contains(&ZSTD_2026_02) diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index e37c0ad1a84..b06f1a1a268 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -54,6 +54,7 @@ strum = { workspace = true, features = ["derive"] } # Vortex core - no default features for WASM compatibility (files feature pulls in tokio) vortex = { path = "../vortex", default-features = false } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["arbitrary", "_test-harness"] } vortex-btrblocks = { workspace = true } vortex-buffer = { workspace = true } diff --git a/fuzz/array.rs b/fuzz/array.rs index 999c0876eff..ac3198cb0cd 100644 --- a/fuzz/array.rs +++ b/fuzz/array.rs @@ -20,6 +20,9 @@ use strum::EnumDiscriminants; use strum::EnumIter; use strum::IntoEnumIterator; use tracing::debug; +use vortex_aggregates::min_max::MinMaxResult; +use vortex_aggregates::min_max::min_max; +use vortex_aggregates::sum::sum; use vortex_array::ArrayEq; use vortex_array::ArrayRef; use vortex_array::Canonical; @@ -29,9 +32,6 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::fns::all_non_distinct::all_non_distinct; -use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DecimalArray; diff --git a/fuzz/error.rs b/fuzz/error.rs index d307b2b42e7..563bff93dc2 100644 --- a/fuzz/error.rs +++ b/fuzz/error.rs @@ -10,9 +10,9 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; +use vortex_aggregates::min_max::MinMaxResult; use vortex_array::ArrayRef; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; use vortex_array::scalar::Scalar; use vortex_array::search_sorted::SearchResult; use vortex_array::search_sorted::SearchSortedSide; diff --git a/lang/java/vortex-jni-native/src/statistics.rs b/lang/java/vortex-jni-native/src/statistics.rs index 5e5e91f94cc..b9613db0017 100644 --- a/lang/java/vortex-jni-native/src/statistics.rs +++ b/lang/java/vortex-jni-native/src/statistics.rs @@ -16,6 +16,7 @@ use jni::sys::JNI_FALSE; use jni::sys::JNI_TRUE; use jni::sys::jlong; use vortex::aggregate_fn::AggregateFnRef; +use vortex::aggregates::stat_aggregate_fn; use vortex::array::scalar::PValue; use vortex::array::scalar::Scalar; use vortex::array::scalar::ScalarValue; @@ -169,7 +170,7 @@ impl ColumnStatistics { fn from_aggregates(aggregates: Option<&AggregateStats>) -> Self { let get = |stat: Stat| { aggregates - .zip(stat.aggregate_fn()) + .zip(stat_aggregate_fn(stat)) .map_or(Precision::Absent, |(aggregates, aggregate_fn)| { aggregates.get(&aggregate_fn) }) @@ -215,8 +216,7 @@ async fn resolve_statistic( stat: Stat, legacy: &mut Option, ) -> VortexResult> { - let aggregate_fn = stat - .aggregate_fn() + let aggregate_fn = stat_aggregate_fn(stat) .ok_or_else(|| vortex_err!("statistic {stat} has no aggregate function"))?; let partial = source.field_statistic(path, &aggregate_fn).await?; diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index e3853743655..cf30ba30ddc 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -9,7 +9,10 @@ }, "vortex-aggregates": { "accumulator_construction": 1, - "aggregate_grouped": 18 + "aggregate_definedness": 6, + "aggregate_grouped": 18, + "aggregate_max": 15, + "aggregate_sum": 15 }, "vortex-alp": { "alp_chain_decode": 4, @@ -19,9 +22,6 @@ "alp_slice_take": 2 }, "vortex-array": { - "aggregate_definedness": 6, - "aggregate_max": 15, - "aggregate_sum": 15, "binary_ops": 7, "block_program": 3, "cast_decimal": 8, diff --git a/scripts/codspeed_bench_durations.json b/scripts/codspeed_bench_durations.json index 2547c0cc520..3317d998a0e 100644 --- a/scripts/codspeed_bench_durations.json +++ b/scripts/codspeed_bench_durations.json @@ -9,14 +9,14 @@ "take_union": 3.473 }, "vortex-aggregates": { - "aggregate_grouped": 3.823 + "aggregate_grouped": 3.823, + "aggregate_max": 3.586, + "aggregate_sum": 3.199 }, "vortex-alp": { "alp_compress": 5.189 }, "vortex-array": { - "aggregate_max": 3.586, - "aggregate_sum": 3.199, "binary_ops": 2.881, "cast_decimal": 2.634, "cast_primitive": 2.705, diff --git a/vortex-aggregates/Cargo.toml b/vortex-aggregates/Cargo.toml index 37753072ff1..a51b2e5b26a 100644 --- a/vortex-aggregates/Cargo.toml +++ b/vortex-aggregates/Cargo.toml @@ -13,6 +13,9 @@ rust-version = { workspace = true } version = { workspace = true } [dependencies] +cfg-if = { workspace = true } +itertools = { workspace = true } +num-traits = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } @@ -24,10 +27,17 @@ workspace = true [dev-dependencies] divan = { workspace = true } +enum-iterator = { workspace = true } mimalloc = { workspace = true } +prost = { workspace = true } rand = { workspace = true } +rstest = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } +[[bench]] +name = "aggregate_definedness" +harness = false + [[bench]] name = "aggregate_grouped" harness = false @@ -35,3 +45,11 @@ harness = false [[bench]] name = "accumulator_construction" harness = false + +[[bench]] +name = "aggregate_max" +harness = false + +[[bench]] +name = "aggregate_sum" +harness = false diff --git a/vortex-array/benches/aggregate_definedness.rs b/vortex-aggregates/benches/aggregate_definedness.rs similarity index 97% rename from vortex-array/benches/aggregate_definedness.rs rename to vortex-aggregates/benches/aggregate_definedness.rs index 5b24e98cb8a..82cacc367d6 100644 --- a/vortex-array/benches/aggregate_definedness.rs +++ b/vortex-aggregates/benches/aggregate_definedness.rs @@ -19,8 +19,8 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::null_count::NullCount; -use vortex_array::aggregate_fn::fns::sum::Sum; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::sum::Sum; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::list::ListArraySlotsExt; @@ -46,7 +46,11 @@ fn main() { // Sized to keep the CodSpeed simulation under 1ms per benchmark. const N: usize = 15_000; -static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); + session +}); /// An aggregate that skips nulls and one that counts them. const AGGREGATES: &[&str] = &["sum", "null_count"]; diff --git a/vortex-aggregates/benches/aggregate_grouped.rs b/vortex-aggregates/benches/aggregate_grouped.rs index 9056ec84ba4..0e7ad32cf56 100644 --- a/vortex-aggregates/benches/aggregate_grouped.rs +++ b/vortex-aggregates/benches/aggregate_grouped.rs @@ -12,6 +12,8 @@ use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; use vortex_aggregates::count::Count; +use vortex_aggregates::sum::Sum; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; @@ -20,8 +22,6 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynGroupedAccumulator; use vortex_array::aggregate_fn::GroupedAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum::Sum; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::ListViewArray; use vortex_array::arrays::PrimitiveArray; diff --git a/vortex-array/benches/aggregate_max.rs b/vortex-aggregates/benches/aggregate_max.rs similarity index 98% rename from vortex-array/benches/aggregate_max.rs rename to vortex-aggregates/benches/aggregate_max.rs index ec70507b418..ad1d201476e 100644 --- a/vortex-array/benches/aggregate_max.rs +++ b/vortex-aggregates/benches/aggregate_max.rs @@ -8,10 +8,10 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; use rand::prelude::*; +use vortex_aggregates::min_max::min_max; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::DecimalArray; use vortex_array::arrays::PrimitiveArray; @@ -39,9 +39,11 @@ fn main() { const N: usize = 15_000; static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); #[divan::bench] diff --git a/vortex-array/benches/aggregate_sum.rs b/vortex-aggregates/benches/aggregate_sum.rs similarity index 89% rename from vortex-array/benches/aggregate_sum.rs rename to vortex-aggregates/benches/aggregate_sum.rs index 2359209dc59..b61ed06935f 100644 --- a/vortex-array/benches/aggregate_sum.rs +++ b/vortex-aggregates/benches/aggregate_sum.rs @@ -6,21 +6,30 @@ use std::sync::LazyLock; use divan::Bencher; +use divan::black_box; +use divan::counter::ItemsCount; use mimalloc::MiMalloc; use rand::prelude::*; +use vortex_aggregates::sum_v2::SumV2; +use vortex_aggregates::sum_v2::sum_v2; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::sum::sum; -use vortex_array::aggregate_fn::fns::sum_v2::sum_v2; +use vortex_aggregates::sum::sum; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::DecimalArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::DecimalDType; use vortex_array::optimizer::kernels::KernelSession; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_array::stats::Stat; use vortex_array::test_harness::mark_optimized; use vortex_array::validity::Validity; use vortex_buffer::Buffer; +use vortex_error::VortexExpect; use vortex_session::VortexSession; #[global_allocator] @@ -35,9 +44,11 @@ fn main() { const N: usize = 15_000; static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); #[divan::bench] @@ -297,3 +308,23 @@ fn sum_decimal_i32_nulls_scattered(bencher: Bencher) { }) .bench_refs(|(array, ctx)| sum(array, ctx)); } + +/// Number of accumulators created per iteration of `accumulator_sum_v2`. +const ACCUMULATORS: usize = 1024; + +#[divan::bench] +fn accumulator_sum_v2(bencher: Bencher) { + let dtype = DType::Primitive(PType::I64, Nullability::Nullable); + let aggregate_fn = SumV2.bind(NumericalAggregateOpts::default()); + bencher + .counter(ItemsCount::new(ACCUMULATORS)) + .bench_local(|| { + for _ in 0..ACCUMULATORS { + black_box( + aggregate_fn + .accumulator(black_box(&dtype)) + .vortex_expect("accumulator"), + ); + } + }); +} diff --git a/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs b/vortex-aggregates/src/all_nan/mod.rs similarity index 83% rename from vortex-array/src/aggregate_fn/fns/all_nan/mod.rs rename to vortex-aggregates/src/all_nan/mod.rs index 9b82e818e32..d1cd4e3d073 100644 --- a/vortex-array/src/aggregate_fn/fns/all_nan/mod.rs +++ b/vortex-aggregates/src/all_nan/mod.rs @@ -1,31 +1,31 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::fns::nan_count::columnar_nan_count; -use crate::aggregate_fn::fns::nan_count::nan_count; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::scalar::Scalar; +use crate::nan_count::columnar_nan_count; +use crate::nan_count::nan_count; /// Compute whether every value in an array is NaN. /// /// Like other `all` aggregates, this is vacuously true for empty input. /// /// This is a pruning aggregate, not just a convenience wrapper around -/// [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount]. Pruning aggregates must prove a +/// [`NanCount`][crate::nan_count::NanCount]. Pruning aggregates must prove a /// row-wise fact for every value in the scope, so their partials remain valid when a stats column is -/// sliced or concatenated alongside the data. [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount] +/// sliced or concatenated alongside the data. [`NanCount`][crate::nan_count::NanCount] /// carries cross-row count information instead, so it is useful as a legacy storage format but not /// as the pruning expression itself. #[derive(Clone, Debug)] @@ -153,23 +153,28 @@ impl AggregateFnVTable for AllNan { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::all_nan::AllNan; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::all_nan::AllNan; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn all_nan_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs b/vortex-aggregates/src/all_non_nan/mod.rs similarity index 81% rename from vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs rename to vortex-aggregates/src/all_non_nan/mod.rs index fe1e704b7a2..93b9c582e73 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_nan/mod.rs +++ b/vortex-aggregates/src/all_non_nan/mod.rs @@ -1,31 +1,31 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::fns::nan_count::columnar_nan_count; -use crate::aggregate_fn::fns::nan_count::nan_count; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::scalar::Scalar; +use crate::nan_count::columnar_nan_count; +use crate::nan_count::nan_count; /// Compute whether every value in an array is not NaN. /// /// Like other `all` aggregates, this is vacuously true for empty input. /// /// This is a pruning aggregate, not just a convenience wrapper around -/// [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount]. Pruning aggregates must prove a +/// [`NanCount`][crate::nan_count::NanCount]. Pruning aggregates must prove a /// row-wise fact for every value in the scope, so their partials remain valid when a stats column is -/// sliced or concatenated alongside the data. [`NanCount`][crate::aggregate_fn::fns::nan_count::NanCount] +/// sliced or concatenated alongside the data. [`NanCount`][crate::nan_count::NanCount] /// carries cross-row count information instead, so it is useful as a legacy storage format but not /// as the pruning expression itself. #[derive(Clone, Debug)] @@ -143,23 +143,28 @@ impl AggregateFnVTable for AllNonNan { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::all_non_nan::AllNonNan; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::all_non_nan::AllNonNan; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn all_non_nan_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs b/vortex-aggregates/src/all_non_null/mod.rs similarity index 82% rename from vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs rename to vortex-aggregates/src/all_non_null/mod.rs index 044d9f42d79..97dbd789fdf 100644 --- a/vortex-array/src/aggregate_fn/fns/all_non_null/mod.rs +++ b/vortex-aggregates/src/all_non_null/mod.rs @@ -1,22 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::scalar::Scalar; - /// Compute whether every value in an array is non-null. /// /// Like other `all` aggregates, this is vacuously true for empty input. @@ -137,23 +136,28 @@ impl AggregateFnVTable for AllNonNull { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::all_non_null::AllNonNull; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::all_non_null::AllNonNull; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn all_non_null_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/all_null/mod.rs b/vortex-aggregates/src/all_null/mod.rs similarity index 82% rename from vortex-array/src/aggregate_fn/fns/all_null/mod.rs rename to vortex-aggregates/src/all_null/mod.rs index cba4b6c10e3..3025c6458c1 100644 --- a/vortex-array/src/aggregate_fn/fns/all_null/mod.rs +++ b/vortex-aggregates/src/all_null/mod.rs @@ -1,22 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::scalar::Scalar; - /// Compute whether every value in an array is null. /// /// Like other `all` aggregates, this is vacuously true for empty input. @@ -140,23 +139,28 @@ impl AggregateFnVTable for AllNull { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::all_null::AllNull; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::all_null::AllNull; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn all_null_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-aggregates/src/bounded_max/mod.rs b/vortex-aggregates/src/bounded_max/mod.rs index ec139d6de26..3b443ffc122 100644 --- a/vortex-aggregates/src/bounded_max/mod.rs +++ b/vortex-aggregates/src/bounded_max/mod.rs @@ -15,9 +15,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; @@ -37,28 +34,10 @@ use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use vortex_array::ArrayRef; -use vortex_array::Columnar; -use vortex_array::ExecutionCtx; -use vortex_array::aggregate_fn::AggregateArgs; -use vortex_array::aggregate_fn::AggregateFnId; -use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::AggregateFnSatisfaction; -use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::builtins::ArrayBuiltins; -use vortex_array::dtype::DType; -use vortex_array::dtype::FieldNames; -use vortex_array::dtype::Nullability; -use vortex_array::dtype::StructFields; -use vortex_array::partial_ord::partial_max; -use vortex_array::scalar::Scalar; -use vortex_array::scalar::ScalarTruncation; -use vortex_array::scalar::upper_bound; +use crate::max::Max; +use crate::min_max::MinMax; +use crate::min_max::columnar_min_max; +use crate::min_max::min_max; /// Field name for the bounded maximum upper-bound value in the partial state. pub const BOUNDED_MAX_BOUND: &str = "bound"; @@ -396,8 +375,6 @@ mod tests { use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::dtype::Nullability; @@ -412,6 +389,8 @@ mod tests { use crate::bounded_max::BoundedMaxOptions; use crate::bounded_max::BoundedMaxPartial; use crate::bounded_max::BoundedMaxState; + use crate::max::Max; + use crate::min::Min; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -420,7 +399,7 @@ mod tests { } fn fresh_session() -> VortexSession { - VortexSession::empty() + SESSION.clone() } #[test] diff --git a/vortex-aggregates/src/bounded_min/mod.rs b/vortex-aggregates/src/bounded_min/mod.rs index f7099f8d399..d24df555ddd 100644 --- a/vortex-aggregates/src/bounded_min/mod.rs +++ b/vortex-aggregates/src/bounded_min/mod.rs @@ -14,9 +14,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; use vortex_array::dtype::DType; use vortex_array::partial_ord::partial_min; use vortex_array::scalar::Scalar; @@ -31,24 +28,10 @@ use vortex_error::vortex_ensure_eq; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use vortex_array::ArrayRef; -use vortex_array::Columnar; -use vortex_array::ExecutionCtx; -use vortex_array::aggregate_fn::AggregateArgs; -use vortex_array::aggregate_fn::AggregateFnId; -use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::AggregateFnSatisfaction; -use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::min_max::columnar_min_max; -use vortex_array::aggregate_fn::fns::min_max::min_max; -use vortex_array::dtype::DType; -use vortex_array::partial_ord::partial_min; -use vortex_array::scalar::Scalar; -use vortex_array::scalar::ScalarTruncation; -use vortex_array::scalar::lower_bound; +use crate::min::Min; +use crate::min_max::MinMax; +use crate::min_max::columnar_min_max; +use crate::min_max::min_max; /// Options for [`BoundedMin`]. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -306,8 +289,6 @@ mod tests { use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::dtype::Nullability; @@ -320,6 +301,8 @@ mod tests { use crate::bounded_min::BoundedMin; use crate::bounded_min::BoundedMinOptions; + use crate::max::Max; + use crate::min::Min; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -328,7 +311,7 @@ mod tests { } fn fresh_session() -> VortexSession { - VortexSession::empty() + SESSION.clone() } #[test] diff --git a/vortex-aggregates/src/combined_tests.rs b/vortex-aggregates/src/combined_tests.rs index bd6000036a5..b38332e8ab3 100644 --- a/vortex-aggregates/src/combined_tests.rs +++ b/vortex-aggregates/src/combined_tests.rs @@ -15,7 +15,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::Dict; @@ -32,9 +31,13 @@ use vortex_session::VortexSession; use crate::combined::Combined; use crate::combined::PairOptions; use crate::mean::Mean; +use crate::sum::Sum; +/// Each test registers its own kernels, so it needs a session no other test shares. fn fresh_session() -> VortexSession { - crate::test_session() + let session = VortexSession::empty(); + crate::initialize(&session); + session } fn dict_of_seven() -> ArrayRef { diff --git a/vortex-aggregates/src/count/grouped.rs b/vortex-aggregates/src/count/grouped.rs index d612c336f8e..cb363ace387 100644 --- a/vortex-aggregates/src/count/grouped.rs +++ b/vortex-aggregates/src/count/grouped.rs @@ -111,7 +111,11 @@ mod tests { use crate::count::Count; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); /// Run a grouped count through the accumulator. fn grouped_count_actual( diff --git a/vortex-aggregates/src/count/mod.rs b/vortex-aggregates/src/count/mod.rs index 333e2f082bd..f9b4303ceb1 100644 --- a/vortex-aggregates/src/count/mod.rs +++ b/vortex-aggregates/src/count/mod.rs @@ -10,7 +10,6 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::nan_count::nan_count; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; @@ -20,6 +19,8 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; +use crate::nan_count::nan_count; + /// Count the number of non-null elements in an array. /// /// Applies to all types. Returns a `u64` count. diff --git a/vortex-array/src/arrays/dict/compute/is_constant.rs b/vortex-aggregates/src/dict/is_constant.rs similarity index 93% rename from vortex-array/src/arrays/dict/compute/is_constant.rs rename to vortex-aggregates/src/dict/is_constant.rs index 2f9fcecc705..cdf7124c338 100644 --- a/vortex-array/src/arrays/dict/compute/is_constant.rs +++ b/vortex-aggregates/src/dict/is_constant.rs @@ -1,19 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::Dict; +use vortex_array::arrays::dict::DictArrayExt; +use vortex_array::arrays::dict::DictArraySlotsExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_mask::Mask; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_constant::is_constant; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::Dict; -use crate::arrays::dict::DictArrayExt; -use crate::arrays::dict::DictArraySlotsExt; -use crate::scalar::Scalar; +use crate::is_constant::IsConstant; +use crate::is_constant::is_constant; /// Dict-specific is_constant kernel. /// diff --git a/vortex-array/src/arrays/dict/compute/is_sorted.rs b/vortex-aggregates/src/dict/is_sorted.rs similarity index 74% rename from vortex-array/src/arrays/dict/compute/is_sorted.rs rename to vortex-aggregates/src/dict/is_sorted.rs index 4470962b8c2..5e24184a2c2 100644 --- a/vortex-array/src/arrays/dict/compute/is_sorted.rs +++ b/vortex-aggregates/src/dict/is_sorted.rs @@ -1,20 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::Dict; +use vortex_array::arrays::dict::DictArrayExt; +use vortex_array::arrays::dict::DictArraySlotsExt; +use vortex_array::arrays::dict::has_fallible_scalar_fn; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; -use super::select::has_fallible_scalar_fn; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::is_sorted::is_sorted; -use crate::aggregate_fn::fns::is_sorted::is_strict_sorted; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::Dict; -use crate::arrays::dict::DictArrayExt; -use crate::arrays::dict::DictArraySlotsExt; -use crate::scalar::Scalar; +use crate::is_sorted::IsSorted; +use crate::is_sorted::is_sorted; +use crate::is_sorted::is_strict_sorted; /// Dict-specific is_sorted kernel. /// diff --git a/vortex-array/src/arrays/dict/compute/min_max.rs b/vortex-aggregates/src/dict/min_max.rs similarity index 88% rename from vortex-array/src/arrays/dict/compute/min_max.rs rename to vortex-aggregates/src/dict/min_max.rs index e8dab67b052..de0f1d5585e 100644 --- a/vortex-array/src/arrays/dict/compute/min_max.rs +++ b/vortex-aggregates/src/dict/min_max.rs @@ -1,20 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::Dict; +use vortex_array::arrays::dict::DictArrayExt; +use vortex_array::arrays::dict::DictArraySlotsExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_mask::Mask; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::make_minmax_dtype; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::Dict; -use crate::arrays::dict::DictArrayExt; -use crate::arrays::dict::DictArraySlotsExt; -use crate::scalar::Scalar; +use crate::min_max::MinMax; +use crate::min_max::make_minmax_dtype; +use crate::min_max::min_max; /// Dict-specific min/max kernel. /// @@ -63,18 +63,18 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::DictArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::builders::dict::dict_encode; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min_max::min_max; - use crate::arrays::DictArray; - use crate::arrays::PrimitiveArray; - use crate::builders::dict::dict_encode; + use crate::min_max::min_max; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-aggregates/src/dict/mod.rs b/vortex-aggregates/src/dict/mod.rs new file mode 100644 index 00000000000..d2dd812d5d2 --- /dev/null +++ b/vortex-aggregates/src/dict/mod.rs @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Aggregate kernels for dictionary-encoded arrays. + +pub(crate) mod is_constant; +pub(crate) mod is_sorted; +pub(crate) mod min_max; diff --git a/vortex-aggregates/src/first/mod.rs b/vortex-aggregates/src/first/mod.rs index a2ab11362f7..2562ca98737 100644 --- a/vortex-aggregates/src/first/mod.rs +++ b/vortex-aggregates/src/first/mod.rs @@ -160,6 +160,7 @@ impl AggregateFnVTable for First { #[cfg(test)] mod tests { + use std::sync::LazyLock; use vortex_array::IntoArray; @@ -186,7 +187,11 @@ mod tests { use crate::first::First; use crate::first::first; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn first_non_null() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/fixed_size_bytes.rs b/vortex-aggregates/src/fixed_size_bytes.rs similarity index 81% rename from vortex-array/src/aggregate_fn/fns/fixed_size_bytes.rs rename to vortex-aggregates/src/fixed_size_bytes.rs index 55c9f612124..8611808e028 100644 --- a/vortex-array/src/aggregate_fn/fns/fixed_size_bytes.rs +++ b/vortex-aggregates/src/fixed_size_bytes.rs @@ -6,17 +6,16 @@ //! This is the storage of byte-string extension types such as UUID, so order-based aggregates can //! support it without implementing general list comparison. +use vortex_array::ExecutionCtx; +use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; +use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; use vortex_error::VortexResult; -use crate::ExecutionCtx; -use crate::arrays::FixedSizeListArray; -use crate::arrays::PrimitiveArray; -use crate::arrays::fixed_size_list::FixedSizeListArrayExt; -use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; - /// Whether `dtype` is a fixed-size list of non-nullable `u8`. pub(crate) fn is_fixed_size_bytes(dtype: &DType) -> bool { matches!( diff --git a/vortex-aggregates/src/framework_tests/accumulator.rs b/vortex-aggregates/src/framework_tests/accumulator.rs new file mode 100644 index 00000000000..f1aaf270bb4 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/accumulator.rs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::LazyLock; + +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VTable; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AccumulatorRef; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::arrays::Dict; +use vortex_array::arrays::DictArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarValue; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::SessionExt; +use vortex_session::VortexSession; + +use crate::min::Min; +use crate::sum::Sum; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +/// A sentinel sum of `42.0`, distinguishable from `dict_of_seven()`'s natural sum of `7.0`. +#[derive(Debug)] +struct SentinelSumPartialKernel; +impl DynAggregateKernel for SentinelSumPartialKernel { + fn aggregate( + &self, + _aggregate_fn: &AggregateFnRef, + _batch: &ArrayRef, + _ctx: &mut ExecutionCtx, + ) -> VortexResult> { + Ok(Some(Scalar::primitive(42.0f64, Nullability::Nullable))) + } +} + +fn fresh_session() -> VortexSession { + SESSION.clone() +} + +fn dict_of_seven() -> ArrayRef { + DictArray::try_new(buffer![0u32].into_array(), buffer![7.0f64].into_array()) + .expect("valid dictionary") + .into_array() +} + +#[test] +fn cached_sum_precedes_encoding_kernel() -> VortexResult<()> { + static KERNEL: SentinelSumPartialKernel = SentinelSumPartialKernel; + let session = fresh_session(); + session + .get::() + .register_aggregate_kernel(Dict.id(), Some(Sum.id()), &KERNEL); + let mut ctx = session.create_execution_ctx(); + + let batch = dict_of_seven(); + batch + .statistics() + .set(Stat::Sum, Precision::Exact(ScalarValue::from(7.0f64))); + + let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); + let mut acc = Accumulator::try_new(Sum, NumericalAggregateOpts::default(), dtype)?; + acc.accumulate(&batch, &mut ctx)?; + + assert_eq!(acc.finish()?.as_primitive().as_::(), Some(7.0)); + Ok(()) +} + +/// Each batch caches its own result, not the running result and not on the canonical array +/// it executes into. +#[test] +fn caches_result_on_requested_batch() -> VortexResult<()> { + let mut ctx = fresh_session().create_execution_ctx(); + let dict = |codes: ArrayRef| -> VortexResult { + Ok(DictArray::try_new(codes, buffer![5i32, 1, 9].into_array())?.into_array()) + }; + let batch1 = dict(buffer![0u32, 1, 2].into_array())?; + let batch2 = dict(buffer![2u32, 0].into_array())?; + + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + let mut acc = Accumulator::try_new(Min, NumericalAggregateOpts::default(), dtype)?; + acc.accumulate(&batch1, &mut ctx)?; + acc.accumulate(&batch2, &mut ctx)?; + + assert_eq!( + acc.finish()?, + Scalar::primitive(1i32, Nullability::Nullable) + ); + assert_eq!( + batch1.statistics().get_as::(Stat::Min), + Precision::exact(1i32) + ); + assert_eq!( + batch2.statistics().get_as::(Stat::Min), + Precision::exact(5i32) + ); + Ok(()) +} + +#[test] +fn overflowed_sum_is_not_cached() -> VortexResult<()> { + let mut ctx = fresh_session().create_execution_ctx(); + let batch = buffer![i64::MAX, i64::MAX].into_array(); + + let dtype = DType::Primitive(PType::I64, Nullability::NonNullable); + let mut acc = Accumulator::try_new(Sum, NumericalAggregateOpts::default(), dtype)?; + acc.accumulate(&batch, &mut ctx)?; + + assert!(acc.finish()?.is_null()); + assert!(batch.statistics().get(Stat::Sum).as_exact().is_none()); + Ok(()) +} + +fn sum_i32_accumulator(options: NumericalAggregateOpts) -> VortexResult { + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + Ok(Box::new(Accumulator::try_new(Sum, options, dtype)?)) +} + +#[test] +fn merge_from_drains_other_accumulator() -> VortexResult<()> { + let mut ctx = fresh_session().create_execution_ctx(); + let mut global = sum_i32_accumulator(NumericalAggregateOpts::default())?; + let mut local = sum_i32_accumulator(NumericalAggregateOpts::default())?; + + global.accumulate(&buffer![10i32, 20].into_array(), &mut ctx)?; + local.accumulate(&buffer![5i32].into_array(), &mut ctx)?; + global.merge_from(local.as_mut())?; + + assert_eq!( + global.finish()?, + Scalar::primitive(35i64, Nullability::Nullable) + ); + // The merged-from accumulator is reset back to the empty state. + assert_eq!( + local.finish()?, + Scalar::primitive(0i64, Nullability::Nullable) + ); + Ok(()) +} + +#[test] +fn merge_from_rejects_a_different_aggregate() -> VortexResult<()> { + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + let mut sum = sum_i32_accumulator(NumericalAggregateOpts::default())?; + let mut min: AccumulatorRef = Box::new(Accumulator::try_new( + Min, + NumericalAggregateOpts::default(), + dtype, + )?); + + assert!(sum.merge_from(min.as_mut()).is_err()); + Ok(()) +} + +#[test] +fn merge_from_rejects_mismatched_options() -> VortexResult<()> { + let mut skipping = sum_i32_accumulator(NumericalAggregateOpts::skip_nans())?; + let mut including = sum_i32_accumulator(NumericalAggregateOpts::include_nans())?; + + assert!(skipping.merge_from(including.as_mut()).is_err()); + Ok(()) +} diff --git a/vortex-aggregates/src/framework_tests/chunked_kernel.rs b/vortex-aggregates/src/framework_tests/chunked_kernel.rs new file mode 100644 index 00000000000..50b212877df --- /dev/null +++ b/vortex-aggregates/src/framework_tests/chunked_kernel.rs @@ -0,0 +1,217 @@ +// 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::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; +use vortex_buffer::Buffer; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::sum::Sum; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +fn run_sum(batch: &vortex_array::ArrayRef) -> VortexResult { + let mut ctx = SESSION.create_execution_ctx(); + let mut acc = Accumulator::try_new( + Sum, + NumericalAggregateOpts::default(), + batch.dtype().clone(), + )?; + acc.accumulate(batch, &mut ctx)?; + acc.finish() +} + +#[test] +fn sum_chunked_i32() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + buffer![1i32, 2, 3].into_array(), + buffer![4i32, 5, 6].into_array(), + ], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(21)); + Ok(()) +} + +#[test] +fn sum_chunked_f64() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + buffer![1.5f64, 2.5].into_array(), + buffer![3.0f64].into_array(), + ], + DType::Primitive(PType::F64, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(7.0)); + Ok(()) +} + +#[test] +fn sum_chunked_with_nulls() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), + PrimitiveArray::from_option_iter([None, Some(5)]).into_array(), + ], + DType::Primitive(PType::I32, Nullability::Nullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(9)); + Ok(()) +} + +#[test] +fn sum_chunked_all_null() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + PrimitiveArray::from_option_iter([None::, None]).into_array(), + PrimitiveArray::from_option_iter([None::]).into_array(), + ], + DType::Primitive(PType::I32, Nullability::Nullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(0)); + Ok(()) +} + +#[test] +fn sum_chunked_single_chunk() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![buffer![10i32, 20, 30].into_array()], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(60)); + Ok(()) +} + +#[test] +fn sum_chunked_empty_chunks() -> VortexResult<()> { + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + let chunked = ChunkedArray::try_new( + vec![ + Buffer::::empty().into_array(), + buffer![1i32, 2, 3].into_array(), + Buffer::::empty().into_array(), + buffer![4i32, 5].into_array(), + Buffer::::empty().into_array(), + ], + dtype, + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(15)); + Ok(()) +} + +#[test] +fn sum_chunked_all_empty() -> VortexResult<()> { + let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); + let chunked = ChunkedArray::try_new(vec![], dtype)?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(0)); + Ok(()) +} + +#[test] +fn sum_chunked_many_small_chunks() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + buffer![1i32].into_array(), + buffer![2i32].into_array(), + buffer![3i32].into_array(), + buffer![4i32].into_array(), + buffer![5i32].into_array(), + ], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(15)); + Ok(()) +} + +#[test] +fn sum_chunked_u64() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![ + buffer![100u64, 200].into_array(), + buffer![300u64].into_array(), + ], + DType::Primitive(PType::U64, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(600)); + Ok(()) +} + +#[test] +fn sum_chunked_bool() -> VortexResult<()> { + let b1: BoolArray = [true, false, true].into_iter().collect(); + let b2: BoolArray = [true, true].into_iter().collect(); + let chunked = ChunkedArray::try_new( + vec![b1.into_array(), b2.into_array()], + DType::Bool(Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(4)); + Ok(()) +} + +#[test] +fn sum_chunked_bool_with_nulls() -> VortexResult<()> { + let b1 = BoolArray::from_iter([Some(true), None, Some(true)]); + let b2 = BoolArray::from_iter([Some(false), None]); + let chunked = ChunkedArray::try_new( + vec![b1.into_array(), b2.into_array()], + DType::Bool(Nullability::Nullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(2)); + Ok(()) +} + +#[test] +fn sum_chunked_checked_overflow() -> VortexResult<()> { + let chunked = ChunkedArray::try_new( + vec![buffer![i64::MAX].into_array(), buffer![1i64].into_array()], + DType::Primitive(PType::I64, Nullability::NonNullable), + )?; + let result = run_sum(&chunked.into_array())?; + assert!(result.is_null()); + Ok(()) +} + +#[test] +fn sum_chunked_nested() -> VortexResult<()> { + let inner = ChunkedArray::try_new( + vec![buffer![1i32, 2].into_array(), buffer![3i32].into_array()], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let outer = ChunkedArray::try_new( + vec![inner.into_array(), buffer![4i32, 5, 6].into_array()], + DType::Primitive(PType::I32, Nullability::NonNullable), + )?; + let result = run_sum(&outer.into_array())?; + assert_eq!(result.as_primitive().typed_value::(), Some(21)); + Ok(()) +} diff --git a/vortex-aggregates/src/framework_tests/core_consistency.rs b/vortex-aggregates/src/framework_tests/core_consistency.rs new file mode 100644 index 00000000000..38f4ede76b0 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/core_consistency.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Aggregate consistency of the core encodings. +//! +//! `test_array_consistency` only checks aggregates when the session registers them, which the +//! core crate's own tests cannot do, so the core encodings are checked here. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DictArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::compute::conformance::consistency::test_slice_aggregate_consistency; +use vortex_buffer::buffer; +use vortex_session::VortexSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[rstest] +#[case::primitive(buffer![5i32, 1, 9, 3, 7, 2, 8].into_array())] +#[case::nullable( + PrimitiveArray::from_option_iter([Some(4u64), None, Some(1), Some(9), None, Some(6), Some(2)]) + .into_array() +)] +#[case::float_with_nan(buffer![1.5f64, f64::NAN, -2.0, 8.25, f64::NAN, 0.0, 3.5].into_array())] +#[case::constant(ConstantArray::new(7i64, 9).into_array())] +#[case::dict( + DictArray::new( + buffer![0u8, 2, 1, 2, 0, 1, 2].into_array(), + buffer![10i32, -3, 42].into_array(), + ) + .into_array() +)] +#[case::chunked( + ChunkedArray::from_iter([ + buffer![3i16, 1, 4].into_array(), + buffer![1i16, 5, 9, 2].into_array(), + ]) + .into_array() +)] +fn core_encodings_aggregate_consistency(#[case] array: ArrayRef) { + test_slice_aggregate_consistency(&array, &mut SESSION.create_execution_ctx()); +} diff --git a/vortex-aggregates/src/framework_tests/extension_validation.rs b/vortex-aggregates/src/framework_tests/extension_validation.rs new file mode 100644 index 00000000000..5c3f44416dd --- /dev/null +++ b/vortex-aggregates/src/framework_tests/extension_validation.rs @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Extrema over an extension type whose storage values can fail validation. + +use std::fmt::Debug; +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFn; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::ExtensionArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::extension::ExtDType; +use vortex_array::dtype::extension::ExtDTypeRef; +use vortex_array::dtype::extension::ExtId; +use vortex_array::dtype::extension::ExtVTable; +use vortex_array::scalar::ScalarValue; +use vortex_buffer::buffer; +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_session::VortexSession; +use vortex_session::registry::CachedId; + +use crate::max::Max; +use crate::min::Min; +use crate::min_max::MinMax; +use crate::min_max::min_max; +use crate::min_max::nan_scalar; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[track_caller] +fn assert_non_zero_error(result: VortexResult, value: &str) { + let error = result.unwrap_err().to_string(); + let expected = format!("NonZero requires a finite nonzero value, got {value}"); + assert!(error.contains(&expected), "{error}"); +} + +/// A test extension that rejects zero and non-finite storage values. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +struct NonZero; + +impl NonZero { + fn dtype(ptype: PType, nullability: Nullability) -> VortexResult { + Ok(ExtDType::::try_new(ptype, nullability)?.erased()) + } + + fn array(storage: ArrayRef) -> VortexResult { + let dtype = Self::dtype(storage.dtype().as_ptype(), storage.dtype().nullability())?; + + Ok(ExtensionArray::try_new(dtype, storage)?.into_array()) + } +} + +impl ExtVTable for NonZero { + type Metadata = PType; + type StoredMetadata = (); + type NativeValue<'a> = &'a ScalarValue; + + fn id(&self) -> ExtId { + static ID: CachedId = CachedId::new("test.non_zero"); + *ID + } + + fn serialize_metadata(&self, _metadata: &Self::Metadata) -> VortexResult> { + Ok(vec![]) + } + + fn deserialize_metadata(&self, _metadata: &[u8]) -> VortexResult { + Ok(()) + } + + fn metadata_from_storage( + &self, + _stored_metadata: Self::StoredMetadata, + storage_dtype: &DType, + ) -> VortexResult { + PType::try_from(storage_dtype) + } + + fn storage_dtype(metadata: &Self::Metadata) -> DType { + DType::Primitive(*metadata, Nullability::NonNullable) + } + + fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> { + vortex_ensure!( + matches!(metadata, PType::I64 | PType::F64), + "NonZero requires i64 or f64 storage, got {metadata}" + ); + + Ok(()) + } + + fn unpack_native<'a>( + _ext_dtype: &'a ExtDType, + storage_value: &'a ScalarValue, + ) -> VortexResult> { + let value = storage_value.as_primitive().cast::()?; + vortex_ensure!( + value.is_finite() && value != 0.0, + "NonZero requires a finite nonzero value, got {value}" + ); + + Ok(storage_value) + } +} + +#[rstest] +#[case::min(AggregateFn::new(Min, NumericalAggregateOpts::default()).erased())] +#[case::max(AggregateFn::new(Max, NumericalAggregateOpts::default()).erased())] +#[case::min_max(AggregateFn::new(MinMax, NumericalAggregateOpts::default()).erased())] +fn test_aggregates_return_extension_validation_errors( + #[case] aggregate: AggregateFnRef, +) -> VortexResult<()> { + let array = NonZero::array(buffer![0i64, 1].into_array())?; + let mut ctx = SESSION.create_execution_ctx(); + let mut accumulator = aggregate.accumulator(array.dtype())?; + + assert_non_zero_error(accumulator.accumulate(&array, &mut ctx), "0"); + + Ok(()) +} + +#[test] +fn test_nan_extrema_return_extension_validation_errors() -> VortexResult<()> { + let array = NonZero::array(buffer![f64::NAN, 1.0].into_array())?; + let mut ctx = SESSION.create_execution_ctx(); + + assert_non_zero_error( + min_max(&array, &mut ctx, NumericalAggregateOpts::include_nans()), + "NaN", + ); + + Ok(()) +} + +#[rstest] +fn test_nan_scalar_returns_extension_validation_errors( + #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, +) -> VortexResult<()> { + let dtype = DType::Extension(NonZero::dtype(PType::F64, nullability)?); + + assert_non_zero_error(nan_scalar(&dtype), "NaN"); + + Ok(()) +} diff --git a/vortex-aggregates/src/framework_tests/listview_is_constant.rs b/vortex-aggregates/src/framework_tests/listview_is_constant.rs new file mode 100644 index 00000000000..89907e8ad68 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/listview_is_constant.rs @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! `is_constant` over list view arrays. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::validity::Validity; +use vortex_buffer::buffer; +use vortex_session::VortexSession; + +use crate::is_constant::is_constant; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +// Parameterized tests for is_constant scenarios. +#[rstest] +#[case::different_sizes( + buffer![1i32, 2, 3, 4], + buffer![0i32, 1, 2], + buffer![1i32, 1, 2], // Different sizes + Validity::NonNullable, + false +)] +#[case::different_elements( + buffer![1i32, 2, 3, 4], + buffer![0i32, 2], + buffer![2i32, 2], // Same size, different elements + Validity::NonNullable, + false +)] +#[case::same_empty_lists( + buffer![99i32], // Dummy element + buffer![0i32, 0, 0], + buffer![0i32, 0, 0], // All empty lists + Validity::NonNullable, + true +)] +#[case::single_list( + buffer![1i32, 2, 3], + buffer![0i32], + buffer![3i32], + Validity::NonNullable, + true +)] +#[case::overlapping_different( + buffer![1i32, 2, 3, 4], + buffer![0i32, 1, 2], // Overlapping but different + buffer![2i32, 2, 2], + Validity::NonNullable, + false +)] +fn test_is_constant_basic( + #[case] elements: vortex_buffer::Buffer, + #[case] offsets: vortex_buffer::Buffer, + #[case] sizes: vortex_buffer::Buffer, + #[case] validity: Validity, + #[case] expected: bool, +) { + let listview = ListViewArray::new( + elements.into_array(), + offsets.into_array(), + sizes.into_array(), + validity, + &mut SESSION.create_execution_ctx(), + ) + .into_array(); + + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!(is_constant(&listview, &mut ctx).unwrap(), expected); +} + +#[test] +fn test_constant_with_constant_elements() { + // Test with ConstantArray as elements - all lists point to same constant value. + // Logical lists: [[42,42], [42,42], [42,42]] + let elements = ConstantArray::new(42i32, 10).into_array(); + let offsets = buffer![0i32, 2, 4].into_array(); + let sizes = buffer![2i32, 2, 2].into_array(); + + let listview = unsafe { + ListViewArray::new_unchecked(elements, offsets, sizes, Validity::NonNullable) + .with_zero_copy_to_list(true) + } + .into_array(); + + // All lists contain [42, 42] so should be constant. + let mut ctx = SESSION.create_execution_ctx(); + assert!(is_constant(&listview, &mut ctx).unwrap()); +} + +#[test] +fn test_constant_with_nulls() { + // Test nullable ListView scenarios. + // Logical lists: [[1,2], [3,4]] (validity varies by case) + let elements = buffer![1i32, 2, 3, 4].into_array(); + let offsets = buffer![0i32, 2].into_array(); + let sizes = buffer![2i32, 2].into_array(); + + // Case 1: Mixed valid and null - not constant. + let validity_mixed = Validity::Array(BoolArray::from_iter(vec![true, false]).into_array()); + let listview_mixed = unsafe { + ListViewArray::new_unchecked( + elements.clone(), + offsets.clone(), + sizes.clone(), + validity_mixed, + ) + .with_zero_copy_to_list(true) + } + .into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert!(!is_constant(&listview_mixed, &mut ctx).unwrap()); + + // Case 2: All nulls - should be constant. + let validity_all_null = Validity::AllInvalid; + let listview_all_null = unsafe { + ListViewArray::new_unchecked(elements, offsets, sizes, validity_all_null) + .with_zero_copy_to_list(true) + } + .into_array(); + let mut ctx2 = SESSION.create_execution_ctx(); + assert!(is_constant(&listview_all_null, &mut ctx2).unwrap()); +} + +#[test] +fn test_constant_repeated_same_lists() { + // Test multiple lists that are identical (overlapping). + // Logical lists: [[10,20,30], [10,20,30], [10,20,30], [10,20,30]] + let elements = buffer![10i32, 20, 30].into_array(); + let offsets = buffer![0i32, 0, 0, 0].into_array(); // All point to same start. + let sizes = buffer![3i32, 3, 3, 3].into_array(); // All same size. + + let mut ctx = SESSION.create_execution_ctx(); + let listview = + ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx).into_array(); + + // All lists are [10, 20, 30] so should be constant. + assert!(is_constant(&listview, &mut ctx).unwrap()); +} diff --git a/vortex-aggregates/src/framework_tests/mod.rs b/vortex-aggregates/src/framework_tests/mod.rs new file mode 100644 index 00000000000..6c27515bd17 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/mod.rs @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Tests of the `vortex_array::aggregate_fn` framework that need concrete aggregate functions. + +mod accumulator; +mod chunked_kernel; +mod core_consistency; +mod extension_validation; +mod listview_is_constant; +mod proto; +mod stats; +mod storage_pushdown; +mod struct_is_constant; +mod union_uncompressed_size; diff --git a/vortex-aggregates/src/framework_tests/proto.rs b/vortex-aggregates/src/framework_tests/proto.rs new file mode 100644 index 00000000000..bace8acf0a3 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/proto.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use std::sync::LazyLock; + +use prost::Message; +use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::session::AggregateFnSession; +use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::dtype::DType; +use vortex_array::proto::expr as pb; +use vortex_array::scalar::Scalar; +use vortex_error::VortexResult; +use vortex_error::vortex_panic; +use vortex_session::VortexSession; + +use crate::combined::PairOptions; +use crate::count::Count; +use crate::first::First; +use crate::is_constant::IsConstant; +use crate::is_sorted::IsSorted; +use crate::is_sorted::IsSortedOptions; +use crate::last::Last; +use crate::max::Max; +use crate::mean::Mean; +use crate::min::Min; +use crate::null_count::NullCount; +use crate::sum::Sum; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty().with::(); + session.allow_unknown(); + session +}); + +/// A minimal serializable aggregate function used solely to exercise the serde round-trip. +#[derive(Clone, Debug)] +struct TestAgg; + +impl AggregateFnVTable for TestAgg { + type Options = EmptyOptions; + type Partial = (); + + #[expect(clippy::disallowed_methods, reason = "test-only id")] + fn id(&self) -> AggregateFnId { + AggregateFnId::new("vortex.test.proto") + } + + fn serialize(&self, _options: &Self::Options) -> VortexResult>> { + Ok(Some(vec![])) + } + + fn deserialize( + &self, + _metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + Ok(EmptyOptions) + } + + fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { + Some(input_dtype.clone()) + } + + fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { + self.return_dtype(options, input_dtype) + } + + fn empty_partial( + &self, + _args: AggregateArgs<'_, Self::Options>, + ) -> VortexResult { + Ok(()) + } + + fn partial_from_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _scalar: &Scalar, + ) -> VortexResult { + Ok(()) + } + + fn merge_partials( + &self, + _args: AggregateArgs<'_, Self::Options>, + _first: Self::Partial, + _second: Self::Partial, + ) -> VortexResult { + Ok(()) + } + + fn to_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &Self::Partial, + ) -> VortexResult { + vortex_panic!("TestAgg is for serde tests only"); + } + + fn is_saturated( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &Self::Partial, + ) -> bool { + true + } + + fn accumulate( + &self, + _args: AggregateArgs<'_, Self::Options>, + _state: &mut Self::Partial, + _batch: &Columnar, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + Ok(()) + } + + fn finalize( + &self, + _args: AggregateArgs<'_, Self::Options>, + partials: ArrayRef, + ) -> VortexResult { + Ok(partials) + } + + fn finalize_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &Self::Partial, + ) -> VortexResult { + vortex_panic!("TestAgg is for serde tests only"); + } +} + +#[test] +fn aggregate_fn_serde() { + let session = VortexSession::empty(); + crate::initialize(&session); + session.aggregate_fns().register(TestAgg); + + let agg_fn = TestAgg.bind(EmptyOptions); + + let serialized = agg_fn.serialize_proto().unwrap(); + let buf = serialized.encode_to_vec(); + let deserialized_proto = pb::AggregateFn::decode(buf.as_slice()).unwrap(); + let deserialized = AggregateFnRef::from_proto(&deserialized_proto, &session).unwrap(); + + assert_eq!(deserialized, agg_fn); +} + +/// The `skip_nans` option must survive a protobuf serialize/deserialize round-trip for the +/// numeric aggregates, including the non-default NaN-including configuration. +#[rstest] +#[case(Sum.bind(NumericalAggregateOpts::skip_nans()))] +#[case(Sum.bind(NumericalAggregateOpts::include_nans()))] +#[case(Count.bind(NumericalAggregateOpts::skip_nans()))] +#[case(Count.bind(NumericalAggregateOpts::include_nans()))] +fn numeric_aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> { + assert_round_trip(agg_fn) +} + +#[rstest] +#[case(First.bind(EmptyOptions))] +#[case(Last.bind(EmptyOptions))] +#[case(IsConstant.bind(EmptyOptions))] +#[case(IsSorted.bind(IsSortedOptions { strict: false }))] +#[case(IsSorted.bind(IsSortedOptions { strict: true }))] +fn aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> { + assert_round_trip(agg_fn) +} + +#[rstest] +fn mean_options_round_trip( + #[values(false, true)] sum_skip_nans: bool, + #[values(false, true)] count_skip_nans: bool, +) -> VortexResult<()> { + assert_round_trip(Mean::combined().bind(PairOptions( + NumericalAggregateOpts { + skip_nans: sum_skip_nans, + }, + NumericalAggregateOpts { + skip_nans: count_skip_nans, + }, + ))) +} + +#[rstest] +#[case(IsSorted.id(), vec![])] +#[case(IsSorted.id(), vec![2])] +#[case(IsSorted.id(), vec![0, 1])] +#[case(Mean::combined().id(), vec![])] +#[case(Mean::combined().id(), vec![0])] +#[case(Mean::combined().id(), vec![2, 0])] +#[case(Mean::combined().id(), vec![0, 2])] +#[case(Mean::combined().id(), vec![0, 1, 0])] +fn invalid_aggregate_options(#[case] id: AggregateFnId, #[case] metadata: Vec) { + let proto = pb::AggregateFn { + id: id.to_string(), + metadata: Some(metadata), + }; + assert!(AggregateFnRef::from_proto(&proto, &initialized_session()).is_err()); +} + +fn initialized_session() -> VortexSession { + let session = VortexSession::empty(); + crate::initialize(&session); + session +} + +fn assert_round_trip(agg_fn: AggregateFnRef) -> VortexResult<()> { + let proto = agg_fn.serialize_proto()?; + let buf = proto.encode_to_vec(); + let decoded = pb::AggregateFn::decode(buf.as_slice())?; + let round_tripped = AggregateFnRef::from_proto(&decoded, &initialized_session())?; + + assert_eq!(round_tripped, agg_fn); + Ok(()) +} + +#[test] +fn unknown_aggregate_fn_id_allow_unknown() { + let proto = pb::AggregateFn { + id: "vortex.test.foreign_aggregate".to_string(), + metadata: Some(vec![7, 8, 9]), + }; + + let agg_fn = AggregateFnRef::from_proto(&proto, &SESSION).unwrap(); + assert_eq!(agg_fn.id().as_ref(), "vortex.test.foreign_aggregate"); + + let roundtrip = agg_fn.serialize_proto().unwrap(); + assert_eq!(roundtrip.id, proto.id); + assert_eq!(roundtrip.metadata(), proto.metadata()); +} + +/// Pins the persisted encoding: `serialize_proto` output is stored in zoned layout metadata, +/// so any change to these bytes breaks existing files. +#[rstest] +#[case::empty_options(IsConstant.bind(EmptyOptions), b"\x0a\x12vortex.is_constant\x12\x00".as_slice())] +#[case::numeric_options(Sum.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.sum\x12\x02\x08\x01".as_slice())] +#[case::numeric_default_options(Sum.bind(NumericalAggregateOpts::include_nans()), b"\x0a\x0avortex.sum\x12\x00".as_slice())] +#[case::count(Count.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0cvortex.count\x12\x02\x08\x01".as_slice())] +#[case::min(Min.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.min\x12\x02\x08\x01".as_slice())] +#[case::max(Max.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.max\x12\x02\x08\x01".as_slice())] +#[case::first(First.bind(EmptyOptions), b"\x0a\x0cvortex.first\x12\x00".as_slice())] +#[case::last(Last.bind(EmptyOptions), b"\x0a\x0bvortex.last\x12\x00".as_slice())] +#[case::null_count(NullCount.bind(EmptyOptions), b"\x0a\x11vortex.null_count\x12\x00".as_slice())] +#[case::is_sorted(IsSorted.bind(IsSortedOptions { strict: true }), b"\x0a\x10vortex.is_sorted\x12\x01\x01".as_slice())] +#[case::mean_options( + Mean::combined().bind(PairOptions( + NumericalAggregateOpts::skip_nans(), + NumericalAggregateOpts::include_nans(), + )), + b"\x0a\x0bvortex.mean\x12\x02\x01\x00".as_slice(), +)] +fn golden_encoding(#[case] agg_fn: AggregateFnRef, #[case] bytes: &[u8]) -> VortexResult<()> { + assert_eq!(agg_fn.serialize_proto()?.encode_to_vec(), bytes); + let decoded = pb::AggregateFn::decode(bytes)?; + assert_eq!( + AggregateFnRef::from_proto(&decoded, &initialized_session())?, + agg_fn + ); + Ok(()) +} + +/// Zoned layouts written before `vortex.expr.AggregateFn` replaced their private spec message +/// omit the options field when it is empty. Absent metadata must read as empty options. +#[rstest] +#[case::empty_options(b"\x0a\x12vortex.is_constant".as_slice(), IsConstant.bind(EmptyOptions))] +#[case::numeric_default_options(b"\x0a\x0avortex.sum".as_slice(), Sum.bind(NumericalAggregateOpts::include_nans()))] +fn decodes_absent_metadata( + #[case] bytes: &[u8], + #[case] expected: AggregateFnRef, +) -> VortexResult<()> { + let decoded = pb::AggregateFn::decode(bytes)?; + assert!(decoded.metadata.is_none()); + assert_eq!( + AggregateFnRef::from_proto(&decoded, &initialized_session())?, + expected + ); + Ok(()) +} + +#[test] +fn from_parts_unknown_id_is_none() -> VortexResult<()> { + let session = VortexSession::empty(); + #[expect(clippy::disallowed_methods, reason = "test-only id")] + let id = AggregateFnId::new("vortex.test.unknown"); + assert!(AggregateFnRef::from_parts(id, &[], &session)?.is_none()); + Ok(()) +} diff --git a/vortex-aggregates/src/framework_tests/stats.rs b/vortex-aggregates/src/framework_tests/stats.rs new file mode 100644 index 00000000000..89cdacaad79 --- /dev/null +++ b/vortex-aggregates/src/framework_tests/stats.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Computing array statistics through the registered aggregate functions. + +use std::sync::LazyLock; + +use enum_iterator::all; +use itertools::Itertools; +use vortex_array::Canonical; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::scalar::ScalarValue; +use vortex_array::validity::Validity; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[test] +fn test_uncompressed_size_in_bytes() -> VortexResult<()> { + let struct_array = StructArray::new( + FieldNames::from(["integers"]), + vec![ConstantArray::new(5, 1000).into_array()], + 1000, + Validity::NonNullable, + ); + + let canonical_size = struct_array + .clone() + .into_array() + .execute::(&mut SESSION.create_execution_ctx())? + .into_array() + .nbytes(); + let uncompressed_size = struct_array + .statistics() + .compute_uncompressed_size_in_bytes(&mut SESSION.create_execution_ctx()); + + assert_eq!(canonical_size, 2); + assert_eq!(uncompressed_size, Some(4000)); + Ok(()) +} + +#[test] +fn merge_unordered() { + let array = + PrimitiveArray::from_option_iter([Some(1), None, Some(2), Some(42), Some(10000), None]); + let all_stats = all::() + .filter(|s| !matches!(s, Stat::Sum)) + .filter(|s| !matches!(s, Stat::NaNCount)) + .collect_vec(); + array + .statistics() + .compute_all(&all_stats, &mut SESSION.create_execution_ctx()) + .unwrap(); + + let stats = array.statistics().to_owned(); + for stat in &all_stats { + assert!(!stats.get(*stat).is_absent(), "Stat {stat} is missing"); + } + + let merged = stats.clone().merge_unordered( + &stats, + &DType::Primitive(PType::I32, Nullability::NonNullable), + ); + for (stat, expected) in [ + (Stat::Min, Precision::exact(ScalarValue::from(1i32))), + (Stat::Max, Precision::exact(ScalarValue::from(10000i32))), + (Stat::NullCount, Precision::exact(ScalarValue::from(4u64))), + ( + Stat::UncompressedSizeInBytes, + Precision::exact(ScalarValue::from(50u64)), + ), + (Stat::IsConstant, Precision::exact(ScalarValue::from(false))), + (Stat::IsSorted, Precision::Absent), + (Stat::IsStrictSorted, Precision::Absent), + ] { + assert_eq!(merged.get(stat), expected, "{stat}"); + } +} diff --git a/vortex-aggregates/src/framework_tests/storage_pushdown.rs b/vortex-aggregates/src/framework_tests/storage_pushdown.rs new file mode 100644 index 00000000000..6d5ea8ec00d --- /dev/null +++ b/vortex-aggregates/src/framework_tests/storage_pushdown.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! [`ExtensionStoragePushdown`] over the order-based aggregates. + +use std::sync::LazyLock; + +use rstest::rstest; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::ExtensionStoragePushdown; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::extension::datetime::Date; +use vortex_array::extension::datetime::Duration; +use vortex_array::extension::datetime::Time; +use vortex_array::extension::datetime::TimeUnit; +use vortex_array::extension::datetime::Timestamp; +use vortex_array::scalar::Scalar; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::is_sorted::IsSorted; +use crate::is_sorted::IsSortedOptions; +use crate::min_max::MinMax; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[test] +fn pushes_down_into_storage() -> VortexResult<()> { + let session = VortexSession::empty(); + crate::initialize(&session); + let aggregate = ExtensionStoragePushdown::new(MinMax, Timestamp); + session.aggregate_fns().register(aggregate.clone()); + assert!( + session + .aggregate_fns() + .find_plugin(&aggregate.id()) + .is_some() + ); + + let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); + let storage = + PrimitiveArray::from_option_iter([Some(3_000i64), None, Some(1_000)]).into_array(); + let array = ExtensionArray::new(ext_dtype.clone(), storage.clone()).into_array(); + + let mut ctx = session.create_execution_ctx(); + let mut acc = Accumulator::try_new( + aggregate, + NumericalAggregateOpts::default(), + DType::Extension(ext_dtype), + )?; + acc.accumulate(&array, &mut ctx)?; + + let mut expected = Accumulator::try_new( + MinMax, + NumericalAggregateOpts::default(), + storage.dtype().clone(), + )?; + expected.accumulate(&storage, &mut ctx)?; + + assert_eq!(acc.finish()?, expected.finish()?); + Ok(()) +} + +#[test] +fn combines_flushed_partials() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); + let batch = |values: [Option; 2]| { + ExtensionArray::new( + ext_dtype.clone(), + PrimitiveArray::from_option_iter(values).into_array(), + ) + .into_array() + }; + let accumulator = || { + Accumulator::try_new( + ExtensionStoragePushdown::new(MinMax, Timestamp), + NumericalAggregateOpts::default(), + DType::Extension(ext_dtype.clone()), + ) + }; + + let mut first = accumulator()?; + first.accumulate(&batch([Some(3_000), None]), &mut ctx)?; + let mut second = accumulator()?; + second.accumulate(&batch([Some(1_000), Some(500)]), &mut ctx)?; + first.combine_partials(&second.flush()?)?; + + let mut expected = accumulator()?; + expected.accumulate(&batch([Some(3_000), None]), &mut ctx)?; + expected.accumulate(&batch([Some(1_000), Some(500)]), &mut ctx)?; + + assert_eq!(first.finish()?, expected.finish()?); + Ok(()) +} + +#[test] +fn accumulates_constant_batches() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); + let constant = |value: i64| { + ConstantArray::new( + Scalar::extension_ref( + ext_dtype.clone(), + Scalar::primitive(value, Nullability::Nullable), + ), + 3, + ) + .into_array() + }; + + let mut acc = Accumulator::try_new( + ExtensionStoragePushdown::new(MinMax, Timestamp), + NumericalAggregateOpts::default(), + DType::Extension(ext_dtype.clone()), + )?; + acc.accumulate(&constant(2_000), &mut ctx)?; + acc.accumulate(&constant(1_000), &mut ctx)?; + + let mut expected = Accumulator::try_new( + MinMax, + NumericalAggregateOpts::default(), + ext_dtype.storage_dtype().clone(), + )?; + expected.accumulate( + &PrimitiveArray::from_option_iter([Some(2_000i64), Some(1_000)]).into_array(), + &mut ctx, + )?; + + assert_eq!(acc.finish()?, expected.finish()?); + Ok(()) +} + +#[test] +fn rejects_other_extension_types() { + let date = DType::Extension(Date::new(TimeUnit::Days, Nullability::Nullable).erased()); + assert!( + ExtensionStoragePushdown::new(MinMax, Timestamp) + .return_dtype(&NumericalAggregateOpts::default(), &date) + .is_none() + ); +} + +#[test] +fn default_session_registers_temporal_order_aggregates() { + let aggregate_fns = SESSION.aggregate_fns(); + for id in [ + ExtensionStoragePushdown::new(IsSorted, Date).id(), + ExtensionStoragePushdown::new(IsSorted, Duration).id(), + ExtensionStoragePushdown::new(IsSorted, Time).id(), + ExtensionStoragePushdown::new(IsSorted, Timestamp).id(), + ExtensionStoragePushdown::new(MinMax, Date).id(), + ExtensionStoragePushdown::new(MinMax, Duration).id(), + ExtensionStoragePushdown::new(MinMax, Time).id(), + ExtensionStoragePushdown::new(MinMax, Timestamp).id(), + ] { + assert!( + aggregate_fns.find_plugin(&id).is_some(), + "{id} is not registered" + ); + } +} + +#[rstest] +// Nulls sort first. +#[case::sorted([None, Some(1_000), Some(2_000), Some(2_000)], false, true)] +#[case::unsorted([Some(2_000), Some(1_000), None, Some(3_000)], false, false)] +#[case::strict_with_duplicates([None, Some(1_000), Some(2_000), Some(2_000)], true, false)] +fn is_sorted_over_timestamps( + #[case] values: [Option; 4], + #[case] strict: bool, + #[case] expected: bool, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); + let array = ExtensionArray::new( + ext_dtype.clone(), + PrimitiveArray::from_option_iter(values).into_array(), + ) + .into_array(); + + let mut acc = Accumulator::try_new( + ExtensionStoragePushdown::new(IsSorted, Timestamp), + IsSortedOptions { strict }, + DType::Extension(ext_dtype), + )?; + acc.accumulate(&array, &mut ctx)?; + + assert_eq!(bool::try_from(&acc.finish()?)?, expected); + Ok(()) +} + +#[test] +fn min_max_over_dates_matches_storage() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let ext_dtype = Date::new(TimeUnit::Days, Nullability::Nullable).erased(); + let storage = + PrimitiveArray::from_option_iter([Some(20i32), None, Some(-3), Some(7)]).into_array(); + let array = ExtensionArray::new(ext_dtype.clone(), storage.clone()).into_array(); + + let mut acc = Accumulator::try_new( + ExtensionStoragePushdown::new(MinMax, Date), + NumericalAggregateOpts::default(), + DType::Extension(ext_dtype), + )?; + acc.accumulate(&array, &mut ctx)?; + + let mut expected = Accumulator::try_new( + MinMax, + NumericalAggregateOpts::default(), + storage.dtype().clone(), + )?; + expected.accumulate(&storage, &mut ctx)?; + + assert_eq!(acc.finish()?, expected.finish()?); + Ok(()) +} diff --git a/vortex-aggregates/src/framework_tests/struct_is_constant.rs b/vortex-aggregates/src/framework_tests/struct_is_constant.rs new file mode 100644 index 00000000000..a08db4d293f --- /dev/null +++ b/vortex-aggregates/src/framework_tests/struct_is_constant.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! `is_constant` over struct arrays. + +use std::sync::LazyLock; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::StructArray; +use vortex_error::VortexExpect; +use vortex_session::VortexSession; + +use crate::is_constant::is_constant; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +#[test] +fn test_empty_struct_is_constant() { + let array = StructArray::new_fieldless_with_len(2); + let mut ctx = SESSION.create_execution_ctx(); + let result = is_constant(&array.into_array(), &mut ctx) + .vortex_expect("operation should succeed in test"); + assert!(result); +} diff --git a/vortex-aggregates/src/framework_tests/union_uncompressed_size.rs b/vortex-aggregates/src/framework_tests/union_uncompressed_size.rs new file mode 100644 index 00000000000..1e5548a20fe --- /dev/null +++ b/vortex-aggregates/src/framework_tests/union_uncompressed_size.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! The uncompressed size of union arrays. + +use std::sync::LazyLock; + +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::arrays::ConstantArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::UnionVariants; +use vortex_array::scalar::Scalar; +use vortex_error::VortexResult; +use vortex_session::VortexSession; + +use crate::uncompressed_size_in_bytes::uncompressed_size_in_bytes; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +fn variants() -> VortexResult { + UnionVariants::try_new( + ["number", "flag"].into(), + vec![ + DType::Primitive(PType::I32, Nullability::NonNullable), + DType::Bool(Nullability::NonNullable), + ], + vec![5, 9], + ) +} + +#[test] +fn constant_union_reports_uncompressed_size() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let scalar = Scalar::union(variants()?, 5, 10i32.into(), Nullability::NonNullable)?; + + // Four `u8` type IDs, four `i32` rows, and four `bool` placeholder bits rounded up to a byte. + let size = uncompressed_size_in_bytes(&ConstantArray::new(scalar, 4).into_array(), &mut ctx)?; + + assert_eq!(size, 4 + 4 * 4 + 1); + + Ok(()) +} diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/bool.rs b/vortex-aggregates/src/is_constant/bool.rs similarity index 76% rename from vortex-array/src/aggregate_fn/fns/is_constant/bool.rs rename to vortex-aggregates/src/is_constant/bool.rs index 967f19058b6..4b936c948eb 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/bool.rs +++ b/vortex-aggregates/src/is_constant/bool.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use crate::arrays::BoolArray; -use crate::arrays::bool::BoolArrayExt; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::bool::BoolArrayExt; pub(super) fn check_bool_constant(array: &BoolArray) -> bool { let true_count = array.bit_buffer_view().true_count(); diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs b/vortex-aggregates/src/is_constant/decimal.rs similarity index 82% rename from vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs rename to vortex-aggregates/src/is_constant/decimal.rs index 1bf7ba4818d..502990e4d29 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/decimal.rs +++ b/vortex-aggregates/src/is_constant/decimal.rs @@ -2,9 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use itertools::Itertools; - -use crate::arrays::DecimalArray; -use crate::match_each_decimal_value_type; +use vortex_array::arrays::DecimalArray; +use vortex_array::match_each_decimal_value_type; pub(super) fn check_decimal_constant(array: &DecimalArray) -> bool { match_each_decimal_value_type!(array.values_type(), |S| { diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/extension.rs b/vortex-aggregates/src/is_constant/extension.rs similarity index 75% rename from vortex-array/src/aggregate_fn/fns/is_constant/extension.rs rename to vortex-aggregates/src/is_constant/extension.rs index fa9393ede64..daf6eb8881f 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/extension.rs +++ b/vortex-aggregates/src/is_constant/extension.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_error::VortexResult; use super::is_constant; -use crate::ExecutionCtx; -use crate::arrays::ExtensionArray; -use crate::arrays::extension::ExtensionArrayExt; /// Check if an extension array is constant by delegating to its storage array. pub(super) fn check_extension_constant( diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/fixed_size_list.rs b/vortex-aggregates/src/is_constant/fixed_size_list.rs similarity index 82% rename from vortex-array/src/aggregate_fn/fns/is_constant/fixed_size_list.rs rename to vortex-aggregates/src/is_constant/fixed_size_list.rs index 1382f34344a..62848184e99 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/fixed_size_list.rs +++ b/vortex-aggregates/src/is_constant/fixed_size_list.rs @@ -1,15 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; +use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; +use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use vortex_error::VortexResult; use super::arrays_value_equal; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::RecursiveCanonical; -use crate::arrays::FixedSizeListArray; -use crate::arrays::fixed_size_list::FixedSizeListArrayExt; -use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; /// Check if a fixed-size list array is constant by comparing each list's elements. /// diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/list.rs b/vortex-aggregates/src/is_constant/list.rs similarity index 89% rename from vortex-array/src/aggregate_fn/fns/is_constant/list.rs rename to vortex-aggregates/src/is_constant/list.rs index db9e91c6ad1..7f628fa1e1f 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/list.rs +++ b/vortex-aggregates/src/is_constant/list.rs @@ -1,16 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::listview::ListViewArrayExt; +use vortex_array::arrays::listview::ListViewArraySlotsExt; use vortex_error::VortexResult; use super::arrays_value_equal; use super::is_constant; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::RecursiveCanonical; -use crate::arrays::ListViewArray; -use crate::arrays::listview::ListViewArrayExt; -use crate::arrays::listview::ListViewArraySlotsExt; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; /// Check if a list view array is constant by comparing each list's elements. /// diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/map.rs b/vortex-aggregates/src/is_constant/map.rs similarity index 69% rename from vortex-array/src/aggregate_fn/fns/is_constant/map.rs rename to vortex-aggregates/src/is_constant/map.rs index 63d82b463d9..b44d97c4b13 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/map.rs +++ b/vortex-aggregates/src/is_constant/map.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ListView; +use vortex_array::arrays::MapArray; +use vortex_array::arrays::map::MapArraySlotsExt; use vortex_error::VortexResult; use super::list::check_listview_constant; -use crate::ExecutionCtx; -use crate::arrays::ListView; -use crate::arrays::MapArray; -use crate::arrays::map::MapArraySlotsExt; pub(super) fn check_map_constant(map: &MapArray, ctx: &mut ExecutionCtx) -> VortexResult { check_listview_constant(&map.entries().as_::().into_owned(), ctx) diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs b/vortex-aggregates/src/is_constant/mod.rs similarity index 91% rename from vortex-array/src/aggregate_fn/fns/is_constant/mod.rs rename to vortex-aggregates/src/is_constant/mod.rs index 9829ec3a362..4c476e340b1 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/mod.rs +++ b/vortex-aggregates/src/is_constant/mod.rs @@ -13,12 +13,35 @@ mod varbin; use std::mem; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::arrays::Constant; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::operators::Operator; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_mask::Mask; use vortex_session::VortexSession; -use vortex_session::registry::CachedId; use self::bool::check_bool_constant; use self::decimal::check_decimal_constant; @@ -29,31 +52,8 @@ use self::map::check_map_constant; use self::primitive::check_primitive_constant; use self::struct_::check_struct_constant; use self::varbin::check_varbinview_constant; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::stat_aggregates; -use crate::arrays::Constant; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::StructFields; -use crate::scalar::Scalar; -use crate::scalar_fn::builtin::operators::CompareMode; -use crate::scalar_fn::builtin::operators::CompareOperator; -use crate::stats::Precision; -use crate::stats::Stat; -use crate::stats::StatsProvider; -use crate::stats::StatsProviderExt; +use vortex_array::scalar_fn::builtin::operators::CompareMode; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; /// Check if two arrays of the same length have equal values at every position (null-safe). /// @@ -90,7 +90,7 @@ fn arrays_value_equal(a: &ArrayRef, b: &ArrayRef, ctx: &mut ExecutionCtx) -> Vor /// /// An array is constant IFF at least one of the following conditions apply: /// 1. It has at least one element (**Note** - an empty array isn't constant). -/// 2. It's encoded as a [`ConstantArray`](crate::arrays::ConstantArray) or [`NullArray`](crate::arrays::NullArray) +/// 2. It's encoded as a [`ConstantArray`](vortex_array::arrays::ConstantArray) or [`NullArray`](vortex_array::arrays::NullArray) /// 3. Has an exact statistic attached to it, saying its constant. /// 4. Is all invalid. /// 5. Is all valid AND has minimum and maximum statistics that are equal. @@ -482,54 +482,59 @@ impl AggregateFnVTable for IsConstant { #[cfg(test)] mod tests { + use std::sync::LazyLock; use rstest::rstest; + use vortex_array::IntoArray as _; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::DictArray; + use vortex_array::arrays::ListArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; + use vortex_array::arrays::runend::RunEnd; + use vortex_array::assert_arrays_eq; + use vortex_array::builders::MapBuilder; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::FieldNames; + use vortex_array::dtype::MapDType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray as _; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::fns::is_constant::IsConstant; - use crate::aggregate_fn::fns::is_constant::IsConstantPartial; - use crate::aggregate_fn::fns::is_constant::is_constant; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::DecimalArray; - use crate::arrays::DictArray; - use crate::arrays::ListArray; - use crate::arrays::ListViewArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::StructArray; - use crate::arrays::runend::RunEnd; - use crate::assert_arrays_eq; - use crate::builders::MapBuilder; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::FieldNames; - use crate::dtype::MapDType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::stats::Stat; - use crate::validity::Validity; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::is_constant::IsConstant; + use crate::is_constant::IsConstantPartial; + use crate::is_constant::is_constant; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); type MapEntryFixture<'a> = (i32, Option<&'a str>); type MapRowFixture<'a> = Option>>; - fn map_array_from_rows(rows: &[MapRowFixture<'_>]) -> VortexResult { + fn map_array_from_rows(rows: &[MapRowFixture<'_>]) -> VortexResult { let map_dtype = MapDType::try_new( DType::Primitive(PType::I32, Nullability::NonNullable), DType::Utf8(Nullability::Nullable), diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/primitive.rs b/vortex-aggregates/src/is_constant/primitive.rs similarity index 94% rename from vortex-array/src/aggregate_fn/fns/is_constant/primitive.rs rename to vortex-aggregates/src/is_constant/primitive.rs index c078f4dab09..5f6189a1fb8 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/primitive.rs +++ b/vortex-aggregates/src/is_constant/primitive.rs @@ -1,11 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::arrays::PrimitiveArray; +use vortex_array::match_each_ptype_width; use vortex_error::VortexExpect; -use crate::arrays::PrimitiveArray; -use crate::match_each_ptype_width; - cfg_if::cfg_if! { if #[cfg(target_feature = "avx2")] { pub const IS_CONST_LANE_WIDTH: usize = 32; @@ -58,9 +57,9 @@ pub(super) fn check_primitive_constant(array: &PrimitiveArray) -> bool { #[cfg(test)] mod tests { use rstest::rstest; + use vortex_array::arrays::PrimitiveArray; use super::check_primitive_constant; - use crate::arrays::PrimitiveArray; #[rstest] #[case::zero(&[0], true)] diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/struct_.rs b/vortex-aggregates/src/is_constant/struct_.rs similarity index 79% rename from vortex-array/src/aggregate_fn/fns/is_constant/struct_.rs rename to vortex-aggregates/src/is_constant/struct_.rs index 84c829dfaca..2ca5f311217 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/struct_.rs +++ b/vortex-aggregates/src/is_constant/struct_.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::struct_::StructArrayExt; use vortex_error::VortexResult; use super::is_constant; -use crate::ExecutionCtx; -use crate::arrays::StructArray; -use crate::arrays::struct_::StructArrayExt; /// Check if a struct array is constant by checking each field independently. pub(super) fn check_struct_constant(s: &StructArray, ctx: &mut ExecutionCtx) -> VortexResult { diff --git a/vortex-array/src/aggregate_fn/fns/is_constant/varbin.rs b/vortex-aggregates/src/is_constant/varbin.rs similarity index 93% rename from vortex-array/src/aggregate_fn/fns/is_constant/varbin.rs rename to vortex-aggregates/src/is_constant/varbin.rs index aff91f0fffa..27d6205add4 100644 --- a/vortex-array/src/aggregate_fn/fns/is_constant/varbin.rs +++ b/vortex-aggregates/src/is_constant/varbin.rs @@ -1,11 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::varbinview::Ref; use vortex_error::VortexExpect; -use crate::arrays::VarBinViewArray; -use crate::arrays::varbinview::Ref; - pub(super) fn check_varbinview_constant(array: &VarBinViewArray) -> bool { let mut views_iter = array.views().iter(); let first_value = views_iter diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs b/vortex-aggregates/src/is_sorted/bool.rs similarity index 91% rename from vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs rename to vortex-aggregates/src/is_sorted/bool.rs index 27a67c400d1..41f648bdbbb 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/bool.rs +++ b/vortex-aggregates/src/is_sorted/bool.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::bool::BoolArrayExt; use vortex_error::VortexResult; use vortex_mask::Mask; use super::IsSortedIteratorExt; -use crate::ExecutionCtx; -use crate::arrays::BoolArray; -use crate::arrays::bool::BoolArrayExt; pub(super) fn check_bool_sorted( array: &BoolArray, diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/decimal.rs b/vortex-aggregates/src/is_sorted/decimal.rs similarity index 90% rename from vortex-array/src/aggregate_fn/fns/is_sorted/decimal.rs rename to vortex-aggregates/src/is_sorted/decimal.rs index 1a9fc96aad2..e31e6147897 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/decimal.rs +++ b/vortex-aggregates/src/is_sorted/decimal.rs @@ -2,14 +2,14 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use itertools::Itertools; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::DecimalArray; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::match_each_decimal_value_type; use vortex_error::VortexResult; use vortex_mask::Mask; use super::IsSortedIteratorExt; -use crate::ExecutionCtx; -use crate::arrays::DecimalArray; -use crate::dtype::NativeDecimalType; -use crate::match_each_decimal_value_type; pub(super) fn check_decimal_sorted( array: &DecimalArray, diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/fixed_size_list.rs b/vortex-aggregates/src/is_sorted/fixed_size_list.rs similarity index 86% rename from vortex-array/src/aggregate_fn/fns/is_sorted/fixed_size_list.rs rename to vortex-aggregates/src/is_sorted/fixed_size_list.rs index 3ef6b2546c4..b48abb25b7e 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/fixed_size_list.rs +++ b/vortex-aggregates/src/is_sorted/fixed_size_list.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::FixedSizeListArray; use vortex_error::VortexResult; use super::IsSortedIteratorExt; -use crate::ExecutionCtx; -use crate::aggregate_fn::fns::fixed_size_bytes::FixedSizeBytes; -use crate::arrays::FixedSizeListArray; +use crate::fixed_size_bytes::FixedSizeBytes; /// Check whether a fixed-size list of bytes is sorted by byte, with nulls first. pub(super) fn check_fixed_size_bytes_sorted( diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs b/vortex-aggregates/src/is_sorted/mod.rs similarity index 93% rename from vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs rename to vortex-aggregates/src/is_sorted/mod.rs index def2e2fd092..bb845877a37 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/mod.rs +++ b/vortex-aggregates/src/is_sorted/mod.rs @@ -9,39 +9,37 @@ mod varbin; use std::mem; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::stat_aggregates; +pub use vortex_array::aggregate_fn::stat_aggregates::IsSortedOptions; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::StructFields; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProviderExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use vortex_error::vortex_bail; -use vortex_session::registry::CachedId; use self::bool::check_bool_sorted; use self::decimal::check_decimal_sorted; use self::fixed_size_list::check_fixed_size_bytes_sorted; use self::primitive::check_primitive_sorted; use self::varbin::check_varbinview_sorted; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::fns::fixed_size_bytes::is_fixed_size_bytes; -use crate::aggregate_fn::stat_aggregates; -pub use crate::aggregate_fn::stat_aggregates::IsSortedOptions; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::StructFields; -use crate::scalar::Scalar; -use crate::stats::Precision; -use crate::stats::Stat; -use crate::stats::StatsProviderExt; +use crate::fixed_size_bytes::is_fixed_size_bytes; /// Compute whether an array is sorted in non-decreasing order. /// @@ -614,49 +612,54 @@ where #[cfg(test)] mod tests { + use std::sync::LazyLock; use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::DictArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::arrays::runend::RunEnd; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::fns::is_sorted::IsSorted; - use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; - use crate::aggregate_fn::fns::is_sorted::IsSortedPartial; - use crate::aggregate_fn::fns::is_sorted::is_sorted; - use crate::aggregate_fn::fns::is_sorted::is_strict_sorted; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::DecimalArray; - use crate::arrays::DictArray; - use crate::arrays::ListViewArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::VarBinViewArray; - use crate::arrays::runend::RunEnd; - use crate::assert_arrays_eq; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::stats::Precision; - use crate::stats::Stat; - use crate::validity::Validity; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::is_sorted::IsSorted; + use crate::is_sorted::IsSortedOptions; + use crate::is_sorted::IsSortedPartial; + use crate::is_sorted::is_sorted; + use crate::is_sorted::is_strict_sorted; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn singleton_ignores_stale_sortedness_stats() -> VortexResult<()> { @@ -774,6 +777,9 @@ mod tests { // Tests migrated from arrays/decimal/compute/is_sorted.rs #[test] fn test_decimal_is_sorted() -> VortexResult<()> { + use vortex_array::arrays::DecimalArray; + use vortex_array::dtype::DecimalDType; + let mut ctx = SESSION.create_execution_ctx(); let dtype = DecimalDType::new(19, 2); // "100.00" and "200.00" at scale 2. diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/primitive.rs b/vortex-aggregates/src/is_sorted/primitive.rs similarity index 87% rename from vortex-array/src/aggregate_fn/fns/is_sorted/primitive.rs rename to vortex-aggregates/src/is_sorted/primitive.rs index da9cc12b7aa..284c6bf9833 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/primitive.rs +++ b/vortex-aggregates/src/is_sorted/primitive.rs @@ -2,15 +2,15 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use itertools::Itertools; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::NativeValue; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_native_ptype; use vortex_error::VortexResult; use vortex_mask::Mask; use super::IsSortedIteratorExt; -use crate::ExecutionCtx; -use crate::arrays::PrimitiveArray; -use crate::arrays::primitive::NativeValue; -use crate::dtype::NativePType; -use crate::match_each_native_ptype; pub(super) fn check_primitive_sorted( array: &PrimitiveArray, diff --git a/vortex-array/src/aggregate_fn/fns/is_sorted/varbin.rs b/vortex-aggregates/src/is_sorted/varbin.rs similarity index 93% rename from vortex-array/src/aggregate_fn/fns/is_sorted/varbin.rs rename to vortex-aggregates/src/is_sorted/varbin.rs index 9e17e12e291..4ee932546fa 100644 --- a/vortex-array/src/aggregate_fn/fns/is_sorted/varbin.rs +++ b/vortex-aggregates/src/is_sorted/varbin.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::VarBinViewArray; use vortex_error::VortexResult; use super::IsSortedIteratorExt; -use crate::ExecutionCtx; -use crate::arrays::VarBinViewArray; pub(super) fn check_varbinview_sorted( array: &VarBinViewArray, diff --git a/vortex-aggregates/src/last/mod.rs b/vortex-aggregates/src/last/mod.rs index e8ed09d2437..edeb9e8cf9f 100644 --- a/vortex-aggregates/src/last/mod.rs +++ b/vortex-aggregates/src/last/mod.rs @@ -158,6 +158,7 @@ impl AggregateFnVTable for Last { #[cfg(test)] mod tests { + use std::sync::LazyLock; use vortex_array::IntoArray; @@ -184,7 +185,11 @@ mod tests { use crate::last::Last; use crate::last::last; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn last_non_null() -> VortexResult<()> { diff --git a/vortex-aggregates/src/lib.rs b/vortex-aggregates/src/lib.rs index d7a94648c6a..216a8193814 100644 --- a/vortex-aggregates/src/lib.rs +++ b/vortex-aggregates/src/lib.rs @@ -1,49 +1,253 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Aggregate functions built on the vortex-array aggregate framework that the core array crate -//! does not itself depend on. +//! The built-in aggregate functions, built on the `vortex_array::aggregate_fn` framework. //! -//! The aggregates backing array statistics (min/max, sum, null and NaN counts, sortedness, -//! constancy, uncompressed size) live in `vortex_array::aggregate_fn::fns`. This crate holds the -//! remaining built-ins: [`count`], [`first`], [`last`], [`mean`], the byte-bounded -//! [`bounded_min`]/[`bounded_max`] used by zone maps, and the [`combined`] adapter that composes -//! two aggregates into one. +//! This includes the aggregates that back array statistics (min/max, sum, null and NaN counts, +//! sortedness, constancy, uncompressed size and the `all_*` predicates), the general-purpose +//! [`count`], [`first`], [`last`] and [`mean`], the byte-bounded [`bounded_min`]/[`bounded_max`] +//! used by zone maps, and the [`combined`] adapter that composes two aggregates into one. //! -//! Call [`initialize`] to register them with a session. +//! Array statistics resolve their aggregate through the session's registry, so call +//! [`initialize`] on any session that computes statistics. +use vortex_array::VTable; +use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::ExtensionStoragePushdown; +use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::arrays::Bool; +use vortex_array::arrays::Dict; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::RunEnd; +use vortex_array::arrays::Widen; +use vortex_array::dtype::extension::ExtVTable; +use vortex_array::stats::Stat; +use vortex_array::extension::datetime::Date; +use vortex_array::extension::datetime::Duration; +use vortex_array::extension::datetime::Time; +use vortex_array::extension::datetime::Timestamp; use vortex_session::VortexSession; +pub mod all_nan; +pub mod all_non_nan; +pub mod all_non_null; +pub mod all_null; pub mod bounded_max; pub mod bounded_min; pub mod combined; pub mod count; +mod dict; pub mod first; +mod fixed_size_bytes; +pub mod is_constant; +pub mod is_sorted; pub mod last; +pub mod max; pub mod mean; +pub mod min; +pub mod min_max; +pub mod nan_count; +pub mod null_count; +mod runend; +pub mod sum; +pub mod sum_v2; +pub mod uncompressed_size_in_bytes; +mod widen; #[cfg(test)] mod combined_tests; #[cfg(test)] +mod framework_tests; +#[cfg(test)] mod grouped_tests; -/// Register this crate's aggregate functions and grouped kernels with the given session. +/// Register this crate's aggregate functions and kernels with the given session. pub fn initialize(session: &VortexSession) { let aggregate_fns = session.aggregate_fns(); + + aggregate_fns.register(all_non_nan::AllNonNan); + aggregate_fns.register(all_non_null::AllNonNull); + aggregate_fns.register(all_nan::AllNan); + aggregate_fns.register(all_null::AllNull); aggregate_fns.register(bounded_max::BoundedMax); aggregate_fns.register(bounded_min::BoundedMin); aggregate_fns.register(count::Count); aggregate_fns.register(first::First); + aggregate_fns.register(is_constant::IsConstant); + aggregate_fns.register(is_sorted::IsSorted); aggregate_fns.register(last::Last); aggregate_fns.register(mean::Mean::combined()); + aggregate_fns.register(max::Max); + aggregate_fns.register(min::Min); + aggregate_fns.register(min_max::MinMax); + aggregate_fns.register(nan_count::NanCount); + aggregate_fns.register(null_count::NullCount); + aggregate_fns.register(sum::Sum); + aggregate_fns.register(sum_v2::SumV2); + aggregate_fns.register(uncompressed_size_in_bytes::UncompressedSizeInBytes); + + // Temporal extension types compare like their integer storage, so comparison-based + // aggregates are pushed down into it. + register_storage_ordered(session, Date); + register_storage_ordered(session, Duration); + register_storage_ordered(session, Time); + register_storage_ordered(session, Timestamp); + + aggregate_fns.register_aggregate_kernel( + Dict.id(), + Some(min_max::MinMax.id()), + &dict::min_max::DictMinMaxKernel, + ); + aggregate_fns.register_aggregate_kernel( + Dict.id(), + Some(is_constant::IsConstant.id()), + &dict::is_constant::DictIsConstantKernel, + ); + aggregate_fns.register_aggregate_kernel( + Dict.id(), + Some(is_sorted::IsSorted.id()), + &dict::is_sorted::DictIsSortedKernel, + ); + + aggregate_fns.register_aggregate_kernel( + RunEnd.id(), + Some(min_max::MinMax.id()), + &runend::min_max::RunEndMinMaxKernel, + ); + aggregate_fns.register_aggregate_kernel( + RunEnd.id(), + Some(is_constant::IsConstant.id()), + &runend::is_constant::RunEndIsConstantKernel, + ); + aggregate_fns.register_aggregate_kernel( + RunEnd.id(), + Some(is_sorted::IsSorted.id()), + &runend::is_sorted::RunEndIsSortedKernel, + ); + aggregate_fns.register_aggregate_kernel( + RunEnd.id(), + Some(sum::Sum.id()), + &runend::sum::RunEndSumKernel, + ); + aggregate_fns.register_aggregate_kernel( + RunEnd.id(), + Some(sum_v2::SumV2.id()), + &runend::sum::RunEndSumKernel, + ); + + for aggregate_fn in [ + min_max::MinMax.id(), + min::Min.id(), + max::Max.id(), + is_constant::IsConstant.id(), + is_sorted::IsSorted.id(), + sum::Sum.id(), + ] { + aggregate_fns.register_aggregate_kernel( + Widen.id(), + Some(aggregate_fn), + &widen::WidenArrayAggregate, + ); + } + aggregate_fns.register_grouped_kernel(count::Count.id(), &count::CountGroupedKernel); + aggregate_fns.register_grouped_encoding_kernel( + Primitive.id(), + sum::Sum.id(), + &sum::PrimitiveGroupedSumEncodingKernel, + ); + aggregate_fns.register_grouped_encoding_kernel( + Primitive.id(), + sum_v2::SumV2.id(), + &sum_v2::PrimitiveGroupedSumV2EncodingKernel, + ); + aggregate_fns.register_grouped_encoding_kernel( + Bool.id(), + sum_v2::SumV2.id(), + &sum_v2::BoolGroupedSumV2EncodingKernel, + ); } -#[cfg(test)] -fn test_session() -> VortexSession { - let session = VortexSession::empty(); - initialize(&session); - session +/// Push the comparison-based aggregates [`IsSorted`](is_sorted::IsSorted) and +/// [`MinMax`](min_max::MinMax) down into the storage of extension type `ext`, through +/// [`ExtensionStoragePushdown`]. +/// +/// Only call this when comparing two values of `ext` is the same as comparing their storage, as +/// for the temporal types and for UUIDs, which are stored big-endian. See +/// [`ExtensionStoragePushdown`] for how to check. +/// +/// # Example +/// +/// Registering one pair by hand and binding it like any other aggregate: +/// +/// ``` +/// # use vortex_array::IntoArray; +/// # use vortex_session::VortexSession; +/// # use vortex_array::VortexSessionExecute; +/// # use vortex_array::aggregate_fn::Accumulator; +/// # use vortex_array::aggregate_fn::DynAccumulator; +/// # use vortex_array::aggregate_fn::ExtensionStoragePushdown; +/// # use vortex_aggregates::is_sorted::IsSorted; +/// # use vortex_aggregates::is_sorted::IsSortedOptions; +/// # use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +/// # use vortex_array::arrays::ExtensionArray; +/// # use vortex_array::arrays::PrimitiveArray; +/// # use vortex_array::dtype::DType; +/// # use vortex_array::dtype::Nullability; +/// # use vortex_array::extension::datetime::TimeUnit; +/// # use vortex_array::extension::datetime::Timestamp; +/// # fn main() -> vortex_error::VortexResult<()> { +/// let session = VortexSession::empty(); +/// +/// // Register `vortex.is_sorted[vortex.timestamp]`. +/// let is_sorted = ExtensionStoragePushdown::new(IsSorted, Timestamp); +/// session.aggregate_fns().register(is_sorted.clone()); +/// +/// // Aggregate a timestamp column through its storage. +/// let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(); +/// let column = ExtensionArray::new( +/// ext_dtype.clone(), +/// PrimitiveArray::from_iter([1_000i64, 2_000, 3_000]).into_array(), +/// ) +/// .into_array(); +/// +/// let mut acc = Accumulator::try_new( +/// is_sorted, +/// IsSortedOptions { strict: true }, +/// DType::Extension(ext_dtype), +/// )?; +/// acc.accumulate(&column, &mut session.create_execution_ctx())?; +/// assert!(bool::try_from(&acc.finish()?)?); +/// # Ok(()) +/// # } +/// ``` +pub fn register_storage_ordered(session: &VortexSession, ext: E) { + let aggregate_fns = session.aggregate_fns(); + aggregate_fns.register(ExtensionStoragePushdown::new( + is_sorted::IsSorted, + ext.clone(), + )); + aggregate_fns.register(ExtensionStoragePushdown::new(min_max::MinMax, ext)); +} + +/// Return the aggregate function backing `stat`, if the statistic has a stat slot. +/// +/// Statistics follow NaN-skipping semantics. +/// Sortedness and constancy have no stat slot, so they return `None`. +pub fn stat_aggregate_fn(stat: Stat) -> Option { + Some(match stat { + Stat::Max => max::Max.bind(NumericalAggregateOpts::skip_nans()), + Stat::Min => min::Min.bind(NumericalAggregateOpts::skip_nans()), + Stat::Sum => sum::Sum.bind(NumericalAggregateOpts::skip_nans()), + Stat::NullCount => null_count::NullCount.bind(EmptyOptions), + Stat::NaNCount => nan_count::NanCount.bind(EmptyOptions), + Stat::UncompressedSizeInBytes => { + uncompressed_size_in_bytes::UncompressedSizeInBytes.bind(EmptyOptions) + } + Stat::IsConstant | Stat::IsSorted | Stat::IsStrictSorted => return None, + }) } diff --git a/vortex-array/src/aggregate_fn/fns/max/mod.rs b/vortex-aggregates/src/max/mod.rs similarity index 87% rename from vortex-array/src/aggregate_fn/fns/max/mod.rs rename to vortex-aggregates/src/max/mod.rs index 68bfbdce78e..e229e4be89c 100644 --- a/vortex-array/src/aggregate_fn/fns/max/mod.rs +++ b/vortex-aggregates/src/max/mod.rs @@ -1,32 +1,32 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::partial_ord::partial_max; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnSatisfaction; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::columnar_min_max; -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::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -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; +use crate::min_max::MinMax; +use crate::min_max::columnar_min_max; +use crate::min_max::min_max; +use crate::min_max::nan_scalar; +use crate::min_max::scalar_is_nan; /// Compute the maximum non-null value of an array. /// @@ -245,29 +245,34 @@ impl AggregateFnVTable for Max { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray as _; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray as _; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::max::Max; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - 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); + use crate::max::Max; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn max_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-aggregates/src/mean/mod.rs b/vortex-aggregates/src/mean/mod.rs index 1c13cc0f3b3..15ec9bce797 100644 --- a/vortex-aggregates/src/mean/mod.rs +++ b/vortex-aggregates/src/mean/mod.rs @@ -9,8 +9,6 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum::Sum; -use vortex_array::aggregate_fn::fns::sum::sum_decimal_dtype; use vortex_array::arrays::ConstantArray; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; @@ -33,6 +31,8 @@ use crate::combined::Combined; use crate::combined::CombinedOptions; use crate::combined::PairOptions; use crate::count::Count; +use crate::sum::Sum; +use crate::sum::sum_decimal_dtype; use vortex_array::scalar::NumericOperator; use vortex_array::scalar_fn::builtin::operators::CompareMode; use vortex_array::scalar_fn::builtin::operators::CompareOperator; @@ -242,6 +242,7 @@ fn finalize_decimal_scalar( #[cfg(test)] mod tests { + use std::sync::LazyLock; use vortex_array::VortexSessionExecute; @@ -261,7 +262,11 @@ mod tests { use super::*; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn mean_all_valid() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/min/mod.rs b/vortex-aggregates/src/min/mod.rs similarity index 87% rename from vortex-array/src/aggregate_fn/fns/min/mod.rs rename to vortex-aggregates/src/min/mod.rs index 136d1e7c70b..58f2a3b0723 100644 --- a/vortex-array/src/aggregate_fn/fns/min/mod.rs +++ b/vortex-aggregates/src/min/mod.rs @@ -1,32 +1,32 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnSatisfaction; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnSatisfaction; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::columnar_min_max; -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::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -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; +use crate::min_max::MinMax; +use crate::min_max::columnar_min_max; +use crate::min_max::min_max; +use crate::min_max::nan_scalar; +use crate::min_max::scalar_is_nan; /// Compute the minimum non-null value of an array. /// @@ -245,29 +245,34 @@ impl AggregateFnVTable for Min { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray as _; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray as _; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min::Min; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - 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); + use crate::min::Min; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn min_aggregate_fn() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/min_max/bool.rs b/vortex-aggregates/src/min_max/bool.rs similarity index 80% rename from vortex-array/src/aggregate_fn/fns/min_max/bool.rs rename to vortex-aggregates/src/min_max/bool.rs index 19df7d4c68e..941fbc900fa 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/bool.rs +++ b/vortex-aggregates/src/min_max/bool.rs @@ -3,18 +3,18 @@ use std::ops::BitAnd; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::bool::BoolArrayExt; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_mask::AllOr; use super::MinMaxPartial; use super::MinMaxResult; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::arrays::BoolArray; -use crate::arrays::bool::BoolArrayExt; -use crate::dtype::Nullability::NonNullable; -use crate::scalar::Scalar; pub(super) fn accumulate_bool( args: AggregateArgs<'_, NumericalAggregateOpts>, diff --git a/vortex-aggregates/src/min_max/decimal.rs b/vortex-aggregates/src/min_max/decimal.rs new file mode 100644 index 00000000000..61bab293f40 --- /dev/null +++ b/vortex-aggregates/src/min_max/decimal.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::decimal::valid_range; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::match_each_decimal_value_type; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; +use vortex_error::VortexResult; +use vortex_mask::Mask; + +use super::MinMaxPartial; +use super::MinMaxResult; + +pub(super) fn accumulate_decimal( + args: AggregateArgs<'_, NumericalAggregateOpts>, + partial: &mut MinMaxPartial, + array: &DecimalArray, + ctx: &mut ExecutionCtx, +) -> VortexResult<()> { + let local = match_each_decimal_value_type!(array.values_type(), |T| { + compute_min_max_with_validity::(array, ctx) + })?; + partial.merge(args, local) +} + +fn compute_min_max_with_validity( + array: &DecimalArray, + ctx: &mut ExecutionCtx, +) -> VortexResult> +where + D: Into + NativeDecimalType, +{ + let validity = array + .as_ref() + .validity()? + .execute_mask(array.as_ref().len(), ctx)?; + if matches!(&validity, Mask::AllFalse(_)) { + return Ok(None); + } + + let decimal_dtype = array.decimal_dtype(); + + let Some((min, max)) = valid_range(array.buffer::().as_slice(), &validity) else { + return Ok(None); + }; + + let min_scalar = Scalar::try_decimal(min.into(), decimal_dtype, NonNullable)?; + let max_scalar = if min == max { + min_scalar.clone() + } else { + Scalar::try_decimal(max.into(), decimal_dtype, NonNullable)? + }; + + Ok(Some(MinMaxResult { + min: min_scalar, + max: max_scalar, + })) +} diff --git a/vortex-array/src/aggregate_fn/fns/min_max/extension.rs b/vortex-aggregates/src/min_max/extension.rs similarity index 75% rename from vortex-array/src/aggregate_fn/fns/min_max/extension.rs rename to vortex-aggregates/src/min_max/extension.rs index e43a4f222ae..e14222d936f 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/extension.rs +++ b/vortex-aggregates/src/min_max/extension.rs @@ -1,18 +1,18 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::extension::ExtensionArrayExt; +use vortex_array::dtype::Nullability; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use super::MinMaxPartial; use super::MinMaxResult; use super::min_max; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::arrays::ExtensionArray; -use crate::arrays::extension::ExtensionArrayExt; -use crate::dtype::Nullability; -use crate::scalar::Scalar; pub(super) fn accumulate_extension( args: AggregateArgs<'_, NumericalAggregateOpts>, diff --git a/vortex-array/src/aggregate_fn/fns/min_max/fixed_size_list.rs b/vortex-aggregates/src/min_max/fixed_size_list.rs similarity index 80% rename from vortex-array/src/aggregate_fn/fns/min_max/fixed_size_list.rs rename to vortex-aggregates/src/min_max/fixed_size_list.rs index 153abc97993..3b6ab61fae1 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/fixed_size_list.rs +++ b/vortex-aggregates/src/min_max/fixed_size_list.rs @@ -1,18 +1,18 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use super::MinMaxPartial; use super::MinMaxResult; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::fixed_size_bytes::FixedSizeBytes; -use crate::arrays::FixedSizeListArray; -use crate::arrays::fixed_size_list::FixedSizeListArrayExt; -use crate::dtype::Nullability::NonNullable; -use crate::scalar::Scalar; +use crate::fixed_size_bytes::FixedSizeBytes; /// Accumulate the byte-wise extrema of a fixed-size list of bytes. pub(super) fn accumulate_fixed_size_bytes( diff --git a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs b/vortex-aggregates/src/min_max/mod.rs similarity index 94% rename from vortex-array/src/aggregate_fn/fns/min_max/mod.rs rename to vortex-aggregates/src/min_max/mod.rs index 5e3f38dfa61..a8f39c455d3 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/mod.rs +++ b/vortex-aggregates/src/min_max/mod.rs @@ -3,7 +3,7 @@ mod bool; mod decimal; -pub use decimal::valid_range; +pub use vortex_array::arrays::decimal::valid_range; mod extension; mod fixed_size_list; mod primitive; @@ -11,6 +11,30 @@ mod varbinview; use std::sync::LazyLock; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateDTypes; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::dtype::DType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::StructFields; +use vortex_array::dtype::half::f16; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::partial_ord::partial_max; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -23,31 +47,7 @@ use self::extension::accumulate_extension; use self::fixed_size_list::accumulate_fixed_size_bytes; use self::primitive::accumulate_primitive; use self::varbinview::accumulate_varbinview; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateDTypes; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::fixed_size_bytes::is_fixed_size_bytes; -use crate::dtype::DType; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::PType; -use crate::dtype::StructFields; -use crate::dtype::half::f16; -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; +use crate::fixed_size_bytes::is_fixed_size_bytes; static NAMES: LazyLock = LazyLock::new(|| FieldNames::from(["min", "max"])); @@ -544,6 +544,44 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::EmptyMetadata; + use vortex_array::IntoArray as _; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::ExtensionArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListArray; + use vortex_array::arrays::NullArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::TemporalArray; + use vortex_array::arrays::VarBinArray; + use vortex_array::dtype::BigCast; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::DecimalType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::extension::ExtDType; + use vortex_array::dtype::extension::ExtId; + use vortex_array::dtype::extension::ExtVTable; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProvider; + use vortex_array::extension::datetime::TimeUnit; + use vortex_array::match_each_decimal_value_type; + use vortex_array::scalar::DecimalValue; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; use vortex_buffer::buffer; @@ -551,48 +589,11 @@ mod tests { use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::EmptyMetadata; - use crate::IntoArray as _; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min_max::MinMax; - use crate::aggregate_fn::fns::min_max::MinMaxPartial; - use crate::aggregate_fn::fns::min_max::MinMaxResult; - use crate::aggregate_fn::fns::min_max::make_minmax_dtype; - use crate::aggregate_fn::fns::min_max::min_max; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::DecimalArray; - use crate::arrays::ExtensionArray; - use crate::arrays::FixedSizeListArray; - use crate::arrays::ListArray; - use crate::arrays::NullArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::TemporalArray; - use crate::arrays::VarBinArray; - use crate::dtype::BigCast; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::dtype::extension::ExtDType; - use crate::dtype::extension::ExtId; - use crate::dtype::extension::ExtVTable; - 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; + use crate::min_max::MinMax; + use crate::min_max::MinMaxPartial; + use crate::min_max::MinMaxResult; + use crate::min_max::make_minmax_dtype; + use crate::min_max::min_max; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -1302,7 +1303,7 @@ mod tests { Ok(()) } - use crate::dtype::half::f16; + use vortex_array::dtype::half::f16; #[test] fn test_bool_with_nulls() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs b/vortex-aggregates/src/min_max/primitive.rs similarity index 95% rename from vortex-array/src/aggregate_fn/fns/min_max/primitive.rs rename to vortex-aggregates/src/min_max/primitive.rs index f81f4a4802e..63c714028fd 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/primitive.rs +++ b/vortex-aggregates/src/min_max/primitive.rs @@ -6,20 +6,21 @@ use num_traits::Float; use vortex_buffer::BitBuffer; use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_error::VortexExpect; +use itertools::Itertools; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::match_each_native_ptype; +use vortex_array::scalar::PValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_mask::Mask; use super::MinMaxPartial; use super::MinMaxResult; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::arrays::PrimitiveArray; -use crate::dtype::NativePType; -use crate::dtype::Nullability::NonNullable; -use crate::match_each_native_ptype; -use crate::scalar::PValue; -use crate::scalar::Scalar; pub(super) fn accumulate_primitive( args: AggregateArgs<'_, NumericalAggregateOpts>, diff --git a/vortex-array/src/aggregate_fn/fns/min_max/varbinview.rs b/vortex-aggregates/src/min_max/varbinview.rs similarity index 94% rename from vortex-array/src/aggregate_fn/fns/min_max/varbinview.rs rename to vortex-aggregates/src/min_max/varbinview.rs index 8570377edc9..f402f0341f7 100644 --- a/vortex-array/src/aggregate_fn/fns/min_max/varbinview.rs +++ b/vortex-aggregates/src/min_max/varbinview.rs @@ -1,20 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::varbinview::BinaryView; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_error::vortex_panic; use vortex_mask::Mask; use super::MinMaxPartial; use super::MinMaxResult; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::arrays::VarBinViewArray; -use crate::arrays::varbinview::BinaryView; -use crate::dtype::DType; -use crate::dtype::Nullability::NonNullable; -use crate::scalar::Scalar; pub(super) fn accumulate_varbinview( args: AggregateArgs<'_, NumericalAggregateOpts>, @@ -165,17 +165,17 @@ mod tests { use rand::SeedableRng; use rand::rngs::StdRng; use rstest::rstest; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::dtype::Nullability; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; use super::*; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min_max::min_max; - use crate::arrays::VarBinViewArray; - use crate::dtype::Nullability; + use crate::min_max::min_max; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs b/vortex-aggregates/src/nan_count/mod.rs similarity index 85% rename from vortex-array/src/aggregate_fn/fns/nan_count/mod.rs rename to vortex-aggregates/src/nan_count/mod.rs index 78bd7b7c001..7eefac2a6b7 100644 --- a/vortex-array/src/aggregate_fn/fns/nan_count/mod.rs +++ b/vortex-aggregates/src/nan_count/mod.rs @@ -3,31 +3,31 @@ mod primitive; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateDTypes; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; use self::primitive::accumulate_primitive; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateDTypes; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::PType; -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. /// @@ -220,30 +220,35 @@ impl AggregateFnVTable for NanCount { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::nan_count::NanCount; - use crate::aggregate_fn::fns::nan_count::nan_count; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::validity::Validity; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::nan_count::NanCount; + use crate::nan_count::nan_count; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn nan_count_multi_batch() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs b/vortex-aggregates/src/nan_count/primitive.rs similarity index 81% rename from vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs rename to vortex-aggregates/src/nan_count/primitive.rs index 2c1764fd6c1..71177975be7 100644 --- a/vortex-array/src/aggregate_fn/fns/nan_count/primitive.rs +++ b/vortex-aggregates/src/nan_count/primitive.rs @@ -2,14 +2,13 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use vortex_compute::lane_kernels::IndexedFoldExt; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_float_ptype; use vortex_error::VortexResult; use vortex_mask::Mask; -use crate::ExecutionCtx; -use crate::arrays::PrimitiveArray; -use crate::dtype::NativePType; -use crate::match_each_float_ptype; - pub(super) fn accumulate_primitive( count: &mut u64, p: &PrimitiveArray, @@ -39,19 +38,24 @@ fn count_primitive_nans( #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::fns::nan_count::nan_count; - use crate::arrays::PrimitiveArray; - use crate::validity::Validity; + use crate::nan_count::nan_count; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn primitive_nan_count() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/null_count/mod.rs b/vortex-aggregates/src/null_count/mod.rs similarity index 78% rename from vortex-array/src/aggregate_fn/fns/null_count/mod.rs rename to vortex-aggregates/src/null_count/mod.rs index 4aa3416012d..24647bf634d 100644 --- a/vortex-array/src/aggregate_fn/fns/null_count/mod.rs +++ b/vortex-aggregates/src/null_count/mod.rs @@ -1,29 +1,28 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::PType; -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 { if let Precision::Exact(null_count_scalar) = array.statistics().get(Stat::NullCount) { @@ -171,27 +170,32 @@ impl AggregateFnVTable for NullCount { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProviderExt; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::null_count::NullCount; - use crate::aggregate_fn::fns::null_count::null_count; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::stats::Precision; - use crate::stats::Stat; - use crate::stats::StatsProviderExt; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::null_count::NullCount; + use crate::null_count::null_count; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn null_count_with_nulls() -> VortexResult<()> { diff --git a/vortex-array/src/arrays/runend/compute/is_constant.rs b/vortex-aggregates/src/runend/is_constant.rs similarity index 91% rename from vortex-array/src/arrays/runend/compute/is_constant.rs rename to vortex-aggregates/src/runend/is_constant.rs index 9573e6614c8..1e108ffec13 100644 --- a/vortex-array/src/arrays/runend/compute/is_constant.rs +++ b/vortex-aggregates/src/runend/is_constant.rs @@ -1,18 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use super::active_physical_range; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_constant::is_constant; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::array::RunEndArraySlotsExt; -use crate::scalar::Scalar; +use crate::is_constant::IsConstant; +use crate::is_constant::is_constant; +use vortex_array::arrays::runend::array::RunEndArraySlotsExt; /// RunEnd-specific is_constant kernel. /// diff --git a/vortex-array/src/arrays/runend/compute/is_sorted.rs b/vortex-aggregates/src/runend/is_sorted.rs similarity index 88% rename from vortex-array/src/arrays/runend/compute/is_sorted.rs rename to vortex-aggregates/src/runend/is_sorted.rs index 4c7fa9c8de5..d007c4193de 100644 --- a/vortex-array/src/arrays/runend/compute/is_sorted.rs +++ b/vortex-aggregates/src/runend/is_sorted.rs @@ -1,19 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use super::active_physical_range; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::is_sorted::is_sorted; -use crate::aggregate_fn::fns::is_sorted::is_strict_sorted; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::array::RunEndArraySlotsExt; -use crate::scalar::Scalar; +use crate::is_sorted::IsSorted; +use crate::is_sorted::is_sorted; +use crate::is_sorted::is_strict_sorted; /// RunEnd-specific is_sorted kernel. /// @@ -68,21 +68,21 @@ impl DynAggregateKernel for RunEndIsSortedKernel { #[cfg(test)] mod tests { use rstest::rstest; + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::runend::RunEnd; + use vortex_array::dtype::Nullability; + use vortex_array::scalar::Scalar; use vortex_buffer::buffer; use vortex_error::VortexResult; - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::fns::is_sorted::IsSorted; - use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; - use crate::arrays::PrimitiveArray; - use crate::arrays::runend::RunEnd; - use crate::arrays::runend::tests::SESSION; - use crate::dtype::Nullability; - use crate::scalar::Scalar; + use crate::is_sorted::IsSorted; + use crate::is_sorted::IsSortedOptions; + use crate::runend::tests::SESSION; fn run_is_sorted(array: &ArrayRef, strict: bool, ctx: &mut ExecutionCtx) -> VortexResult { let mut acc = IsSorted diff --git a/vortex-array/src/arrays/runend/compute/min_max.rs b/vortex-aggregates/src/runend/min_max.rs similarity index 91% rename from vortex-array/src/arrays/runend/compute/min_max.rs rename to vortex-aggregates/src/runend/min_max.rs index ff5561a8785..e2839d3f400 100644 --- a/vortex-array/src/arrays/runend/compute/min_max.rs +++ b/vortex-aggregates/src/runend/min_max.rs @@ -1,19 +1,20 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use super::active_physical_range; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::make_minmax_dtype; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::array::RunEndArraySlotsExt; -use crate::scalar::Scalar; +use crate::min_max::MinMax; +use crate::min_max::make_minmax_dtype; +use crate::min_max::min_max; +use vortex_array::arrays::runend::array::RunEndArraySlotsExt; /// RunEnd-specific min/max kernel. /// diff --git a/vortex-aggregates/src/runend/mod.rs b/vortex-aggregates/src/runend/mod.rs new file mode 100644 index 00000000000..0afad922c4b --- /dev/null +++ b/vortex-aggregates/src/runend/mod.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Aggregate kernels for run-end encoded arrays. + +pub(crate) mod is_constant; +pub(crate) mod is_sorted; +pub(crate) mod min_max; +pub(crate) mod sum; + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::RunEnd; + use vortex_buffer::buffer; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::is_constant::is_constant; + + pub(crate) static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); + + #[test] + fn sliced_single_run_is_constant() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = RunEnd::try_new( + buffer![7_u64, 10].into_array(), + buffer![2_u64, 3].into_array(), + &mut ctx, + )?; + + assert!(is_constant(&array.slice(2..5)?, &mut ctx)?); + Ok(()) + } +} diff --git a/vortex-array/src/arrays/runend/compute/sum/kernel.rs b/vortex-aggregates/src/runend/sum/kernel.rs similarity index 84% rename from vortex-array/src/arrays/runend/compute/sum/kernel.rs rename to vortex-aggregates/src/runend/sum/kernel.rs index 30a0c02de0d..118235c649c 100644 --- a/vortex-array/src/arrays/runend/compute/sum/kernel.rs +++ b/vortex-aggregates/src/runend/sum/kernel.rs @@ -7,6 +7,23 @@ use std::ops::Range; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::RunEndArrayExt; +use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::UnsignedPType; +use vortex_array::match_each_native_ptype; +use vortex_array::match_each_unsigned_integer_ptype; +use vortex_array::scalar::PValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_mask::Mask; @@ -15,25 +32,8 @@ use super::runs::add_float_run; use super::runs::add_signed_run; use super::runs::add_unsigned_run; use super::runs::sum_range; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum_v2::SumV2; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::PrimitiveArray; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::RunEndArrayExt; -use crate::arrays::runend::RunEndArraySlotsExt; -use crate::dtype::DType; -use crate::dtype::NativePType; -use crate::dtype::Nullability::Nullable; -use crate::dtype::UnsignedPType; -use crate::match_each_native_ptype; -use crate::match_each_unsigned_integer_ptype; -use crate::scalar::PValue; -use crate::scalar::Scalar; +use crate::sum::Sum; +use crate::sum_v2::SumV2; /// Whole-array primitive sum kernel for [`RunEnd`]. #[derive(Debug)] diff --git a/vortex-array/src/arrays/runend/compute/sum/mod.rs b/vortex-aggregates/src/runend/sum/mod.rs similarity index 83% rename from vortex-array/src/arrays/runend/compute/sum/mod.rs rename to vortex-aggregates/src/runend/sum/mod.rs index 6e495ad81a9..e98778084be 100644 --- a/vortex-array/src/arrays/runend/compute/sum/mod.rs +++ b/vortex-aggregates/src/runend/sum/mod.rs @@ -9,8 +9,8 @@ //! //! Floating-point multiplication can round differently from repeated addition, as with constant sums. //! -//! [`Sum`]: vortex_array::aggregate_fn::fns::sum::Sum -//! [`SumV2`]: vortex_array::aggregate_fn::fns::sum_v2::SumV2 +//! [`Sum`]: crate::sum::Sum +//! [`SumV2`]: crate::sum_v2::SumV2 mod kernel; pub(crate) use kernel::RunEndSumKernel; diff --git a/vortex-array/src/arrays/runend/compute/sum/runs.rs b/vortex-aggregates/src/runend/sum/runs.rs similarity index 98% rename from vortex-array/src/arrays/runend/compute/sum/runs.rs rename to vortex-aggregates/src/runend/sum/runs.rs index 5e8762f55e9..fd40da33e4b 100644 --- a/vortex-array/src/arrays/runend/compute/sum/runs.rs +++ b/vortex-aggregates/src/runend/sum/runs.rs @@ -19,13 +19,12 @@ use std::ops::Range; use num_traits::AsPrimitive; use num_traits::ToPrimitive; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::UnsignedPType; use vortex_error::VortexExpect; use vortex_mask::Mask; use vortex_mask::MaskValues; -use crate::dtype::NativePType; -use crate::dtype::UnsignedPType; - /// Return `None` if the run's product or the accumulated sum exceeds `u64`. pub(super) fn add_unsigned_run>(sum: u64, value: T, len: usize) -> Option { value diff --git a/vortex-array/src/arrays/runend/compute/sum/tests.rs b/vortex-aggregates/src/runend/sum/tests.rs similarity index 90% rename from vortex-array/src/arrays/runend/compute/sum/tests.rs rename to vortex-aggregates/src/runend/sum/tests.rs index 015428e34c8..c55eaf19518 100644 --- a/vortex-array/src/arrays/runend/compute/sum/tests.rs +++ b/vortex-aggregates/src/runend/sum/tests.rs @@ -4,6 +4,25 @@ use std::ops::Range; use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; +#[cfg(not(codspeed))] +use vortex_array::test_harness::trace::trace_op; +use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; @@ -13,27 +32,9 @@ use vortex_mask::Mask; use super::RunEndSumKernel; use super::runs::add_unsigned_run; use super::runs::sum_range; -use crate::ArrayRef; -use crate::IntoArray; -use crate::VortexSessionExecute; -use crate::aggregate_fn::AggregateFnVTableExt; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum_v2::SumV2; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::ConstantArray; -use crate::arrays::DecimalArray; -use crate::arrays::PrimitiveArray; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::tests::SESSION; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::Nullability::Nullable; -use crate::dtype::PType; -use crate::scalar::Scalar; -#[cfg(not(codspeed))] -use crate::test_harness::trace::trace_op; +use crate::runend::tests::SESSION; +use crate::sum::Sum; +use crate::sum_v2::SumV2; /// Compare registered dispatch and the direct kernel with a decoded primitive reference. #[track_caller] diff --git a/vortex-array/src/aggregate_fn/fns/sum/bool.rs b/vortex-aggregates/src/sum/bool.rs similarity index 84% rename from vortex-array/src/aggregate_fn/fns/sum/bool.rs rename to vortex-aggregates/src/sum/bool.rs index d6c42f31ba3..21f0a88acf0 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/bool.rs +++ b/vortex-aggregates/src/sum/bool.rs @@ -3,15 +3,15 @@ use std::ops::BitAnd; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::bool::BoolArrayExt; use vortex_error::VortexResult; use vortex_error::vortex_panic; use vortex_mask::AllOr; use super::SumState; use super::checked_add_u64; -use crate::ExecutionCtx; -use crate::arrays::BoolArray; -use crate::arrays::bool::BoolArrayExt; pub(crate) fn accumulate_bool( inner: &mut SumState, @@ -34,25 +34,30 @@ pub(crate) fn accumulate_bool( #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::BoolArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::BoolArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::executor::VortexSessionExecute; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::sum::Sum; + use crate::sum::sum; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn sum_bool_all_true() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/sum/constant.rs b/vortex-aggregates/src/sum/constant.rs similarity index 90% rename from vortex-array/src/aggregate_fn/fns/sum/constant.rs rename to vortex-aggregates/src/sum/constant.rs index 0752b67dfcb..c3ade7888a6 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/constant.rs +++ b/vortex-aggregates/src/sum/constant.rs @@ -1,17 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_err; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; -use crate::dtype::i256; -use crate::scalar::DecimalValue; -use crate::scalar::Scalar; - /// Compute `scalar * len` for a constant array, returning the product as a sum-typed scalar. /// /// Returns `Ok(None)` if the scalar is null (no contribution to the sum). @@ -95,26 +94,31 @@ pub(crate) fn multiply_constant( #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::arrays::ConstantArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::dtype::i256; + use vortex_array::stats::Stat; + use vortex_array::scalar::DecimalValue; + use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::ConstantArray; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::dtype::i256; - use crate::scalar::DecimalValue; - use crate::scalar::Scalar; - use crate::stats::Stat; + use crate::sum::sum; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn sum_constant_unsigned() -> VortexResult<()> { diff --git a/vortex-array/src/aggregate_fn/fns/sum/decimal.rs b/vortex-aggregates/src/sum/decimal.rs similarity index 92% rename from vortex-array/src/aggregate_fn/fns/sum/decimal.rs rename to vortex-aggregates/src/sum/decimal.rs index 94645331833..17f0220a92e 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/decimal.rs +++ b/vortex-aggregates/src/sum/decimal.rs @@ -5,6 +5,13 @@ use itertools::Itertools; use num_traits::AsPrimitive; use num_traits::CheckedAdd; use num_traits::NumOps; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::DecimalArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::NativeDecimalType; +use vortex_array::match_each_decimal_value_type; +use vortex_array::scalar::DecimalValue; use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; use vortex_error::VortexExpect; @@ -16,15 +23,8 @@ use super::SumState; use super::checked_add_sum_states; use super::primitive::sum_signed_valid; use super::sum_signed_all; -use crate::ExecutionCtx; -use crate::arrays::DecimalArray; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::DecimalType; -use crate::dtype::NativeDecimalType; -use crate::dtype::NativePType; -use crate::match_each_decimal_value_type; -use crate::scalar::DecimalValue; +use vortex_array::dtype::DecimalType; +use vortex_array::dtype::NativePType; /// Accumulate a decimal array into the sum state. /// Returns Ok(true) if saturated (overflow), Ok(false) if not. @@ -161,36 +161,41 @@ where #[cfg(test)] mod tests { + use std::sync::LazyLock; use vortex_buffer::Buffer; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::DecimalArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::NativeDecimalType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::i256; + use vortex_array::scalar::DecimalValue; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::fns::sum::SumPartial; - use crate::aggregate_fn::fns::sum::SumState; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::DecimalArray; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::NativeDecimalType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::i256; - use crate::scalar::DecimalValue; - use crate::scalar::Scalar; - use crate::scalar::ScalarValue; - use crate::validity::Validity; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::sum::Sum; + use crate::sum::SumPartial; + use crate::sum::SumState; + use crate::sum::sum; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); /// A partial whose running decimal sum is `value` (test-only helper bypassing scalar parsing). fn partial_with_decimal(value: DecimalValue) -> SumPartial { @@ -545,7 +550,7 @@ mod tests { ); // Drive accumulate through the vtable directly. - let columnar = crate::Columnar::Canonical(crate::Canonical::Decimal(decimal)); + let columnar = vortex_array::Columnar::Canonical(vortex_array::Canonical::Decimal(decimal)); Sum.accumulate(dtypes.args(&options), &mut state, &columnar, &mut ctx)?; let result = Sum.to_scalar(dtypes.args(&options), &state)?; diff --git a/vortex-array/src/aggregate_fn/fns/sum/grouped.rs b/vortex-aggregates/src/sum/grouped.rs similarity index 90% rename from vortex-array/src/aggregate_fn/fns/sum/grouped.rs rename to vortex-aggregates/src/sum/grouped.rs index e661a4d4372..5a76bc2e2ce 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/grouped.rs +++ b/vortex-aggregates/src/sum/grouped.rs @@ -1,6 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::GroupRanges; +use vortex_array::aggregate_fn::GroupedArray; +use vortex_array::aggregate_fn::kernels::DynGroupedAggregateKernel; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::match_each_native_ptype; use vortex_error::VortexResult; use vortex_mask::AllOr; use vortex_mask::Mask; @@ -9,17 +20,6 @@ use super::Sum; use super::primitive::sum_float_all; use super::primitive::sum_signed_all; use super::primitive::sum_unsigned_all; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::GroupRanges; -use crate::aggregate_fn::GroupedArray; -use crate::aggregate_fn::kernels::DynGroupedAggregateKernel; -use crate::arrays::Primitive; -use crate::arrays::PrimitiveArray; -use crate::dtype::NativePType; -use crate::match_each_native_ptype; /// Encoding-specific grouped [`Sum`] kernel for primitive element arrays. #[derive(Debug)] @@ -156,30 +156,34 @@ mod tests { use std::sync::LazyLock; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::assert_arrays_eq; + use vortex_array::builders::builder_with_capacity_in; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability::NonNullable; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::FixedSizeListArray; - use crate::arrays::ListViewArray; - use crate::arrays::PrimitiveArray; - use crate::assert_arrays_eq; - use crate::builders::builder_with_capacity_in; - use crate::dtype::DType; - use crate::dtype::Nullability::NonNullable; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::validity::Validity; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::sum::Sum; + use crate::sum::sum; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); /// Run a grouped sum through the accumulator. fn grouped_sum_actual(groups: &ArrayRef, elem_dtype: &DType) -> VortexResult { @@ -200,7 +204,7 @@ mod tests { group_valid: &[bool], elem_dtype: &DType, ) -> VortexResult { - use crate::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::AggregateFnVTable; let mut ctx = SESSION.create_execution_ctx(); let sum_dtype = Sum diff --git a/vortex-array/src/aggregate_fn/fns/sum/mod.rs b/vortex-aggregates/src/sum/mod.rs similarity index 92% rename from vortex-array/src/aggregate_fn/fns/sum/mod.rs rename to vortex-aggregates/src/sum/mod.rs index c042ce34ac9..40acea21442 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/mod.rs +++ b/vortex-aggregates/src/sum/mod.rs @@ -7,6 +7,26 @@ mod decimal; mod grouped; mod primitive; pub(crate) use grouped::PrimitiveGroupedSumEncodingKernel; +use vortex_array::ArrayRef; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::stats::StatsProviderExt; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -21,26 +41,6 @@ pub(crate) use self::primitive::accumulate_primitive; pub(crate) use self::primitive::sum_float_all; pub(crate) use self::primitive::sum_signed_all; pub(crate) use self::primitive::sum_unsigned_all; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::stat_aggregates; -use crate::dtype::DType; -use crate::dtype::Nullability; -use crate::dtype::PType; -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. /// @@ -73,7 +73,7 @@ pub fn sum(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { #[derive(Clone, Debug)] pub struct Sum; -pub use crate::aggregate_fn::stat_aggregates::sum_decimal_dtype; +pub use vortex_array::aggregate_fn::stat_aggregates::sum_decimal_dtype; impl AggregateFnVTable for Sum { type Options = NumericalAggregateOpts; @@ -410,49 +410,54 @@ fn checked_add_i64(acc: &mut i64, val: i64) -> bool { #[cfg(test)] mod tests { + use std::sync::LazyLock; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::DynGroupedAccumulator; + use vortex_array::aggregate_fn::GroupedAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::assert_arrays_eq; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::dtype::i256; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProvider; + use vortex_array::scalar::DecimalValue; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::DynGroupedAccumulator; - use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::fns::sum::SumPartial; - use crate::aggregate_fn::fns::sum::SumState; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::DecimalArray; - use crate::arrays::FixedSizeListArray; - use crate::arrays::ListViewArray; - use crate::arrays::PrimitiveArray; - use crate::assert_arrays_eq; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - use crate::dtype::i256; - 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); + use crate::sum::Sum; + use crate::sum::SumPartial; + use crate::sum::SumState; + use crate::sum::sum; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); // Multi-batch and reset tests diff --git a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs b/vortex-aggregates/src/sum/primitive.rs similarity index 96% rename from vortex-array/src/aggregate_fn/fns/sum/primitive.rs rename to vortex-aggregates/src/sum/primitive.rs index 4a51c8e5f08..55131a48c73 100644 --- a/vortex-array/src/aggregate_fn/fns/sum/primitive.rs +++ b/vortex-aggregates/src/sum/primitive.rs @@ -8,6 +8,11 @@ use num_traits::AsPrimitive; use num_traits::ToPrimitive; use vortex_buffer::BitBuffer; use vortex_compute::lane_kernels::IndexedFoldExt; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::PType; +use vortex_array::match_each_native_ptype; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_panic; @@ -17,11 +22,6 @@ use vortex_mask::MaskValues; use super::SumState; use super::checked_add_i64; use super::checked_add_u64; -use crate::ExecutionCtx; -use crate::arrays::PrimitiveArray; -use crate::dtype::NativePType; -use crate::dtype::PType; -use crate::match_each_native_ptype; /// Number of elements summed without an overflow check. Chosen so that a chunk of values narrower /// than 64 bits cannot overflow the 64-bit accumulator: `2^16 * (2^32 - 1) < 2^64`. @@ -443,10 +443,27 @@ impl WrappingSum for u64 { #[cfg(test)] mod tests { + use std::sync::LazyLock; use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::Nullability::Nullable; + use vortex_array::dtype::PType; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -455,26 +472,14 @@ mod tests { use super::SumBound; use super::UnsignedBound; use super::sum_wide; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::fns::sum::sum; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::Nullability::Nullable; - use crate::dtype::PType; - 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); + use crate::sum::Sum; + use crate::sum::sum; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); #[test] fn sum_i32() -> VortexResult<()> { @@ -658,7 +663,7 @@ mod tests { /// Sum an array with explicit [`NumericalAggregateOpts`] (test-only helper). fn sum_with_options( - arr: &crate::ArrayRef, + arr: &vortex_array::ArrayRef, options: NumericalAggregateOpts, ) -> VortexResult { let mut acc = Accumulator::try_new(Sum, options, arr.dtype().clone())?; diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs b/vortex-aggregates/src/sum_v2/grouped.rs similarity index 91% rename from vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs rename to vortex-aggregates/src/sum_v2/grouped.rs index 6e268a2cf45..953bba80989 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/grouped.rs +++ b/vortex-aggregates/src/sum_v2/grouped.rs @@ -1,6 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::GroupRanges; +use vortex_array::aggregate_fn::GroupedArray; +use vortex_array::aggregate_fn::kernels::DynGroupedAggregateKernel; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::Primitive; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::dtype::NativePType; +use vortex_array::dtype::Nullability; +use vortex_array::match_each_native_ptype; +use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::BitBufferMut; use vortex_buffer::Buffer; @@ -10,26 +25,11 @@ use vortex_mask::Mask; use super::SumV2; use super::sum_v2_partial_fields; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::GroupRanges; -use crate::aggregate_fn::GroupedArray; -use crate::aggregate_fn::fns::sum::sum_float_all; -use crate::aggregate_fn::fns::sum::sum_signed_all; -use crate::aggregate_fn::fns::sum::sum_unsigned_all; -use crate::aggregate_fn::kernels::DynGroupedAggregateKernel; -use crate::arrays::Bool; -use crate::arrays::BoolArray; -use crate::arrays::Primitive; -use crate::arrays::PrimitiveArray; -use crate::arrays::StructArray; -use crate::arrays::bool::BoolArrayExt; -use crate::dtype::NativePType; -use crate::dtype::Nullability; -use crate::match_each_native_ptype; -use crate::validity::Validity; +use crate::sum::sum_float_all; +use crate::sum::sum_signed_all; +use crate::sum::sum_unsigned_all; +use vortex_array::arrays::Bool; +use vortex_array::arrays::bool::BoolArrayExt; /// Encoding-specific grouped [`SumV2`] kernel for primitive element arrays. #[derive(Debug)] diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs b/vortex-aggregates/src/sum_v2/mod.rs similarity index 92% rename from vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs rename to vortex-aggregates/src/sum_v2/mod.rs index 00a4d06a56b..a006a424450 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/mod.rs +++ b/vortex-aggregates/src/sum_v2/mod.rs @@ -10,6 +10,33 @@ mod grouped; pub(crate) use grouped::BoolGroupedSumV2EncodingKernel; pub(crate) use grouped::PrimitiveGroupedSumV2EncodingKernel; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::Struct; +use vortex_array::arrays::struct_::StructArrayExt; +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::PType; +use vortex_array::dtype::StructFields; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProviderExt; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarValue; +use vortex_array::scalar_fn::builtin::operators::Operator; +use vortex_array::validity::Validity; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -18,41 +45,15 @@ use vortex_error::vortex_err; use vortex_session::VortexSession; use vortex_session::registry::CachedId; -use crate::ArrayRef; -use crate::ArrayView; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum::SumState; -use crate::aggregate_fn::fns::sum::accumulate_bool; -use crate::aggregate_fn::fns::sum::accumulate_decimal; -use crate::aggregate_fn::fns::sum::accumulate_primitive; -use crate::aggregate_fn::fns::sum::checked_add_sum_states; -use crate::aggregate_fn::fns::sum::make_zero_state; -use crate::aggregate_fn::fns::sum::multiply_constant; -use crate::arrays::Struct; -use crate::arrays::struct_::StructArrayExt; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::FieldName; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::PType; -use crate::dtype::StructFields; -use crate::scalar::Scalar; -use crate::scalar::ScalarValue; -use crate::scalar_fn::builtin::operators::BooleanOperator; -use crate::stats::Precision; -use crate::stats::Stat; -use crate::stats::StatsProviderExt; -use crate::validity::Validity; +use crate::sum::Sum; +use crate::sum::SumState; +use crate::sum::accumulate_bool; +use crate::sum::accumulate_decimal; +use crate::sum::accumulate_primitive; +use crate::sum::checked_add_sum_states; +use crate::sum::make_zero_state; +use crate::sum::multiply_constant; +use vortex_array::scalar_fn::builtin::operators::BooleanOperator; const SUM_FIELD: &str = "sum"; const IS_OVERFLOW_FIELD: &str = "is_overflow"; @@ -60,7 +61,7 @@ const IS_EMPTY_FIELD: &str = "is_empty"; /// Return the SQL-style sum of an array. /// -/// Unlike [`sum`](crate::aggregate_fn::fns::sum::sum), this returns null when the array has no +/// Unlike [`sum`](crate::sum::sum), this returns null when the array has no /// valid values. pub fn sum_v2(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { let mut acc = Accumulator::try_new( diff --git a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs b/vortex-aggregates/src/sum_v2/tests.rs similarity index 91% rename from vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs rename to vortex-aggregates/src/sum_v2/tests.rs index 4251fec4cbd..1366e126bbb 100644 --- a/vortex-array/src/aggregate_fn/fns/sum_v2/tests.rs +++ b/vortex-aggregates/src/sum_v2/tests.rs @@ -5,48 +5,52 @@ use std::sync::LazyLock; use prost::Message; use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateDTypes; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::DynGroupedAccumulator; +use vortex_array::aggregate_fn::GroupedAccumulator; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::BoolArray; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::assert_arrays_eq; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::proto::expr as pb; +use vortex_array::scalar::Scalar; +use vortex_array::scalar::ScalarValue; +use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; use super::SumV2; use super::sum_v2; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::VortexSessionExecute; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateDTypes; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::AggregateFnVTableExt; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::DynGroupedAccumulator; -use crate::aggregate_fn::GroupedAccumulator; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::sum::Sum; -use crate::arrays::BoolArray; -use crate::arrays::ChunkedArray; -use crate::arrays::ConstantArray; -use crate::arrays::DecimalArray; -use crate::arrays::ListViewArray; -use crate::arrays::PrimitiveArray; -use crate::arrays::StructArray; -use crate::assert_arrays_eq; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::FieldNames; -use crate::dtype::Nullability; -use crate::dtype::Nullability::Nullable; -use crate::dtype::PType; -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); +use crate::sum::Sum; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); fn sum_with_options(array: &ArrayRef, options: NumericalAggregateOpts) -> VortexResult { let mut accumulator = Accumulator::try_new(SumV2, options, array.dtype().clone())?; diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/bool.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/bool.rs similarity index 91% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/bool.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/bool.rs index 4c5c0a4df8d..466da1795d9 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/bool.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/bool.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::BoolArray; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::packed_bit_buffer_size_in_bytes; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::BoolArray; pub(super) fn bool_uncompressed_size_in_bytes( array: &BoolArray, diff --git a/vortex-array/src/arrays/constant/compute/uncompressed_size.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/constant_tests.rs similarity index 83% rename from vortex-array/src/arrays/constant/compute/uncompressed_size.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/constant_tests.rs index d4e79f843c3..db3d111680e 100644 --- a/vortex-array/src/arrays/constant/compute/uncompressed_size.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/constant_tests.rs @@ -10,23 +10,23 @@ mod tests { use vortex_error::vortex_err; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::Canonical; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; - use crate::aggregate_fn::fns::uncompressed_size_in_bytes::canonical_uncompressed_size_in_bytes; - use crate::arrays::BoolArray; - use crate::arrays::ConstantArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::validity::Validity; + use vortex_array::ArrayRef; + use vortex_array::Canonical; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use crate::uncompressed_size_in_bytes::UncompressedSizeInBytes; + use crate::uncompressed_size_in_bytes::canonical_uncompressed_size_in_bytes; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; + use vortex_array::validity::Validity; + use vortex_array::aggregate_fn::EmptyOptions; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/decimal.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/decimal.rs similarity index 89% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/decimal.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/decimal.rs index 8fb1c8a94fe..d8b6c0ef0b0 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/decimal.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/decimal.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::decimal::DecimalArrayExt; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::DecimalArray; -use crate::arrays::decimal::DecimalArrayExt; pub(super) fn decimal_uncompressed_size_in_bytes( array: &DecimalArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/extension.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/extension.rs similarity index 74% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/extension.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/extension.rs index a125c417ea3..371e142c35f 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/extension.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/extension.rs @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::extension::ExtensionArrayExt; use vortex_error::VortexResult; use super::uncompressed_size_in_bytes_u64; -use crate::ExecutionCtx; -use crate::arrays::ExtensionArray; -use crate::arrays::extension::ExtensionArrayExt; pub(super) fn extension_uncompressed_size_in_bytes( array: &ExtensionArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/fixed_size_list.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/fixed_size_list.rs similarity index 84% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/fixed_size_list.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/fixed_size_list.rs index 03512cb8345..004a593dad7 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/fixed_size_list.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/fixed_size_list.rs @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::FixedSizeListArray; +use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::uncompressed_size_in_bytes_u64; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::FixedSizeListArray; -use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt; pub(super) fn fixed_size_list_uncompressed_size_in_bytes( array: &FixedSizeListArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/list_view.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/list_view.rs similarity index 93% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/list_view.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/list_view.rs index 9c1c58c35ba..18496c63d1f 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/list_view.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/list_view.rs @@ -1,6 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::ListViewArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::listview::ListViewArraySlotsExt; +use vortex_array::arrays::listview::ListViewRebuildMode; +use vortex_array::arrays::primitive::PrimitiveArrayExt; +use vortex_array::dtype::DType; +use vortex_array::dtype::IntegerPType; +use vortex_array::match_each_integer_ptype; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_mask::Mask; @@ -9,15 +18,6 @@ use super::checked_len_mul; use super::packed_bit_buffer_size_in_bytes; use super::uncompressed_size_in_bytes_u64; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::ListViewArray; -use crate::arrays::PrimitiveArray; -use crate::arrays::listview::ListViewArraySlotsExt; -use crate::arrays::listview::ListViewRebuildMode; -use crate::arrays::primitive::PrimitiveArrayExt; -use crate::dtype::DType; -use crate::dtype::IntegerPType; -use crate::match_each_integer_ptype; pub(super) fn list_view_uncompressed_size_in_bytes( array: &ListViewArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs similarity index 89% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs index d8cabcd1192..c6fe7f5344b 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/mod.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs @@ -24,6 +24,32 @@ use primitive::primitive_uncompressed_size_in_bytes; use struct_::struct_uncompressed_size_in_bytes; use union::union_uncompressed_size_in_bytes; use varbinview::varbinview_uncompressed_size_in_bytes; +use vortex_array::ArrayRef; +use vortex_array::ArrayView; +use vortex_array::Canonical; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::aggregate_fn::Accumulator; +use vortex_array::aggregate_fn::AggregateArgs; +use vortex_array::aggregate_fn::AggregateFnId; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::DynAccumulator; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::aggregate_fn::stat_aggregates::supports_uncompressed_size_in_bytes; +use vortex_array::arrays::Constant; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::ListView; +use vortex_array::arrays::map::MapArraySlotsExt; +use vortex_array::arrays::varbinview::BinaryView; +use vortex_array::dtype::DType; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -31,34 +57,6 @@ use vortex_error::vortex_err; use vortex_mask::Mask; use vortex_session::VortexSession; -use crate::ArrayRef; -use crate::Canonical; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::aggregate_fn::Accumulator; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::AggregateFnId; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::DynAccumulator; -use crate::aggregate_fn::stat_aggregates; -pub use crate::aggregate_fn::stat_aggregates::UncompressedSizeOpts; -pub use crate::aggregate_fn::stat_aggregates::UncompressedSizePrecision; -use crate::aggregate_fn::EmptyOptions; -use crate::array::ArrayView; -use crate::arrays::Constant; -use crate::arrays::ConstantArray; -use crate::arrays::ListView; -use crate::arrays::map::MapArraySlotsExt; -use crate::arrays::varbinview::BinaryView; -use crate::dtype::DType; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::PType; -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. /// /// See [`UncompressedSizeInBytes`] for details. The result is cached as a statistic on `array` and @@ -105,7 +103,7 @@ pub struct UncompressedSizeInBytes; impl UncompressedSizeInBytes { /// Whether arrays of `dtype` can be measured. Variant arrays cannot. pub fn supports_dtype(dtype: &DType) -> bool { - stat_aggregates::supports_uncompressed_size_in_bytes(dtype) + supports_uncompressed_size_in_bytes(dtype) } } @@ -130,7 +128,7 @@ impl AggregateFnVTable for UncompressedSizeInBytes { } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - stat_aggregates::supports_uncompressed_size_in_bytes(input_dtype) + supports_uncompressed_size_in_bytes(input_dtype) .then_some(DType::Primitive(PType::U64, NonNullable)) } @@ -341,6 +339,46 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; + use vortex_array::ArrayRef; + use vortex_array::IntoArray; + use vortex_array::RecursiveCanonical; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::AggregateDTypes; + use vortex_array::aggregate_fn::AggregateFnVTable; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::ChunkedArray; + use vortex_array::arrays::ConstantArray; + use vortex_array::arrays::DecimalArray; + use vortex_array::arrays::ExtensionArray; + use vortex_array::arrays::FixedSizeListArray; + use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::NullArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::StructArray; + use vortex_array::arrays::UnionArray; + use vortex_array::arrays::VarBinViewArray; + use vortex_array::arrays::VariantArray; + use vortex_array::arrays::listview::ListViewRebuildMode; + use vortex_array::arrays::varbinview::BinaryView; + use vortex_array::builders::builder_with_capacity_in; + use vortex_array::dtype::DType; + use vortex_array::dtype::DecimalDType; + use vortex_array::dtype::FieldNames; + use vortex_array::dtype::Nullability; + use vortex_array::dtype::PType; + use vortex_array::dtype::UnionVariants; + use vortex_array::stats::Precision; + use vortex_array::stats::Stat; + use vortex_array::stats::StatsProvider; + use vortex_array::extension::datetime::Date; + use vortex_array::extension::datetime::TimeUnit; + use vortex_array::scalar::Scalar; + use vortex_array::scalar::ScalarValue; + use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::ByteBuffer; use vortex_buffer::buffer; @@ -349,50 +387,14 @@ mod tests { use vortex_error::vortex_err; use vortex_session::VortexSession; - use crate::ArrayRef; - use crate::IntoArray; - use crate::RecursiveCanonical; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateDTypes; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; - use crate::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::ConstantArray; - use crate::arrays::DecimalArray; - use crate::arrays::ExtensionArray; - use crate::arrays::FixedSizeListArray; - use crate::arrays::ListViewArray; - use crate::arrays::NullArray; - use crate::arrays::PrimitiveArray; - use crate::arrays::StructArray; - use crate::arrays::UnionArray; - use crate::arrays::VarBinViewArray; - use crate::arrays::VariantArray; - use crate::arrays::listview::ListViewRebuildMode; - use crate::arrays::varbinview::BinaryView; - use crate::builders::builder_with_capacity_in; - use crate::dtype::DType; - use crate::dtype::DecimalDType; - use crate::dtype::FieldNames; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::dtype::UnionVariants; - 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); + use crate::uncompressed_size_in_bytes::UncompressedSizeInBytes; + use crate::uncompressed_size_in_bytes::uncompressed_size_in_bytes; + + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session + }); /// The size the array occupies once rebuilt through the canonical builders, which is the /// layout [`UncompressedSizeInBytes`] is defined against: the builders normalize physical diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/null.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/null.rs similarity index 83% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/null.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/null.rs index e2687e9d19d..927042a2df5 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/null.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/null.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use crate::arrays::NullArray; +use vortex_array::arrays::NullArray; pub(super) fn null_uncompressed_size_in_bytes(_array: &NullArray) -> u64 { 0 diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/primitive.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/primitive.rs similarity index 89% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/primitive.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/primitive.rs index 8ca149e791a..bc4ebd2e4fc 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/primitive.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/primitive.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::PrimitiveArray; -use crate::arrays::primitive::PrimitiveArrayExt; pub(super) fn primitive_uncompressed_size_in_bytes( array: &PrimitiveArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/struct_.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/struct_.rs similarity index 88% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/struct_.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/struct_.rs index ffed40babd2..4281b81d49b 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/struct_.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/struct_.rs @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::struct_::StructArrayExt; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::uncompressed_size_in_bytes_u64; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::StructArray; -use crate::arrays::struct_::StructArrayExt; pub(super) fn struct_uncompressed_size_in_bytes( array: &StructArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/union.rs similarity index 79% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/union.rs index cf43ed4e186..127113a4548 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/union.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/union.rs @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_array::ExecutionCtx; +use vortex_array::arrays::UnionArray; +use vortex_array::arrays::union::UnionArrayExt; +use vortex_array::arrays::union::UnionArraySlotsExt; use vortex_error::VortexResult; use vortex_error::vortex_err; use super::uncompressed_size_in_bytes_u64; -use crate::ExecutionCtx; -use crate::arrays::UnionArray; -use crate::arrays::union::UnionArrayExt; -use crate::arrays::union::UnionArraySlotsExt; pub(super) fn union_uncompressed_size_in_bytes( array: &UnionArray, diff --git a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/varbinview.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/varbinview.rs similarity index 94% rename from vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/varbinview.rs rename to vortex-aggregates/src/uncompressed_size_in_bytes/varbinview.rs index 50b1890b746..a09357d9fce 100644 --- a/vortex-array/src/aggregate_fn/fns/uncompressed_size_in_bytes/varbinview.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/varbinview.rs @@ -3,14 +3,14 @@ use std::mem::size_of; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::VarBinViewArray; +use vortex_array::arrays::varbinview::BinaryView; use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_mask::Mask; use super::validity_uncompressed_size_in_bytes; -use crate::ExecutionCtx; -use crate::arrays::VarBinViewArray; -use crate::arrays::varbinview::BinaryView; pub(super) fn varbinview_uncompressed_size_in_bytes( array: &VarBinViewArray, diff --git a/vortex-array/src/arrays/widen/compute/aggregate.rs b/vortex-aggregates/src/widen/mod.rs similarity index 89% rename from vortex-array/src/arrays/widen/compute/aggregate.rs rename to vortex-aggregates/src/widen/mod.rs index 6aa15593430..fb413e8c705 100644 --- a/vortex-array/src/arrays/widen/compute/aggregate.rs +++ b/vortex-aggregates/src/widen/mod.rs @@ -6,30 +6,30 @@ //! Results must match aggregation over the widened values. Widening preserves order and equality, //! but sums also depend on the logical dtype's precision and overflow rules. +use vortex_array::ArrayRef; +use vortex_array::Columnar; +use vortex_array::ExecutionCtx; +use vortex_array::aggregate_fn::AggregateDTypes; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTable; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::kernels::DynAggregateKernel; +use vortex_array::arrays::Widen; +use vortex_array::arrays::widen::WidenArraySlotsExt; +use vortex_array::dtype::DType; +use vortex_array::stats::Stat; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; -use crate::ArrayRef; -use crate::Columnar; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateDTypes; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::MinMaxResult; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::kernels::DynAggregateKernel; -use crate::arrays::Widen; -use crate::arrays::widen::WidenArraySlotsExt; -use crate::dtype::DType; -use crate::scalar::Scalar; -use crate::stats::Stat; +use crate::is_constant::IsConstant; +use crate::is_sorted::IsSorted; +use crate::max::Max; +use crate::min::Min; +use crate::min_max::MinMax; +use crate::min_max::MinMaxResult; +use crate::min_max::min_max; +use crate::sum::Sum; /// Computes aggregate partials from a [`Widen`]'s child without materializing widened values. #[derive(Debug)] @@ -191,3 +191,6 @@ fn is_exact_sum(aggregate_fn: &AggregateFnRef, batch: &ArrayRef, values: &ArrayR Stat::from_aggregate_fn(aggregate_fn) == Some(Stat::Sum) && batch.len() as u64 <= max_len } + +#[cfg(test)] +mod tests; diff --git a/vortex-array/src/arrays/widen/tests/aggregates.rs b/vortex-aggregates/src/widen/tests/aggregates.rs similarity index 85% rename from vortex-array/src/arrays/widen/tests/aggregates.rs rename to vortex-aggregates/src/widen/tests/aggregates.rs index 7b4d7b1ba72..4e407e84eed 100644 --- a/vortex-array/src/arrays/widen/tests/aggregates.rs +++ b/vortex-aggregates/src/widen/tests/aggregates.rs @@ -9,57 +9,58 @@ use std::fmt::Debug; use std::num::NonZeroUsize; use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VTable; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +use vortex_array::arrays::ChunkedArray; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::Widen; +use vortex_array::arrays::WidenArray; +use vortex_array::builtins::ArrayBuiltins; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::dtype::PType; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use super::SESSION; use super::widen; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::VTable; -use crate::VortexSessionExecute; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTableExt; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::all_non_null::AllNonNull; -use crate::aggregate_fn::fns::all_null::AllNull; -use crate::aggregate_fn::fns::bounded_max::BoundedMax; -use crate::aggregate_fn::fns::bounded_max::BoundedMaxOptions; -use crate::aggregate_fn::fns::bounded_min::BoundedMin; -use crate::aggregate_fn::fns::bounded_min::BoundedMinOptions; -use crate::aggregate_fn::fns::count::Count; -use crate::aggregate_fn::fns::first::First; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; -use crate::aggregate_fn::fns::last::Last; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::make_minmax_dtype; -use crate::aggregate_fn::fns::null_count::NullCount; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum_v2::SumV2; -use crate::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; -use crate::arrays::ChunkedArray; -use crate::arrays::ConstantArray; -use crate::arrays::DecimalArray; -use crate::arrays::PrimitiveArray; -use crate::arrays::Widen; -use crate::arrays::WidenArray; -use crate::builtins::ArrayBuiltins; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::Nullability; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::Nullability::Nullable; -use crate::dtype::PType; -use crate::scalar::DecimalValue; -use crate::scalar::Scalar; -use crate::stats::Precision; -use crate::stats::Stat; +use crate::all_non_null::AllNonNull; +use crate::all_null::AllNull; +use crate::bounded_max::BoundedMax; +use crate::bounded_max::BoundedMaxOptions; +use crate::bounded_min::BoundedMin; +use crate::bounded_min::BoundedMinOptions; +use crate::count::Count; +use crate::first::First; +use crate::is_constant::IsConstant; +use crate::is_sorted::IsSorted; +use crate::is_sorted::IsSortedOptions; +use crate::last::Last; +use crate::max::Max; +use crate::min::Min; +use crate::min_max::MinMax; +use crate::min_max::make_minmax_dtype; +use crate::null_count::NullCount; +use crate::sum::Sum; +use crate::sum_v2::SumV2; +use crate::uncompressed_size_in_bytes::UncompressedSizeInBytes; /// Every aggregate that applies to integers, and whether the `Widen` aggregate kernel serves it. fn aggregates() -> Vec<(AggregateFnRef, bool)> { @@ -107,8 +108,8 @@ pub(super) fn kernel_partial( array: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - match ctx - .aggregate_kernels() + match SESSION + .aggregate_fns() .find_aggregate_kernel(Widen.id(), aggregate.id()) { Some(kernel) => kernel.aggregate(aggregate, array, ctx), diff --git a/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs b/vortex-aggregates/src/widen/tests/decimal_aggregates.rs similarity index 87% rename from vortex-array/src/arrays/widen/tests/decimal_aggregates.rs rename to vortex-aggregates/src/widen/tests/decimal_aggregates.rs index 668258fefb1..de8b15611ae 100644 --- a/vortex-array/src/arrays/widen/tests/decimal_aggregates.rs +++ b/vortex-aggregates/src/widen/tests/decimal_aggregates.rs @@ -6,47 +6,47 @@ //! Compares decimal [`Widen`] arrays with canonical inputs and checks sum precision and statistics. use rstest::rstest; +use vortex_array::ArrayRef; +use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::aggregate_fn::AggregateFnVTableExt; +use vortex_array::aggregate_fn::EmptyOptions; +use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::arrays::ConstantArray; +use vortex_array::arrays::DecimalArray; +use vortex_array::arrays::Widen; +use vortex_array::arrays::WidenArray; +use vortex_array::arrays::widen::WidenArraySlotsExt; +use vortex_array::dtype::BigCast; +use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::Nullability; +use vortex_array::dtype::Nullability::NonNullable; +use vortex_array::dtype::Nullability::Nullable; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; +use vortex_array::match_each_decimal_value_type; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use super::SESSION; use super::aggregates::assert_aggregate_batches; use super::aggregates::kernel_partial; -use crate::ArrayRef; -use crate::ExecutionCtx; -use crate::IntoArray; -use crate::VortexSessionExecute; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTableExt; -use crate::aggregate_fn::EmptyOptions; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::first::First; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; -use crate::aggregate_fn::fns::last::Last; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum_v2::SumV2; -use crate::arrays::ConstantArray; -use crate::arrays::DecimalArray; -use crate::arrays::Widen; -use crate::arrays::WidenArray; -use crate::arrays::widen::WidenArraySlotsExt; -use crate::dtype::BigCast; -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::Nullability; -use crate::dtype::Nullability::NonNullable; -use crate::dtype::Nullability::Nullable; -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::first::First; +use crate::is_constant::IsConstant; +use crate::is_sorted::IsSorted; +use crate::is_sorted::IsSortedOptions; +use crate::last::Last; +use crate::max::Max; +use crate::min::Min; +use crate::min_max::MinMax; +use crate::sum::Sum; +use crate::sum_v2::SumV2; /// Decimal aggregates paired with whether the [`Widen`] kernel must return a partial. fn aggregates() -> Vec<(AggregateFnRef, bool)> { diff --git a/vortex-aggregates/src/widen/tests/mod.rs b/vortex-aggregates/src/widen/tests/mod.rs new file mode 100644 index 00000000000..4667cd5b807 --- /dev/null +++ b/vortex-aggregates/src/widen/tests/mod.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Tests of aggregates over integer and decimal `Widen` arrays. + +mod aggregates; +mod decimal_aggregates; + +use std::sync::LazyLock; + +use vortex_array::IntoArray; +use vortex_array::arrays::WidenArray; +use vortex_array::dtype::DType; +use vortex_array::dtype::PType; +use vortex_error::VortexExpect; +use vortex_session::VortexSession; + +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + crate::initialize(&session); + session +}); + +/// Returns a `Widen` of the `logical` type over `values`, with the nullability of `values`. +fn widen(values: impl IntoArray, logical: PType) -> WidenArray { + let values = values.into_array(); + let dtype = DType::Primitive(logical, values.dtype().nullability()); + WidenArray::try_new(values, dtype).vortex_expect("fixture values are narrower integers") +} diff --git a/vortex-array/Cargo.toml b/vortex-array/Cargo.toml index 55538b37b4d..8046e10856b 100644 --- a/vortex-array/Cargo.toml +++ b/vortex-array/Cargo.toml @@ -93,6 +93,7 @@ rstest = { workspace = true } serde_json = { workspace = true } serde_test = { workspace = true } test-with = { workspace = true } +vortex-aggregates = { path = "../vortex-aggregates" } vortex-array = { path = ".", features = [ "_test-harness", "table-display", @@ -106,18 +107,6 @@ vortex-functions = { path = "../vortex-functions" } name = "block_program" harness = false -[[bench]] -name = "aggregate_max" -harness = false - -[[bench]] -name = "aggregate_sum" -harness = false - -[[bench]] -name = "aggregate_definedness" -harness = false - [[bench]] name = "cast_primitive" harness = false diff --git a/vortex-array/benches/run_end_sum.rs b/vortex-array/benches/run_end_sum.rs index 63d47ea3107..87f17ca7f60 100644 --- a/vortex-array/benches/run_end_sum.rs +++ b/vortex-array/benches/run_end_sum.rs @@ -7,10 +7,10 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; +use vortex_aggregates::sum_v2::sum_v2; use vortex_array::ArrayRef; use vortex_array::IntoArray; 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::arrays::runend::RunEnd; diff --git a/vortex-array/benches/scalar_construction.rs b/vortex-array/benches/scalar_construction.rs index a39a0c7579f..1c46804ba9a 100644 --- a/vortex-array/benches/scalar_construction.rs +++ b/vortex-array/benches/scalar_construction.rs @@ -15,9 +15,6 @@ use divan::counter::ItemsCount; use mimalloc::MiMalloc; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::AggregateFnVTableExt; -use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; @@ -187,14 +184,3 @@ fn stats_merge_ordered(bencher: Bencher) { } }); } - -#[divan::bench] -fn accumulator_sum_v2(bencher: Bencher) { - let dtype = DType::Primitive(PType::I64, Nullability::Nullable); - let aggregate_fn = SumV2.bind(NumericalAggregateOpts::default()); - bencher.counter(ItemsCount::new(N)).bench_local(|| { - for _ in 0..N { - black_box(aggregate_fn.accumulator(black_box(&dtype)).unwrap()); - } - }); -} diff --git a/vortex-array/benches/widen.rs b/vortex-array/benches/widen.rs index 621a5333bca..85e167f2d7f 100644 --- a/vortex-array/benches/widen.rs +++ b/vortex-array/benches/widen.rs @@ -14,14 +14,14 @@ use mimalloc::MiMalloc; use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; +use vortex_aggregates::min_max; +use vortex_aggregates::sum; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::min_max; -use vortex_array::aggregate_fn::fns::sum; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; @@ -73,6 +73,7 @@ static SESSION: LazyLock = LazyLock::new(|| { .with::() .with::() .with::(); + vortex_aggregates::initialize(&session); vortex_functions::initialize(&session); session }); diff --git a/vortex-array/src/aggregate_fn/accumulator.rs b/vortex-array/src/aggregate_fn/accumulator.rs index f88dfc1b1c9..1eb483f6989 100644 --- a/vortex-array/src/aggregate_fn/accumulator.rs +++ b/vortex-array/src/aggregate_fn/accumulator.rs @@ -378,179 +378,3 @@ impl DynAccumulator for Accumulator { Ok(result) } } - -#[cfg(test)] -mod tests { - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_session::SessionExt; - use vortex_session::VortexSession; - - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AccumulatorRef; - use crate::aggregate_fn::AggregateFnRef; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min::Min; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::kernels::DynAggregateKernel; - use crate::aggregate_fn::session::AggregateFnSession; - use crate::array::VTable; - use crate::arrays::Dict; - use crate::arrays::DictArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - use crate::scalar::ScalarValue; - use crate::stats::Precision; - use crate::stats::Stat; - use crate::stats::StatsProvider; - use crate::stats::StatsProviderExt; - - /// A sentinel sum of `42.0`, distinguishable from `dict_of_seven()`'s natural sum of `7.0`. - #[derive(Debug)] - struct SentinelSumPartialKernel; - impl DynAggregateKernel for SentinelSumPartialKernel { - fn aggregate( - &self, - _aggregate_fn: &AggregateFnRef, - _batch: &ArrayRef, - _ctx: &mut ExecutionCtx, - ) -> VortexResult> { - Ok(Some(Scalar::primitive(42.0f64, Nullability::Nullable))) - } - } - - fn fresh_session() -> VortexSession { - VortexSession::empty() - } - - fn dict_of_seven() -> ArrayRef { - DictArray::try_new(buffer![0u32].into_array(), buffer![7.0f64].into_array()) - .expect("valid dictionary") - .into_array() - } - - #[test] - fn cached_sum_precedes_encoding_kernel() -> VortexResult<()> { - static KERNEL: SentinelSumPartialKernel = SentinelSumPartialKernel; - let session = fresh_session(); - session - .get::() - .register_aggregate_kernel(Dict.id(), Some(Sum.id()), &KERNEL); - let mut ctx = session.create_execution_ctx(); - - let batch = dict_of_seven(); - batch - .statistics() - .set(Stat::Sum, Precision::Exact(ScalarValue::from(7.0f64))); - - let dtype = DType::Primitive(PType::F64, Nullability::NonNullable); - let mut acc = Accumulator::try_new(Sum, NumericalAggregateOpts::default(), dtype)?; - acc.accumulate(&batch, &mut ctx)?; - - assert_eq!(acc.finish()?.as_primitive().as_::(), Some(7.0)); - Ok(()) - } - - /// Each batch caches its own result, not the running result and not on the canonical array - /// it executes into. - #[test] - fn caches_result_on_requested_batch() -> VortexResult<()> { - let mut ctx = fresh_session().create_execution_ctx(); - let dict = |codes: ArrayRef| -> VortexResult { - Ok(DictArray::try_new(codes, buffer![5i32, 1, 9].into_array())?.into_array()) - }; - let batch1 = dict(buffer![0u32, 1, 2].into_array())?; - let batch2 = dict(buffer![2u32, 0].into_array())?; - - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let mut acc = Accumulator::try_new(Min, NumericalAggregateOpts::default(), dtype)?; - acc.accumulate(&batch1, &mut ctx)?; - acc.accumulate(&batch2, &mut ctx)?; - - assert_eq!( - acc.finish()?, - Scalar::primitive(1i32, Nullability::Nullable) - ); - assert_eq!( - batch1.statistics().get_as::(Stat::Min), - Precision::exact(1i32) - ); - assert_eq!( - batch2.statistics().get_as::(Stat::Min), - Precision::exact(5i32) - ); - Ok(()) - } - - #[test] - fn overflowed_sum_is_not_cached() -> VortexResult<()> { - let mut ctx = fresh_session().create_execution_ctx(); - let batch = buffer![i64::MAX, i64::MAX].into_array(); - - let dtype = DType::Primitive(PType::I64, Nullability::NonNullable); - let mut acc = Accumulator::try_new(Sum, NumericalAggregateOpts::default(), dtype)?; - acc.accumulate(&batch, &mut ctx)?; - - assert!(acc.finish()?.is_null()); - assert!(batch.statistics().get(Stat::Sum).as_exact().is_none()); - Ok(()) - } - - fn sum_i32_accumulator(options: NumericalAggregateOpts) -> VortexResult { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - Ok(Box::new(Accumulator::try_new(Sum, options, dtype)?)) - } - - #[test] - fn merge_from_drains_other_accumulator() -> VortexResult<()> { - let mut ctx = fresh_session().create_execution_ctx(); - let mut global = sum_i32_accumulator(NumericalAggregateOpts::default())?; - let mut local = sum_i32_accumulator(NumericalAggregateOpts::default())?; - - global.accumulate(&buffer![10i32, 20].into_array(), &mut ctx)?; - local.accumulate(&buffer![5i32].into_array(), &mut ctx)?; - global.merge_from(local.as_mut())?; - - assert_eq!( - global.finish()?, - Scalar::primitive(35i64, Nullability::Nullable) - ); - // The merged-from accumulator is reset back to the empty state. - assert_eq!( - local.finish()?, - Scalar::primitive(0i64, Nullability::Nullable) - ); - Ok(()) - } - - #[test] - fn merge_from_rejects_a_different_aggregate() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let mut sum = sum_i32_accumulator(NumericalAggregateOpts::default())?; - let mut min: AccumulatorRef = Box::new(Accumulator::try_new( - Min, - NumericalAggregateOpts::default(), - dtype, - )?); - - assert!(sum.merge_from(min.as_mut()).is_err()); - Ok(()) - } - - #[test] - fn merge_from_rejects_mismatched_options() -> VortexResult<()> { - let mut skipping = sum_i32_accumulator(NumericalAggregateOpts::skip_nans())?; - let mut including = sum_i32_accumulator(NumericalAggregateOpts::include_nans())?; - - assert!(skipping.merge_from(including.as_mut()).is_err()); - Ok(()) - } -} diff --git a/vortex-array/src/aggregate_fn/accumulator_grouped.rs b/vortex-array/src/aggregate_fn/accumulator_grouped.rs index 1b22b98f3da..4965d2033b6 100644 --- a/vortex-array/src/aggregate_fn/accumulator_grouped.rs +++ b/vortex-array/src/aggregate_fn/accumulator_grouped.rs @@ -437,14 +437,19 @@ mod tests { use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; + use vortex_session::registry::CachedId; use crate::ArrayRef; + use crate::Columnar; + use crate::ExecutionCtx; use crate::IntoArray; use crate::VortexSessionExecute; + use crate::aggregate_fn::AggregateArgs; + use crate::aggregate_fn::AggregateFnId; + use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::DynGroupedAccumulator; use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::GroupedAccumulator; - use crate::aggregate_fn::fns::null_count::NullCount; use crate::arrays::Chunked; use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; @@ -454,12 +459,111 @@ mod tests { use crate::dtype::Nullability::Nullable; use crate::dtype::PType; use crate::validity::Validity; + use crate::scalar::Scalar; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - fn accumulator() -> VortexResult> { + static ROW_COUNT_ID: CachedId = CachedId::new("test.row_count"); + + /// A minimal aggregate counting rows, so these tests need no concrete aggregate function. + #[derive(Clone, Debug)] + struct RowCount; + + impl AggregateFnVTable for RowCount { + type Options = EmptyOptions; + type Partial = u64; + + fn id(&self) -> AggregateFnId { + *ROW_COUNT_ID + } + + fn deserialize( + &self, + _metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + Ok(EmptyOptions) + } + + fn return_dtype(&self, _options: &Self::Options, _input_dtype: &DType) -> Option { + Some(DType::Primitive(PType::U64, NonNullable)) + } + + fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { + self.return_dtype(options, input_dtype) + } + + fn empty_partial( + &self, + _args: AggregateArgs<'_, Self::Options>, + ) -> VortexResult { + Ok(0) + } + + fn partial_from_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + scalar: &Scalar, + ) -> VortexResult { + Ok(scalar.as_primitive().typed_value::().unwrap_or(0)) + } + + fn merge_partials( + &self, + _args: AggregateArgs<'_, Self::Options>, + first: Self::Partial, + second: Self::Partial, + ) -> VortexResult { + Ok(first + second) + } + + fn to_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + partial: &Self::Partial, + ) -> VortexResult { + Ok(Scalar::primitive(*partial, NonNullable)) + } + + fn is_saturated( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &Self::Partial, + ) -> bool { + false + } + + fn accumulate( + &self, + _args: AggregateArgs<'_, Self::Options>, + partial: &mut Self::Partial, + batch: &Columnar, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + *partial += batch.len() as u64; + Ok(()) + } + + fn finalize( + &self, + _args: AggregateArgs<'_, Self::Options>, + partials: ArrayRef, + ) -> VortexResult { + Ok(partials) + } + + fn finalize_scalar( + &self, + args: AggregateArgs<'_, Self::Options>, + partial: &Self::Partial, + ) -> VortexResult { + self.to_scalar(args, partial) + } + } + + fn accumulator() -> VortexResult> { GroupedAccumulator::try_new( - NullCount, + RowCount, EmptyOptions, DType::Primitive(PType::I32, NonNullable), ) diff --git a/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs b/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs deleted file mode 100644 index db6aaefa0c7..00000000000 --- a/vortex-array/src/aggregate_fn/fns/min_max/decimal.rs +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -use vortex_compute::lane_kernels::IndexedFoldExt; -use vortex_error::VortexExpect; -use vortex_error::VortexResult; -use vortex_mask::Mask; - -use super::MinMaxPartial; -use super::MinMaxResult; -use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateArgs; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::arrays::DecimalArray; -use crate::dtype::DecimalType; -use crate::dtype::NativeDecimalType; -use crate::dtype::Nullability::NonNullable; -use crate::match_each_decimal_value_type; -use crate::scalar::DecimalValue; -use crate::scalar::Scalar; - -pub(super) fn accumulate_decimal( - args: AggregateArgs<'_, NumericalAggregateOpts>, - partial: &mut MinMaxPartial, - array: &DecimalArray, - ctx: &mut ExecutionCtx, -) -> VortexResult<()> { - let local = match_each_decimal_value_type!(array.values_type(), |T| { - compute_min_max_with_validity::(array, ctx) - })?; - partial.merge(args, local) -} - -fn compute_min_max_with_validity( - array: &DecimalArray, - ctx: &mut ExecutionCtx, -) -> VortexResult> -where - D: Into + NativeDecimalType, -{ - let validity = array - .as_ref() - .validity()? - .execute_mask(array.as_ref().len(), ctx)?; - if matches!(&validity, Mask::AllFalse(_)) { - return Ok(None); - } - - let decimal_dtype = array.decimal_dtype(); - - let Some((min, max)) = valid_range(array.buffer::().as_slice(), &validity) else { - return Ok(None); - }; - - let min_scalar = Scalar::try_decimal(min.into(), decimal_dtype, NonNullable)?; - let max_scalar = if min == max { - min_scalar.clone() - } else { - Scalar::try_decimal(max.into(), decimal_dtype, NonNullable)? - }; - - Ok(Some(MinMaxResult { - min: min_scalar, - max: max_scalar, - })) -} - -/// Returns the smallest and the largest valid value, or `None` when no value is valid. -/// -/// Null slots can hold any value and do not contribute to the range. The scan allocates nothing -/// and does not check decimal precision. -/// -/// # Panics -/// -/// Panics if `validity` and `values` have different lengths. -pub fn valid_range(values: &[T], validity: &Mask) -> Option<(T, T)> { - assert_eq!( - validity.len(), - values.len(), - "valid_range requires one validity bit per value" - ); - - let min_max = |(min, max): (T, T), v: T| (min.min(v), max.max(v)); - match validity { - Mask::AllTrue(_) if T::DECIMAL_TYPE == DecimalType::I256 => wide_range(values.iter()), - Mask::AllTrue(_) => values - .first() - .map(|&first| values.iter().copied().fold((first, first), min_max)), - Mask::AllFalse(_) => None, - Mask::Values(validity) - if matches!(T::DECIMAL_TYPE, DecimalType::I128 | DecimalType::I256) => - { - wide_range(validity.bit_buffer().set_indices().map(|i| &values[i])) - } - // Null lanes read as a valid value, which leaves both extrema unchanged, so the reduction - // needs no branch per lane. - Mask::Values(validity) => validity.bit_buffer().set_indices().next().map(|first| { - let first = values[first]; - values.fold_masked(validity.bit_buffer(), first, (first, first), min_max) - }), - } -} - -/// Compare the most significant machine word first. Most rows lie strictly between the -/// current extrema, so their remaining words need no comparison. -fn wide_range<'a, T: NativeDecimalType>(mut values: impl Iterator) -> Option<(T, T)> { - let first = values.next()?; - let (mut min_word, mut min) = (leading_word(first), first); - let (mut max_word, mut max) = (min_word, first); - for value in values { - let word = leading_word(value); - if word <= min_word && value < min { - (min_word, min) = (word, value); - } else if word >= max_word && value > max { - (max_word, max) = (word, value); - } - } - Some((*min, *max)) -} - -fn leading_word(value: &T) -> i64 { - let upper = if T::DECIMAL_TYPE == DecimalType::I256 { - value - .to_i256() - .vortex_expect("decimal values fit i256") - .to_parts() - .1 - } else { - value.to_i128().vortex_expect("i128 decimal storage") - }; - (upper >> 64) as i64 -} diff --git a/vortex-array/src/aggregate_fn/fns/mod.rs b/vortex-array/src/aggregate_fn/fns/mod.rs index 7d5684d5a3d..c0f4d813829 100644 --- a/vortex-array/src/aggregate_fn/fns/mod.rs +++ b/vortex-array/src/aggregate_fn/fns/mod.rs @@ -1,19 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -pub mod all_nan; pub mod all_non_distinct; -pub mod all_non_nan; -pub mod all_non_null; -pub mod all_null; -mod fixed_size_bytes; -pub mod is_constant; -pub mod is_sorted; -pub mod max; -pub mod min; -pub mod min_max; -pub mod nan_count; -pub mod null_count; -pub mod sum; -pub mod sum_v2; -pub mod uncompressed_size_in_bytes; diff --git a/vortex-array/src/aggregate_fn/proto.rs b/vortex-array/src/aggregate_fn/proto.rs index f5e37ceb300..f19e3948c2f 100644 --- a/vortex-array/src/aggregate_fn/proto.rs +++ b/vortex-array/src/aggregate_fn/proto.rs @@ -75,300 +75,3 @@ impl AggregateFnRef { vortex_bail!("unknown aggregate function id: {}", proto.id) } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use prost::Message; - use rstest::rstest; - use vortex_error::VortexResult; - use vortex_error::vortex_panic; - use vortex_session::VortexSession; - - use crate::ArrayRef; - use crate::Columnar; - use crate::ExecutionCtx; - use crate::aggregate_fn::AggregateArgs; - use crate::aggregate_fn::AggregateFnId; - use crate::aggregate_fn::AggregateFnRef; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::combined::PairOptions; - use crate::aggregate_fn::fns::count::Count; - use crate::aggregate_fn::fns::first::First; - use crate::aggregate_fn::fns::is_constant::IsConstant; - use crate::aggregate_fn::fns::is_sorted::IsSorted; - use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; - use crate::aggregate_fn::fns::last::Last; - use crate::aggregate_fn::fns::max::Max; - use crate::aggregate_fn::fns::mean::Mean; - use crate::aggregate_fn::fns::min::Min; - use crate::aggregate_fn::fns::null_count::NullCount; - use crate::aggregate_fn::fns::sum::Sum; - use crate::aggregate_fn::session::AggregateFnSession; - use crate::aggregate_fn::session::AggregateFnSessionExt; - use crate::dtype::DType; - use crate::proto::expr as pb; - use crate::scalar::Scalar; - - static SESSION: LazyLock = LazyLock::new(|| { - let session = VortexSession::empty(); - session.aggregate_fns().register(TestAgg); - session - }); - - /// A minimal serializable aggregate function used solely to exercise the serde round-trip. - #[derive(Clone, Debug)] - struct TestAgg; - - impl AggregateFnVTable for TestAgg { - type Options = EmptyOptions; - type Partial = (); - - #[expect(clippy::disallowed_methods, reason = "test-only id")] - fn id(&self) -> AggregateFnId { - AggregateFnId::new("vortex.test.proto") - } - - fn serialize(&self, _options: &Self::Options) -> VortexResult>> { - Ok(Some(vec![])) - } - - fn deserialize( - &self, - _metadata: &[u8], - _session: &VortexSession, - ) -> VortexResult { - Ok(EmptyOptions) - } - - fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - Some(input_dtype.clone()) - } - - fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { - self.return_dtype(options, input_dtype) - } - - fn empty_partial( - &self, - _args: AggregateArgs<'_, Self::Options>, - ) -> VortexResult { - Ok(()) - } - - fn partial_from_scalar( - &self, - _args: AggregateArgs<'_, Self::Options>, - _scalar: &Scalar, - ) -> VortexResult { - Ok(()) - } - - fn merge_partials( - &self, - _args: AggregateArgs<'_, Self::Options>, - _first: Self::Partial, - _second: Self::Partial, - ) -> VortexResult { - Ok(()) - } - - fn to_scalar( - &self, - _args: AggregateArgs<'_, Self::Options>, - _partial: &Self::Partial, - ) -> VortexResult { - vortex_panic!("TestAgg is for serde tests only"); - } - - fn is_saturated( - &self, - _args: AggregateArgs<'_, Self::Options>, - _partial: &Self::Partial, - ) -> bool { - true - } - - fn accumulate( - &self, - _args: AggregateArgs<'_, Self::Options>, - _state: &mut Self::Partial, - _batch: &Columnar, - _ctx: &mut ExecutionCtx, - ) -> VortexResult<()> { - Ok(()) - } - - fn finalize( - &self, - _args: AggregateArgs<'_, Self::Options>, - partials: ArrayRef, - ) -> VortexResult { - Ok(partials) - } - - fn finalize_scalar( - &self, - _args: AggregateArgs<'_, Self::Options>, - _partial: &Self::Partial, - ) -> VortexResult { - vortex_panic!("TestAgg is for serde tests only"); - } - } - - #[test] - fn aggregate_fn_serde() { - let agg_fn = TestAgg.bind(EmptyOptions); - - let serialized = agg_fn.serialize_proto().unwrap(); - let buf = serialized.encode_to_vec(); - let deserialized_proto = pb::AggregateFn::decode(buf.as_slice()).unwrap(); - let deserialized = AggregateFnRef::from_proto(&deserialized_proto, &SESSION).unwrap(); - - assert_eq!(deserialized, agg_fn); - } - - /// The `skip_nans` option must survive a protobuf serialize/deserialize round-trip for the - /// numeric aggregates, including the non-default NaN-including configuration. - #[rstest] - #[case(Sum.bind(NumericalAggregateOpts::skip_nans()))] - #[case(Sum.bind(NumericalAggregateOpts::include_nans()))] - #[case(Count.bind(NumericalAggregateOpts::skip_nans()))] - #[case(Count.bind(NumericalAggregateOpts::include_nans()))] - fn numeric_aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> { - assert_round_trip(agg_fn) - } - - #[rstest] - #[case(First.bind(EmptyOptions))] - #[case(Last.bind(EmptyOptions))] - #[case(IsConstant.bind(EmptyOptions))] - #[case(IsSorted.bind(IsSortedOptions { strict: false }))] - #[case(IsSorted.bind(IsSortedOptions { strict: true }))] - fn aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> { - assert_round_trip(agg_fn) - } - - #[rstest] - fn mean_options_round_trip( - #[values(false, true)] sum_skip_nans: bool, - #[values(false, true)] count_skip_nans: bool, - ) -> VortexResult<()> { - assert_round_trip(Mean::combined().bind(PairOptions( - NumericalAggregateOpts { - skip_nans: sum_skip_nans, - }, - NumericalAggregateOpts { - skip_nans: count_skip_nans, - }, - ))) - } - - #[rstest] - #[case(IsSorted.id(), vec![])] - #[case(IsSorted.id(), vec![2])] - #[case(IsSorted.id(), vec![0, 1])] - #[case(Mean::combined().id(), vec![])] - #[case(Mean::combined().id(), vec![0])] - #[case(Mean::combined().id(), vec![2, 0])] - #[case(Mean::combined().id(), vec![0, 2])] - #[case(Mean::combined().id(), vec![0, 1, 0])] - fn invalid_aggregate_options(#[case] id: AggregateFnId, #[case] metadata: Vec) { - let proto = pb::AggregateFn { - id: id.to_string(), - metadata: Some(metadata), - }; - assert!(AggregateFnRef::from_proto(&proto, &VortexSession::empty()).is_err()); - } - - fn assert_round_trip(agg_fn: AggregateFnRef) -> VortexResult<()> { - let session = VortexSession::empty(); - - let proto = agg_fn.serialize_proto()?; - let buf = proto.encode_to_vec(); - let decoded = pb::AggregateFn::decode(buf.as_slice())?; - let round_tripped = AggregateFnRef::from_proto(&decoded, &session)?; - - assert_eq!(round_tripped, agg_fn); - Ok(()) - } - - #[test] - fn unknown_aggregate_fn_id_allow_unknown() { - let session = VortexSession::empty().with::(); - session.allow_unknown(); - - let proto = pb::AggregateFn { - id: "vortex.test.foreign_aggregate".to_string(), - metadata: Some(vec![7, 8, 9]), - }; - - let agg_fn = AggregateFnRef::from_proto(&proto, &session).unwrap(); - assert_eq!(agg_fn.id().as_ref(), "vortex.test.foreign_aggregate"); - - let roundtrip = agg_fn.serialize_proto().unwrap(); - assert_eq!(roundtrip.id, proto.id); - assert_eq!(roundtrip.metadata(), proto.metadata()); - } - - /// Pins the persisted encoding: `serialize_proto` output is stored in zoned layout metadata, - /// so any change to these bytes breaks existing files. - #[rstest] - #[case::empty_options(IsConstant.bind(EmptyOptions), b"\x0a\x12vortex.is_constant\x12\x00".as_slice())] - #[case::numeric_options(Sum.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.sum\x12\x02\x08\x01".as_slice())] - #[case::numeric_default_options(Sum.bind(NumericalAggregateOpts::include_nans()), b"\x0a\x0avortex.sum\x12\x00".as_slice())] - #[case::count(Count.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0cvortex.count\x12\x02\x08\x01".as_slice())] - #[case::min(Min.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.min\x12\x02\x08\x01".as_slice())] - #[case::max(Max.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.max\x12\x02\x08\x01".as_slice())] - #[case::first(First.bind(EmptyOptions), b"\x0a\x0cvortex.first\x12\x00".as_slice())] - #[case::last(Last.bind(EmptyOptions), b"\x0a\x0bvortex.last\x12\x00".as_slice())] - #[case::null_count(NullCount.bind(EmptyOptions), b"\x0a\x11vortex.null_count\x12\x00".as_slice())] - #[case::is_sorted(IsSorted.bind(IsSortedOptions { strict: true }), b"\x0a\x10vortex.is_sorted\x12\x01\x01".as_slice())] - #[case::mean_options( - Mean::combined().bind(PairOptions( - NumericalAggregateOpts::skip_nans(), - NumericalAggregateOpts::include_nans(), - )), - b"\x0a\x0bvortex.mean\x12\x02\x01\x00".as_slice(), - )] - fn golden_encoding(#[case] agg_fn: AggregateFnRef, #[case] bytes: &[u8]) -> VortexResult<()> { - assert_eq!(agg_fn.serialize_proto()?.encode_to_vec(), bytes); - let decoded = pb::AggregateFn::decode(bytes)?; - assert_eq!( - AggregateFnRef::from_proto(&decoded, &VortexSession::empty())?, - agg_fn - ); - Ok(()) - } - - /// Zoned layouts written before `vortex.expr.AggregateFn` replaced their private spec message - /// omit the options field when it is empty. Absent metadata must read as empty options. - #[rstest] - #[case::empty_options(b"\x0a\x12vortex.is_constant".as_slice(), IsConstant.bind(EmptyOptions))] - #[case::numeric_default_options(b"\x0a\x0avortex.sum".as_slice(), Sum.bind(NumericalAggregateOpts::include_nans()))] - fn decodes_absent_metadata( - #[case] bytes: &[u8], - #[case] expected: AggregateFnRef, - ) -> VortexResult<()> { - let decoded = pb::AggregateFn::decode(bytes)?; - assert!(decoded.metadata.is_none()); - assert_eq!( - AggregateFnRef::from_proto(&decoded, &VortexSession::empty())?, - expected - ); - Ok(()) - } - - #[test] - fn from_parts_unknown_id_is_none() -> VortexResult<()> { - let session = VortexSession::empty(); - #[expect(clippy::disallowed_methods, reason = "test-only id")] - let id = AggregateFnId::new("vortex.test.unknown"); - assert!(AggregateFnRef::from_parts(id, &[], &session)?.is_none()); - Ok(()) - } -} diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 20a3c8087e0..959d9a4b7b8 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -13,49 +13,13 @@ use vortex_utils::aliases::hash_map::HashMap; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnPluginRef; use crate::aggregate_fn::AggregateFnVTable; -use crate::aggregate_fn::ExtensionStoragePushdown; -use crate::aggregate_fn::fns::all_nan::AllNan; use crate::aggregate_fn::fns::all_non_distinct::AllNonDistinct; -use crate::aggregate_fn::fns::all_non_nan::AllNonNan; -use crate::aggregate_fn::fns::all_non_null::AllNonNull; -use crate::aggregate_fn::fns::all_null::AllNull; -use crate::aggregate_fn::fns::is_constant::IsConstant; -use crate::aggregate_fn::fns::is_sorted::IsSorted; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::nan_count::NanCount; -use crate::aggregate_fn::fns::null_count::NullCount; -use crate::aggregate_fn::fns::sum::PrimitiveGroupedSumEncodingKernel; -use crate::aggregate_fn::fns::sum::Sum; -use crate::aggregate_fn::fns::sum_v2::BoolGroupedSumV2EncodingKernel; -use crate::aggregate_fn::fns::sum_v2::PrimitiveGroupedSumV2EncodingKernel; -use crate::aggregate_fn::fns::sum_v2::SumV2; -use crate::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use crate::aggregate_fn::kernels::DynAggregateKernel; use crate::aggregate_fn::kernels::DynGroupedAggregateKernel; use crate::array::ArrayId; use crate::array::VTable; -use crate::arrays::Bool; use crate::arrays::Chunked; -use crate::arrays::Dict; -use crate::arrays::Primitive; -use crate::arrays::RunEnd; -use crate::arrays::Widen; use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate; -use crate::arrays::dict::compute::is_constant::DictIsConstantKernel; -use crate::arrays::dict::compute::is_sorted::DictIsSortedKernel; -use crate::arrays::dict::compute::min_max::DictMinMaxKernel; -use crate::arrays::runend::compute::is_constant::RunEndIsConstantKernel; -use crate::arrays::runend::compute::is_sorted::RunEndIsSortedKernel; -use crate::arrays::runend::compute::min_max::RunEndMinMaxKernel; -use crate::arrays::runend::compute::sum::RunEndSumKernel; -use crate::arrays::widen::compute::aggregate::WidenArrayAggregate; -use crate::dtype::extension::ExtVTable; -use crate::extension::datetime::Date; -use crate::extension::datetime::Duration; -use crate::extension::datetime::Time; -use crate::extension::datetime::Timestamp; /// Session state for aggregate functions and encoding-specific aggregate kernels. /// @@ -103,63 +67,11 @@ impl Default for AggregateFnSession { grouped_encoding_kernels: GroupedEncodingKernelRegistry::default(), }; - // Register the built-in aggregate functions + // Register the built-in aggregate functions. this.register(AllNonDistinct); - this.register(AllNonNan); - this.register(AllNonNull); - this.register(AllNan); - this.register(AllNull); - this.register(IsConstant); - this.register(IsSorted); - this.register(Max); - this.register(Min); - this.register(MinMax); - this.register(NanCount); - this.register(NullCount); - this.register(Sum); - this.register(SumV2); - this.register(UncompressedSizeInBytes); - - // Temporal extension types compare like their integer storage, so comparison-based - // aggregates are pushed down into it. - this.register_storage_ordered(Date); - this.register_storage_ordered(Duration); - this.register_storage_ordered(Time); - this.register_storage_ordered(Timestamp); // Register the built-in aggregate kernels. this.register_aggregate_kernel(Chunked.id(), None::, &ChunkedArrayAggregate); - this.register_aggregate_kernel(Dict.id(), Some(MinMax.id()), &DictMinMaxKernel); - this.register_aggregate_kernel(Dict.id(), Some(IsConstant.id()), &DictIsConstantKernel); - this.register_aggregate_kernel(Dict.id(), Some(IsSorted.id()), &DictIsSortedKernel); - this.register_aggregate_kernel(RunEnd.id(), Some(MinMax.id()), &RunEndMinMaxKernel); - this.register_aggregate_kernel(RunEnd.id(), Some(IsConstant.id()), &RunEndIsConstantKernel); - this.register_aggregate_kernel(RunEnd.id(), Some(IsSorted.id()), &RunEndIsSortedKernel); - this.register_aggregate_kernel(RunEnd.id(), Some(Sum.id()), &RunEndSumKernel); - this.register_aggregate_kernel(RunEnd.id(), Some(SumV2.id()), &RunEndSumKernel); - this.register_aggregate_kernel(Widen.id(), Some(MinMax.id()), &WidenArrayAggregate); - this.register_aggregate_kernel(Widen.id(), Some(Min.id()), &WidenArrayAggregate); - this.register_aggregate_kernel(Widen.id(), Some(Max.id()), &WidenArrayAggregate); - this.register_aggregate_kernel(Widen.id(), Some(IsConstant.id()), &WidenArrayAggregate); - this.register_aggregate_kernel(Widen.id(), Some(IsSorted.id()), &WidenArrayAggregate); - this.register_aggregate_kernel(Widen.id(), Some(Sum.id()), &WidenArrayAggregate); - - // Register the built-in grouped aggregate kernels. - this.register_grouped_encoding_kernel( - Primitive.id(), - Sum.id(), - &PrimitiveGroupedSumEncodingKernel, - ); - this.register_grouped_encoding_kernel( - Primitive.id(), - SumV2.id(), - &PrimitiveGroupedSumV2EncodingKernel, - ); - this.register_grouped_encoding_kernel( - Bool.id(), - SumV2.id(), - &BoolGroupedSumV2EncodingKernel, - ); this } @@ -179,17 +91,6 @@ impl AggregateFnSession { self.registry.insert(id, pluginref); } - /// Push the comparison-based aggregates `is_sorted` and `min_max` down into the storage of - /// extension type `ext`, through [`ExtensionStoragePushdown`]. - /// - /// Only call this when comparing two values of `ext` is the same as comparing their storage, - /// as for the temporal types and for UUIDs, which are stored big-endian. See - /// [`ExtensionStoragePushdown`] for how to check. - pub fn register_storage_ordered(&self, ext: E) { - self.register(ExtensionStoragePushdown::new(IsSorted, ext.clone())); - self.register(ExtensionStoragePushdown::new(MinMax, ext)); - } - /// Returns the aggregate kernel registered for `array_id` and `agg_fn_id`, if any. /// /// Lookup first checks for a kernel registered for the exact aggregate function, then falls diff --git a/vortex-array/src/aggregate_fn/stat_aggregates.rs b/vortex-array/src/aggregate_fn/stat_aggregates.rs index 1ac6fc8afd1..33bb0bbcca5 100644 --- a/vortex-array/src/aggregate_fn/stat_aggregates.rs +++ b/vortex-array/src/aggregate_fn/stat_aggregates.rs @@ -3,7 +3,7 @@ //! Identifiers and options of the aggregate functions that back array statistics. //! -//! [`Stat`](crate::expr::stats::Stat) names each of these aggregates by ID and options, and +//! [`Stat`](crate::stats::Stat) names each of these aggregates by ID and options, and //! array statistics are computed by resolving them through the session's //! [`AggregateFnSession`](crate::aggregate_fn::session::AggregateFnSession). The //! implementations themselves can therefore be registered from any crate. @@ -12,7 +12,6 @@ use std::fmt; use std::fmt::Display; use std::fmt::Formatter; -use prost::Message; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::registry::CachedId; @@ -22,7 +21,6 @@ use crate::dtype::DecimalDType; use crate::dtype::MAX_PRECISION; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::proto::expr as pb; /// ID of the aggregate computing the minimum, the `Min` statistic. pub static MIN_ID: CachedId = CachedId::new("vortex.min"); @@ -50,74 +48,6 @@ pub static ALL_NAN_ID: CachedId = CachedId::new("vortex.all_nan"); /// ID of the aggregate checking that no value is NaN. pub static ALL_NON_NAN_ID: CachedId = CachedId::new("vortex.all_non_nan"); -/// Whether the `vortex.uncompressed_size_in_bytes` aggregate approximates the bytes an array uses or counts them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum UncompressedSizePrecision { - /// An approximation: every byte of every buffer the canonical array holds, whether or not a - /// row uses it. Cheap, but a view array sharing or sliced from a larger buffer reports the - /// whole buffer. - #[default] - Inexact, - /// The actual number of bytes the array's rows use, which costs a pass over view and list - /// arrays. - Exact, -} - -/// Options for the `vortex.uncompressed_size_in_bytes` aggregate. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct UncompressedSizeOpts { - pub precision: UncompressedSizePrecision, -} - -impl UncompressedSizeOpts { - /// Approximate the bytes the array uses by the buffers it holds. This is the default. - pub const fn inexact() -> Self { - Self { - precision: UncompressedSizePrecision::Inexact, - } - } - - /// Count the actual bytes the array's rows use. - pub const fn exact() -> Self { - Self { - precision: UncompressedSizePrecision::Exact, - } - } - - pub const fn is_exact(&self) -> bool { - matches!(self.precision, UncompressedSizePrecision::Exact) - } - - /// Serialize these options to protobuf-encoded metadata bytes. - pub fn serialize(&self) -> Vec { - pb::UncompressedSizeInBytesOpts { - exact: self.is_exact(), - } - .encode_to_vec() - } - - /// Deserialize these options from protobuf-encoded metadata bytes. - pub fn deserialize(metadata: &[u8]) -> VortexResult { - let opts = pb::UncompressedSizeInBytesOpts::decode(metadata)?; - Ok(if opts.exact { - Self::exact() - } else { - Self::inexact() - }) - } -} - -impl Display for UncompressedSizeOpts { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - // Only the non-default configuration is displayed, so the default renders as - // `vortex.uncompressed_size_in_bytes()`. - if self.is_exact() { - write!(f, "precision=exact")?; - } - Ok(()) - } -} - /// Options for the `is_sorted` aggregate function. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct IsSortedOptions { diff --git a/vortex-array/src/aggregate_fn/storage_pushdown.rs b/vortex-array/src/aggregate_fn/storage_pushdown.rs index faa4f6fd54d..ab07efbf3c6 100644 --- a/vortex-array/src/aggregate_fn/storage_pushdown.rs +++ b/vortex-array/src/aggregate_fn/storage_pushdown.rs @@ -64,50 +64,8 @@ use crate::scalar::Scalar; /// /// # Example /// -/// Timestamps compare like their `i64` storage, so `is_sorted` can be pushed down. Register the -/// pair once on the session, then bind it like any other aggregate: -/// -/// ``` -/// # use vortex_array::IntoArray; -/// # use vortex_session::VortexSession; -/// # use vortex_array::VortexSessionExecute; -/// # use vortex_array::aggregate_fn::Accumulator; -/// # use vortex_array::aggregate_fn::DynAccumulator; -/// # use vortex_array::aggregate_fn::ExtensionStoragePushdown; -/// # use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; -/// # use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; -/// # use vortex_array::aggregate_fn::session::AggregateFnSessionExt; -/// # use vortex_array::arrays::ExtensionArray; -/// # use vortex_array::arrays::PrimitiveArray; -/// # use vortex_array::dtype::DType; -/// # use vortex_array::dtype::Nullability; -/// # use vortex_array::extension::datetime::TimeUnit; -/// # use vortex_array::extension::datetime::Timestamp; -/// # fn main() -> vortex_error::VortexResult<()> { -/// let session = VortexSession::empty(); -/// -/// // Register `vortex.is_sorted[vortex.timestamp]`. -/// let is_sorted = ExtensionStoragePushdown::new(IsSorted, Timestamp); -/// session.aggregate_fns().register(is_sorted.clone()); -/// -/// // Aggregate a timestamp column through its storage. -/// let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(); -/// let column = ExtensionArray::new( -/// ext_dtype.clone(), -/// PrimitiveArray::from_iter([1_000i64, 2_000, 3_000]).into_array(), -/// ) -/// .into_array(); -/// -/// let mut acc = Accumulator::try_new( -/// is_sorted, -/// IsSortedOptions { strict: true }, -/// DType::Extension(ext_dtype), -/// )?; -/// acc.accumulate(&column, &mut session.create_execution_ctx())?; -/// assert!(bool::try_from(&acc.finish()?)?); -/// # Ok(()) -/// # } -/// ``` +/// `vortex_aggregates::register_storage_ordered` registers the `is_sorted` and `min_max` aggregates +/// this way for the temporal extension types. #[derive(Clone, Debug)] pub struct ExtensionStoragePushdown { aggregate: A, @@ -313,229 +271,3 @@ impl AggregateFnVTable for ExtensionStorageP .finalize_scalar(self.storage_args(args)?, partial) } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use rstest::rstest; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use super::ExtensionStoragePushdown; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::AggregateFnVTable; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::is_sorted::IsSorted; - use crate::aggregate_fn::fns::is_sorted::IsSortedOptions; - use crate::aggregate_fn::fns::min_max::MinMax; - use crate::aggregate_fn::session::AggregateFnSessionExt; - use crate::arrays::ConstantArray; - use crate::arrays::ExtensionArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::extension::datetime::Date; - use crate::extension::datetime::Duration; - use crate::extension::datetime::Time; - use crate::extension::datetime::TimeUnit; - use crate::extension::datetime::Timestamp; - use crate::scalar::Scalar; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn pushes_down_into_storage() -> VortexResult<()> { - let session = VortexSession::empty(); - let aggregate = ExtensionStoragePushdown::new(MinMax, Timestamp); - session.aggregate_fns().register(aggregate.clone()); - assert!( - session - .aggregate_fns() - .find_plugin(&aggregate.id()) - .is_some() - ); - - let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); - let storage = - PrimitiveArray::from_option_iter([Some(3_000i64), None, Some(1_000)]).into_array(); - let array = ExtensionArray::new(ext_dtype.clone(), storage.clone()).into_array(); - - let mut ctx = session.create_execution_ctx(); - let mut acc = Accumulator::try_new( - aggregate, - NumericalAggregateOpts::default(), - DType::Extension(ext_dtype), - )?; - acc.accumulate(&array, &mut ctx)?; - - let mut expected = Accumulator::try_new( - MinMax, - NumericalAggregateOpts::default(), - storage.dtype().clone(), - )?; - expected.accumulate(&storage, &mut ctx)?; - - assert_eq!(acc.finish()?, expected.finish()?); - Ok(()) - } - - #[test] - fn combines_flushed_partials() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); - let batch = |values: [Option; 2]| { - ExtensionArray::new( - ext_dtype.clone(), - PrimitiveArray::from_option_iter(values).into_array(), - ) - .into_array() - }; - let accumulator = || { - Accumulator::try_new( - ExtensionStoragePushdown::new(MinMax, Timestamp), - NumericalAggregateOpts::default(), - DType::Extension(ext_dtype.clone()), - ) - }; - - let mut first = accumulator()?; - first.accumulate(&batch([Some(3_000), None]), &mut ctx)?; - let mut second = accumulator()?; - second.accumulate(&batch([Some(1_000), Some(500)]), &mut ctx)?; - first.combine_partials(&second.flush()?)?; - - let mut expected = accumulator()?; - expected.accumulate(&batch([Some(3_000), None]), &mut ctx)?; - expected.accumulate(&batch([Some(1_000), Some(500)]), &mut ctx)?; - - assert_eq!(first.finish()?, expected.finish()?); - Ok(()) - } - - #[test] - fn accumulates_constant_batches() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); - let constant = |value: i64| { - ConstantArray::new( - Scalar::extension_ref( - ext_dtype.clone(), - Scalar::primitive(value, Nullability::Nullable), - ), - 3, - ) - .into_array() - }; - - let mut acc = Accumulator::try_new( - ExtensionStoragePushdown::new(MinMax, Timestamp), - NumericalAggregateOpts::default(), - DType::Extension(ext_dtype.clone()), - )?; - acc.accumulate(&constant(2_000), &mut ctx)?; - acc.accumulate(&constant(1_000), &mut ctx)?; - - let mut expected = Accumulator::try_new( - MinMax, - NumericalAggregateOpts::default(), - ext_dtype.storage_dtype().clone(), - )?; - expected.accumulate( - &PrimitiveArray::from_option_iter([Some(2_000i64), Some(1_000)]).into_array(), - &mut ctx, - )?; - - assert_eq!(acc.finish()?, expected.finish()?); - Ok(()) - } - - #[test] - fn rejects_other_extension_types() { - let date = DType::Extension(Date::new(TimeUnit::Days, Nullability::Nullable).erased()); - assert!( - ExtensionStoragePushdown::new(MinMax, Timestamp) - .return_dtype(&NumericalAggregateOpts::default(), &date) - .is_none() - ); - } - - #[test] - fn default_session_registers_temporal_order_aggregates() { - let session = VortexSession::empty(); - let aggregate_fns = session.aggregate_fns(); - for id in [ - ExtensionStoragePushdown::new(IsSorted, Date).id(), - ExtensionStoragePushdown::new(IsSorted, Duration).id(), - ExtensionStoragePushdown::new(IsSorted, Time).id(), - ExtensionStoragePushdown::new(IsSorted, Timestamp).id(), - ExtensionStoragePushdown::new(MinMax, Date).id(), - ExtensionStoragePushdown::new(MinMax, Duration).id(), - ExtensionStoragePushdown::new(MinMax, Time).id(), - ExtensionStoragePushdown::new(MinMax, Timestamp).id(), - ] { - assert!( - aggregate_fns.find_plugin(&id).is_some(), - "{id} is not registered" - ); - } - } - - #[rstest] - // Nulls sort first. - #[case::sorted([None, Some(1_000), Some(2_000), Some(2_000)], false, true)] - #[case::unsorted([Some(2_000), Some(1_000), None, Some(3_000)], false, false)] - #[case::strict_with_duplicates([None, Some(1_000), Some(2_000), Some(2_000)], true, false)] - fn is_sorted_over_timestamps( - #[case] values: [Option; 4], - #[case] strict: bool, - #[case] expected: bool, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::Nullable).erased(); - let array = ExtensionArray::new( - ext_dtype.clone(), - PrimitiveArray::from_option_iter(values).into_array(), - ) - .into_array(); - - let mut acc = Accumulator::try_new( - ExtensionStoragePushdown::new(IsSorted, Timestamp), - IsSortedOptions { strict }, - DType::Extension(ext_dtype), - )?; - acc.accumulate(&array, &mut ctx)?; - - assert_eq!(bool::try_from(&acc.finish()?)?, expected); - Ok(()) - } - - #[test] - fn min_max_over_dates_matches_storage() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let ext_dtype = Date::new(TimeUnit::Days, Nullability::Nullable).erased(); - let storage = - PrimitiveArray::from_option_iter([Some(20i32), None, Some(-3), Some(7)]).into_array(); - let array = ExtensionArray::new(ext_dtype.clone(), storage.clone()).into_array(); - - let mut acc = Accumulator::try_new( - ExtensionStoragePushdown::new(MinMax, Date), - NumericalAggregateOpts::default(), - DType::Extension(ext_dtype), - )?; - acc.accumulate(&array, &mut ctx)?; - - let mut expected = Accumulator::try_new( - MinMax, - NumericalAggregateOpts::default(), - storage.dtype().clone(), - )?; - expected.accumulate(&storage, &mut ctx)?; - - assert_eq!(acc.finish()?, expected.finish()?); - Ok(()) - } -} diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index 8a317d1ffb4..18136910f56 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -45,6 +45,7 @@ use crate::arrays::SliceArray; use crate::block::BlockOp; use crate::block::BlockSource; use crate::arrays::bool::BoolArrayExt; +use crate::arrays::bool::bool_bounds; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; @@ -355,7 +356,7 @@ impl ArrayRef { match self.validity()? { Validity::NonNullable | Validity::AllValid => Ok(true), Validity::AllInvalid => Ok(false), - Validity::Array(a) => Ok(a.statistics().compute_min::(ctx).unwrap_or(false)), + Validity::Array(a) => Ok(bool_bounds(&a, ctx)?.is_some_and(|bounds| bounds.all_true)), } } @@ -368,7 +369,7 @@ impl ArrayRef { match self.validity()? { Validity::NonNullable | Validity::AllValid => Ok(false), Validity::AllInvalid => Ok(true), - Validity::Array(a) => Ok(!a.statistics().compute_max::(ctx).unwrap_or(true)), + Validity::Array(a) => Ok(!bool_bounds(&a, ctx)?.is_none_or(|bounds| bounds.any_true)), } } diff --git a/vortex-array/src/arrays/bool/array.rs b/vortex-array/src/arrays/bool/array.rs index d8f82150d00..efbdd135582 100644 --- a/vortex-array/src/arrays/bool/array.rs +++ b/vortex-array/src/arrays/bool/array.rs @@ -27,6 +27,7 @@ use crate::array::validity_to_child; use crate::array_slots; use crate::arrays::Bool; use crate::arrays::BoolArray; +use crate::arrays::bool::bool_bounds; use crate::buffer::BufferHandle; use crate::dtype::DType; use crate::validity::Validity; @@ -115,7 +116,7 @@ pub trait BoolArrayExt: TypedArrayRef { let all_valid = match &BoolArrayExt::validity(self) { Validity::NonNullable | Validity::AllValid => true, Validity::AllInvalid => false, - Validity::Array(a) => a.statistics().compute_min::(ctx).unwrap_or(false), + Validity::Array(a) => bool_bounds(a, ctx)?.is_some_and(|bounds| bounds.all_true), }; Ok(all_valid.then(|| Mask::from_buffer(self.to_bit_buffer()))) } diff --git a/vortex-array/src/arrays/bool/bounds.rs b/vortex-array/src/arrays/bool/bounds.rs new file mode 100644 index 00000000000..f79149e3ac0 --- /dev/null +++ b/vortex-array/src/arrays/bool/bounds.rs @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Whether a boolean array is all true or contains a true value, computed directly from its bits. +//! +//! Validity checks need these answers for every array. They are computed here without the +//! aggregate function registry, so they work with any session. Exact cached `Min`/`Max` +//! statistics are used when present, and computed answers are written back to the cache. + +use vortex_error::VortexResult; +use vortex_error::vortex_ensure; +use vortex_mask::Mask; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::arrays::BoolArray; +use crate::arrays::bool::BoolArrayExt; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProviderExt; + +/// The minimum and maximum of the valid values of a boolean array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BoolBounds { + /// Whether every valid value is true. + pub all_true: bool, + /// Whether any valid value is true. + pub any_true: bool, +} + +/// Returns the [`BoolBounds`] of the valid values of `array`, or `None` if it has no valid values. +/// +/// # Errors +/// +/// Fails if `array` is not a boolean array, or if it cannot be executed to a [`BoolArray`]. +pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { + vortex_ensure!( + array.dtype().is_boolean(), + "boolean bounds require a boolean array, got {}", + array.dtype() + ); + + let stats = array.statistics(); + if let Some(all_true) = stats.get_as::(Stat::Min).as_exact() + && let Some(any_true) = stats.get_as::(Stat::Max).as_exact() + { + return Ok(Some(BoolBounds { all_true, any_true })); + } + + let bools = array.clone().execute::(ctx)?; + let values = bools.to_bit_buffer(); + let (valid, true_count) = match BoolArrayExt::validity(&bools).execute_mask(bools.len(), ctx)? { + Mask::AllTrue(len) => (len, values.true_count()), + Mask::AllFalse(_) => return Ok(None), + Mask::Values(mask) => ( + mask.true_count(), + (&values & mask.bit_buffer()).true_count(), + ), + }; + if valid == 0 { + return Ok(None); + } + + let bounds = BoolBounds { + all_true: true_count == valid, + any_true: true_count > 0, + }; + stats.set(Stat::Min, Precision::exact(bounds.all_true)); + stats.set(Stat::Max, Precision::exact(bounds.any_true)); + Ok(Some(bounds)) +} + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use super::BoolBounds; + use super::bool_bounds; + use crate::IntoArray; + use crate::VortexSessionExecute; + use crate::arrays::BoolArray; + + static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + + #[test] + fn bounds_of_mixed_values() -> VortexResult<()> { + let array = BoolArray::from_iter([true, false, true]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + bool_bounds(&array, &mut ctx)?, + Some(BoolBounds { + all_true: false, + any_true: true + }) + ); + Ok(()) + } + + #[test] + fn bounds_skip_nulls() -> VortexResult<()> { + let array = BoolArray::from_iter([Some(true), None, Some(true)]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!( + bool_bounds(&array, &mut ctx)?, + Some(BoolBounds { + all_true: true, + any_true: true + }) + ); + Ok(()) + } + + #[test] + fn bounds_of_all_null_array() -> VortexResult<()> { + let array = BoolArray::from_iter([None::, None]).into_array(); + let mut ctx = SESSION.create_execution_ctx(); + assert_eq!(bool_bounds(&array, &mut ctx)?, None); + Ok(()) + } +} diff --git a/vortex-array/src/arrays/bool/mod.rs b/vortex-array/src/arrays/bool/mod.rs index a8dcba2f406..d3d77d97c6f 100644 --- a/vortex-array/src/arrays/bool/mod.rs +++ b/vortex-array/src/arrays/bool/mod.rs @@ -2,6 +2,9 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors mod array; +mod bounds; +pub use bounds::BoolBounds; +pub use bounds::bool_bounds; mod compact; mod patch; diff --git a/vortex-array/src/arrays/chunked/compute/aggregate.rs b/vortex-array/src/arrays/chunked/compute/aggregate.rs index a4c211c0344..0cf26ceec50 100644 --- a/vortex-array/src/arrays/chunked/compute/aggregate.rs +++ b/vortex-array/src/arrays/chunked/compute/aggregate.rs @@ -35,217 +35,3 @@ impl DynAggregateKernel for ChunkedArrayAggregate { Ok(Some(acc.flush()?)) } } - -#[cfg(test)] -mod tests { - use std::sync::LazyLock; - - use vortex_buffer::Buffer; - use vortex_buffer::buffer; - use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::sum::Sum; - use crate::arrays::BoolArray; - use crate::arrays::ChunkedArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::DType; - use crate::dtype::Nullability; - use crate::dtype::PType; - use crate::scalar::Scalar; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - fn run_sum(batch: &crate::ArrayRef) -> VortexResult { - let mut ctx = SESSION.create_execution_ctx(); - let mut acc = Accumulator::try_new( - Sum, - NumericalAggregateOpts::default(), - batch.dtype().clone(), - )?; - acc.accumulate(batch, &mut ctx)?; - acc.finish() - } - - #[test] - fn sum_chunked_i32() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - buffer![1i32, 2, 3].into_array(), - buffer![4i32, 5, 6].into_array(), - ], - DType::Primitive(PType::I32, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(21)); - Ok(()) - } - - #[test] - fn sum_chunked_f64() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - buffer![1.5f64, 2.5].into_array(), - buffer![3.0f64].into_array(), - ], - DType::Primitive(PType::F64, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(7.0)); - Ok(()) - } - - #[test] - fn sum_chunked_with_nulls() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(), - PrimitiveArray::from_option_iter([None, Some(5)]).into_array(), - ], - DType::Primitive(PType::I32, Nullability::Nullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(9)); - Ok(()) - } - - #[test] - fn sum_chunked_all_null() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - PrimitiveArray::from_option_iter([None::, None]).into_array(), - PrimitiveArray::from_option_iter([None::]).into_array(), - ], - DType::Primitive(PType::I32, Nullability::Nullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(0)); - Ok(()) - } - - #[test] - fn sum_chunked_single_chunk() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![buffer![10i32, 20, 30].into_array()], - DType::Primitive(PType::I32, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(60)); - Ok(()) - } - - #[test] - fn sum_chunked_empty_chunks() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let chunked = ChunkedArray::try_new( - vec![ - Buffer::::empty().into_array(), - buffer![1i32, 2, 3].into_array(), - Buffer::::empty().into_array(), - buffer![4i32, 5].into_array(), - Buffer::::empty().into_array(), - ], - dtype, - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(15)); - Ok(()) - } - - #[test] - fn sum_chunked_all_empty() -> VortexResult<()> { - let dtype = DType::Primitive(PType::I32, Nullability::NonNullable); - let chunked = ChunkedArray::try_new(vec![], dtype)?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(0)); - Ok(()) - } - - #[test] - fn sum_chunked_many_small_chunks() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - buffer![1i32].into_array(), - buffer![2i32].into_array(), - buffer![3i32].into_array(), - buffer![4i32].into_array(), - buffer![5i32].into_array(), - ], - DType::Primitive(PType::I32, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(15)); - Ok(()) - } - - #[test] - fn sum_chunked_u64() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![ - buffer![100u64, 200].into_array(), - buffer![300u64].into_array(), - ], - DType::Primitive(PType::U64, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(600)); - Ok(()) - } - - #[test] - fn sum_chunked_bool() -> VortexResult<()> { - let b1: BoolArray = [true, false, true].into_iter().collect(); - let b2: BoolArray = [true, true].into_iter().collect(); - let chunked = ChunkedArray::try_new( - vec![b1.into_array(), b2.into_array()], - DType::Bool(Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(4)); - Ok(()) - } - - #[test] - fn sum_chunked_bool_with_nulls() -> VortexResult<()> { - let b1 = BoolArray::from_iter([Some(true), None, Some(true)]); - let b2 = BoolArray::from_iter([Some(false), None]); - let chunked = ChunkedArray::try_new( - vec![b1.into_array(), b2.into_array()], - DType::Bool(Nullability::Nullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(2)); - Ok(()) - } - - #[test] - fn sum_chunked_checked_overflow() -> VortexResult<()> { - let chunked = ChunkedArray::try_new( - vec![buffer![i64::MAX].into_array(), buffer![1i64].into_array()], - DType::Primitive(PType::I64, Nullability::NonNullable), - )?; - let result = run_sum(&chunked.into_array())?; - assert!(result.is_null()); - Ok(()) - } - - #[test] - fn sum_chunked_nested() -> VortexResult<()> { - let inner = ChunkedArray::try_new( - vec![buffer![1i32, 2].into_array(), buffer![3i32].into_array()], - DType::Primitive(PType::I32, Nullability::NonNullable), - )?; - let outer = ChunkedArray::try_new( - vec![inner.into_array(), buffer![4i32, 5, 6].into_array()], - DType::Primitive(PType::I32, Nullability::NonNullable), - )?; - let result = run_sum(&outer.into_array())?; - assert_eq!(result.as_primitive().typed_value::(), Some(21)); - Ok(()) - } -} diff --git a/vortex-array/src/arrays/constant/compute/mod.rs b/vortex-array/src/arrays/constant/compute/mod.rs index 1303992bea0..18ef8e67288 100644 --- a/vortex-array/src/arrays/constant/compute/mod.rs +++ b/vortex-array/src/arrays/constant/compute/mod.rs @@ -8,7 +8,6 @@ mod not; pub(crate) mod rules; mod slice; mod take; -pub(crate) mod uncompressed_size; #[cfg(test)] mod test { diff --git a/vortex-array/src/arrays/decimal/utils.rs b/vortex-array/src/arrays/decimal/utils.rs index 86b2b669812..746cd1f1ebf 100644 --- a/vortex-array/src/arrays/decimal/utils.rs +++ b/vortex-array/src/arrays/decimal/utils.rs @@ -5,6 +5,7 @@ use std::ops::RangeInclusive; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; +use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_compute::lane_kernels::IndexedSourceExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -14,13 +15,13 @@ use vortex_error::vortex_panic; use vortex_mask::AllOr; use vortex_mask::Mask; -pub use crate::aggregate_fn::fns::min_max::valid_range; use crate::arrays::DecimalArray; use crate::arrays::decimal::DecimalArrayExt; use crate::arrays::decimal::DecimalData; use crate::buffer::BufferHandle; use crate::dtype::BigCast; use crate::dtype::DecimalDType; +use crate::dtype::DecimalType; use crate::dtype::NativeDecimalType; use crate::match_each_decimal_value_type; @@ -287,6 +288,72 @@ pub(crate) fn cast_value_in_precision(values: &[T], validity: &Mask) -> Option<(T, T)> { + assert_eq!( + validity.len(), + values.len(), + "valid_range requires one validity bit per value" + ); + + let min_max = |(min, max): (T, T), v: T| (min.min(v), max.max(v)); + match validity { + Mask::AllTrue(_) if T::DECIMAL_TYPE == DecimalType::I256 => wide_range(values.iter()), + Mask::AllTrue(_) => values + .first() + .map(|&first| values.iter().copied().fold((first, first), min_max)), + Mask::AllFalse(_) => None, + Mask::Values(validity) + if matches!(T::DECIMAL_TYPE, DecimalType::I128 | DecimalType::I256) => + { + wide_range(validity.bit_buffer().set_indices().map(|i| &values[i])) + } + // Null lanes read as a valid value, which leaves both extrema unchanged, so the reduction + // needs no branch per lane. + Mask::Values(validity) => validity.bit_buffer().set_indices().next().map(|first| { + let first = values[first]; + values.fold_masked(validity.bit_buffer(), first, (first, first), min_max) + }), + } +} + +/// Compare the most significant machine word first. Most rows lie strictly between the +/// current extrema, so their remaining words need no comparison. +fn wide_range<'a, T: NativeDecimalType>(mut values: impl Iterator) -> Option<(T, T)> { + let first = values.next()?; + let (mut min_word, mut min) = (leading_word(first), first); + let (mut max_word, mut max) = (min_word, first); + for value in values { + let word = leading_word(value); + if word <= min_word && value < min { + (min_word, min) = (word, value); + } else if word >= max_word && value > max { + (max_word, max) = (word, value); + } + } + Some((*min, *max)) +} + +fn leading_word(value: &T) -> i64 { + let upper = if T::DECIMAL_TYPE == DecimalType::I256 { + value + .to_i256() + .vortex_expect("decimal values fit i256") + .to_parts() + .1 + } else { + value.to_i128().vortex_expect("i128 decimal storage") + }; + (upper >> 64) as i64 +} + #[cfg(test)] mod tests { use rstest::rstest; @@ -303,6 +370,7 @@ mod tests { use crate::arrays::DecimalArray; use crate::dtype::BigCast; use crate::dtype::DecimalDType; +use crate::dtype::DecimalType; use crate::dtype::DecimalType; use crate::dtype::NativeDecimalType; use crate::dtype::ToI256; diff --git a/vortex-array/src/arrays/dict/compute/mod.rs b/vortex-array/src/arrays/dict/compute/mod.rs index cdd28f902a6..fab7b710778 100644 --- a/vortex-array/src/arrays/dict/compute/mod.rs +++ b/vortex-array/src/arrays/dict/compute/mod.rs @@ -5,10 +5,7 @@ mod cast; mod compare; mod fill_null; mod filter; -pub(crate) mod is_constant; -pub(crate) mod is_sorted; mod mask; -pub(crate) mod min_max; pub(crate) mod rules; pub(crate) mod select; mod slice; diff --git a/vortex-array/src/arrays/dict/compute/select.rs b/vortex-array/src/arrays/dict/compute/select.rs index 2aa8a3d7b06..8f08f706f92 100644 --- a/vortex-array/src/arrays/dict/compute/select.rs +++ b/vortex-array/src/arrays/dict/compute/select.rs @@ -93,7 +93,7 @@ pub(crate) fn select_codes( } /// Returns whether the scalar function tree of `array` contains a fallible function. -pub(crate) fn has_fallible_scalar_fn(array: &ArrayRef) -> bool { +pub fn has_fallible_scalar_fn(array: &ArrayRef) -> bool { let Some(scalar_fn) = array.as_opt::() else { return false; }; diff --git a/vortex-array/src/arrays/dict/mod.rs b/vortex-array/src/arrays/dict/mod.rs index 8a7456b137a..1935975ded9 100644 --- a/vortex-array/src/arrays/dict/mod.rs +++ b/vortex-array/src/arrays/dict/mod.rs @@ -17,6 +17,7 @@ pub use array::*; mod block; pub(crate) use block::gather_checked; pub(crate) mod compute; +pub use compute::select::has_fallible_scalar_fn; mod execute; mod take; diff --git a/vortex-array/src/arrays/extension/tests.rs b/vortex-array/src/arrays/extension/tests.rs index 7c3253bd73a..9302f154d8c 100644 --- a/vortex-array/src/arrays/extension/tests.rs +++ b/vortex-array/src/arrays/extension/tests.rs @@ -18,14 +18,6 @@ use crate::ArrayRef; use crate::EmptyArrayData; use crate::IntoArray; use crate::VortexSessionExecute; -use crate::aggregate_fn::AggregateFn; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::max::Max; -use crate::aggregate_fn::fns::min::Min; -use crate::aggregate_fn::fns::min_max::MinMax; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::fns::min_max::nan_scalar; use crate::arrays::ConstantArray; use crate::arrays::Extension; use crate::arrays::ExtensionArray; @@ -229,46 +221,6 @@ fn test_array_parts_require_the_storage_dtype(#[case] storage: ArrayRef) -> Vort Ok(()) } -#[rstest] -#[case::min(AggregateFn::new(Min, NumericalAggregateOpts::default()).erased())] -#[case::max(AggregateFn::new(Max, NumericalAggregateOpts::default()).erased())] -#[case::min_max(AggregateFn::new(MinMax, NumericalAggregateOpts::default()).erased())] -fn test_aggregates_return_extension_validation_errors( - #[case] aggregate: AggregateFnRef, -) -> VortexResult<()> { - let array = NonZero::array(buffer![0i64, 1].into_array())?; - let mut ctx = SESSION.create_execution_ctx(); - let mut accumulator = aggregate.accumulator(array.dtype())?; - - assert_non_zero_error(accumulator.accumulate(&array, &mut ctx), "0"); - - Ok(()) -} - -#[test] -fn test_nan_extrema_return_extension_validation_errors() -> VortexResult<()> { - let array = NonZero::array(buffer![f64::NAN, 1.0].into_array())?; - let mut ctx = SESSION.create_execution_ctx(); - - assert_non_zero_error( - min_max(&array, &mut ctx, NumericalAggregateOpts::include_nans()), - "NaN", - ); - - Ok(()) -} - -#[rstest] -fn test_nan_scalar_returns_extension_validation_errors( - #[values(Nullability::NonNullable, Nullability::Nullable)] nullability: Nullability, -) -> VortexResult<()> { - let dtype = DType::Extension(NonZero::dtype(PType::F64, nullability)?); - - assert_non_zero_error(nan_scalar(&dtype), "NaN"); - - Ok(()) -} - #[rstest] #[case::extension(false)] #[case::nested(true)] diff --git a/vortex-array/src/arrays/listview/tests/operations.rs b/vortex-array/src/arrays/listview/tests/operations.rs index d823115ae74..e983b9ad416 100644 --- a/vortex-array/src/arrays/listview/tests/operations.rs +++ b/vortex-array/src/arrays/listview/tests/operations.rs @@ -17,7 +17,6 @@ use super::common::create_nullable_listview; use super::common::create_overlapping_listview; use crate::IntoArray; use crate::VortexSessionExecute; -use crate::aggregate_fn::fns::is_constant::is_constant; use crate::arrays::BoolArray; use crate::arrays::ConstantArray; use crate::arrays::ListView; @@ -546,137 +545,6 @@ fn test_cast_large_dataset() { assert_arrays_eq!(result_list, expected, &mut SESSION.create_execution_ctx()); } -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Constant tests -//////////////////////////////////////////////////////////////////////////////////////////////////// - -// Parameterized tests for is_constant scenarios. -#[rstest] -#[case::different_sizes( - buffer![1i32, 2, 3, 4], - buffer![0i32, 1, 2], - buffer![1i32, 1, 2], // Different sizes - Validity::NonNullable, - false -)] -#[case::different_elements( - buffer![1i32, 2, 3, 4], - buffer![0i32, 2], - buffer![2i32, 2], // Same size, different elements - Validity::NonNullable, - false -)] -#[case::same_empty_lists( - buffer![99i32], // Dummy element - buffer![0i32, 0, 0], - buffer![0i32, 0, 0], // All empty lists - Validity::NonNullable, - true -)] -#[case::single_list( - buffer![1i32, 2, 3], - buffer![0i32], - buffer![3i32], - Validity::NonNullable, - true -)] -#[case::overlapping_different( - buffer![1i32, 2, 3, 4], - buffer![0i32, 1, 2], // Overlapping but different - buffer![2i32, 2, 2], - Validity::NonNullable, - false -)] -fn test_is_constant_basic( - #[case] elements: vortex_buffer::Buffer, - #[case] offsets: vortex_buffer::Buffer, - #[case] sizes: vortex_buffer::Buffer, - #[case] validity: Validity, - #[case] expected: bool, -) { - let listview = ListViewArray::new( - elements.into_array(), - offsets.into_array(), - sizes.into_array(), - validity, - &mut SESSION.create_execution_ctx(), - ) - .into_array(); - - let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(is_constant(&listview, &mut ctx).unwrap(), expected); -} - -#[test] -fn test_constant_with_constant_elements() { - // Test with ConstantArray as elements - all lists point to same constant value. - // Logical lists: [[42,42], [42,42], [42,42]] - let elements = ConstantArray::new(42i32, 10).into_array(); - let offsets = buffer![0i32, 2, 4].into_array(); - let sizes = buffer![2i32, 2, 2].into_array(); - - let listview = unsafe { - ListViewArray::new_unchecked(elements, offsets, sizes, Validity::NonNullable) - .with_zero_copy_to_list(true) - } - .into_array(); - - // All lists contain [42, 42] so should be constant. - let mut ctx = SESSION.create_execution_ctx(); - assert!(is_constant(&listview, &mut ctx).unwrap()); -} - -#[test] -fn test_constant_with_nulls() { - // Test nullable ListView scenarios. - // Logical lists: [[1,2], [3,4]] (validity varies by case) - let elements = buffer![1i32, 2, 3, 4].into_array(); - let offsets = buffer![0i32, 2].into_array(); - let sizes = buffer![2i32, 2].into_array(); - - // Case 1: Mixed valid and null - not constant. - let validity_mixed = Validity::Array(BoolArray::from_iter(vec![true, false]).into_array()); - let listview_mixed = unsafe { - ListViewArray::new_unchecked( - elements.clone(), - offsets.clone(), - sizes.clone(), - validity_mixed, - ) - .with_zero_copy_to_list(true) - } - .into_array(); - let mut ctx = SESSION.create_execution_ctx(); - assert!(!is_constant(&listview_mixed, &mut ctx).unwrap()); - - // Case 2: All nulls - should be constant. - let validity_all_null = Validity::AllInvalid; - let listview_all_null = unsafe { - ListViewArray::new_unchecked(elements, offsets, sizes, validity_all_null) - .with_zero_copy_to_list(true) - } - .into_array(); - let mut ctx2 = SESSION.create_execution_ctx(); - assert!(is_constant(&listview_all_null, &mut ctx2).unwrap()); -} - -#[test] -fn test_constant_repeated_same_lists() { - let mut ctx = SESSION.create_execution_ctx(); - // Test multiple lists that are identical (overlapping). - // Logical lists: [[10,20,30], [10,20,30], [10,20,30], [10,20,30]] - let elements = buffer![10i32, 20, 30].into_array(); - let offsets = buffer![0i32, 0, 0, 0].into_array(); // All point to same start. - let sizes = buffer![3i32, 3, 3, 3].into_array(); // All same size. - - let listview = - ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx).into_array(); - - // All lists are [10, 20, 30] so should be constant. - let mut ctx = SESSION.create_execution_ctx(); - assert!(is_constant(&listview, &mut ctx).unwrap()); -} - //////////////////////////////////////////////////////////////////////////////////////////////////// // Mask tests //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/vortex-array/src/arrays/runend/array/mod.rs b/vortex-array/src/arrays/runend/array/mod.rs index 71ac29f727c..631a340a107 100644 --- a/vortex-array/src/arrays/runend/array/mod.rs +++ b/vortex-array/src/arrays/runend/array/mod.rs @@ -45,6 +45,7 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::listview::ListViewArraySlotsExt; +use crate::arrays::primitive::integer_is_strict_sorted; use crate::arrays::runend::compress::runend_decode_decimal; use crate::arrays::runend::compress::runend_decode_primitive; use crate::arrays::runend::compress::runend_decode_varbinview; @@ -343,12 +344,9 @@ impl RunEndData { // Run ends must be strictly sorted for binary search to work correctly. let pre_validation = ends.statistics().to_owned(); - let is_sorted = ends - .statistics() - .compute_is_strict_sorted(ctx) - .unwrap_or(false); + let is_sorted = integer_is_strict_sorted(ends, ctx)?; - // Preserve the original statistics since compute_is_strict_sorted may have mutated them. + // Preserve the original statistics since computing sortedness may have cached new ones. // We don't want to run with different stats in debug mode and outside. ends.statistics().inherit(pre_validation.iter()); debug_assert!(is_sorted); diff --git a/vortex-array/src/arrays/runend/compute/mod.rs b/vortex-array/src/arrays/runend/compute/mod.rs index b7faf2b7bd6..214cdb9b0a9 100644 --- a/vortex-array/src/arrays/runend/compute/mod.rs +++ b/vortex-array/src/arrays/runend/compute/mod.rs @@ -5,50 +5,9 @@ mod cast; mod compare; mod fill_null; pub(crate) mod filter; -pub(crate) mod is_constant; -pub(crate) mod is_sorted; -pub(crate) mod min_max; -pub(crate) mod sum; pub(crate) mod take; pub(crate) mod take_from; -use std::ops::Range; - -use vortex_error::VortexResult; - -use crate::ArrayView; -use crate::ExecutionCtx; -use crate::arrays::runend::RunEnd; -use crate::arrays::runend::array::RunEndArrayExt; -use crate::arrays::runend::array::RunEndArraySlotsExt; - -/// Returns the active physical run range covering `[offset..offset + len)` for a non-empty -/// [`RunEnd`] array. -pub(super) fn active_physical_range( - run_end: ArrayView<'_, RunEnd>, - ctx: &mut ExecutionCtx, -) -> VortexResult> { - debug_assert!(!run_end.is_empty()); - - let ends = run_end.ends(); - let num_runs = ends.len(); - if num_runs == 1 { - return Ok(0..1); - } - - if run_end.offset() == 0 { - let last_end = usize::try_from(&ends.execute_scalar(num_runs - 1, ctx)?)?; - if last_end == run_end.len() { - let first_end = usize::try_from(&ends.execute_scalar(0, ctx)?)?; - if first_end > 0 { - return Ok(0..num_runs); - } - } - } - - run_end.find_physical_range(0..run_end.len(), ctx) -} - #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-array/src/arrays/runend/ops.rs b/vortex-array/src/arrays/runend/ops.rs index 6c833d85787..e257b986643 100644 --- a/vortex-array/src/arrays/runend/ops.rs +++ b/vortex-array/src/arrays/runend/ops.rs @@ -111,7 +111,6 @@ mod tests { use crate::IntoArray; use crate::VortexSessionExecute; - use crate::aggregate_fn::fns::is_constant::is_constant; use crate::arrays::PrimitiveArray; use crate::arrays::runend::RunEnd; use crate::assert_arrays_eq; @@ -212,7 +211,6 @@ mod tests { let sliced_array = re_array.slice(2..5).unwrap(); - assert!(is_constant(&sliced_array, &mut ctx).unwrap()); assert_arrays_eq!( sliced_array, PrimitiveArray::from_iter([2u64, 2, 2]), diff --git a/vortex-array/src/arrays/struct_/compute/mod.rs b/vortex-array/src/arrays/struct_/compute/mod.rs index 6edc2c92e19..bc02bf868c0 100644 --- a/vortex-array/src/arrays/struct_/compute/mod.rs +++ b/vortex-array/src/arrays/struct_/compute/mod.rs @@ -16,13 +16,11 @@ mod tests { use rstest::rstest; use vortex_buffer::BitBuffer; use vortex_buffer::buffer; - use vortex_error::VortexExpect; use vortex_session::VortexSession; use crate::Canonical; use crate::IntoArray as _; use crate::VortexSessionExecute; - use crate::aggregate_fn::fns::is_constant::is_constant; use crate::arrays::BoolArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; @@ -321,15 +319,6 @@ mod tests { ); } - #[test] - fn test_empty_struct_is_constant() { - let array = StructArray::new_fieldless_with_len(2); - let mut ctx = SESSION.create_execution_ctx(); - let result = is_constant(&array.into_array(), &mut ctx) - .vortex_expect("operation should succeed in test"); - assert!(result); - } - #[test] fn test_take_empty_struct_conformance() { test_take_conformance( diff --git a/vortex-array/src/arrays/struct_/tests.rs b/vortex-array/src/arrays/struct_/tests.rs index 7b32b42a81b..547d496cdae 100644 --- a/vortex-array/src/arrays/struct_/tests.rs +++ b/vortex-array/src/arrays/struct_/tests.rs @@ -7,11 +7,9 @@ use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::Canonical; use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::BoolArray; -use crate::arrays::ConstantArray; use crate::arrays::PrimitiveArray; use crate::arrays::StructArray; use crate::arrays::VarBinArray; @@ -153,30 +151,6 @@ fn test_duplicate_field_names() { ); } -#[test] -fn test_uncompressed_size_in_bytes() -> VortexResult<()> { - let struct_array = StructArray::new( - FieldNames::from(["integers"]), - vec![ConstantArray::new(5, 1000).into_array()], - 1000, - Validity::NonNullable, - ); - - let canonical_size = struct_array - .clone() - .into_array() - .execute::(&mut SESSION.create_execution_ctx())? - .into_array() - .nbytes(); - let uncompressed_size = struct_array - .statistics() - .compute_uncompressed_size_in_bytes(&mut SESSION.create_execution_ctx()); - - assert_eq!(canonical_size, 2); - assert_eq!(uncompressed_size, Some(4000)); - Ok(()) -} - #[test] fn test_push_validity_into_children_drops_struct_validity() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); diff --git a/vortex-array/src/arrays/union/tests/mod.rs b/vortex-array/src/arrays/union/tests/mod.rs index 4c300a9c91d..ab4e2764c5a 100644 --- a/vortex-array/src/arrays/union/tests/mod.rs +++ b/vortex-array/src/arrays/union/tests/mod.rs @@ -19,7 +19,6 @@ use crate::ArrayRef; use crate::Canonical; use crate::IntoArray; use crate::VortexSessionExecute; -use crate::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use crate::arrays::BoolArray; use crate::arrays::ConstantArray; use crate::arrays::PrimitiveArray; @@ -319,19 +318,6 @@ fn constant_union_canonicalizes_to_sparse_union() -> VortexResult<()> { Ok(()) } -#[test] -fn constant_union_reports_uncompressed_size() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let scalar = Scalar::union(variants()?, 5, 10i32.into(), Nullability::NonNullable)?; - - // Four `u8` type IDs, four `i32` rows, and four `bool` placeholder bits rounded up to a byte. - let size = uncompressed_size_in_bytes(&ConstantArray::new(scalar, 4).into_array(), &mut ctx)?; - - assert_eq!(size, 4 + 4 * 4 + 1); - - Ok(()) -} - /// Serialize `array` into its wire form and the context that resolves its encoding IDs. fn serialize(array: &UnionArray) -> VortexResult<(SerializedArray, ReadContext)> { let array_ctx = ArrayContext::empty(); diff --git a/vortex-array/src/arrays/widen/compute/mod.rs b/vortex-array/src/arrays/widen/compute/mod.rs index f06b9e4623f..d7d1b21ad6d 100644 --- a/vortex-array/src/arrays/widen/compute/mod.rs +++ b/vortex-array/src/arrays/widen/compute/mod.rs @@ -12,13 +12,8 @@ //! needs the min and max of each operand, which come from cached statistics or from one scan of the //! operand. That scan is the one hidden cost in this module. //! -//! [`AggregateFnSession::default`] registers the aggregate kernel, not the `Widen` encoding's -//! `initialize`, because the kernel session runs `initialize` on a temporary session and drops its -//! aggregate registry. -//! -//! [`AggregateFnSession::default`]: crate::aggregate_fn::session::AggregateFnSession::default +//! The aggregate kernel lives in `vortex-aggregates`, next to the aggregates it computes. -pub(crate) mod aggregate; mod cast; mod compare; mod fill_null; diff --git a/vortex-array/src/arrays/widen/compute/numeric.rs b/vortex-array/src/arrays/widen/compute/numeric.rs index 3762e9a489e..b6f521752d4 100644 --- a/vortex-array/src/arrays/widen/compute/numeric.rs +++ b/vortex-array/src/arrays/widen/compute/numeric.rs @@ -12,13 +12,12 @@ use crate::Canonical; use crate::Columnar; use crate::ExecutionCtx; use crate::IntoArray; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::min_max; use crate::array::ArrayView; use crate::arrays::Constant; use crate::arrays::ConstantArray; use crate::arrays::ScalarFn; use crate::arrays::Widen; +use crate::arrays::primitive::integer_bounds; use crate::arrays::scalar_fn::ExactScalarFn; use crate::arrays::scalar_fn::ScalarFnArrayExt; use crate::arrays::scalar_fn::ScalarFnArrayView; @@ -145,13 +144,13 @@ fn smallest_arithmetic_ptype( /// Returns the extrema of the valid values of an integer array, or `None` when no row is valid. /// -/// [`min_max`] reads the exact cached `Min` and `Max` statistics of `array`. Without them it scans +/// [`integer_bounds`] reads the exact `Min` and `Max` statistics of `array`. Without them it scans /// `array` once and caches the result on it. fn valid_value_interval( array: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult>> { - let Some(bounds) = min_max(array, ctx, NumericalAggregateOpts::default())? else { + let Some(bounds) = integer_bounds(array, ctx)? else { return Ok(None); }; diff --git a/vortex-array/src/arrays/widen/encode/integer.rs b/vortex-array/src/arrays/widen/encode/integer.rs index f9758562f1b..6e626779c2c 100644 --- a/vortex-array/src/arrays/widen/encode/integer.rs +++ b/vortex-array/src/arrays/widen/encode/integer.rs @@ -8,23 +8,20 @@ use std::ops::RangeInclusive; -use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::MinMaxResult; -use crate::aggregate_fn::fns::min_max::min_max; use crate::arrays::PrimitiveArray; use crate::arrays::WidenArray; +use crate::arrays::primitive::IntegerBounds; +use crate::arrays::primitive::integer_bounds; use crate::arrays::widen::compute::wrap_values; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::PType; -use crate::scalar::PValue; impl WidenArray { /// Stores `array` as a `Widen` over the smallest integer type with the same signedness that @@ -74,7 +71,7 @@ fn narrow_values(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult< } // An array without valid values fits any type, and the bounds `0..=0` select the 1-byte type. - let bounds = match min_max(array.as_ref(), ctx, NumericalAggregateOpts::default())? { + let bounds = match integer_bounds(array.as_ref(), ctx)? { Some(bounds) => integer_extrema(bounds), None => 0..=0, }; @@ -91,19 +88,9 @@ fn narrow_values(array: PrimitiveArray, ctx: &mut ExecutionCtx) -> VortexResult< .execute::(ctx) } -/// Widens integer extrema to `i128`, which holds every integer [`PValue`] exactly. -/// -/// Both extrema **must** be non-null integers, as returned by [`min_max`] on an integer array. -pub(in crate::arrays::widen) fn integer_extrema(bounds: MinMaxResult) -> RangeInclusive { - let [min, max] = [bounds.min, bounds.max].map(|bound| { - bound - .as_primitive() - .pvalue() - .and_then(PValue::as_i128) - .vortex_expect("min_max of an integer array returns non-null integer extrema") - }); - - min..=max +/// Returns the extrema of an integer array as an inclusive range. +pub(in crate::arrays::widen) fn integer_extrema(bounds: IntegerBounds) -> RangeInclusive { + bounds.min..=bounds.max } /// Returns the smallest integer type with the given signedness that holds every value in `bounds`, diff --git a/vortex-array/src/arrays/widen/tests/mod.rs b/vortex-array/src/arrays/widen/tests/mod.rs index de5ad2dad8c..2624502324e 100644 --- a/vortex-array/src/arrays/widen/tests/mod.rs +++ b/vortex-array/src/arrays/widen/tests/mod.rs @@ -7,10 +7,8 @@ //! row, and the `compute` tests run their operations over them. The `decimal` modules build their //! own decimal fixtures, and compare each result with the result on the canonical array. -mod aggregates; mod compute; mod decimal; -mod decimal_aggregates; mod decimal_cast; mod decimal_compare; mod decimal_fallback; diff --git a/vortex-array/src/compute/conformance/cast.rs b/vortex-array/src/compute/conformance/cast.rs index 9ac8c154877..694b6419370 100644 --- a/vortex-array/src/compute/conformance/cast.rs +++ b/vortex-array/src/compute/conformance/cast.rs @@ -9,9 +9,6 @@ use crate::ArrayRef; use crate::ExecutionCtx; use crate::IntoArray; use crate::RecursiveCanonical; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::MinMaxResult; -use crate::aggregate_fn::fns::min_max::min_max; use crate::arrays::ConstantArray; use crate::assert_arrays_eq; use crate::builders::builder_with_capacity_in; @@ -226,12 +223,15 @@ fn test_cast_to_primitive( test_round_trip: bool, ctx: &mut ExecutionCtx, ) { - let maybe_min_max = min_max(array, ctx, NumericalAggregateOpts::default()) - .vortex_expect("cast should succeed in conformance test"); - - if let Some(MinMaxResult { min, max }) = maybe_min_max - && (!fits(&min, target_ptype) || !fits(&max, target_ptype)) - { + let out_of_range = (0..array.len()) + .map(|idx| { + array + .execute_scalar(idx, ctx) + .vortex_expect("scalar_at should succeed in conformance test") + }) + .find(|value| !value.is_null() && !fits(value, target_ptype)); + + if let Some(value) = out_of_range { cast_and_execute( &array.clone(), DType::Primitive(target_ptype, array.dtype().nullability()), @@ -240,10 +240,9 @@ fn test_cast_to_primitive( .err() .unwrap_or_else(|| { vortex_panic!( - "Cast must fail because some values are out of bounds. {} {:?} {:?} {} {}", + "Cast must fail because value {:?} is out of bounds for {}. {} {}", + value, target_ptype, - min, - max, array, array.display_values(ctx), ) diff --git a/vortex-array/src/compute/conformance/consistency.rs b/vortex-array/src/compute/conformance/consistency.rs index c275b2e8847..b045e6796e6 100644 --- a/vortex-array/src/compute/conformance/consistency.rs +++ b/vortex-array/src/compute/conformance/consistency.rs @@ -31,21 +31,19 @@ use crate::Canonical; use crate::ExecutionCtx; use crate::IntoArray; use crate::RecursiveCanonical; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::fns::nan_count::nan_count; -use crate::aggregate_fn::fns::sum::sum; use crate::arrays::BoolArray; use crate::arrays::ConstantArray; use crate::arrays::PrimitiveArray; use crate::assert_arrays_eq; use crate::builtins::ArrayBuiltins; +use crate::compute::conformance::conformance_stat; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; use crate::scalar_fn::builtin::operators::BooleanOperator; use crate::scalar_fn::builtin::operators::CompareMode; use crate::scalar_fn::builtin::operators::CompareOperator; +use crate::stats::Stat; /// Tests that filter and take operations produce consistent results. /// @@ -815,7 +813,14 @@ fn test_boolean_demorgan_consistency(array: &ArrayRef, ctx: &mut ExecutionCtx) { /// # Why This Matters /// Aggregate operations on sliced arrays must produce correct results /// regardless of the underlying encoding's offset handling. -fn test_slice_aggregate_consistency(array: &ArrayRef, ctx: &mut ExecutionCtx) { +/// +/// # Panics +/// +/// Panics if the session has no aggregate functions registered for these statistics; register +/// them with `vortex_aggregates::initialize`. +pub fn test_slice_aggregate_consistency(array: &ArrayRef, ctx: &mut ExecutionCtx) { + use crate::dtype::DType; + let len = array.len(); if len < 5 { return; // Need enough elements for meaningful slice @@ -856,34 +861,32 @@ fn test_slice_aggregate_consistency(array: &ArrayRef, ctx: &mut ExecutionCtx) { return; } - let slice_sum = sum(&sliced, ctx).vortex_expect("slice sum should succeed"); - let canonical_sum = sum(&canonical_sliced, ctx).vortex_expect("canonical sum should succeed"); - assert_eq!( - slice_sum, canonical_sum, - "sum on sliced array should match canonical" - ); - - let slice_minmax = min_max(&sliced, ctx, NumericalAggregateOpts::default()) - .vortex_expect("slice min_max should succeed"); - let canonical_minmax = min_max(&canonical_sliced, ctx, NumericalAggregateOpts::default()) - .vortex_expect("canonical min_max should succeed"); - assert_eq!( - slice_minmax, canonical_minmax, - "min_max on sliced array should match canonical" - ); - - if array.dtype().is_float() { - let slice_nan_count = - nan_count(&sliced, ctx).vortex_expect("slice nan_count should succeed"); - let canonical_nan_count = - nan_count(&canonical_sliced, ctx).vortex_expect("canonical nan_count should succeed"); + for stat in [Stat::Sum, Stat::Min, Stat::Max, Stat::NaNCount] { + if stat.dtype(array.dtype()).is_none() { + continue; + } + let sliced_stat = conformance_stat(&sliced, stat, ctx); + let canonical_stat = conformance_stat(&canonical_sliced, stat, ctx); assert_eq!( - slice_nan_count, canonical_nan_count, - "nan_count on sliced array should match canonical" + sliced_stat, canonical_stat, + "{stat} on sliced array should match canonical. \ + Sliced: {sliced_stat:?}, Canonical: {canonical_stat:?}" ); } } +/// Whether the session can compute the statistics [`test_slice_aggregate_consistency`] checks. +fn aggregates_registered(ctx: &ExecutionCtx) -> bool { + [Stat::Sum, Stat::Min, Stat::Max, Stat::NaNCount] + .into_iter() + .all(|stat| { + stat.resolve_aggregate_fn(ctx.session()) + .ok() + .flatten() + .is_some() + }) +} + fn widened_primitive_dtype(dtype: &DType) -> Option { let DType::Primitive(ptype, nullability) = dtype else { return None; @@ -1332,7 +1335,10 @@ pub fn test_array_consistency(array: &ArrayRef, ctx: &mut ExecutionCtx) { test_comparison_symmetry_consistency(array, ctx); // Aggregate operations - test_slice_aggregate_consistency(array, ctx); + // Aggregates resolve through the session, and the core array crate cannot register them. + if aggregates_registered(ctx) { + test_slice_aggregate_consistency(array, ctx); + } // Identity operations test_filter_identity(array, ctx); diff --git a/vortex-array/src/compute/conformance/mod.rs b/vortex-array/src/compute/conformance/mod.rs index d10c2f46cf8..bc00f9ccda2 100644 --- a/vortex-array/src/compute/conformance/mod.rs +++ b/vortex-array/src/compute/conformance/mod.rs @@ -1,6 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_error::VortexExpect; + +use crate::ArrayRef; +use crate::ExecutionCtx; +use crate::stats::Stat; +use crate::scalar::Scalar; + pub mod binary_numeric; pub mod cast; pub mod consistency; @@ -10,3 +17,30 @@ pub mod hegel; pub mod mask; pub mod search_sorted; pub mod take; + +/// Computes `stat` for `array` through the session's aggregate function registry. +/// +/// # Panics +/// +/// Panics if no aggregate function computing `stat` is registered, so that a conformance suite run +/// with an incomplete session fails rather than silently skipping its statistics checks. Register +/// the aggregate functions with `vortex_aggregates::initialize`. +pub(crate) fn conformance_stat( + array: &ArrayRef, + stat: Stat, + ctx: &mut ExecutionCtx, +) -> Option { + let registered = stat + .resolve_aggregate_fn(ctx.session()) + .vortex_expect("aggregate function should resolve in conformance test") + .is_some(); + assert!( + registered, + "conformance tests require the aggregate function {} to be registered in the session", + stat.aggregate_fn_id() + ); + array + .statistics() + .compute_stat(stat, ctx) + .vortex_expect("statistic should compute in conformance test") +} diff --git a/vortex-array/src/scalar/typed_view/decimal/dvalue.rs b/vortex-array/src/scalar/typed_view/decimal/dvalue.rs index 9bfa87732f1..ed68ca9ad3d 100644 --- a/vortex-array/src/scalar/typed_view/decimal/dvalue.rs +++ b/vortex-array/src/scalar/typed_view/decimal/dvalue.rs @@ -203,7 +203,7 @@ impl DecimalValue { } /// Checks the dtype precision and returns the value in the dtype's native storage width. - pub(crate) fn normalize(&self, decimal_type: DecimalDType) -> Option { + pub fn normalize(&self, decimal_type: DecimalDType) -> Option { let value_type = decimal_type.canonical_values_type(); match_each_decimal_value_type!(value_type, |T| { let value = self.cast::()?; diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 3cf01ffa170..780d96569fb 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -17,20 +17,11 @@ use super::StatsSetIntoIter; use super::TypedStatsSetRef; use crate::ArrayRef; use crate::ExecutionCtx; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::is_constant::is_constant; -use crate::aggregate_fn::fns::is_sorted::is_sorted; -use crate::aggregate_fn::fns::is_sorted::is_strict_sorted; -use crate::aggregate_fn::fns::min_max::MinMaxResult; -use crate::aggregate_fn::fns::min_max::min_max; -use crate::aggregate_fn::fns::nan_count::nan_count; -use crate::aggregate_fn::fns::sum::sum; -use crate::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; -use crate::scalar::Scalar; -use crate::scalar::ScalarValue; use crate::stats::Precision; use crate::stats::Stat; use crate::stats::StatsProvider; +use crate::scalar::Scalar; +use crate::scalar::ScalarValue; /// A shared [`StatsSet`] stored in an array. Can be shared by copies of the array and can also be mutated in place. /// Stats are created lazily on read or write. diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index fa4299d75aa..5ebab9c7454 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -13,11 +13,8 @@ use num_enum::TryFromPrimitive; use vortex_error::VortexResult; use vortex_session::VortexSession; -use crate::aggregate_fn; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::AggregateFnVTableExt; -use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::NumericalAggregateOpts; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; @@ -28,7 +25,6 @@ use crate::stats::UpperBound; use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::aggregate_fn::stat_aggregates; use crate::aggregate_fn::stat_aggregates::IsSortedOptions; -use crate::aggregate_fn::stat_aggregates::UncompressedSizeOpts; use crate::dtype::PType; #[derive( @@ -204,14 +200,15 @@ impl Stat { /// The serialized options the aggregate function computing this statistic is bound to. /// - /// Min/max/sum statistics skip NaN values, and the uncompressed size statistic is exact. + /// Min/max/sum statistics skip NaN values. pub fn aggregate_fn_options(&self) -> Vec { match self { Self::Max | Self::Min | Self::Sum => NumericalAggregateOpts::skip_nans().serialize(), - Self::UncompressedSizeInBytes => UncompressedSizeOpts::exact().serialize(), Self::IsSorted => IsSortedOptions { strict: false }.serialize(), Self::IsStrictSorted => IsSortedOptions { strict: true }.serialize(), - Self::IsConstant | Self::NullCount | Self::NaNCount => vec![], + Self::IsConstant | Self::NullCount | Self::NaNCount | Self::UncompressedSizeInBytes => { + vec![] + } } } @@ -230,29 +227,11 @@ impl Stat { .map(Some) } - /// Return the built-in aggregate function corresponding to this statistic, if one exists. - pub fn aggregate_fn(&self) -> Option { - // Statistics follow NaN-skipping semantics; request it explicitly rather than the default. - Some(match self { - Self::Max => aggregate_fn::fns::max::Max.bind(NumericalAggregateOpts::skip_nans()), - Self::Min => aggregate_fn::fns::min::Min.bind(NumericalAggregateOpts::skip_nans()), - Self::Sum => aggregate_fn::fns::sum::Sum.bind(NumericalAggregateOpts::skip_nans()), - Self::NullCount => aggregate_fn::fns::null_count::NullCount.bind(EmptyOptions), - Self::NaNCount => aggregate_fn::fns::nan_count::NanCount.bind(EmptyOptions), - Self::UncompressedSizeInBytes => { - aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes - .bind(EmptyOptions) - } - Self::IsConstant | Self::IsSorted | Self::IsStrictSorted => return None, - }) - } - /// Return the statistic represented by `aggregate_fn`, if it has a legacy stat slot. /// /// The aggregate must have this statistic's ID and options. Min/max/sum statistics skip NaN - /// values, so NaN-including configurations of those aggregates have no stat slot. The - /// uncompressed size statistic is exact, so the inexact configuration of that aggregate has - /// no stat slot either. Sortedness and constancy have no stat slot. + /// values, so NaN-including configurations of those aggregates have no stat slot. Sortedness + /// and constancy have no stat slot. pub fn from_aggregate_fn(aggregate_fn: &AggregateFnRef) -> Option { let id = aggregate_fn.id(); let stat = [ diff --git a/vortex-array/src/stats/stats_set.rs b/vortex-array/src/stats/stats_set.rs index 324fa7082cb..aeef5d41ca4 100644 --- a/vortex-array/src/stats/stats_set.rs +++ b/vortex-array/src/stats/stats_set.rs @@ -619,10 +619,7 @@ impl MutTypedStatsSetRef<'_, '_> { #[cfg(test)] mod test { - use std::sync::LazyLock; - use enum_iterator::all; - use itertools::Itertools; use rstest::rstest; use smallvec::smallvec; use vortex_error::VortexResult; @@ -633,6 +630,7 @@ mod test { use crate::VortexSessionExecute; use crate::aggregate_fn::fns::min_max::has_nan_values; use crate::arrays::PrimitiveArray; + use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::MAX_PRECISION; @@ -652,8 +650,6 @@ mod test { use crate::stats::StatsSet; use crate::stats::stats_set::Scalar; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - #[test] fn test_iter() { // SAFETY: No duplicate stats. @@ -1026,44 +1022,6 @@ mod test { ); } - #[test] - fn merge_unordered() { - let array = - PrimitiveArray::from_option_iter([Some(1), None, Some(2), Some(42), Some(10000), None]); - let all_stats = all::() - .filter(|s| !matches!(s, Stat::Sum)) - .filter(|s| !matches!(s, Stat::NaNCount)) - .collect_vec(); - array - .statistics() - .compute_all(&all_stats, &mut SESSION.create_execution_ctx()) - .unwrap(); - - let stats = array.statistics().to_owned(); - for stat in &all_stats { - assert!(!stats.get(*stat).is_absent(), "Stat {stat} is missing"); - } - - let merged = stats.clone().merge_unordered( - &stats, - &DType::Primitive(PType::I32, Nullability::NonNullable), - ); - for (stat, expected) in [ - (Stat::Min, Precision::exact(ScalarValue::from(1i32))), - (Stat::Max, Precision::exact(ScalarValue::from(10000i32))), - (Stat::NullCount, Precision::exact(ScalarValue::from(4u64))), - ( - Stat::UncompressedSizeInBytes, - Precision::exact(ScalarValue::from(50u64)), - ), - (Stat::IsConstant, Precision::exact(ScalarValue::from(false))), - (Stat::IsSorted, Precision::Absent), - (Stat::IsStrictSorted, Precision::Absent), - ] { - assert_eq!(merged.get(stat), expected, "{stat}"); - } - } - #[test] fn merge_min_bound_same() { // Merging a stat with a bound and another with an exact results in exact stat. diff --git a/vortex-array/src/validity.rs b/vortex-array/src/validity.rs index bc7e921ca06..b303117f7d2 100644 --- a/vortex-array/src/validity.rs +++ b/vortex-array/src/validity.rs @@ -31,6 +31,7 @@ use crate::arrays::BoolArray; use crate::arrays::ChunkedArray; use crate::arrays::ConstantArray; use crate::arrays::bool::BoolArrayExt; +use crate::arrays::bool::bool_bounds; use crate::builtins::ArrayBuiltins; use crate::dtype::DType; use crate::dtype::Nullability; @@ -424,16 +425,10 @@ impl Validity { Self::NonNullable => Some(Self::NonNullable), Self::AllValid => Some(Self::NonNullable), Self::AllInvalid => None, - Self::Array(is_valid) => { - is_valid - .statistics() - .compute_min::(ctx) - .vortex_expect("validity array must support min") - .then(|| { - // min true => all true - Self::NonNullable - }) - } + Self::Array(is_valid) => bool_bounds(&is_valid, ctx) + .vortex_expect("validity array must be a readable boolean array") + .is_some_and(|bounds| bounds.all_true) + .then_some(Self::NonNullable), } } diff --git a/vortex-btrblocks/Cargo.toml b/vortex-btrblocks/Cargo.toml index 8486268319f..f70246c23d6 100644 --- a/vortex-btrblocks/Cargo.toml +++ b/vortex-btrblocks/Cargo.toml @@ -19,6 +19,7 @@ itertools = { workspace = true } parking_lot = { workspace = true } pco = { workspace = true, optional = true } rand = { workspace = true } +vortex-aggregates = { workspace = true } vortex-alp = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } diff --git a/vortex-btrblocks/src/lib.rs b/vortex-btrblocks/src/lib.rs index 18103da3fba..6b7556eda05 100644 --- a/vortex-btrblocks/src/lib.rs +++ b/vortex-btrblocks/src/lib.rs @@ -105,7 +105,11 @@ pub use vortex_compressor::stats::StringStats; #[cfg(test)] static SESSION: std::sync::LazyLock = - std::sync::LazyLock::new(vortex_session::VortexSession::empty); + std::sync::LazyLock::new(|| { + let session = vortex_session::VortexSession::empty(); + vortex_aggregates::initialize(&session); + session + }); #[cfg(test)] mod tests; diff --git a/vortex-btrblocks/src/schemes/string/sparse.rs b/vortex-btrblocks/src/schemes/string/sparse.rs index 16d2738d609..7067e89dbbb 100644 --- a/vortex-btrblocks/src/schemes/string/sparse.rs +++ b/vortex-btrblocks/src/schemes/string/sparse.rs @@ -3,13 +3,13 @@ //! Sparse encoding for null-dominated string arrays. +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayId; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VTable; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::primitive::PrimitiveArrayExt; diff --git a/vortex-btrblocks/src/tests.rs b/vortex-btrblocks/src/tests.rs index b9c89c4de25..271745e0174 100644 --- a/vortex-btrblocks/src/tests.rs +++ b/vortex-btrblocks/src/tests.rs @@ -20,6 +20,7 @@ use rstest::rstest; use vortex_alp::ALP; use vortex_alp::ALPArrayExt; use vortex_alp::ALPArraySlotsExt; +use vortex_aggregates::sum::sum; use vortex_array::ArrayId; #[cfg(feature = "zstd")] use vortex_array::ArrayPlugin; @@ -28,7 +29,6 @@ use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::sum::sum; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DecimalArray; @@ -586,6 +586,7 @@ fn test_cuda_binary_zstd_follows_editions( // The CUDA preset enables both Zstd schemes; the edition filter must choose between them. let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); vortex_zstd::initialize(&session); for family in EDITION_FAMILIES { session.editions().declare_family(family)?; diff --git a/vortex-btrblocks/tests/golden.rs b/vortex-btrblocks/tests/golden.rs index c36e3518577..7bc63dc61dc 100644 --- a/vortex-btrblocks/tests/golden.rs +++ b/vortex-btrblocks/tests/golden.rs @@ -62,7 +62,11 @@ use vortex_edition::declarations::core::CORE_2026_08_3; use vortex_error::VortexResult; use vortex_session::VortexSession; -static SESSION: LazyLock = LazyLock::new(VortexSession::empty); +static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); + session +}); /// Number of values in each numeric corpus entry: comfortably above the 1024-value sampling /// threshold so scheme selection runs on sampled estimates, as it does for real file chunks. diff --git a/vortex-compressor/Cargo.toml b/vortex-compressor/Cargo.toml index ecdfedfc251..ae7d8e94114 100644 --- a/vortex-compressor/Cargo.toml +++ b/vortex-compressor/Cargo.toml @@ -18,6 +18,7 @@ parking_lot = { workspace = true } rand = { workspace = true } rustc-hash = { workspace = true } tracing = { workspace = true, features = ["std", "attributes"] } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/vortex-compressor/src/compressor/cascade.rs b/vortex-compressor/src/compressor/cascade.rs index 7fdb09464e0..a27893f8fa1 100644 --- a/vortex-compressor/src/compressor/cascade.rs +++ b/vortex-compressor/src/compressor/cascade.rs @@ -4,14 +4,15 @@ //! Core cascading compression flow. use vortex_array::ArrayId; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::CanonicalValidity; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VTable; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; +use vortex_array::arrays::Constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::Extension; use vortex_array::arrays::ExtensionArray; diff --git a/vortex-compressor/src/compressor/constant/mod.rs b/vortex-compressor/src/compressor/constant/mod.rs index d656450724d..44518f7e66c 100644 --- a/vortex-compressor/src/compressor/constant/mod.rs +++ b/vortex-compressor/src/compressor/constant/mod.rs @@ -10,13 +10,13 @@ //! //! [`Scheme`]: crate::scheme::Scheme +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::Canonical; use vortex_array::Columnar; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::MaskedArray; use vortex_array::arrays::VarBinView; diff --git a/vortex-compressor/src/compressor/tests.rs b/vortex-compressor/src/compressor/tests.rs index 6de5e206a92..1343a5e5e9e 100644 --- a/vortex-compressor/src/compressor/tests.rs +++ b/vortex-compressor/src/compressor/tests.rs @@ -9,13 +9,13 @@ use std::sync::atomic::Ordering; use parking_lot::Mutex; use rstest::rstest; +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayId; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::Constant; diff --git a/vortex-datafusion/src/persistent/format.rs b/vortex-datafusion/src/persistent/format.rs index 6ceb10c7e02..a72cc492a74 100644 --- a/vortex-datafusion/src/persistent/format.rs +++ b/vortex-datafusion/src/persistent/format.rs @@ -47,7 +47,7 @@ use object_store::ObjectStore; use vortex::VortexSessionDefault; use vortex::aggregate_fn::AggregateFnVTableExt; use vortex::aggregate_fn::EmptyOptions; -use vortex::aggregate_fn::fns::is_constant::IsConstant; +use vortex::aggregates::is_constant::IsConstant; use vortex::array::memory::MemorySessionExt; use vortex::dtype::DType; use vortex::dtype::FieldPath; diff --git a/vortex-duckdb/src/column_statistics.rs b/vortex-duckdb/src/column_statistics.rs index 6a3660ed73a..ff671b5cd8a 100644 --- a/vortex-duckdb/src/column_statistics.rs +++ b/vortex-duckdb/src/column_statistics.rs @@ -5,11 +5,11 @@ use vortex::aggregate_fn::AggregateFnRef; use vortex::aggregate_fn::AggregateFnVTableExt; use vortex::aggregate_fn::EmptyOptions; use vortex::aggregate_fn::NumericalAggregateOpts; -use vortex::aggregate_fn::fns::max::Max; -use vortex::aggregate_fn::fns::min::Min; -use vortex::aggregate_fn::fns::nan_count::NanCount; -use vortex::aggregate_fn::fns::null_count::NullCount; -use vortex::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; +use vortex::aggregates::max::Max; +use vortex::aggregates::min::Min; +use vortex::aggregates::nan_count::NanCount; +use vortex::aggregates::null_count::NullCount; +use vortex::aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex::array::match_each_float_ptype; use vortex::dtype::DType; use vortex::error::VortexExpect as _; diff --git a/vortex-duckdb/src/convert/expr.rs b/vortex-duckdb/src/convert/expr.rs index d3279eae930..4a81495b437 100644 --- a/vortex-duckdb/src/convert/expr.rs +++ b/vortex-duckdb/src/convert/expr.rs @@ -11,13 +11,13 @@ use vortex::aggregate_fn::Accumulator; use vortex::aggregate_fn::DynAccumulator; use vortex::aggregate_fn::EmptyOptions as AggregateEmptyOptions; use vortex::aggregate_fn::NumericalAggregateOpts; -use vortex::aggregate_fn::fns::max::Max; -use vortex::aggregate_fn::fns::min::Min; -use vortex::aggregate_fn::fns::sum_v2::SumV2; use vortex::aggregates::combined::PairOptions; use vortex::aggregates::count::Count; use vortex::aggregates::first::First; +use vortex::aggregates::max::Max; use vortex::aggregates::mean::Mean; +use vortex::aggregates::min::Min; +use vortex::aggregates::sum_v2::SumV2; use vortex::dtype::DType; use vortex::dtype::Nullability; use vortex::dtype::PType; diff --git a/vortex-duckdb/src/copy.rs b/vortex-duckdb/src/copy.rs index 89d89f320ce..4c33dc3f347 100644 --- a/vortex-duckdb/src/copy.rs +++ b/vortex-duckdb/src/copy.rs @@ -22,10 +22,10 @@ use vortex::aggregate_fn::AggregateFnRef; use vortex::aggregate_fn::AggregateFnVTableExt; use vortex::aggregate_fn::EmptyOptions; use vortex::aggregate_fn::NumericalAggregateOpts; -use vortex::aggregate_fn::fns::max::Max; -use vortex::aggregate_fn::fns::min::Min; -use vortex::aggregate_fn::fns::nan_count::NanCount; -use vortex::aggregate_fn::fns::null_count::NullCount; +use vortex::aggregates::max::Max; +use vortex::aggregates::min::Min; +use vortex::aggregates::nan_count::NanCount; +use vortex::aggregates::null_count::NullCount; use vortex::array::ArrayRef; use vortex::array::stream::ArrayStreamAdapter; use vortex::dtype::DType; @@ -485,7 +485,7 @@ mod tests { fn pruning_aggregate_fns() -> Vec { [Stat::Min, Stat::Max, Stat::NullCount, Stat::NaNCount] .into_iter() - .filter_map(|stat| stat.aggregate_fn()) + .filter_map(vortex::aggregates::stat_aggregate_fn) .collect() } diff --git a/vortex-expr/Cargo.toml b/vortex-expr/Cargo.toml index 5af068792fb..c7507e247d7 100644 --- a/vortex-expr/Cargo.toml +++ b/vortex-expr/Cargo.toml @@ -19,6 +19,7 @@ parking_lot = { workspace = true } prost = { workspace = true } smallvec = { workspace = true } tracing = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-error = { workspace = true } vortex-session = { workspace = true } diff --git a/vortex-expr/src/stats/expr.rs b/vortex-expr/src/stats/expr.rs index c9d7d76856b..9af69c630fe 100644 --- a/vortex-expr/src/stats/expr.rs +++ b/vortex-expr/src/stats/expr.rs @@ -3,18 +3,21 @@ //! Expression constructors for statistics backed by aggregate functions. +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; +use vortex_aggregates::min_max::MinMax; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::min_max::MinMax; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; -use vortex_array::aggregate_fn::fns::sum::Sum; +use vortex_array::expr::BoundExpression; +use vortex_array::expr::Expression; +use vortex_array::scalar_fn::ScalarFnVTableExt; use vortex_error::VortexExpect; use crate::BoundExpression; @@ -170,6 +173,7 @@ pub mod bound { mod tests { use std::sync::LazyLock; + use vortex_aggregates::stat_aggregate_fn; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -518,12 +522,14 @@ mod tests { .statistics() .set(Stat::Max, Precision::exact(ScalarValue::from(3i32))); - let min_result = array.clone().apply(&stat( - root(), - Stat::Min - .aggregate_fn() - .vortex_expect("min should have an aggregate function"), - ))?; + let min_result = array + .clone() + .apply(&stat( + root(), + stat_aggregate_fn(Stat::Min).vortex_expect("min should have an aggregate function"), + ))? + .execute::(&mut SESSION.create_execution_ctx())? + .into_array(); let expected_min = ConstantArray::new(Scalar::primitive(1i32, Nullability::Nullable), 3).into_array(); assert_arrays_eq!( @@ -532,12 +538,13 @@ mod tests { &mut SESSION.create_execution_ctx() ); - let max_result = array.apply(&stat( - root(), - Stat::Max - .aggregate_fn() - .vortex_expect("max should have an aggregate function"), - ))?; + let max_result = array + .apply(&stat( + root(), + stat_aggregate_fn(Stat::Max).vortex_expect("max should have an aggregate function"), + ))? + .execute::(&mut SESSION.create_execution_ctx())? + .into_array(); let expected_max = ConstantArray::new(Scalar::primitive(3i32, Nullability::Nullable), 3).into_array(); assert_arrays_eq!( diff --git a/vortex-expr/src/stats/rewrite/builtins.rs b/vortex-expr/src/stats/rewrite/builtins.rs index f9bfa01c36a..19ee753069b 100644 --- a/vortex-expr/src/stats/rewrite/builtins.rs +++ b/vortex-expr/src/stats/rewrite/builtins.rs @@ -1,15 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::dtype::DType; use vortex_array::expr::BoundExpression; use vortex_array::optimizer::kernels::ArrayKernelsExt; @@ -515,11 +515,12 @@ mod tests { use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; + use vortex_aggregates::all_non_nan::AllNonNan; + use vortex_aggregates::nan_count::NanCount; + use vortex_aggregates::stat_aggregate_fn; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions as AggregateEmptyOptions; - use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; - use vortex_array::aggregate_fn::fns::nan_count::NanCount; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; @@ -566,7 +567,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(VortexSession::empty); fn stat(expr: Expression, stat: Stat) -> Expression { - let aggregate_fn = stat.aggregate_fn().expect("stat should have aggregate fn"); + let aggregate_fn = stat_aggregate_fn(stat).expect("stat should have aggregate fn"); stat_fn(expr, aggregate_fn) } diff --git a/vortex-extensions/vortex-spatial/Cargo.toml b/vortex-extensions/vortex-spatial/Cargo.toml index dfd2df31c44..705a5c7af7e 100644 --- a/vortex-extensions/vortex-spatial/Cargo.toml +++ b/vortex-extensions/vortex-spatial/Cargo.toml @@ -41,6 +41,7 @@ divan = { workspace = true } hegeltest = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-arrow = { workspace = true, features = ["_test-harness-hegel"] } vortex-file = { workspace = true } diff --git a/vortex-extensions/vortex-spatial/README.md b/vortex-extensions/vortex-spatial/README.md index 0884adef985..a128cad1b09 100644 --- a/vortex-extensions/vortex-spatial/README.md +++ b/vortex-extensions/vortex-spatial/README.md @@ -63,8 +63,8 @@ Avoid per-row `scalar_at` or validity lookups in either path. Materialize coordi To record file-wide bounds, enable nested statistics and include `GeometryAabb` in the requested aggregates: ```rust +use vortex_aggregates::null_count::NullCount; use vortex_array::aggregate_fn::{AggregateFnVTableExt, EmptyOptions}; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_file::WriteOptionsSessionExt; use vortex_spatial::aggregate_fn::GeometryAabb; # let session = vortex_session::VortexSession::empty(); @@ -86,8 +86,8 @@ For zone bounds, explicitly configure `ZonedLayoutOptions::aggregate_fns`: ```rust use std::sync::Arc; +use vortex_aggregates::null_count::NullCount; use vortex_array::aggregate_fn::{AggregateFnVTableExt, EmptyOptions}; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_layout::layouts::zoned::writer::ZonedLayoutOptions; use vortex_spatial::aggregate_fn::GeometryAabb; diff --git a/vortex-extensions/vortex-spatial/src/tests/mod.rs b/vortex-extensions/vortex-spatial/src/tests/mod.rs index 5eadd2be8e3..d3f16fde1f7 100644 --- a/vortex-extensions/vortex-spatial/src/tests/mod.rs +++ b/vortex-extensions/vortex-spatial/src/tests/mod.rs @@ -15,10 +15,10 @@ mod wkb; use std::sync::Arc; use std::sync::LazyLock; +use vortex_aggregates::null_count::NullCount; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::StructArray; use vortex_array::dtype::FieldPath; use vortex_array::dtype::Nullability; diff --git a/vortex-extensions/vortex-uuid/Cargo.toml b/vortex-extensions/vortex-uuid/Cargo.toml index ad25d93b2fe..e5374f82f86 100644 --- a/vortex-extensions/vortex-uuid/Cargo.toml +++ b/vortex-extensions/vortex-uuid/Cargo.toml @@ -19,6 +19,7 @@ workspace = true arrow-array = { workspace = true } arrow-schema = { workspace = true, features = ["canonical_extension_types"] } uuid = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-arrow = { workspace = true } vortex-buffer = { workspace = true, features = ["arrow"] } diff --git a/vortex-extensions/vortex-uuid/src/lib.rs b/vortex-extensions/vortex-uuid/src/lib.rs index 113e5dcb400..c3c099c1506 100644 --- a/vortex-extensions/vortex-uuid/src/lib.rs +++ b/vortex-extensions/vortex-uuid/src/lib.rs @@ -30,7 +30,6 @@ mod vtable; pub use metadata::UuidMetadata; pub use text::format_uuid; pub use text::parse_uuid; -use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::dtype::session::DTypeSessionExt; use vortex_array::optimizer::kernels::ArrayKernelsExt; use vortex_array::scalar_fn::session::ScalarFnSessionExt; @@ -58,7 +57,7 @@ pub fn initialize(session: &VortexSession) { session .kernels() .register_scalar_fn_supports(text::FormatUuid); - session.aggregate_fns().register_storage_ordered(Uuid); + vortex_aggregates::register_storage_ordered(session, Uuid); session.arrow().register_extension(Uuid); } @@ -68,6 +67,10 @@ mod arrow_properties; #[cfg(test)] mod tests { use rstest::rstest; + use vortex_aggregates::is_sorted::IsSorted; + use vortex_aggregates::is_sorted::IsSortedOptions; + use vortex_aggregates::min_max::MinMax; + use vortex_aggregates::min_max::MinMaxResult; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -76,10 +79,6 @@ mod tests { use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::ExtensionStoragePushdown; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; - use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; - use vortex_array::aggregate_fn::fns::min_max::MinMax; - use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::FixedSizeListArray; diff --git a/vortex-file/src/footer/file_statistics.rs b/vortex-file/src/footer/file_statistics.rs index d51dc48f2d4..bee9cd0e112 100644 --- a/vortex-file/src/footer/file_statistics.rs +++ b/vortex-file/src/footer/file_statistics.rs @@ -347,7 +347,7 @@ fn aggregates_from_array_stats( stats_set .iter() .filter_map(|(stat, value)| { - let aggregate_fn = stat.aggregate_fn()?; + let aggregate_fn = vortex_aggregates::stat_aggregate_fn(*stat)?; let stat_dtype = stat.dtype(dtype)?; let value = value .clone() @@ -578,19 +578,20 @@ impl WriteFlatBuffer for FileStatistics { #[cfg(test)] mod tests { use std::num::NonZeroUsize; + use std::sync::LazyLock; use flatbuffers::FlatBufferBuilder; use rstest::rstest; + use vortex_aggregates::bounded_max::BoundedMax; + use vortex_aggregates::bounded_max::BoundedMaxOptions; + use vortex_aggregates::max::Max; + use vortex_aggregates::min::Min; + use vortex_aggregates::null_count::NullCount; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; - use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; - use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::VarBinViewArray; use vortex_array::dtype::FieldPath; use vortex_array::dtype::Nullability; @@ -602,6 +603,13 @@ mod tests { use super::*; + /// Reading statistics back resolves their aggregate functions through the session. + static SESSION: LazyLock = LazyLock::new(|| { + let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); + session + }); + fn i32_dtype() -> DType { DType::Primitive(PType::I32, Nullability::NonNullable) } @@ -637,7 +645,7 @@ mod tests { let bytes = file_stats.write_flatbuffer_bytes()?; let fb = flatbuffers::root::(bytes.as_ref()) .vortex_expect("valid flatbuffer"); - FileStatistics::from_flatbuffer(&fb, file_dtype, &VortexSession::empty()) + FileStatistics::from_flatbuffer(&fb, file_dtype, &SESSION) } #[test] @@ -781,7 +789,7 @@ mod tests { let mut accumulator = bounded_max.accumulator(&field_dtype)?; accumulator.accumulate( &VarBinViewArray::from_iter_str(["a value past the bound"]).into_array(), - &mut VortexSession::empty().create_execution_ctx(), + &mut SESSION.create_execution_ctx(), )?; let partial = accumulator.partial_scalar()?; let file_stats = FileStatistics::new_with_dtype( @@ -859,7 +867,7 @@ mod tests { fn read_raw(bytes: &[u8], file_dtype: &DType) -> VortexResult { let fb = flatbuffers::root::(bytes).vortex_expect("valid flatbuffer"); - FileStatistics::from_flatbuffer(&fb, file_dtype, &VortexSession::empty()) + FileStatistics::from_flatbuffer(&fb, file_dtype, &SESSION) } /// The options of `min` and its partial state for `value`, length-prefixed as in `partials`. diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 93700e9fa0c..512b828d70c 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -29,13 +29,13 @@ use rand::rngs::StdRng; use rstest::rstest; use tempfile::tempdir; use tokio::sync::watch; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; @@ -161,14 +161,13 @@ static SESSION: LazyLock = LazyLock::new(|| { fn pruning_aggregate_fns() -> Vec { [Stat::Min, Stat::Max, Stat::NullCount, Stat::NaNCount] .into_iter() - .filter_map(|stat| stat.aggregate_fn()) + .filter_map(vortex_aggregates::stat_aggregate_fn) .collect() } /// The value the file statistics entry `aggregates` resolves for `stat`. fn stat_value(aggregates: &AggregateStats, stat: Stat) -> Precision { - let aggregate_fn = stat - .aggregate_fn() + let aggregate_fn = vortex_aggregates::stat_aggregate_fn(stat) .vortex_expect("test only uses stats with an aggregate fn"); aggregates.get(&aggregate_fn).and_then(Scalar::into_value) } @@ -2823,8 +2822,7 @@ async fn file_sum_is_absent_when_a_chunk_overflows() -> VortexResult<()> { .write_options() .disable_editions() .with_file_statistics(vec![ - Stat::Sum - .aggregate_fn() + vortex_aggregates::stat_aggregate_fn(Stat::Sum) .vortex_expect("sum has an aggregate fn"), ]) .writer(&mut buf, dtype); diff --git a/vortex-file/src/v2/file_stats_reader.rs b/vortex-file/src/v2/file_stats_reader.rs index 8c1b6f94a9f..c1d53a3c225 100644 --- a/vortex-file/src/v2/file_stats_reader.rs +++ b/vortex-file/src/v2/file_stats_reader.rs @@ -243,14 +243,14 @@ mod tests { use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; + use vortex_aggregates::max::Max; + use vortex_aggregates::min::Min; + use vortex_aggregates::null_count::NullCount; use vortex_array::ArrayContext; use vortex_array::IntoArray as _; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; - use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::arrays::datetime::TemporalData; diff --git a/vortex-file/src/writer.rs b/vortex-file/src/writer.rs index cdb29bcd367..fe3ec4b4c9a 100644 --- a/vortex-file/src/writer.rs +++ b/vortex-file/src/writer.rs @@ -21,12 +21,12 @@ use futures::pin_mut; use futures::select; use itertools::Itertools; use parking_lot::Mutex; +use vortex_aggregates::min::Min; use vortex_array::ArrayContext; use vortex_array::ArrayId; use vortex_array::ArrayRef; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::dtype::DType; use vortex_array::dtype::FieldPath; use vortex_array::iter::ArrayIterator; diff --git a/vortex-functions/Cargo.toml b/vortex-functions/Cargo.toml index c01ac11dd68..6563e43c9c0 100644 --- a/vortex-functions/Cargo.toml +++ b/vortex-functions/Cargo.toml @@ -24,6 +24,7 @@ regex = { workspace = true } regex-syntax = { workspace = true } rustc-hash = { workspace = true } tracing = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["unstable_row_fns"] } vortex-buffer = { workspace = true } vortex-compute = { workspace = true } diff --git a/vortex-functions/src/list_sum.rs b/vortex-functions/src/list_sum.rs index f2aca539e53..ec0b5d5dd22 100644 --- a/vortex-functions/src/list_sum.rs +++ b/vortex-functions/src/list_sum.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::sum_v2::SumV2; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::Columnar; @@ -10,7 +11,6 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynGroupedAccumulator; use vortex_array::aggregate_fn::GroupedAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; use vortex_array::scalar_fn::Arity; diff --git a/vortex-functions/src/pruning/dynamic_expression.rs b/vortex-functions/src/pruning/dynamic_expression.rs index 6de9ff40c8f..291b3f71cd8 100644 --- a/vortex-functions/src/pruning/dynamic_expression.rs +++ b/vortex-functions/src/pruning/dynamic_expression.rs @@ -7,13 +7,13 @@ use std::fmt::Display; use std::fmt::Formatter; use std::sync::Arc; +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions as AggregateEmptyOptions; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; @@ -94,7 +94,7 @@ pub(crate) fn dynamic_stats_proof( fn proof_aggregates() -> Vec { [Stat::Min, Stat::Max, Stat::NullCount, Stat::NaNCount] .into_iter() - .filter_map(|stat| stat.aggregate_fn()) + .filter_map(vortex_aggregates::stat_aggregate_fn) .chain([ AllNull.bind(AggregateEmptyOptions), AllNonNull.bind(AggregateEmptyOptions), diff --git a/vortex-layout/benches/aggregate_partial_merge.rs b/vortex-layout/benches/aggregate_partial_merge.rs index 74c94a6656a..5fb5b901ebd 100644 --- a/vortex-layout/benches/aggregate_partial_merge.rs +++ b/vortex-layout/benches/aggregate_partial_merge.rs @@ -21,6 +21,7 @@ use std::sync::LazyLock; use divan::Bencher; use divan::counter::ItemsCount; use mimalloc::MiMalloc; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -29,7 +30,6 @@ use vortex_array::aggregate_fn::AccumulatorRef; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::sum_v2::SumV2; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::DType; diff --git a/vortex-layout/benches/zone_map_prune.rs b/vortex-layout/benches/zone_map_prune.rs index 86d39988b5c..7bbc5fe1902 100644 --- a/vortex-layout/benches/zone_map_prune.rs +++ b/vortex-layout/benches/zone_map_prune.rs @@ -14,16 +14,17 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; use parking_lot::Mutex; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; +use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::dtype::DType; @@ -57,10 +58,13 @@ fn main() { } static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() + .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); /// Zone counts to sweep. The small case exposes per-call fixed cost, the large case exposes diff --git a/vortex-layout/src/layouts/compressed.rs b/vortex-layout/src/layouts/compressed.rs index 5f84397f3ed..2f819cd6490 100644 --- a/vortex-layout/src/layouts/compressed.rs +++ b/vortex-layout/src/layouts/compressed.rs @@ -5,11 +5,11 @@ use std::sync::Arc; use async_trait::async_trait; use futures::StreamExt as _; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::stats::Stat; use vortex_btrblocks::BtrBlocksCompressor; use vortex_error::VortexResult; diff --git a/vortex-layout/src/layouts/file_stats.rs b/vortex-layout/src/layouts/file_stats.rs index eabbbfaa6f1..9c576caee52 100644 --- a/vortex-layout/src/layouts/file_stats.rs +++ b/vortex-layout/src/layouts/file_stats.rs @@ -7,6 +7,15 @@ use std::sync::Arc; use futures::StreamExt; use itertools::Itertools; use parking_lot::Mutex; +use vortex_aggregates::bounded_max::BoundedMax; +use vortex_aggregates::bounded_max::BoundedMaxOptions; +use vortex_aggregates::bounded_min::BoundedMin; +use vortex_aggregates::bounded_min::BoundedMinOptions; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::VortexSessionExecute; @@ -16,15 +25,6 @@ use vortex_array::aggregate_fn::AggregateFnSatisfaction; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMinOptions; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::arrays::StructArray; use vortex_array::arrays::struct_::StructArrayExt; use vortex_array::dtype::DType; @@ -316,7 +316,7 @@ impl AggregateStats { pub fn to_stats_set(&self) -> StatsSet { let mut stats_set = StatsSet::default(); for stat in Stat::all() { - let Some(requested) = stat.aggregate_fn() else { + let Some(requested) = vortex_aggregates::stat_aggregate_fn(stat) else { continue; }; let value = self.get(&requested).and_then(Scalar::into_value); @@ -337,7 +337,7 @@ fn non_null(value: Precision) -> Precision { /// a string column fills the min slot. fn fills_legacy_stat_slot(aggregate_fn: &AggregateFnRef) -> bool { Stat::all() - .filter_map(|stat| stat.aggregate_fn()) + .filter_map(vortex_aggregates::stat_aggregate_fn) .any(|requested| { !matches!( aggregate_fn.can_satisfy(&requested), @@ -972,7 +972,6 @@ impl FileStatsAccumulator { #[cfg(test)] mod tests { use std::num::NonZeroUsize; - use std::sync::LazyLock; use rstest::rstest; use vortex_array::ArrayContext; @@ -994,8 +993,7 @@ mod tests { use vortex_utils::aliases::hash_set::HashSet; use super::*; - - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + use crate::test::SESSION; /// Pushes `chunk` through `acc` the way the write stream does. fn push( @@ -1020,7 +1018,7 @@ mod tests { } fn agg(stat: Stat) -> AggregateFnRef { - stat.aggregate_fn() + vortex_aggregates::stat_aggregate_fn(stat) .vortex_expect("test only uses stats with an aggregate fn") } diff --git a/vortex-layout/src/layouts/repartition.rs b/vortex-layout/src/layouts/repartition.rs index 187193be877..9d3b780d701 100644 --- a/vortex-layout/src/layouts/repartition.rs +++ b/vortex-layout/src/layouts/repartition.rs @@ -8,13 +8,13 @@ use async_stream::try_stream; use async_trait::async_trait; use futures::StreamExt as _; use futures::pin_mut; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::arrays::ChunkedArray; use vortex_array::dtype::DType; use vortex_error::VortexExpect; diff --git a/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/bool.rs b/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/bool.rs index 3401e359103..a071e57a446 100644 --- a/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/bool.rs +++ b/vortex-layout/src/layouts/zoned/aggregates/bloom_filter/canonical/bool.rs @@ -11,7 +11,7 @@ use vortex_mask::AllOr; use super::BloomPartial; -/// Similar to `accumulate_bool` implementation in [vortex_array::aggregate_fn::fns::min_max] +/// Similar to `accumulate_bool` implementation in [vortex_aggregates::min_max] pub(super) fn accumulate_bool( array: &BoolArray, partial: &mut BloomPartial, diff --git a/vortex-layout/src/layouts/zoned/mod.rs b/vortex-layout/src/layouts/zoned/mod.rs index 122bacd72c2..b1adab30773 100644 --- a/vortex-layout/src/layouts/zoned/mod.rs +++ b/vortex-layout/src/layouts/zoned/mod.rs @@ -32,6 +32,7 @@ pub use schema::MAX_IS_TRUNCATED; pub use schema::MIN_IS_TRUNCATED; pub(crate) use schema::default_bounded_stat_max_bytes; pub(crate) use schema::legacy_stats_to_aggregates; +use vortex_aggregates::stat_aggregate_fn; use vortex_array::DeserializeMetadata; use vortex_array::SerializeMetadata; use vortex_array::aggregate_fn::AggregateFnRef; @@ -475,7 +476,7 @@ impl ZonedData { match &self.zone_map_schema { ZoneMapSchema::LegacyStats(stats) => stats .iter() - .filter_map(Stat::aggregate_fn) + .filter_map(|stat| stat_aggregate_fn(*stat)) .collect::>() .into(), ZoneMapSchema::AggregateFns(aggregate_fns) => Arc::clone(aggregate_fns), @@ -487,7 +488,7 @@ fn present_aggregates(schema: &ZoneMapSchema) -> Arc<[String]> { match schema { ZoneMapSchema::LegacyStats(stats) => stats .iter() - .filter_map(Stat::aggregate_fn) + .filter_map(|stat| stat_aggregate_fn(*stat)) .map(|aggregate_fn| aggregate_fn.to_string()) .collect::>() .into(), @@ -606,12 +607,12 @@ mod tests { use rstest::rstest; use vortex_aggregates::bounded_max::BoundedMax; use vortex_aggregates::bounded_max::BoundedMaxOptions; + use vortex_aggregates::max::Max; + use vortex_aggregates::min::Min; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; - use vortex_array::aggregate_fn::fns::sum::Sum; + use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; diff --git a/vortex-layout/src/layouts/zoned/schema.rs b/vortex-layout/src/layouts/zoned/schema.rs index 8797e20fb5a..4bd33940f1d 100644 --- a/vortex-layout/src/layouts/zoned/schema.rs +++ b/vortex-layout/src/layouts/zoned/schema.rs @@ -5,6 +5,7 @@ use std::sync::Arc; +use vortex_aggregates::stat_aggregate_fn; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::dtype::DType; @@ -168,7 +169,7 @@ pub(crate) fn legacy_stats_to_aggregates( let mut aggregate_fns = Vec::with_capacity(stats.len()); let mut elements = Vec::with_capacity(stats.len()); for stat in stats { - let Some(aggregate_fn) = stat.aggregate_fn() else { + let Some(aggregate_fn) = stat_aggregate_fn(*stat) else { continue; }; let Some(stored) = fields.and_then(|fields| fields.field(stat.name())) else { @@ -205,11 +206,11 @@ pub(crate) fn default_bounded_stat_max_bytes() -> std::num::NonZeroUsize { mod tests { use std::sync::LazyLock; + use vortex_aggregates::max::Max; + use vortex_aggregates::min::Min; + use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; - use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index 1b55ae4cb73..26b96cc1417 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -13,16 +13,16 @@ use vortex_aggregates::bounded_max::BoundedMax; use vortex_aggregates::bounded_max::BoundedMaxOptions; use vortex_aggregates::bounded_min::BoundedMin; use vortex_aggregates::bounded_min::BoundedMinOptions; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::dtype::DType; use vortex_error::VortexError; use vortex_error::VortexResult; @@ -412,13 +412,14 @@ mod tests { use rstest::rstest; use vortex_aggregates::bounded_max::BoundedMax; use vortex_aggregates::bounded_min::BoundedMin; + use vortex_aggregates::max::Max; + use vortex_aggregates::min::Min; + use vortex_aggregates::sum::Sum; use vortex_array::ArrayContext; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnVTable; - use vortex_array::aggregate_fn::fns::max::Max; - use vortex_array::aggregate_fn::fns::min::Min; - use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::ChunkedArray; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; diff --git a/vortex-layout/src/layouts/zoned/zone_map.rs b/vortex-layout/src/layouts/zoned/zone_map.rs index e05302e3ed6..36ce57e79d5 100644 --- a/vortex-layout/src/layouts/zoned/zone_map.rs +++ b/vortex-layout/src/layouts/zoned/zone_map.rs @@ -5,8 +5,13 @@ use std::sync::Arc; +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; use vortex_aggregates::bounded_max::BOUNDED_MAX_BOUND; use vortex_aggregates::bounded_max::BoundedMax; +use vortex_aggregates::stat_aggregate_fn; use vortex_array::ArrayRef; use vortex_array::Columnar; use vortex_array::ExecutionCtx; @@ -14,10 +19,6 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; @@ -318,7 +319,7 @@ impl ZoneMap { } fn stat_field_expr(&self, stat: Stat) -> Option { - if let Some(aggregate_fn) = stat.aggregate_fn() + if let Some(aggregate_fn) = stat_aggregate_fn(stat) && let Some(expr) = self.aggregate_field_expr(&aggregate_fn) { return Some(expr); diff --git a/vortex-layout/src/test.rs b/vortex-layout/src/test.rs index c2151edb5a1..5844242d44e 100644 --- a/vortex-layout/src/test.rs +++ b/vortex-layout/src/test.rs @@ -16,6 +16,7 @@ pub fn new_session() -> VortexSession { .with::() .with::(); vortex_functions::initialize(&session); + vortex_aggregates::initialize(&session); session } diff --git a/vortex-scan/src/plan/tests.rs b/vortex-scan/src/plan/tests.rs index bcedd083bf3..6bf089f2633 100644 --- a/vortex-scan/src/plan/tests.rs +++ b/vortex-scan/src/plan/tests.rs @@ -5,10 +5,10 @@ use std::fmt; use std::num::NonZeroUsize; use std::sync::Arc; +use vortex_aggregates::max::Max; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; From 1520c67578795470adfca52f80ce2b4bf7500f9f Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Sat, 24 Oct 2026 14:35:54 +0000 Subject: [PATCH 05/27] Compute integer bounds with the min_max aggregate `integer_bounds` read the `Min` and `Max` statistics separately, which is two passes over a cold array. It now resolves the `min_max` aggregate from the session and computes both extrema in one pass, caching `Min`, `Max` and `NullCount` as the separate statistics would. Exact cached statistics are still read first, and the primitive scan remains the fallback when the session registers no `min_max` aggregate. `stat_aggregates::MIN_MAX_ID` names the aggregate in core, and `MinMax` now serializes its `NumericalAggregateOpts` like `Min` and `Max`, so the session can resolve it by ID. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- vortex-aggregates/src/min_max/mod.rs | 18 +++-- .../src/aggregate_fn/stat_aggregates.rs | 3 + .../src/arrays/primitive/integer_bounds.rs | 74 +++++++++++++++++-- 3 files changed, 82 insertions(+), 13 deletions(-) diff --git a/vortex-aggregates/src/min_max/mod.rs b/vortex-aggregates/src/min_max/mod.rs index a8f39c455d3..6d86da21bc5 100644 --- a/vortex-aggregates/src/min_max/mod.rs +++ b/vortex-aggregates/src/min_max/mod.rs @@ -22,6 +22,7 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; +use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; @@ -39,7 +40,7 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_panic; -use vortex_session::registry::CachedId; +use vortex_session::VortexSession; use self::bool::accumulate_bool; use self::decimal::accumulate_decimal; @@ -348,12 +349,19 @@ impl AggregateFnVTable for MinMax { type Partial = MinMaxPartial; fn id(&self) -> AggregateFnId { - static ID: CachedId = CachedId::new("vortex.min_max"); - *ID + *stat_aggregates::MIN_MAX_ID } - fn serialize(&self, _options: &Self::Options) -> VortexResult>> { - Ok(None) + fn serialize(&self, options: &Self::Options) -> VortexResult>> { + Ok(Some(options.serialize())) + } + + fn deserialize( + &self, + metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + NumericalAggregateOpts::deserialize(metadata) } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { diff --git a/vortex-array/src/aggregate_fn/stat_aggregates.rs b/vortex-array/src/aggregate_fn/stat_aggregates.rs index 33bb0bbcca5..4a27fecd3ff 100644 --- a/vortex-array/src/aggregate_fn/stat_aggregates.rs +++ b/vortex-array/src/aggregate_fn/stat_aggregates.rs @@ -24,6 +24,9 @@ use crate::dtype::PType; /// ID of the aggregate computing the minimum, the `Min` statistic. pub static MIN_ID: CachedId = CachedId::new("vortex.min"); +/// ID of the aggregate computing the minimum and maximum together, the `Min` and `Max` statistics +/// in one pass. +pub static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); /// ID of the aggregate computing the maximum, the `Max` statistic. pub static MAX_ID: CachedId = CachedId::new("vortex.max"); /// ID of the aggregate computing the sum, the `Sum` statistic. diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index 3478ed46647..fcfb2dc684b 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -5,20 +5,27 @@ //! //! These read the array's `Min`, `Max`, `IsSorted` and `IsStrictSorted` statistics, which are //! cached and computed by the aggregate functions the session registers, using any kernel the -//! encoding provides. When a statistic has no answer, because the session registers no aggregate +//! encoding provides. Bounds are computed with the `min_max` aggregate, so both extrema take one +//! pass. When a statistic has no answer, because the session registers no aggregate //! for it, the array is executed to a [`PrimitiveArray`] and scanned once instead, and the scanned //! `Min`, `Max` and `NullCount` are cached. Validation therefore works in every session. +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; use crate::ArrayRef; use crate::ExecutionCtx; +use crate::aggregate_fn::AggregateFnRef; +use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::session::AggregateFnSessionExt; +use crate::aggregate_fn::stat_aggregates; use crate::arrays::PrimitiveArray; use crate::arrays::primitive::PrimitiveArrayExt; use crate::expr::stats::Precision; use crate::expr::stats::Stat; +use crate::expr::stats::StatsProvider; use crate::match_each_integer_ptype; use crate::scalar::Scalar; @@ -44,15 +51,44 @@ pub fn integer_bounds( ) -> VortexResult> { ensure_int(array)?; let stats = array.statistics(); - if let Some(min) = stats - .compute_stat(Stat::Min, ctx)? - .and_then(|s| as_i128(array, &s)) - && let Some(max) = stats - .compute_stat(Stat::Max, ctx)? - .and_then(|s| as_i128(array, &s)) + if let Some(min) = stats.get(Stat::Min).as_exact() + && let Some(max) = stats.get(Stat::Max).as_exact() + && let Some(bounds) = bounds_from(array, &min, &max) { - return Ok(Some(IntegerBounds { min, max })); + return Ok(Some(bounds)); } + + // Compute both extrema in one pass with the session's `min_max` aggregate. + if let Some(min_max) = resolve_min_max(ctx)? + && min_max.return_dtype(array.dtype()).is_some() + { + let mut accumulator = min_max.accumulator(array.dtype())?; + accumulator.accumulate(array, ctx)?; + let result = accumulator.finish()?; + if result.is_null() { + return Ok(None); + } + let min = result + .as_struct() + .field_by_idx(0) + .vortex_expect("min_max has a min field"); + let max = result + .as_struct() + .field_by_idx(1) + .vortex_expect("min_max has a max field"); + if let Some(bounds) = bounds_from(array, &min, &max) { + if let (Some(min), Some(max)) = (min.value(), max.value()) { + stats.set(Stat::Min, Precision::Exact(min.clone())); + stats.set(Stat::Max, Precision::Exact(max.clone())); + } + // Cache the null count too, as computing the `Min` and `Max` statistics does. + if stats.get(Stat::NullCount).as_exact().is_none() { + stats.set(Stat::NullCount, Precision::exact(array.invalid_count(ctx)?)); + } + return Ok(Some(bounds)); + } + } + Ok(scan_array(array, ctx)?.map(|scanned| IntegerBounds { min: scanned.min, max: scanned.max, @@ -104,6 +140,28 @@ fn ensure_int(array: &ArrayRef) -> VortexResult<()> { Ok(()) } +/// Resolves the `min_max` aggregate, skipping NaNs like the `Min` and `Max` statistics, if the +/// session registers one. +fn resolve_min_max(ctx: &ExecutionCtx) -> VortexResult> { + let session = ctx.session(); + let Some(plugin) = session + .aggregate_fns() + .find_plugin(&stat_aggregates::MIN_MAX_ID) + else { + return Ok(None); + }; + plugin + .deserialize(&NumericalAggregateOpts::skip_nans().serialize(), session) + .map(Some) +} + +fn bounds_from(array: &ArrayRef, min: &Scalar, max: &Scalar) -> Option { + Some(IntegerBounds { + min: as_i128(array, min)?, + max: as_i128(array, max)?, + }) +} + fn as_i128(array: &ArrayRef, scalar: &Scalar) -> Option { match_each_integer_ptype!(array.dtype().as_ptype(), |P| { scalar.as_primitive().as_::

().map(i128::from) From 5d31863cbb866f93d646b0840582b01557452977 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Sat, 24 Oct 2026 14:40:31 +0000 Subject: [PATCH 06/27] Count valid rows from the validity array's Sum statistic `valid_count` uses an exact cached `NullCount` first (`len - null count`). Otherwise, for array-backed validity, it now reads the validity array's `Sum` statistic, which is the number of valid rows and can be cached or computed by an encoding kernel, as develop did with the `sum` aggregate. It counts the bitmap only when the session registers no `Sum` aggregate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- vortex-array/src/array/erased.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index 18136910f56..a603066808d 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -384,7 +384,16 @@ impl ArrayRef { let count = match self.validity()? { Validity::NonNullable | Validity::AllValid => len, Validity::AllInvalid => 0, - Validity::Array(a) => a.execute::(ctx)?.to_bit_buffer().true_count(), + // The number of valid rows is the number of `true` values in the validity array, which + // its `Sum` statistic gives. Count the bitmap if the session has no `Sum` aggregate. + Validity::Array(a) => match a + .statistics() + .compute_stat(Stat::Sum, ctx)? + .and_then(|sum| sum.as_primitive().as_::()) + { + Some(count) => count, + None => a.execute::(ctx)?.to_bit_buffer().true_count(), + }, }; vortex_ensure!(count <= len, "Valid count exceeds array length"); From 09997c70eb4239894da00eb76f7f0b696d8eb562 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Mon, 23 Nov 2026 00:27:51 +0000 Subject: [PATCH 07/27] Update aggregate imports and tests after rebasing onto develop Signed-off-by: Will Manning Co-Authored-By: Will Manning --- Cargo.lock | 5 +- encodings/onpair/Cargo.toml | 2 +- .../src/compute/uncompressed_size_in_bytes.rs | 6 +-- encodings/onpair/src/lib.rs | 2 +- vortex-aggregates/src/min_max/decimal.rs | 46 +++++++++++++++++++ vortex-aggregates/src/min_max/mod.rs | 1 - vortex-aggregates/src/runend/sum/tests.rs | 1 - vortex-array/src/arrays/decimal/utils.rs | 2 + .../arrays/decimal/vtable/plugin/tests/mod.rs | 11 ----- .../vortex-uuid/src/arrow_properties.rs | 8 ++-- vortex-file/src/tests.rs | 3 +- vortex-layout/src/layouts/constant.rs | 2 +- vortex-layout/src/layouts/dict/writer.rs | 2 +- vortex-layout/src/lowering/tests.rs | 2 +- vortex-scan/Cargo.toml | 1 + vortex-scan/src/execution/tests.rs | 4 +- vortex-scan/src/execution/zone_map/mod.rs | 16 +++---- vortex-scan/src/execution/zone_map/tests.rs | 33 ++++++------- vortex-scan/src/plan/builtins/zoned/tests.rs | 2 +- 19 files changed, 91 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 80b3300a930..e775dc83591 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11094,8 +11094,8 @@ dependencies = [ "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-array", "vortex-buffer", @@ -12308,6 +12308,7 @@ dependencies = [ "smallvec", "tokio", "tracing", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-error", diff --git a/encodings/onpair/Cargo.toml b/encodings/onpair/Cargo.toml index f91b9e0aec7..2280fc9a7e9 100644 --- a/encodings/onpair/Cargo.toml +++ b/encodings/onpair/Cargo.toml @@ -18,6 +18,7 @@ workspace = true num-traits = { workspace = true } onpair = { workspace = true } prost = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } @@ -32,7 +33,6 @@ _test-harness = ["vortex-array/_test-harness"] divan = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } -vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } [[bench]] diff --git a/encodings/onpair/src/compute/uncompressed_size_in_bytes.rs b/encodings/onpair/src/compute/uncompressed_size_in_bytes.rs index e0723c9240e..72e59868894 100644 --- a/encodings/onpair/src/compute/uncompressed_size_in_bytes.rs +++ b/encodings/onpair/src/compute/uncompressed_size_in_bytes.rs @@ -4,12 +4,12 @@ use std::mem::size_of; use num_traits::ToPrimitive; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; @@ -108,13 +108,13 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; + use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::ArrayVTable; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTable; - use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; - use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinArray; diff --git a/encodings/onpair/src/lib.rs b/encodings/onpair/src/lib.rs index cae63949e32..8cf2aff2d79 100644 --- a/encodings/onpair/src/lib.rs +++ b/encodings/onpair/src/lib.rs @@ -30,9 +30,9 @@ pub use onpair::Error as OnPairError; pub use onpair::MAX_TOKEN_SIZE; pub use onpair::MaxDictBits; pub use onpair::Threshold; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::ArrayVTable; use vortex_array::aggregate_fn::AggregateFnVTable; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; diff --git a/vortex-aggregates/src/min_max/decimal.rs b/vortex-aggregates/src/min_max/decimal.rs index 61bab293f40..0b984bed172 100644 --- a/vortex-aggregates/src/min_max/decimal.rs +++ b/vortex-aggregates/src/min_max/decimal.rs @@ -62,3 +62,49 @@ where max: max_scalar, })) } + +#[cfg(test)] +mod tests { + use std::sync::LazyLock; + + use rstest::rstest; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::DecimalArray; + use vortex_array::dtype::DecimalDType; + use vortex_array::validity::Validity; + use vortex_buffer::Buffer; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + + use crate::min_max::min_max; + + static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + + #[rstest] + #[case::one_value(&[100i8])] + #[case::maximum(&[1i8, 100])] + #[case::minimum(&[-100i8, 1])] + fn invalid_stored_value_errors_in_min_max(#[case] slots: &[i8]) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + // SAFETY: `Validity::NonNullable` requires no validity array; we intentionally store an + // out-of-precision value to verify `min_max` validates both extrema. + let array = unsafe { + DecimalArray::new_unchecked( + Buffer::copy_from(slots), + DecimalDType::new(2, 0), + Validity::NonNullable, + ) + } + .into_array(); + + let err = min_max(&array, &mut ctx, NumericalAggregateOpts::default()).unwrap_err(); + assert!( + err.to_string().contains("does not fit in precision"), + "{err}" + ); + + Ok(()) + } +} diff --git a/vortex-aggregates/src/min_max/mod.rs b/vortex-aggregates/src/min_max/mod.rs index 6d86da21bc5..6aaf74a1edc 100644 --- a/vortex-aggregates/src/min_max/mod.rs +++ b/vortex-aggregates/src/min_max/mod.rs @@ -575,7 +575,6 @@ mod tests { use vortex_array::dtype::BigCast; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; - use vortex_array::dtype::DecimalType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::extension::ExtDType; diff --git a/vortex-aggregates/src/runend/sum/tests.rs b/vortex-aggregates/src/runend/sum/tests.rs index c55eaf19518..9eb2225b461 100644 --- a/vortex-aggregates/src/runend/sum/tests.rs +++ b/vortex-aggregates/src/runend/sum/tests.rs @@ -22,7 +22,6 @@ use vortex_array::dtype::PType; use vortex_array::scalar::Scalar; #[cfg(not(codspeed))] use vortex_array::test_harness::trace::trace_op; -use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; diff --git a/vortex-array/src/arrays/decimal/utils.rs b/vortex-array/src/arrays/decimal/utils.rs index 746cd1f1ebf..07745393955 100644 --- a/vortex-array/src/arrays/decimal/utils.rs +++ b/vortex-array/src/arrays/decimal/utils.rs @@ -3,6 +3,8 @@ use std::ops::RangeInclusive; +use itertools::Itertools; +use itertools::MinMaxResult; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedFoldExt; diff --git a/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs b/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs index 8a2f1243f32..26219e98196 100644 --- a/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs +++ b/vortex-array/src/arrays/decimal/vtable/plugin/tests/mod.rs @@ -26,8 +26,6 @@ use crate::ArrayContext; use crate::ArrayRef; use crate::IntoArray; use crate::VortexSessionExecute; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::fns::min_max::min_max; use crate::array::ArrayDeserialization; use crate::array::ArrayPlugin; use crate::arrays::BoolArray; @@ -272,15 +270,6 @@ fn invalid_stored_value_errors_on_access( "{scalar_error}" ); - let aggregate_error = - min_max(&node.array, &mut ctx, NumericalAggregateOpts::default()).unwrap_err(); - assert!( - aggregate_error - .to_string() - .contains("does not fit in precision"), - "{aggregate_error}" - ); - Ok(()) } diff --git a/vortex-extensions/vortex-uuid/src/arrow_properties.rs b/vortex-extensions/vortex-uuid/src/arrow_properties.rs index 18ddf4d1cd6..a9e1c74e2eb 100644 --- a/vortex-extensions/vortex-uuid/src/arrow_properties.rs +++ b/vortex-extensions/vortex-uuid/src/arrow_properties.rs @@ -19,6 +19,10 @@ mod tests { use hegel::TestCase; use hegel::generators as gs; use uuid::Version; + use vortex_aggregates::is_sorted::IsSorted; + use vortex_aggregates::is_sorted::IsSortedOptions; + use vortex_aggregates::min_max::MinMax; + use vortex_aggregates::min_max::MinMaxResult; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -27,10 +31,6 @@ mod tests { use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::ExtensionStoragePushdown; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::is_sorted::IsSorted; - use vortex_array::aggregate_fn::fns::is_sorted::IsSortedOptions; - use vortex_array::aggregate_fn::fns::min_max::MinMax; - use vortex_array::aggregate_fn::fns::min_max::MinMaxResult; use vortex_array::arrays::ExtensionArray; use vortex_array::arrays::FixedSizeListArray; use vortex_array::arrays::PrimitiveArray; diff --git a/vortex-file/src/tests.rs b/vortex-file/src/tests.rs index 512b828d70c..f0e77f233a2 100644 --- a/vortex-file/src/tests.rs +++ b/vortex-file/src/tests.rs @@ -2769,8 +2769,7 @@ async fn field_file_statistics_record_only_the_selected_fields( .with_field_file_statistics( FieldPath::from_name("a"), vec![ - Stat::Max - .aggregate_fn() + vortex_aggregates::stat_aggregate_fn(Stat::Max) .vortex_expect("max has an aggregate fn"), ], ); diff --git a/vortex-layout/src/layouts/constant.rs b/vortex-layout/src/layouts/constant.rs index 4199faee14a..51cd8ba1f64 100644 --- a/vortex-layout/src/layouts/constant.rs +++ b/vortex-layout/src/layouts/constant.rs @@ -8,10 +8,10 @@ use std::sync::Arc; use async_trait::async_trait; use futures::StreamExt as _; use futures::stream; +use vortex_aggregates::is_constant::is_constant; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::is_constant::is_constant; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; use vortex_array::scalar::Scalar; diff --git a/vortex-layout/src/layouts/dict/writer.rs b/vortex-layout/src/layouts/dict/writer.rs index 5ebb27571c6..21b58939fdb 100644 --- a/vortex-layout/src/layouts/dict/writer.rs +++ b/vortex-layout/src/layouts/dict/writer.rs @@ -26,11 +26,11 @@ use futures::stream::BoxStream; use futures::stream::iter; use futures::stream::once; use futures::try_join; +use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_array::aggregate_fn::fns::uncompressed_size_in_bytes::uncompressed_size_in_bytes; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::Dict; use vortex_array::arrays::WidenArray; diff --git a/vortex-layout/src/lowering/tests.rs b/vortex-layout/src/lowering/tests.rs index c9cfc2957be..8342076ddbe 100644 --- a/vortex-layout/src/lowering/tests.rs +++ b/vortex-layout/src/lowering/tests.rs @@ -4,12 +4,12 @@ use std::num::NonZeroUsize; use std::sync::Arc; +use vortex_aggregates::max::Max; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; diff --git a/vortex-scan/Cargo.toml b/vortex-scan/Cargo.toml index 53a10684596..6df4f6b7c30 100644 --- a/vortex-scan/Cargo.toml +++ b/vortex-scan/Cargo.toml @@ -27,6 +27,7 @@ rustc-hash = { workspace = true } sketches-ddsketch = { workspace = true } smallvec = { workspace = true } tracing = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } diff --git a/vortex-scan/src/execution/tests.rs b/vortex-scan/src/execution/tests.rs index 6f12399b4b5..bcdc1769e98 100644 --- a/vortex-scan/src/execution/tests.rs +++ b/vortex-scan/src/execution/tests.rs @@ -8,13 +8,13 @@ use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; use rstest::rstest; +use vortex_aggregates::max::Max; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; +use vortex_aggregates::min::Min; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; diff --git a/vortex-scan/src/execution/zone_map/mod.rs b/vortex-scan/src/execution/zone_map/mod.rs index b11c160abc8..95896f2b65f 100644 --- a/vortex-scan/src/execution/zone_map/mod.rs +++ b/vortex-scan/src/execution/zone_map/mod.rs @@ -5,6 +5,13 @@ use std::sync::Arc; +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; +use vortex_aggregates::bounded_max::BOUNDED_MAX_BOUND; +use vortex_aggregates::bounded_max::BoundedMax; +use vortex_aggregates::stat_aggregate_fn; use vortex_array::ArrayRef; use vortex_array::Columnar; use vortex_array::ExecutionCtx; @@ -12,12 +19,6 @@ use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; use vortex_array::arrays::BoolArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; @@ -296,8 +297,7 @@ impl ZoneMap { } fn stat_field_expr(&self, stat: Stat) -> Option { - stat.aggregate_fn() - .and_then(|aggregate_fn| self.aggregate_field_expr(&aggregate_fn)) + stat_aggregate_fn(stat).and_then(|aggregate_fn| self.aggregate_field_expr(&aggregate_fn)) } } diff --git a/vortex-scan/src/execution/zone_map/tests.rs b/vortex-scan/src/execution/zone_map/tests.rs index 5129ad3a530..93330c693db 100644 --- a/vortex-scan/src/execution/zone_map/tests.rs +++ b/vortex-scan/src/execution/zone_map/tests.rs @@ -6,23 +6,24 @@ use std::sync::Arc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; +use vortex_aggregates::bounded_max::BOUNDED_MAX_BOUND; +use vortex_aggregates::bounded_max::BOUNDED_MAX_UNKNOWN; +use vortex_aggregates::bounded_max::BoundedMax; +use vortex_aggregates::bounded_max::BoundedMaxOptions; +use vortex_aggregates::bounded_min::BoundedMin; +use vortex_aggregates::bounded_min::BoundedMinOptions; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::stat_aggregate_fn; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_BOUND; -use vortex_array::aggregate_fn::fns::bounded_max::BOUNDED_MAX_UNKNOWN; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMax; -use vortex_array::aggregate_fn::fns::bounded_max::BoundedMaxOptions; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMin; -use vortex_array::aggregate_fn::fns::bounded_min::BoundedMinOptions; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::BoolArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; @@ -383,9 +384,7 @@ fn fixed_size_list_min_max_stat_fn_lowers_to_unknown_mask() { ) .unwrap(); - let max_fn = Stat::Max - .aggregate_fn() - .expect("max should have an aggregate function"); + let max_fn = stat_aggregate_fn(Stat::Max).expect("max should have an aggregate function"); let predicate = is_null(stat(root(), max_fn)); // Missing StatFn lowers to a nullable null literal, so `is_null(...)` is true for every zone. @@ -408,9 +407,7 @@ fn unsupported_aggregate_input_dtype_errors() { ) .unwrap(); - let max_fn = Stat::Max - .aggregate_fn() - .expect("max should have an aggregate function"); + let max_fn = stat_aggregate_fn(Stat::Max).expect("max should have an aggregate function"); let predicate = is_null(stat(root(), max_fn)); let error = prune(&zone_map, &predicate).unwrap_err(); diff --git a/vortex-scan/src/plan/builtins/zoned/tests.rs b/vortex-scan/src/plan/builtins/zoned/tests.rs index 4ef5f770c28..4b36b7d6203 100644 --- a/vortex-scan/src/plan/builtins/zoned/tests.rs +++ b/vortex-scan/src/plan/builtins/zoned/tests.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors +use vortex_aggregates::max::Max; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; use vortex_array::dtype::DType; From 6ae6c64170b768c2db32565ca662b9adca018ea0 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 24 Nov 2026 14:53:07 +0000 Subject: [PATCH 08/27] Update crates for develop's stat derivations and Delta tests after rebase The stat derivations from #11817 name aggregates that now live in vortex-aggregates, and the Delta tests from #11428 compute statistics through fastlanes' shared test session, which now registers the aggregates. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- Cargo.lock | 4 ++-- encodings/fastlanes/src/lib.rs | 1 + vortex-aggregates/src/is_constant/mod.rs | 3 +-- vortex-aggregates/src/mean/mod.rs | 4 ++-- vortex-aggregates/src/sum_v2/mod.rs | 3 +-- vortex-array/src/compute/conformance/consistency.rs | 2 +- 6 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e775dc83591..1d84b5a76f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11094,8 +11094,8 @@ dependencies = [ "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.6", - "rand 0.10.4", + "prost 0.14.4", + "rand 0.10.3", "rstest", "vortex-array", "vortex-buffer", diff --git a/encodings/fastlanes/src/lib.rs b/encodings/fastlanes/src/lib.rs index 1c54f90134b..564bf730fce 100644 --- a/encodings/fastlanes/src/lib.rs +++ b/encodings/fastlanes/src/lib.rs @@ -215,6 +215,7 @@ mod test { pub static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/vortex-aggregates/src/is_constant/mod.rs b/vortex-aggregates/src/is_constant/mod.rs index 4c476e340b1..4bc89ac0f38 100644 --- a/vortex-aggregates/src/is_constant/mod.rs +++ b/vortex-aggregates/src/is_constant/mod.rs @@ -36,7 +36,7 @@ use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; use vortex_array::scalar::Scalar; -use vortex_array::scalar_fn::builtin::operators::Operator; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -53,7 +53,6 @@ use self::primitive::check_primitive_constant; use self::struct_::check_struct_constant; use self::varbin::check_varbinview_constant; use vortex_array::scalar_fn::builtin::operators::CompareMode; -use vortex_array::scalar_fn::builtin::operators::CompareOperator; /// Check if two arrays of the same length have equal values at every position (null-safe). /// diff --git a/vortex-aggregates/src/mean/mod.rs b/vortex-aggregates/src/mean/mod.rs index 15ec9bce797..1ecfa086edd 100644 --- a/vortex-aggregates/src/mean/mod.rs +++ b/vortex-aggregates/src/mean/mod.rs @@ -19,7 +19,9 @@ use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::i256; use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::NumericOperator; use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -33,9 +35,7 @@ use crate::combined::PairOptions; use crate::count::Count; use crate::sum::Sum; use crate::sum::sum_decimal_dtype; -use vortex_array::scalar::NumericOperator; use vortex_array::scalar_fn::builtin::operators::CompareMode; -use vortex_array::scalar_fn::builtin::operators::CompareOperator; /// Compute the arithmetic mean of an array. /// diff --git a/vortex-aggregates/src/sum_v2/mod.rs b/vortex-aggregates/src/sum_v2/mod.rs index a006a424450..2763b03eea9 100644 --- a/vortex-aggregates/src/sum_v2/mod.rs +++ b/vortex-aggregates/src/sum_v2/mod.rs @@ -35,7 +35,7 @@ use vortex_array::stats::Stat; use vortex_array::stats::StatsProviderExt; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; -use vortex_array::scalar_fn::builtin::operators::Operator; +use vortex_array::scalar_fn::builtin::operators::BooleanOperator; use vortex_array::validity::Validity; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -53,7 +53,6 @@ use crate::sum::accumulate_primitive; use crate::sum::checked_add_sum_states; use crate::sum::make_zero_state; use crate::sum::multiply_constant; -use vortex_array::scalar_fn::builtin::operators::BooleanOperator; const SUM_FIELD: &str = "sum"; const IS_OVERFLOW_FIELD: &str = "is_overflow"; diff --git a/vortex-array/src/compute/conformance/consistency.rs b/vortex-array/src/compute/conformance/consistency.rs index b045e6796e6..19f6f7217ce 100644 --- a/vortex-array/src/compute/conformance/consistency.rs +++ b/vortex-array/src/compute/conformance/consistency.rs @@ -40,10 +40,10 @@ use crate::compute::conformance::conformance_stat; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; +use crate::stats::Stat; use crate::scalar_fn::builtin::operators::BooleanOperator; use crate::scalar_fn::builtin::operators::CompareMode; use crate::scalar_fn::builtin::operators::CompareOperator; -use crate::stats::Stat; /// Tests that filter and take operations produce consistent results. /// From 029415cb3c2bfa402862237a578571a0e8f60de1 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 24 Nov 2026 17:06:45 +0000 Subject: [PATCH 09/27] Update aggregate imports for the vortex-expr move after rebase Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ps4mp7KF5c4p66aoSoXx5j Signed-off-by: Robert Kruszewski --- Cargo.lock | 1 + .../fastlanes/src/for_/array/for_compress.rs | 4 +- vortex-aggregates/Cargo.toml | 1 + .../benches/aggregate_definedness.rs | 4 +- vortex-aggregates/benches/aggregate_sum.rs | 6 +-- vortex-aggregates/src/count/mod.rs | 4 +- vortex-aggregates/src/dict/is_constant.rs | 23 +++++---- .../src/framework_tests/accumulator.rs | 4 +- .../src/framework_tests/stats.rs | 43 +++++++++++++++- vortex-aggregates/src/grouped_tests.rs | 14 +++--- vortex-aggregates/src/is_constant/list.rs | 4 +- vortex-aggregates/src/is_constant/mod.rs | 8 +-- vortex-aggregates/src/is_sorted/mod.rs | 4 +- vortex-aggregates/src/lib.rs | 2 +- vortex-aggregates/src/max/mod.rs | 8 +-- vortex-aggregates/src/mean/mod.rs | 2 +- vortex-aggregates/src/min/mod.rs | 8 +-- vortex-aggregates/src/min_max/mod.rs | 21 +++----- vortex-aggregates/src/min_max/primitive.rs | 7 ++- vortex-aggregates/src/nan_count/mod.rs | 2 +- vortex-aggregates/src/nan_count/primitive.rs | 2 +- vortex-aggregates/src/null_count/mod.rs | 2 +- vortex-aggregates/src/runend/is_constant.rs | 25 +++++----- vortex-aggregates/src/runend/min_max.rs | 23 +++++---- vortex-aggregates/src/runend/mod.rs | 36 ++++++++++++++ vortex-aggregates/src/sum/constant.rs | 2 +- vortex-aggregates/src/sum/decimal.rs | 6 +-- vortex-aggregates/src/sum/mod.rs | 8 +-- vortex-aggregates/src/sum/primitive.rs | 12 ++--- vortex-aggregates/src/sum_v2/grouped.rs | 4 +- vortex-aggregates/src/sum_v2/mod.rs | 6 +-- vortex-aggregates/src/sum_v2/tests.rs | 6 +-- .../src/uncompressed_size_in_bytes/mod.rs | 8 +-- vortex-aggregates/src/widen/mod.rs | 2 +- .../src/widen/tests/aggregates.rs | 4 +- .../src/widen/tests/decimal_aggregates.rs | 6 +-- .../src/aggregate_fn/accumulator_grouped.rs | 4 -- .../src/aggregate_fn/stat_aggregates.rs | 8 +++ vortex-array/src/array/erased.rs | 4 +- vortex-array/src/arrays/decimal/utils.rs | 3 -- .../src/arrays/primitive/integer_bounds.rs | 12 ++--- .../src/compute/conformance/consistency.rs | 2 +- vortex-array/src/compute/conformance/mod.rs | 2 +- vortex-array/src/stats/array.rs | 4 +- vortex-array/src/stats/stat.rs | 9 ++-- vortex-array/src/stats/stats_set.rs | 49 +------------------ .../src/schemes/integer/elias_fano.rs | 2 +- vortex-btrblocks/src/tests.rs | 2 +- vortex-compressor/src/compressor/cascade.rs | 3 +- vortex-expr/src/stats/expr.rs | 3 -- vortex-expr/src/stats/rewrite/helpers.rs | 16 +++--- vortex-functions/src/pruning/derive_tests.rs | 4 +- vortex-functions/src/pruning/is_null.rs | 3 +- vortex-functions/src/pruning/mod.rs | 9 ++-- vortex-layout/src/layouts/dict/reader.rs | 2 +- vortex-layout/src/layouts/zoned/mod.rs | 6 ++- vortex-layout/src/layouts/zoned/writer.rs | 1 - vortex-scan/src/execution/tests.rs | 2 +- 58 files changed, 246 insertions(+), 226 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d84b5a76f7..20cd37aff38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11099,6 +11099,7 @@ dependencies = [ "rstest", "vortex-array", "vortex-buffer", + "vortex-compute", "vortex-error", "vortex-mask", "vortex-session", diff --git a/encodings/fastlanes/src/for_/array/for_compress.rs b/encodings/fastlanes/src/for_/array/for_compress.rs index 0a59dfeec57..9eef1b92106 100644 --- a/encodings/fastlanes/src/for_/array/for_compress.rs +++ b/encodings/fastlanes/src/for_/array/for_compress.rs @@ -15,11 +15,11 @@ use vortex_array::arrays::primitive::PrimitiveArrayExt; use vortex_array::arrays::primitive::integer_bounds; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; -use vortex_array::stats::Stat; -use vortex_array::stats::StatsProvider; 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::stats::StatsProvider; use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::BitBufferView; diff --git a/vortex-aggregates/Cargo.toml b/vortex-aggregates/Cargo.toml index a51b2e5b26a..2900c91af53 100644 --- a/vortex-aggregates/Cargo.toml +++ b/vortex-aggregates/Cargo.toml @@ -18,6 +18,7 @@ itertools = { workspace = true } num-traits = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } +vortex-compute = { workspace = true } vortex-error = { workspace = true } vortex-mask = { workspace = true } vortex-session = { workspace = true } diff --git a/vortex-aggregates/benches/aggregate_definedness.rs b/vortex-aggregates/benches/aggregate_definedness.rs index 82cacc367d6..944bf6d4fda 100644 --- a/vortex-aggregates/benches/aggregate_definedness.rs +++ b/vortex-aggregates/benches/aggregate_definedness.rs @@ -11,6 +11,8 @@ use std::sync::LazyLock; use divan::Bencher; use mimalloc::MiMalloc; use rand::prelude::*; +use vortex_aggregates::null_count::NullCount; +use vortex_aggregates::sum::Sum; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; @@ -19,8 +21,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_aggregates::null_count::NullCount; -use vortex_aggregates::sum::Sum; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::list::ListArraySlotsExt; diff --git a/vortex-aggregates/benches/aggregate_sum.rs b/vortex-aggregates/benches/aggregate_sum.rs index b61ed06935f..fadc7cdcb3f 100644 --- a/vortex-aggregates/benches/aggregate_sum.rs +++ b/vortex-aggregates/benches/aggregate_sum.rs @@ -10,21 +10,21 @@ use divan::black_box; use divan::counter::ItemsCount; use mimalloc::MiMalloc; use rand::prelude::*; +use vortex_aggregates::sum::sum; use vortex_aggregates::sum_v2::SumV2; use vortex_aggregates::sum_v2::sum_v2; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; -use vortex_aggregates::sum::sum; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::arrays::DecimalArray; use vortex_array::arrays::PrimitiveArray; -use vortex_array::dtype::DecimalDType; -use vortex_array::optimizer::kernels::KernelSession; use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +use vortex_array::optimizer::kernels::KernelSession; use vortex_array::stats::Stat; use vortex_array::test_harness::mark_optimized; use vortex_array::validity::Validity; diff --git a/vortex-aggregates/src/count/mod.rs b/vortex-aggregates/src/count/mod.rs index f9b4303ceb1..a48508fa157 100644 --- a/vortex-aggregates/src/count/mod.rs +++ b/vortex-aggregates/src/count/mod.rs @@ -168,10 +168,10 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; 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_error::VortexExpect; diff --git a/vortex-aggregates/src/dict/is_constant.rs b/vortex-aggregates/src/dict/is_constant.rs index cdf7124c338..9ac4c686bed 100644 --- a/vortex-aggregates/src/dict/is_constant.rs +++ b/vortex-aggregates/src/dict/is_constant.rs @@ -83,25 +83,24 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::Accumulator; + use vortex_array::aggregate_fn::DynAccumulator; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::DictArray; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::dtype::Nullability; + use vortex_array::scalar::Scalar; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::Accumulator; - use crate::aggregate_fn::DynAccumulator; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::is_constant::IsConstant; - use crate::arrays::DictArray; - use crate::arrays::PrimitiveArray; - use crate::dtype::Nullability; - use crate::scalar::Scalar; - use crate::session::ArraySessionExt; + use crate::is_constant::IsConstant; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); - session.arrays(); + crate::initialize(&session); session }); diff --git a/vortex-aggregates/src/framework_tests/accumulator.rs b/vortex-aggregates/src/framework_tests/accumulator.rs index f1aaf270bb4..0a11fd970b8 100644 --- a/vortex-aggregates/src/framework_tests/accumulator.rs +++ b/vortex-aggregates/src/framework_tests/accumulator.rs @@ -21,12 +21,12 @@ use vortex_array::arrays::DictArray; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +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::StatsProviderExt; -use vortex_array::scalar::Scalar; -use vortex_array::scalar::ScalarValue; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::SessionExt; diff --git a/vortex-aggregates/src/framework_tests/stats.rs b/vortex-aggregates/src/framework_tests/stats.rs index 89cdacaad79..24a629e3bdd 100644 --- a/vortex-aggregates/src/framework_tests/stats.rs +++ b/vortex-aggregates/src/framework_tests/stats.rs @@ -7,6 +7,8 @@ use std::sync::LazyLock; use enum_iterator::all; use itertools::Itertools; +use rstest::rstest; +use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; @@ -17,9 +19,9 @@ use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +use vortex_array::scalar::ScalarValue; use vortex_array::stats::Precision; use vortex_array::stats::Stat; -use vortex_array::scalar::ScalarValue; use vortex_array::validity::Validity; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -91,3 +93,42 @@ fn merge_unordered() { assert_eq!(merged.get(stat), expected, "{stat}"); } } + +#[rstest] +#[case::leading_null_in_right( + PrimitiveArray::from_option_iter([Some(1i32), Some(2)]).into_array(), + PrimitiveArray::from_option_iter([None, Some(3i32)]).into_array(), + Precision::Absent +)] +#[case::nullable_right_proven_non_null( + PrimitiveArray::from_option_iter([None, Some(1i32), Some(2)]).into_array(), + PrimitiveArray::from_option_iter([Some(3i32), Some(4)]).into_array(), + Precision::exact(ScalarValue::from(true)) +)] +#[case::trailing_pos_nan_in_left( + PrimitiveArray::from_iter([1.0f64, f64::NAN]).into_array(), + PrimitiveArray::from_iter([2.0f64]).into_array(), + Precision::Absent +)] +#[case::leading_neg_nan_in_right( + PrimitiveArray::from_iter([1.0f64]).into_array(), + PrimitiveArray::from_iter([-f64::NAN, 2.0f64]).into_array(), + Precision::Absent +)] +fn merge_sortedness_computed_chunks( + #[case] left: ArrayRef, + #[case] right: ArrayRef, + #[case] expected: Precision, +) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let requested = if left.dtype().is_float() { + [Stat::Min, Stat::Max, Stat::NaNCount, Stat::IsSorted] + } else { + [Stat::Min, Stat::Max, Stat::NullCount, Stat::IsSorted] + }; + let left_stats = left.statistics().compute_all(&requested, &mut ctx)?; + let right_stats = right.statistics().compute_all(&requested, &mut ctx)?; + let merged = left_stats.merge_ordered(&right_stats, left.dtype()); + assert_eq!(merged.get(Stat::IsSorted), expected); + Ok(()) +} diff --git a/vortex-aggregates/src/grouped_tests.rs b/vortex-aggregates/src/grouped_tests.rs index 685723f52c9..0d0af68c100 100644 --- a/vortex-aggregates/src/grouped_tests.rs +++ b/vortex-aggregates/src/grouped_tests.rs @@ -7,10 +7,10 @@ use std::sync::LazyLock; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; +use vortex_array::aggregate_fn::DynGroupedAccumulator; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::GroupedAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::arrays::ListViewArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::assert_arrays_eq; @@ -25,6 +25,7 @@ use vortex_session::VortexSession; use crate::combined::PairOptions; use crate::count::Count; use crate::mean::Mean; +use crate::null_count::NullCount; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); @@ -32,8 +33,8 @@ static SESSION: LazyLock = LazyLock::new(VortexSession::empty); fn test_accumulate_list_with_null_group_non_nullable_partials() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); // Groups: [[1.0, null, 3.0], null, [4.0]] - let elements = PrimitiveArray::from_option_iter([Some(1.0f64), None, Some(3.0), Some(4.0)]) - .into_array(); + let elements = + PrimitiveArray::from_option_iter([Some(1.0f64), None, Some(3.0), Some(4.0)]).into_array(); let groups = ListViewArray::try_new( elements, buffer![0u32, 3, 3].into_array(), @@ -44,11 +45,8 @@ fn test_accumulate_list_with_null_group_non_nullable_partials() -> VortexResult< .into_array(); let elem_dtype = DType::Primitive(PType::F64, Nullable); - let mut count_acc = GroupedAccumulator::try_new( - Count, - NumericalAggregateOpts::default(), - elem_dtype.clone(), - )?; + let mut count_acc = + GroupedAccumulator::try_new(Count, NumericalAggregateOpts::default(), elem_dtype.clone())?; count_acc.accumulate_list(&groups, &mut ctx)?; assert_arrays_eq!( count_acc.finish()?, diff --git a/vortex-aggregates/src/is_constant/list.rs b/vortex-aggregates/src/is_constant/list.rs index 7f628fa1e1f..f1f98f943d7 100644 --- a/vortex-aggregates/src/is_constant/list.rs +++ b/vortex-aggregates/src/is_constant/list.rs @@ -2,6 +2,8 @@ // SPDX-FileCopyrightText: Copyright the Vortex contributors use vortex_array::ExecutionCtx; +use vortex_array::IntoArray; +use vortex_array::RecursiveCanonical; use vortex_array::arrays::ListViewArray; use vortex_array::arrays::listview::ListViewArrayExt; use vortex_array::arrays::listview::ListViewArraySlotsExt; @@ -9,8 +11,6 @@ use vortex_error::VortexResult; use super::arrays_value_equal; use super::is_constant; -use vortex_array::IntoArray; -use vortex_array::RecursiveCanonical; /// Check if a list view array is constant by comparing each list's elements. /// diff --git a/vortex-aggregates/src/is_constant/mod.rs b/vortex-aggregates/src/is_constant/mod.rs index 4bc89ac0f38..8ebf3921d02 100644 --- a/vortex-aggregates/src/is_constant/mod.rs +++ b/vortex-aggregates/src/is_constant/mod.rs @@ -31,12 +31,13 @@ use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; +use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::operators::CompareMode; +use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; -use vortex_array::scalar::Scalar; -use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -52,7 +53,6 @@ use self::map::check_map_constant; use self::primitive::check_primitive_constant; use self::struct_::check_struct_constant; use self::varbin::check_varbinview_constant; -use vortex_array::scalar_fn::builtin::operators::CompareMode; /// Check if two arrays of the same length have equal values at every position (null-safe). /// @@ -512,8 +512,8 @@ mod tests { use vortex_array::dtype::MapDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::stats::Stat; use vortex_array::scalar::Scalar; + use vortex_array::stats::Stat; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; diff --git a/vortex-aggregates/src/is_sorted/mod.rs b/vortex-aggregates/src/is_sorted/mod.rs index bb845877a37..29b01c67722 100644 --- a/vortex-aggregates/src/is_sorted/mod.rs +++ b/vortex-aggregates/src/is_sorted/mod.rs @@ -26,10 +26,10 @@ use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProviderExt; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -639,9 +639,9 @@ mod tests { use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; + use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; - use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::buffer; diff --git a/vortex-aggregates/src/lib.rs b/vortex-aggregates/src/lib.rs index 216a8193814..6979691d228 100644 --- a/vortex-aggregates/src/lib.rs +++ b/vortex-aggregates/src/lib.rs @@ -25,11 +25,11 @@ use vortex_array::arrays::Primitive; use vortex_array::arrays::RunEnd; use vortex_array::arrays::Widen; use vortex_array::dtype::extension::ExtVTable; -use vortex_array::stats::Stat; use vortex_array::extension::datetime::Date; use vortex_array::extension::datetime::Duration; use vortex_array::extension::datetime::Time; use vortex_array::extension::datetime::Timestamp; +use vortex_array::stats::Stat; use vortex_session::VortexSession; pub mod all_nan; diff --git a/vortex-aggregates/src/max/mod.rs b/vortex-aggregates/src/max/mod.rs index e229e4be89c..a3791d14022 100644 --- a/vortex-aggregates/src/max/mod.rs +++ b/vortex-aggregates/src/max/mod.rs @@ -12,12 +12,12 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; +use vortex_array::partial_ord::partial_max; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; -use vortex_array::partial_ord::partial_max; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -257,10 +257,10 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; 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_error::VortexResult; diff --git a/vortex-aggregates/src/mean/mod.rs b/vortex-aggregates/src/mean/mod.rs index 1ecfa086edd..d0da7985686 100644 --- a/vortex-aggregates/src/mean/mod.rs +++ b/vortex-aggregates/src/mean/mod.rs @@ -21,6 +21,7 @@ use vortex_array::dtype::i256; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::NumericOperator; use vortex_array::scalar::Scalar; +use vortex_array::scalar_fn::builtin::operators::CompareMode; use vortex_array::scalar_fn::builtin::operators::CompareOperator; use vortex_error::VortexExpect; use vortex_error::VortexResult; @@ -35,7 +36,6 @@ use crate::combined::PairOptions; use crate::count::Count; use crate::sum::Sum; use crate::sum::sum_decimal_dtype; -use vortex_array::scalar_fn::builtin::operators::CompareMode; /// Compute the arithmetic mean of an array. /// diff --git a/vortex-aggregates/src/min/mod.rs b/vortex-aggregates/src/min/mod.rs index 58f2a3b0723..25763d5a0ce 100644 --- a/vortex-aggregates/src/min/mod.rs +++ b/vortex-aggregates/src/min/mod.rs @@ -12,12 +12,12 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; -use vortex_array::partial_ord::partial_min; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; @@ -257,10 +257,10 @@ mod tests { use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; 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_error::VortexResult; diff --git a/vortex-aggregates/src/min_max/mod.rs b/vortex-aggregates/src/min_max/mod.rs index 6aaf74a1edc..b83f356a5c3 100644 --- a/vortex-aggregates/src/min_max/mod.rs +++ b/vortex-aggregates/src/min_max/mod.rs @@ -23,19 +23,20 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::aggregate_fn::stat_aggregates; +use vortex_array::aggregate_fn::stat_aggregates::has_nan_values; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; use vortex_array::dtype::half::f16; +use vortex_array::partial_ord::partial_max; +use vortex_array::partial_ord::partial_min; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; -use vortex_array::partial_ord::partial_max; -use vortex_array::partial_ord::partial_min; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -168,14 +169,6 @@ fn nan_minmax_result(dtype: &DType) -> VortexResult { }) } -/// Whether `dtype` can hold NaN values: floats, and extension types stored as floats. -pub(crate) fn has_nan_values(dtype: &DType) -> bool { - match dtype { - DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()), - _ => dtype.is_float(), - } -} - /// A non-nullable NaN scalar of `dtype`, a float or an extension type stored as a float. /// /// Returns an error if an extension dtype rejects NaN. @@ -580,14 +573,14 @@ mod tests { use vortex_array::dtype::extension::ExtDType; use vortex_array::dtype::extension::ExtId; use vortex_array::dtype::extension::ExtVTable; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; - use vortex_array::stats::StatsProvider; use vortex_array::extension::datetime::TimeUnit; use vortex_array::match_each_decimal_value_type; 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::stats::StatsProvider; use vortex_array::validity::Validity; use vortex_buffer::BitBuffer; use vortex_buffer::Buffer; diff --git a/vortex-aggregates/src/min_max/primitive.rs b/vortex-aggregates/src/min_max/primitive.rs index 63c714028fd..9430f068858 100644 --- a/vortex-aggregates/src/min_max/primitive.rs +++ b/vortex-aggregates/src/min_max/primitive.rs @@ -3,10 +3,6 @@ use itertools::Either; use num_traits::Float; -use vortex_buffer::BitBuffer; -use vortex_compute::lane_kernels::IndexedFoldExt; -use vortex_error::VortexExpect; -use itertools::Itertools; use vortex_array::ExecutionCtx; use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::NumericalAggregateOpts; @@ -16,6 +12,9 @@ use vortex_array::dtype::Nullability::NonNullable; use vortex_array::match_each_native_ptype; use vortex_array::scalar::PValue; use vortex_array::scalar::Scalar; +use vortex_buffer::BitBuffer; +use vortex_compute::lane_kernels::IndexedFoldExt; +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_mask::Mask; diff --git a/vortex-aggregates/src/nan_count/mod.rs b/vortex-aggregates/src/nan_count/mod.rs index 7eefac2a6b7..6c73b2ce2ab 100644 --- a/vortex-aggregates/src/nan_count/mod.rs +++ b/vortex-aggregates/src/nan_count/mod.rs @@ -18,10 +18,10 @@ use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; diff --git a/vortex-aggregates/src/nan_count/primitive.rs b/vortex-aggregates/src/nan_count/primitive.rs index 71177975be7..ff1588ceb4b 100644 --- a/vortex-aggregates/src/nan_count/primitive.rs +++ b/vortex-aggregates/src/nan_count/primitive.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::NativePType; use vortex_array::match_each_float_ptype; +use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_error::VortexResult; use vortex_mask::Mask; diff --git a/vortex-aggregates/src/null_count/mod.rs b/vortex-aggregates/src/null_count/mod.rs index 24647bf634d..b7de267d994 100644 --- a/vortex-aggregates/src/null_count/mod.rs +++ b/vortex-aggregates/src/null_count/mod.rs @@ -15,10 +15,10 @@ use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; diff --git a/vortex-aggregates/src/runend/is_constant.rs b/vortex-aggregates/src/runend/is_constant.rs index 1e108ffec13..d5e1971ac5e 100644 --- a/vortex-aggregates/src/runend/is_constant.rs +++ b/vortex-aggregates/src/runend/is_constant.rs @@ -13,7 +13,6 @@ use vortex_error::VortexResult; use super::active_physical_range; use crate::is_constant::IsConstant; use crate::is_constant::is_constant; -use vortex_array::arrays::runend::array::RunEndArraySlotsExt; /// RunEnd-specific is_constant kernel. /// @@ -60,21 +59,21 @@ impl DynAggregateKernel for RunEndIsConstantKernel { #[cfg(test)] mod tests { + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::EmptyOptions; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::runend::RunEnd; + use vortex_array::dtype::Nullability; + use vortex_array::scalar::Scalar; use vortex_buffer::buffer; use vortex_error::VortexResult; - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::EmptyOptions; - use crate::aggregate_fn::fns::is_constant::IsConstant; - use crate::arrays::PrimitiveArray; - use crate::arrays::runend::RunEnd; - use crate::arrays::runend::tests::SESSION; - use crate::dtype::Nullability; - use crate::scalar::Scalar; + use crate::is_constant::IsConstant; + use crate::runend::tests::SESSION; fn run_is_constant(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { let mut acc = IsConstant.bind(EmptyOptions).accumulator(array.dtype())?; diff --git a/vortex-aggregates/src/runend/min_max.rs b/vortex-aggregates/src/runend/min_max.rs index e2839d3f400..06c46a26baa 100644 --- a/vortex-aggregates/src/runend/min_max.rs +++ b/vortex-aggregates/src/runend/min_max.rs @@ -14,7 +14,6 @@ use super::active_physical_range; use crate::min_max::MinMax; use crate::min_max::make_minmax_dtype; use crate::min_max::min_max; -use vortex_array::arrays::runend::array::RunEndArraySlotsExt; /// RunEnd-specific min/max kernel. /// @@ -64,20 +63,20 @@ impl DynAggregateKernel for RunEndMinMaxKernel { #[cfg(test)] mod tests { + use vortex_array::ArrayRef; + use vortex_array::ExecutionCtx; + use vortex_array::IntoArray; + use vortex_array::VortexSessionExecute; + use vortex_array::aggregate_fn::AggregateFnVTableExt; + use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::PrimitiveArray; + use vortex_array::arrays::runend::RunEnd; use vortex_buffer::buffer; use vortex_error::VortexResult; - use crate::ArrayRef; - use crate::ExecutionCtx; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::AggregateFnVTableExt; - use crate::aggregate_fn::NumericalAggregateOpts; - use crate::aggregate_fn::fns::min_max::MinMax; - use crate::aggregate_fn::fns::min_max::MinMaxResult; - use crate::arrays::PrimitiveArray; - use crate::arrays::runend::RunEnd; - use crate::arrays::runend::tests::SESSION; + use crate::min_max::MinMax; + use crate::min_max::MinMaxResult; + use crate::runend::tests::SESSION; fn run_min_max( array: &ArrayRef, diff --git a/vortex-aggregates/src/runend/mod.rs b/vortex-aggregates/src/runend/mod.rs index 0afad922c4b..9ba7a7f4d20 100644 --- a/vortex-aggregates/src/runend/mod.rs +++ b/vortex-aggregates/src/runend/mod.rs @@ -8,6 +8,42 @@ pub(crate) mod is_sorted; pub(crate) mod min_max; pub(crate) mod sum; +use std::ops::Range; + +use vortex_array::ArrayView; +use vortex_array::ExecutionCtx; +use vortex_array::arrays::runend::RunEnd; +use vortex_array::arrays::runend::RunEndArrayExt; +use vortex_array::arrays::runend::RunEndArraySlotsExt; +use vortex_error::VortexResult; + +/// Returns the active physical run range covering `[offset..offset + len)` for a non-empty +/// [`RunEnd`] array. +pub(super) fn active_physical_range( + run_end: ArrayView<'_, RunEnd>, + ctx: &mut ExecutionCtx, +) -> VortexResult> { + debug_assert!(!run_end.is_empty()); + + let ends = run_end.ends(); + let num_runs = ends.len(); + if num_runs == 1 { + return Ok(0..1); + } + + if run_end.offset() == 0 { + let last_end = usize::try_from(&ends.execute_scalar(num_runs - 1, ctx)?)?; + if last_end == run_end.len() { + let first_end = usize::try_from(&ends.execute_scalar(0, ctx)?)?; + if first_end > 0 { + return Ok(0..num_runs); + } + } + } + + run_end.find_physical_range(0..run_end.len(), ctx) +} + #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-aggregates/src/sum/constant.rs b/vortex-aggregates/src/sum/constant.rs index c3ade7888a6..c4e2ef989f8 100644 --- a/vortex-aggregates/src/sum/constant.rs +++ b/vortex-aggregates/src/sum/constant.rs @@ -106,9 +106,9 @@ mod tests { use vortex_array::dtype::Nullability::Nullable; use vortex_array::dtype::PType; use vortex_array::dtype::i256; - use vortex_array::stats::Stat; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; + use vortex_array::stats::Stat; use vortex_error::VortexResult; use vortex_session::VortexSession; diff --git a/vortex-aggregates/src/sum/decimal.rs b/vortex-aggregates/src/sum/decimal.rs index 17f0220a92e..acb59b5ca40 100644 --- a/vortex-aggregates/src/sum/decimal.rs +++ b/vortex-aggregates/src/sum/decimal.rs @@ -9,7 +9,9 @@ use vortex_array::ExecutionCtx; use vortex_array::arrays::DecimalArray; use vortex_array::dtype::DType; use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::DecimalType; use vortex_array::dtype::NativeDecimalType; +use vortex_array::dtype::NativePType; use vortex_array::match_each_decimal_value_type; use vortex_array::scalar::DecimalValue; use vortex_buffer::BitBuffer; @@ -23,8 +25,6 @@ use super::SumState; use super::checked_add_sum_states; use super::primitive::sum_signed_valid; use super::sum_signed_all; -use vortex_array::dtype::DecimalType; -use vortex_array::dtype::NativePType; /// Accumulate a decimal array into the sum state. /// Returns Ok(true) if saturated (overflow), Ok(false) if not. @@ -164,7 +164,6 @@ mod tests { use std::sync::LazyLock; - use vortex_buffer::Buffer; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateDTypes; @@ -181,6 +180,7 @@ mod tests { use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; use vortex_array::validity::Validity; + use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/vortex-aggregates/src/sum/mod.rs b/vortex-aggregates/src/sum/mod.rs index 40acea21442..f04f532f3fd 100644 --- a/vortex-aggregates/src/sum/mod.rs +++ b/vortex-aggregates/src/sum/mod.rs @@ -21,12 +21,12 @@ use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +use vortex_array::scalar::DecimalValue; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; use vortex_array::stats::StatsProviderExt; -use vortex_array::scalar::DecimalValue; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -437,11 +437,11 @@ mod tests { use vortex_array::dtype::Nullability::Nullable; use vortex_array::dtype::PType; use vortex_array::dtype::i256; + use vortex_array::scalar::DecimalValue; + use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; - use vortex_array::scalar::DecimalValue; - use vortex_array::scalar::Scalar; use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexExpect; diff --git a/vortex-aggregates/src/sum/primitive.rs b/vortex-aggregates/src/sum/primitive.rs index 55131a48c73..e43d3b87894 100644 --- a/vortex-aggregates/src/sum/primitive.rs +++ b/vortex-aggregates/src/sum/primitive.rs @@ -6,13 +6,13 @@ use std::ops::BitOr; use num_traits::AsPrimitive; use num_traits::ToPrimitive; -use vortex_buffer::BitBuffer; -use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_array::ExecutionCtx; use vortex_array::arrays::PrimitiveArray; use vortex_array::dtype::NativePType; use vortex_array::dtype::PType; use vortex_array::match_each_native_ptype; +use vortex_buffer::BitBuffer; +use vortex_compute::lane_kernels::IndexedFoldExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_panic; @@ -446,8 +446,6 @@ mod tests { use std::sync::LazyLock; - use vortex_buffer::BitBuffer; - use vortex_buffer::Buffer; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::Accumulator; @@ -459,11 +457,13 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::Nullability::Nullable; use vortex_array::dtype::PType; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; 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::BitBuffer; + use vortex_buffer::Buffer; use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; diff --git a/vortex-aggregates/src/sum_v2/grouped.rs b/vortex-aggregates/src/sum_v2/grouped.rs index 953bba80989..d6447965336 100644 --- a/vortex-aggregates/src/sum_v2/grouped.rs +++ b/vortex-aggregates/src/sum_v2/grouped.rs @@ -8,10 +8,12 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::GroupRanges; use vortex_array::aggregate_fn::GroupedArray; use vortex_array::aggregate_fn::kernels::DynGroupedAggregateKernel; +use vortex_array::arrays::Bool; use vortex_array::arrays::BoolArray; use vortex_array::arrays::Primitive; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::StructArray; +use vortex_array::arrays::bool::BoolArrayExt; use vortex_array::dtype::NativePType; use vortex_array::dtype::Nullability; use vortex_array::match_each_native_ptype; @@ -28,8 +30,6 @@ use super::sum_v2_partial_fields; use crate::sum::sum_float_all; use crate::sum::sum_signed_all; use crate::sum::sum_unsigned_all; -use vortex_array::arrays::Bool; -use vortex_array::arrays::bool::BoolArrayExt; /// Encoding-specific grouped [`SumV2`] kernel for primitive element arrays. #[derive(Debug)] diff --git a/vortex-aggregates/src/sum_v2/mod.rs b/vortex-aggregates/src/sum_v2/mod.rs index 2763b03eea9..b006b67f972 100644 --- a/vortex-aggregates/src/sum_v2/mod.rs +++ b/vortex-aggregates/src/sum_v2/mod.rs @@ -30,12 +30,12 @@ use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; -use vortex_array::stats::Precision; -use vortex_array::stats::Stat; -use vortex_array::stats::StatsProviderExt; use vortex_array::scalar::Scalar; use vortex_array::scalar::ScalarValue; use vortex_array::scalar_fn::builtin::operators::BooleanOperator; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProviderExt; use vortex_array::validity::Validity; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/vortex-aggregates/src/sum_v2/tests.rs b/vortex-aggregates/src/sum_v2/tests.rs index 1366e126bbb..53ece9c471f 100644 --- a/vortex-aggregates/src/sum_v2/tests.rs +++ b/vortex-aggregates/src/sum_v2/tests.rs @@ -32,11 +32,11 @@ use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::Nullability::Nullable; use vortex_array::dtype::PType; -use vortex_array::stats::Precision; -use vortex_array::stats::Stat; use vortex_array::proto::expr as pb; 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_error::VortexResult; @@ -480,7 +480,7 @@ fn reference_sums( .ok_or_else(|| vortex_error::vortex_err!("no sum dtype"))?; let valid = validity.execute_mask(groups.len(), ctx)?; let mut builder = - crate::builders::builder_with_capacity_in(&dtype, groups.len(), ctx.allocator()); + vortex_array::builders::builder_with_capacity_in(&dtype, groups.len(), ctx.allocator()); for (group, &(offset, size)) in groups.iter().enumerate() { let sum = if valid.value(group) { let slice = elements.slice(offset as usize..(offset + size) as usize)?; diff --git a/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs index c6fe7f5344b..4829ffdd49b 100644 --- a/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs @@ -46,10 +46,10 @@ use vortex_array::arrays::varbinview::BinaryView; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; +use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; use vortex_array::stats::StatsProvider; -use vortex_array::scalar::Scalar; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; @@ -371,13 +371,13 @@ mod tests { use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::UnionVariants; - use vortex_array::stats::Precision; - use vortex_array::stats::Stat; - use vortex_array::stats::StatsProvider; use vortex_array::extension::datetime::Date; use vortex_array::extension::datetime::TimeUnit; 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::validity::Validity; use vortex_buffer::Buffer; use vortex_buffer::ByteBuffer; diff --git a/vortex-aggregates/src/widen/mod.rs b/vortex-aggregates/src/widen/mod.rs index fb413e8c705..2f52e2c2bd3 100644 --- a/vortex-aggregates/src/widen/mod.rs +++ b/vortex-aggregates/src/widen/mod.rs @@ -17,8 +17,8 @@ use vortex_array::aggregate_fn::kernels::DynAggregateKernel; use vortex_array::arrays::Widen; use vortex_array::arrays::widen::WidenArraySlotsExt; use vortex_array::dtype::DType; -use vortex_array::stats::Stat; use vortex_array::scalar::Scalar; +use vortex_array::stats::Stat; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/vortex-aggregates/src/widen/tests/aggregates.rs b/vortex-aggregates/src/widen/tests/aggregates.rs index 4e407e84eed..60a2ce595bc 100644 --- a/vortex-aggregates/src/widen/tests/aggregates.rs +++ b/vortex-aggregates/src/widen/tests/aggregates.rs @@ -32,10 +32,10 @@ use vortex_array::dtype::Nullability; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::Nullability::Nullable; use vortex_array::dtype::PType; -use vortex_array::stats::Precision; -use vortex_array::stats::Stat; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/vortex-aggregates/src/widen/tests/decimal_aggregates.rs b/vortex-aggregates/src/widen/tests/decimal_aggregates.rs index de8b15611ae..b25ef5a8361 100644 --- a/vortex-aggregates/src/widen/tests/decimal_aggregates.rs +++ b/vortex-aggregates/src/widen/tests/decimal_aggregates.rs @@ -25,12 +25,12 @@ use vortex_array::dtype::DecimalDType; use vortex_array::dtype::Nullability; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::Nullability::Nullable; -use vortex_array::stats::Precision; -use vortex_array::stats::Stat; -use vortex_array::stats::StatsProvider; use vortex_array::match_each_decimal_value_type; use vortex_array::scalar::DecimalValue; use vortex_array::scalar::Scalar; +use vortex_array::stats::Precision; +use vortex_array::stats::Stat; +use vortex_array::stats::StatsProvider; use vortex_error::VortexExpect; use vortex_error::VortexResult; diff --git a/vortex-array/src/aggregate_fn/accumulator_grouped.rs b/vortex-array/src/aggregate_fn/accumulator_grouped.rs index 4965d2033b6..e13ad62c3f4 100644 --- a/vortex-array/src/aggregate_fn/accumulator_grouped.rs +++ b/vortex-array/src/aggregate_fn/accumulator_grouped.rs @@ -434,7 +434,6 @@ fn fixed_size_list_group_ranges(groups: &FixedSizeListArray) -> GroupRanges { mod tests { use std::sync::LazyLock; - use vortex_buffer::buffer; use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; @@ -451,14 +450,11 @@ mod tests { use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::GroupedAccumulator; use crate::arrays::Chunked; - use crate::arrays::ListViewArray; use crate::arrays::PrimitiveArray; use crate::assert_arrays_eq; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; - use crate::dtype::Nullability::Nullable; use crate::dtype::PType; - use crate::validity::Validity; use crate::scalar::Scalar; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/aggregate_fn/stat_aggregates.rs b/vortex-array/src/aggregate_fn/stat_aggregates.rs index 4a27fecd3ff..703b0470871 100644 --- a/vortex-array/src/aggregate_fn/stat_aggregates.rs +++ b/vortex-array/src/aggregate_fn/stat_aggregates.rs @@ -146,3 +146,11 @@ pub fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { } } } + +/// Whether `dtype` can hold NaN values: floats, and extension types stored as floats. +pub fn has_nan_values(dtype: &DType) -> bool { + match dtype { + DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()), + _ => dtype.is_float(), + } +} diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index a603066808d..e3e8d87ce2d 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -42,10 +42,10 @@ use crate::arrays::Constant; use crate::arrays::DictArray; use crate::arrays::FilterArray; use crate::arrays::SliceArray; -use crate::block::BlockOp; -use crate::block::BlockSource; use crate::arrays::bool::BoolArrayExt; use crate::arrays::bool::bool_bounds; +use crate::block::BlockOp; +use crate::block::BlockSource; use crate::buffer::BufferHandle; use crate::builders::ArrayBuilder; use crate::dtype::DType; diff --git a/vortex-array/src/arrays/decimal/utils.rs b/vortex-array/src/arrays/decimal/utils.rs index 07745393955..6ec6eb6f93f 100644 --- a/vortex-array/src/arrays/decimal/utils.rs +++ b/vortex-array/src/arrays/decimal/utils.rs @@ -3,8 +3,6 @@ use std::ops::RangeInclusive; -use itertools::Itertools; -use itertools::MinMaxResult; use vortex_buffer::Buffer; use vortex_buffer::BufferMut; use vortex_compute::lane_kernels::IndexedFoldExt; @@ -372,7 +370,6 @@ mod tests { use crate::arrays::DecimalArray; use crate::dtype::BigCast; use crate::dtype::DecimalDType; -use crate::dtype::DecimalType; use crate::dtype::DecimalType; use crate::dtype::NativeDecimalType; use crate::dtype::ToI256; diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index fcfb2dc684b..a36474d6e7e 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -23,11 +23,11 @@ use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::aggregate_fn::stat_aggregates; use crate::arrays::PrimitiveArray; use crate::arrays::primitive::PrimitiveArrayExt; -use crate::expr::stats::Precision; -use crate::expr::stats::Stat; -use crate::expr::stats::StatsProvider; use crate::match_each_integer_ptype; use crate::scalar::Scalar; +use crate::stats::Precision; +use crate::stats::Stat; +use crate::stats::StatsProvider; /// The minimum and maximum of the valid values of an integer array. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -259,9 +259,9 @@ mod tests { use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::PrimitiveArray; - 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; /// A session registering no aggregate functions, so statistics fall back to scanning. static SESSION: LazyLock = LazyLock::new(VortexSession::empty); diff --git a/vortex-array/src/compute/conformance/consistency.rs b/vortex-array/src/compute/conformance/consistency.rs index 19f6f7217ce..b045e6796e6 100644 --- a/vortex-array/src/compute/conformance/consistency.rs +++ b/vortex-array/src/compute/conformance/consistency.rs @@ -40,10 +40,10 @@ use crate::compute::conformance::conformance_stat; use crate::dtype::DType; use crate::dtype::Nullability; use crate::dtype::PType; -use crate::stats::Stat; use crate::scalar_fn::builtin::operators::BooleanOperator; use crate::scalar_fn::builtin::operators::CompareMode; use crate::scalar_fn::builtin::operators::CompareOperator; +use crate::stats::Stat; /// Tests that filter and take operations produce consistent results. /// diff --git a/vortex-array/src/compute/conformance/mod.rs b/vortex-array/src/compute/conformance/mod.rs index bc00f9ccda2..f8485953762 100644 --- a/vortex-array/src/compute/conformance/mod.rs +++ b/vortex-array/src/compute/conformance/mod.rs @@ -5,8 +5,8 @@ use vortex_error::VortexExpect; use crate::ArrayRef; use crate::ExecutionCtx; -use crate::stats::Stat; use crate::scalar::Scalar; +use crate::stats::Stat; pub mod binary_numeric; pub mod cast; diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 780d96569fb..6259fd63e26 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -17,11 +17,11 @@ use super::StatsSetIntoIter; use super::TypedStatsSetRef; use crate::ArrayRef; use crate::ExecutionCtx; +use crate::scalar::Scalar; +use crate::scalar::ScalarValue; use crate::stats::Precision; use crate::stats::Stat; use crate::stats::StatsProvider; -use crate::scalar::Scalar; -use crate::scalar::ScalarValue; /// A shared [`StatsSet`] stored in an array. Can be shared by copies of the array and can also be mutated in place. /// Stats are created lazily on read or write. diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index 5ebab9c7454..b6e279367c7 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -9,23 +9,22 @@ use enum_iterator::Sequence; use enum_iterator::all; use num_enum::IntoPrimitive; use num_enum::TryFromPrimitive; - use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::session::AggregateFnSessionExt; +use crate::aggregate_fn::stat_aggregates; +use crate::aggregate_fn::stat_aggregates::IsSortedOptions; use crate::dtype::DType; use crate::dtype::Nullability::NonNullable; +use crate::dtype::PType; use crate::stats::LowerBound; use crate::stats::Precision; use crate::stats::StatType; use crate::stats::UpperBound; -use crate::aggregate_fn::session::AggregateFnSessionExt; -use crate::aggregate_fn::stat_aggregates; -use crate::aggregate_fn::stat_aggregates::IsSortedOptions; -use crate::dtype::PType; #[derive( Debug, diff --git a/vortex-array/src/stats/stats_set.rs b/vortex-array/src/stats/stats_set.rs index aeef5d41ca4..92c8e9a15f1 100644 --- a/vortex-array/src/stats/stats_set.rs +++ b/vortex-array/src/stats/stats_set.rs @@ -14,7 +14,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_error::vortex_panic; -use crate::aggregate_fn::fns::min_max::has_nan_values; +use crate::aggregate_fn::stat_aggregates::has_nan_values; use crate::dtype::DType; use crate::scalar::Scalar; use crate::scalar::ScalarValue; @@ -623,14 +623,8 @@ mod test { use rstest::rstest; use smallvec::smallvec; use vortex_error::VortexResult; - use vortex_session::VortexSession; - - use crate::ArrayRef; - use crate::IntoArray; - use crate::VortexSessionExecute; - use crate::aggregate_fn::fns::min_max::has_nan_values; - use crate::arrays::PrimitiveArray; + use crate::aggregate_fn::stat_aggregates::has_nan_values; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::MAX_PRECISION; @@ -1193,45 +1187,6 @@ mod test { ); } - #[rstest] - #[case::leading_null_in_right( - PrimitiveArray::from_option_iter([Some(1i32), Some(2)]).into_array(), - PrimitiveArray::from_option_iter([None, Some(3i32)]).into_array(), - Precision::Absent - )] - #[case::nullable_right_proven_non_null( - PrimitiveArray::from_option_iter([None, Some(1i32), Some(2)]).into_array(), - PrimitiveArray::from_option_iter([Some(3i32), Some(4)]).into_array(), - Precision::exact(ScalarValue::from(true)) - )] - #[case::trailing_pos_nan_in_left( - PrimitiveArray::from_iter([1.0f64, f64::NAN]).into_array(), - PrimitiveArray::from_iter([2.0f64]).into_array(), - Precision::Absent - )] - #[case::leading_neg_nan_in_right( - PrimitiveArray::from_iter([1.0f64]).into_array(), - PrimitiveArray::from_iter([-f64::NAN, 2.0f64]).into_array(), - Precision::Absent - )] - fn merge_sortedness_computed_chunks( - #[case] left: ArrayRef, - #[case] right: ArrayRef, - #[case] expected: Precision, - ) -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let requested = if left.dtype().is_float() { - [Stat::Min, Stat::Max, Stat::NaNCount, Stat::IsSorted] - } else { - [Stat::Min, Stat::Max, Stat::NullCount, Stat::IsSorted] - }; - let left_stats = left.statistics().compute_all(&requested, &mut ctx)?; - let right_stats = right.statistics().compute_all(&requested, &mut ctx)?; - let merged = left_stats.merge_ordered(&right_stats, left.dtype()); - assert_eq!(merged.get(Stat::IsSorted), expected); - Ok(()) - } - fn foreign_ext_dtype(id: &'static str, storage: DType) -> VortexResult { #[expect(clippy::disallowed_methods, reason = "test-only extension id")] let ext = ForeignExtDType::from_parts(ExtId::new(id), vec![], storage)?; diff --git a/vortex-btrblocks/src/schemes/integer/elias_fano.rs b/vortex-btrblocks/src/schemes/integer/elias_fano.rs index 07419581128..412e5386760 100644 --- a/vortex-btrblocks/src/schemes/integer/elias_fano.rs +++ b/vortex-btrblocks/src/schemes/integer/elias_fano.rs @@ -3,12 +3,12 @@ //! Elias-Fano encoding for sorted unsigned integers. +use vortex_aggregates::is_sorted::is_sorted; use vortex_array::ArrayId; use vortex_array::Canonical; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VTable; -use vortex_array::aggregate_fn::fns::is_sorted::is_sorted; use vortex_array::arrays::PrimitiveArray; use vortex_compressor::scheme::CompressionEstimate; use vortex_compressor::scheme::DeferredEstimate; diff --git a/vortex-btrblocks/src/tests.rs b/vortex-btrblocks/src/tests.rs index 271745e0174..68723abb8d2 100644 --- a/vortex-btrblocks/src/tests.rs +++ b/vortex-btrblocks/src/tests.rs @@ -17,10 +17,10 @@ use rand::RngExt; use rand::SeedableRng; use rand::rngs::StdRng; use rstest::rstest; +use vortex_aggregates::sum::sum; use vortex_alp::ALP; use vortex_alp::ALPArrayExt; use vortex_alp::ALPArraySlotsExt; -use vortex_aggregates::sum::sum; use vortex_array::ArrayId; #[cfg(feature = "zstd")] use vortex_array::ArrayPlugin; diff --git a/vortex-compressor/src/compressor/cascade.rs b/vortex-compressor/src/compressor/cascade.rs index a27893f8fa1..21ea51eaa3b 100644 --- a/vortex-compressor/src/compressor/cascade.rs +++ b/vortex-compressor/src/compressor/cascade.rs @@ -3,16 +3,15 @@ //! Core cascading compression flow. -use vortex_array::ArrayId; use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_aggregates::uncompressed_size_in_bytes::uncompressed_size_in_bytes; +use vortex_array::ArrayId; use vortex_array::ArrayRef; use vortex_array::Canonical; use vortex_array::CanonicalValidity; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VTable; -use vortex_array::arrays::Constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::Extension; use vortex_array::arrays::ExtensionArray; diff --git a/vortex-expr/src/stats/expr.rs b/vortex-expr/src/stats/expr.rs index 9af69c630fe..2ebf143e3b7 100644 --- a/vortex-expr/src/stats/expr.rs +++ b/vortex-expr/src/stats/expr.rs @@ -15,9 +15,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::expr::BoundExpression; -use vortex_array::expr::Expression; -use vortex_array::scalar_fn::ScalarFnVTableExt; use vortex_error::VortexExpect; use crate::BoundExpression; diff --git a/vortex-expr/src/stats/rewrite/helpers.rs b/vortex-expr/src/stats/rewrite/helpers.rs index c3e793382d1..c67376105f5 100644 --- a/vortex-expr/src/stats/rewrite/helpers.rs +++ b/vortex-expr/src/stats/rewrite/helpers.rs @@ -5,17 +5,17 @@ //! implementations: stat references over bound expressions and the NaN guards that keep //! min/max comparisons sound for floating-point values. +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::nan_count::NanCount; +use vortex_aggregates::null_count::NullCount; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions as AggregateEmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::all_nan::AllNan; -use vortex_array::aggregate_fn::fns::all_non_nan::AllNonNan; -use vortex_array::aggregate_fn::fns::all_non_null::AllNonNull; -use vortex_array::aggregate_fn::fns::all_null::AllNull; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::nan_count::NanCount; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::dtype::DType; use vortex_array::scalar_fn::EmptyOptions; use vortex_array::scalar_fn::builtin::cast::Cast; diff --git a/vortex-functions/src/pruning/derive_tests.rs b/vortex-functions/src/pruning/derive_tests.rs index f27b8201cc1..23c7d8aee39 100644 --- a/vortex-functions/src/pruning/derive_tests.rs +++ b/vortex-functions/src/pruning/derive_tests.rs @@ -3,11 +3,11 @@ //! Registering statistic derivations for a scalar function from outside vortex-expr. +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::dtype::StructFields; diff --git a/vortex-functions/src/pruning/is_null.rs b/vortex-functions/src/pruning/is_null.rs index 5629a72f299..4f891f3d431 100644 --- a/vortex-functions/src/pruning/is_null.rs +++ b/vortex-functions/src/pruning/is_null.rs @@ -117,7 +117,8 @@ mod tests { } fn stat(expr: Expression, stat: Stat) -> Expression { - let aggregate_fn = stat.aggregate_fn().expect("stat should have aggregate fn"); + let aggregate_fn = + vortex_aggregates::stat_aggregate_fn(stat).expect("stat should have aggregate fn"); vortex_expr::stats::stat(expr, aggregate_fn) } diff --git a/vortex-functions/src/pruning/mod.rs b/vortex-functions/src/pruning/mod.rs index 3f0af4514ab..1fb9e3975ca 100644 --- a/vortex-functions/src/pruning/mod.rs +++ b/vortex-functions/src/pruning/mod.rs @@ -5,10 +5,10 @@ use std::cmp::Ordering; +use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; +use vortex_aggregates::null_count::NullCount; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::fns::max::Max; -use vortex_array::aggregate_fn::fns::min::Min; -use vortex_array::aggregate_fn::fns::null_count::NullCount; use vortex_array::scalar::Scalar; use vortex_array::scalar::StringLike; use vortex_array::scalar_fn::ScalarFnId; @@ -486,7 +486,8 @@ mod tests { }); fn stat(expr: Expression, stat: Stat) -> Expression { - let aggregate_fn = stat.aggregate_fn().expect("stat should have aggregate fn"); + let aggregate_fn = + vortex_aggregates::stat_aggregate_fn(stat).expect("stat should have aggregate fn"); stat_fn(expr, aggregate_fn) } diff --git a/vortex-layout/src/layouts/dict/reader.rs b/vortex-layout/src/layouts/dict/reader.rs index 8203c17f7c4..ff979b2fb21 100644 --- a/vortex-layout/src/layouts/dict/reader.rs +++ b/vortex-layout/src/layouts/dict/reader.rs @@ -448,13 +448,13 @@ mod tests { use futures::future; use futures::join; use rstest::rstest; + use vortex_aggregates::min_max::min_max; use vortex_array::ArrayContext; use vortex_array::ArrayRef; use vortex_array::IntoArray as _; use vortex_array::MaskFuture; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::min_max::min_max; use vortex_array::arrays::BoolArray; use vortex_array::arrays::Dict; use vortex_array::arrays::DictArray; diff --git a/vortex-layout/src/layouts/zoned/mod.rs b/vortex-layout/src/layouts/zoned/mod.rs index b1adab30773..205ad4ca1b4 100644 --- a/vortex-layout/src/layouts/zoned/mod.rs +++ b/vortex-layout/src/layouts/zoned/mod.rs @@ -609,10 +609,10 @@ mod tests { use vortex_aggregates::bounded_max::BoundedMaxOptions; use vortex_aggregates::max::Max; use vortex_aggregates::min::Min; + use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::session::AggregateFnSession; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; @@ -691,7 +691,9 @@ mod tests { let metadata = ZonedMetadata::deserialize(bytes)?; assert_eq!(metadata.zone_len, 8); - let aggregate_fns = try_aggregate_fns_from_specs(&metadata.aggregate_specs, &SESSION)? + let session = VortexSession::empty().with::(); + vortex_aggregates::initialize(&session); + let aggregate_fns = try_aggregate_fns_from_specs(&metadata.aggregate_specs, &session)? .expect("known aggregates resolve"); assert_eq!( aggregate_fns.as_ref(), diff --git a/vortex-layout/src/layouts/zoned/writer.rs b/vortex-layout/src/layouts/zoned/writer.rs index 26b96cc1417..adab244d85b 100644 --- a/vortex-layout/src/layouts/zoned/writer.rs +++ b/vortex-layout/src/layouts/zoned/writer.rs @@ -419,7 +419,6 @@ mod tests { use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::arrays::PrimitiveArray; - use vortex_array::arrays::ChunkedArray; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::dtype::StructFields; diff --git a/vortex-scan/src/execution/tests.rs b/vortex-scan/src/execution/tests.rs index bcdc1769e98..b82594db0ea 100644 --- a/vortex-scan/src/execution/tests.rs +++ b/vortex-scan/src/execution/tests.rs @@ -9,12 +9,12 @@ use std::sync::atomic::Ordering; use rstest::rstest; use vortex_aggregates::max::Max; +use vortex_aggregates::min::Min; use vortex_array::ArrayRef; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_aggregates::min::Min; use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ListArray; use vortex_array::arrays::PrimitiveArray; From f705bbb86760351b02fab1195cbc3303cdc12612 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Mon, 30 Nov 2026 15:26:39 +0000 Subject: [PATCH 10/27] Refresh the fuzz workspace dependencies in the lockfile Signed-off-by: Robert Kruszewski --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20cd37aff38..b06c9a8e78f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11094,8 +11094,8 @@ dependencies = [ "itertools 0.14.0", "mimalloc", "num-traits", - "prost 0.14.4", - "rand 0.10.3", + "prost 0.14.6", + "rand 0.10.4", "rstest", "vortex-array", "vortex-buffer", From f9fa140d04c9f0ee3661d30a26e96e714887e419 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Mon, 30 Nov 2026 15:38:58 +0000 Subject: [PATCH 11/27] Keep release imports aligned with statistics validation Signed-off-by: Robert Kruszewski --- vortex-array/src/arrays/runend/array/mod.rs | 1 + vortex-array/src/arrays/varbin/builder.rs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/vortex-array/src/arrays/runend/array/mod.rs b/vortex-array/src/arrays/runend/array/mod.rs index 631a340a107..3e6c8b1415e 100644 --- a/vortex-array/src/arrays/runend/array/mod.rs +++ b/vortex-array/src/arrays/runend/array/mod.rs @@ -45,6 +45,7 @@ use crate::arrays::Primitive; use crate::arrays::PrimitiveArray; use crate::arrays::VarBinView; use crate::arrays::listview::ListViewArraySlotsExt; +#[cfg(debug_assertions)] use crate::arrays::primitive::integer_is_strict_sorted; use crate::arrays::runend::compress::runend_decode_decimal; use crate::arrays::runend::compress::runend_decode_primitive; diff --git a/vortex-array/src/arrays/varbin/builder.rs b/vortex-array/src/arrays/varbin/builder.rs index 820f521ef42..700a105378c 100644 --- a/vortex-array/src/arrays/varbin/builder.rs +++ b/vortex-array/src/arrays/varbin/builder.rs @@ -29,7 +29,6 @@ use crate::arrays::PrimitiveArray; use crate::arrays::VarBin; use crate::arrays::VarBinArray; use crate::arrays::VarBinView; -#[cfg(debug_assertions)] use crate::arrays::varbin::VarBinArrayExt; use crate::arrays::varbin::VarBinArraySlotsExt; use crate::arrays::varbinview::VarBinViewArrayExt; From ec7a1eb2ab9b5e56f24278729d8d4438518564f5 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 1 Dec 2026 14:05:21 +0000 Subject: [PATCH 12/27] Initialize vortex-aggregates in benchmark sessions Register the built-in aggregates and kernels in benchmark sessions that exercise RunEnd aggregates, list_sum, DecimalByteParts/Widen aggregates, Sparse pushdown, and BtrBlocks compression statistics, and sync Cargo.lock for vortex-spatial. Signed-off-by: Robert Kruszewski --- Cargo.lock | 1 + encodings/decimal-byte-parts/benches/dbp_compute.rs | 1 + encodings/sparse/benches/sparse_pushdown.rs | 1 + vortex-aggregates/Cargo.toml | 2 +- vortex-array/benches/run_end_null_count.rs | 6 ++++-- vortex-array/benches/run_end_sum.rs | 6 ++++-- vortex-btrblocks/benches/compress.rs | 7 +++++-- vortex-btrblocks/benches/compress_listview.rs | 6 ++++-- vortex-btrblocks/benches/string_dict_selection.rs | 6 ++++-- vortex-functions/benches/list_sum.rs | 1 + 10 files changed, 26 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b06c9a8e78f..7eeaf69f646 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12392,6 +12392,7 @@ dependencies = [ "mimalloc", "prost 0.14.6", "rstest", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-buffer", diff --git a/encodings/decimal-byte-parts/benches/dbp_compute.rs b/encodings/decimal-byte-parts/benches/dbp_compute.rs index b24807c493a..d35d1959334 100644 --- a/encodings/decimal-byte-parts/benches/dbp_compute.rs +++ b/encodings/decimal-byte-parts/benches/dbp_compute.rs @@ -61,6 +61,7 @@ fn main() { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); vortex_decimal_byte_parts::initialize(&session); session }); diff --git a/encodings/sparse/benches/sparse_pushdown.rs b/encodings/sparse/benches/sparse_pushdown.rs index 05008592ccf..f9708e39696 100644 --- a/encodings/sparse/benches/sparse_pushdown.rs +++ b/encodings/sparse/benches/sparse_pushdown.rs @@ -61,6 +61,7 @@ static SESSION: LazyLock = LazyLock::new(|| { .with::() .with::() .with::(); + vortex_aggregates::initialize(&session); vortex_sparse::initialize(&session); session }); diff --git a/vortex-aggregates/Cargo.toml b/vortex-aggregates/Cargo.toml index 2900c91af53..e833be30e4e 100644 --- a/vortex-aggregates/Cargo.toml +++ b/vortex-aggregates/Cargo.toml @@ -2,7 +2,7 @@ name = "vortex-aggregates" authors = { workspace = true } categories = { workspace = true } -description = "Vortex aggregate functions beyond those backing array statistics" +description = "Vortex built-in aggregate functions" edition = { workspace = true } include = { workspace = true } keywords = { workspace = true } diff --git a/vortex-array/benches/run_end_null_count.rs b/vortex-array/benches/run_end_null_count.rs index 22119978984..dbb4962291a 100644 --- a/vortex-array/benches/run_end_null_count.rs +++ b/vortex-array/benches/run_end_null_count.rs @@ -59,10 +59,12 @@ const BENCH_ARGS: &[(usize, usize, f64)] = &[ ]; static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); #[divan::bench(args = BENCH_ARGS)] diff --git a/vortex-array/benches/run_end_sum.rs b/vortex-array/benches/run_end_sum.rs index 87f17ca7f60..a68ac8af82b 100644 --- a/vortex-array/benches/run_end_sum.rs +++ b/vortex-array/benches/run_end_sum.rs @@ -23,10 +23,12 @@ const LEN: usize = 65_536; const RUN_LENGTH: usize = 64; static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); #[global_allocator] diff --git a/vortex-btrblocks/benches/compress.rs b/vortex-btrblocks/benches/compress.rs index 9a6b00183e3..9b82b1c350a 100644 --- a/vortex-btrblocks/benches/compress.rs +++ b/vortex-btrblocks/benches/compress.rs @@ -41,18 +41,21 @@ mod benchmarks { use vortex_utils::aliases::hash_set::HashSet; pub(super) static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() .with::() .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); /// A session that allows only what a default writer may produce, set up as the golden tests /// set it up: the encodings the compressor emits, limited by the default `core` edition. static WRITE_SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty().with::(); + vortex_aggregates::initialize(&session); vortex_alp::initialize(&session); vortex_datetime_parts::initialize(&session); vortex_decimal_byte_parts::initialize(&session); diff --git a/vortex-btrblocks/benches/compress_listview.rs b/vortex-btrblocks/benches/compress_listview.rs index f9c7cfe6a52..1491e901818 100644 --- a/vortex-btrblocks/benches/compress_listview.rs +++ b/vortex-btrblocks/benches/compress_listview.rs @@ -39,12 +39,14 @@ mod benchmarks { const SEED: u64 = 42; pub(super) static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() .with::() .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); const SHORT_STRINGS: &[&str] = &[ diff --git a/vortex-btrblocks/benches/string_dict_selection.rs b/vortex-btrblocks/benches/string_dict_selection.rs index 39bcd9aebb4..36c071de4eb 100644 --- a/vortex-btrblocks/benches/string_dict_selection.rs +++ b/vortex-btrblocks/benches/string_dict_selection.rs @@ -23,12 +23,14 @@ mod benchmarks { use vortex_session::VortexSession; static SESSION: LazyLock = LazyLock::new(|| { - VortexSession::empty() + let session = VortexSession::empty() .with::() .with::() .with::() .with::() - .with::() + .with::(); + vortex_aggregates::initialize(&session); + session }); #[derive(Clone, Copy)] diff --git a/vortex-functions/benches/list_sum.rs b/vortex-functions/benches/list_sum.rs index 2ed9b3887f5..75596ddc593 100644 --- a/vortex-functions/benches/list_sum.rs +++ b/vortex-functions/benches/list_sum.rs @@ -54,6 +54,7 @@ static SESSION: LazyLock = LazyLock::new(|| { .with::() .with::() .with::(); + vortex_aggregates::initialize(&session); vortex_functions::initialize(&session); session }); From 4fc9f404b2d9c1a0accd8ba72e0a461c2e3c8ae0 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 14:51:58 +0000 Subject: [PATCH 13/27] Fix roborev findings and CI failures on aggregate split - Short-circuit DType::Null in is_sorted_impl and StatsSetRef::compute_stat for IsConstant, IsSorted, and IsStrictSorted, with regression tests - Initialize vortex-aggregates in encoding consistency test sessions so slice-aggregate conformance checks run - Fix vortex-expr test imports for NullCount/Sum and broken rustdoc link in vortex-aggregates Signed-off-by: Will Manning Co-Authored-By: Will Manning --- Cargo.lock | 4 ++ encodings/alp/src/alp/compute/mod.rs | 1 + encodings/alp/src/alp_rd/compute/mod.rs | 1 + encodings/bytebool/Cargo.toml | 1 + encodings/bytebool/src/compute.rs | 1 + encodings/datetime-parts/src/compute/mod.rs | 1 + .../src/decimal_byte_parts/compute/mod.rs | 1 + encodings/elias-fano/src/lib.rs | 1 + .../fastlanes/src/bitpacking/compute/mod.rs | 1 + .../fastlanes/src/delta/vtable/operations.rs | 1 + encodings/fastlanes/src/for_/compute/mod.rs | 2 + encodings/fastlanes/src/for_/tests.rs | 1 + encodings/fsst/src/compute/mod.rs | 1 + encodings/onpair/src/tests.rs | 1 + encodings/pco/Cargo.toml | 1 + encodings/pco/src/compute/mod.rs | 1 + encodings/sequence/src/compute/mod.rs | 1 + encodings/sparse/src/compute/mod.rs | 1 + encodings/zigzag/Cargo.toml | 1 + encodings/zigzag/src/compute/mod.rs | 1 + encodings/zstd/Cargo.toml | 1 + encodings/zstd/src/array/probe.rs | 1 + encodings/zstd/src/compute/mod.rs | 1 + encodings/zstd/src/zstd_buffers/mod.rs | 1 + vortex-aggregates/src/count/grouped.rs | 2 +- vortex-aggregates/src/is_sorted/mod.rs | 46 +++++++++++++++++++ .../src/compute/conformance/consistency.rs | 3 +- vortex-array/src/stats/array.rs | 19 ++++++++ vortex-expr/src/stats/stat_fn.rs | 4 +- 29 files changed, 98 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7eeaf69f646..f63bae5e0f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11379,6 +11379,7 @@ dependencies = [ "mimalloc", "num-traits", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -12212,6 +12213,7 @@ dependencies = [ "prost 0.14.6", "rand 0.10.4", "rstest", + "vortex-aggregates", "vortex-array", "vortex-arrow", "vortex-buffer", @@ -12580,6 +12582,7 @@ dependencies = [ "mimalloc", "num-traits", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-compute", @@ -12598,6 +12601,7 @@ dependencies = [ "num-traits", "prost 0.14.6", "rstest", + "vortex-aggregates", "vortex-array", "vortex-buffer", "vortex-edition", diff --git a/encodings/alp/src/alp/compute/mod.rs b/encodings/alp/src/alp/compute/mod.rs index e75bbc9b9a4..901beeb7512 100644 --- a/encodings/alp/src/alp/compute/mod.rs +++ b/encodings/alp/src/alp/compute/mod.rs @@ -31,6 +31,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/alp/src/alp_rd/compute/mod.rs b/encodings/alp/src/alp_rd/compute/mod.rs index d7f2b5164ee..86d54a73be0 100644 --- a/encodings/alp/src/alp_rd/compute/mod.rs +++ b/encodings/alp/src/alp_rd/compute/mod.rs @@ -25,6 +25,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/bytebool/Cargo.toml b/encodings/bytebool/Cargo.toml index 06e296e45d9..b539c59e59f 100644 --- a/encodings/bytebool/Cargo.toml +++ b/encodings/bytebool/Cargo.toml @@ -28,6 +28,7 @@ vortex-session = { workspace = true } divan = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } [[bench]] diff --git a/encodings/bytebool/src/compute.rs b/encodings/bytebool/src/compute.rs index 84e17d1b370..c52e3c56b69 100644 --- a/encodings/bytebool/src/compute.rs +++ b/encodings/bytebool/src/compute.rs @@ -233,6 +233,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/datetime-parts/src/compute/mod.rs b/encodings/datetime-parts/src/compute/mod.rs index 9afa114da5f..ef7d7a1e586 100644 --- a/encodings/datetime-parts/src/compute/mod.rs +++ b/encodings/datetime-parts/src/compute/mod.rs @@ -31,6 +31,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs index adf5d542963..a09ed591c51 100644 --- a/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs +++ b/encodings/decimal-byte-parts/src/decimal_byte_parts/compute/mod.rs @@ -42,6 +42,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/elias-fano/src/lib.rs b/encodings/elias-fano/src/lib.rs index 3da33b67010..bd398cc204d 100644 --- a/encodings/elias-fano/src/lib.rs +++ b/encodings/elias-fano/src/lib.rs @@ -44,6 +44,7 @@ pub fn initialize(session: &VortexSession) { static SESSION: std::sync::LazyLock = std::sync::LazyLock::new(|| { let session = VortexSession::empty(); initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/fastlanes/src/bitpacking/compute/mod.rs b/encodings/fastlanes/src/bitpacking/compute/mod.rs index 10937e48e39..cfeb39032ab 100644 --- a/encodings/fastlanes/src/bitpacking/compute/mod.rs +++ b/encodings/fastlanes/src/bitpacking/compute/mod.rs @@ -101,6 +101,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/fastlanes/src/delta/vtable/operations.rs b/encodings/fastlanes/src/delta/vtable/operations.rs index b733122d7d2..4051b2af6c4 100644 --- a/encodings/fastlanes/src/delta/vtable/operations.rs +++ b/encodings/fastlanes/src/delta/vtable/operations.rs @@ -54,6 +54,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/fastlanes/src/for_/compute/mod.rs b/encodings/fastlanes/src/for_/compute/mod.rs index a334731ba77..45276bd289b 100644 --- a/encodings/fastlanes/src/for_/compute/mod.rs +++ b/encodings/fastlanes/src/for_/compute/mod.rs @@ -70,6 +70,7 @@ mod test { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); @@ -133,6 +134,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/fastlanes/src/for_/tests.rs b/encodings/fastlanes/src/for_/tests.rs index 2a945ffc084..48a2eda1e1e 100644 --- a/encodings/fastlanes/src/for_/tests.rs +++ b/encodings/fastlanes/src/for_/tests.rs @@ -50,6 +50,7 @@ use crate::FoRReferences; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/fsst/src/compute/mod.rs b/encodings/fsst/src/compute/mod.rs index 3e0f1c75c3f..93aa9be53d5 100644 --- a/encodings/fsst/src/compute/mod.rs +++ b/encodings/fsst/src/compute/mod.rs @@ -469,6 +469,7 @@ mod tests { fn test_fsst_consistency(#[case] build: FsstBuilder) { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); let mut ctx = session.create_execution_ctx(); let array = build(&mut ctx); test_array_consistency(&array.into_array(), &mut ctx); diff --git a/encodings/onpair/src/tests.rs b/encodings/onpair/src/tests.rs index ef9bc48aa88..476d5062a3a 100644 --- a/encodings/onpair/src/tests.rs +++ b/encodings/onpair/src/tests.rs @@ -46,6 +46,7 @@ use crate::compress::onpair_compress; static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/pco/Cargo.toml b/encodings/pco/Cargo.toml index 76c608b5a69..5b8edabca79 100644 --- a/encodings/pco/Cargo.toml +++ b/encodings/pco/Cargo.toml @@ -29,6 +29,7 @@ divan = { workspace = true } mimalloc = { workspace = true } rand = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-arrow = { workspace = true } vortex-zigzag = { workspace = true } diff --git a/encodings/pco/src/compute/mod.rs b/encodings/pco/src/compute/mod.rs index 33c15f07f32..a6e4868c7de 100644 --- a/encodings/pco/src/compute/mod.rs +++ b/encodings/pco/src/compute/mod.rs @@ -21,6 +21,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/sequence/src/compute/mod.rs b/encodings/sequence/src/compute/mod.rs index 96c9b8e89f8..61c11db9105 100644 --- a/encodings/sequence/src/compute/mod.rs +++ b/encodings/sequence/src/compute/mod.rs @@ -29,6 +29,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/sparse/src/compute/mod.rs b/encodings/sparse/src/compute/mod.rs index 6f142d60c85..97c27bf1b3c 100644 --- a/encodings/sparse/src/compute/mod.rs +++ b/encodings/sparse/src/compute/mod.rs @@ -43,6 +43,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/zigzag/Cargo.toml b/encodings/zigzag/Cargo.toml index 0224b29942b..7b8c0fa4b94 100644 --- a/encodings/zigzag/Cargo.toml +++ b/encodings/zigzag/Cargo.toml @@ -26,6 +26,7 @@ zigzag = { workspace = true } divan = { workspace = true } mimalloc = { workspace = true } rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-fastlanes = { workspace = true } diff --git a/encodings/zigzag/src/compute/mod.rs b/encodings/zigzag/src/compute/mod.rs index 0c8fad015f2..ac0ca35f8f5 100644 --- a/encodings/zigzag/src/compute/mod.rs +++ b/encodings/zigzag/src/compute/mod.rs @@ -90,6 +90,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/zstd/Cargo.toml b/encodings/zstd/Cargo.toml index bc4e7af199b..47bc526a95b 100644 --- a/encodings/zstd/Cargo.toml +++ b/encodings/zstd/Cargo.toml @@ -32,4 +32,5 @@ zstd = { workspace = true } [dev-dependencies] rstest = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } diff --git a/encodings/zstd/src/array/probe.rs b/encodings/zstd/src/array/probe.rs index e2c33e02cd3..d56c0ab491f 100644 --- a/encodings/zstd/src/array/probe.rs +++ b/encodings/zstd/src/array/probe.rs @@ -181,6 +181,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/zstd/src/compute/mod.rs b/encodings/zstd/src/compute/mod.rs index 8fd22002086..0011d03b368 100644 --- a/encodings/zstd/src/compute/mod.rs +++ b/encodings/zstd/src/compute/mod.rs @@ -21,6 +21,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/encodings/zstd/src/zstd_buffers/mod.rs b/encodings/zstd/src/zstd_buffers/mod.rs index 96180a94f0f..f05558b7810 100644 --- a/encodings/zstd/src/zstd_buffers/mod.rs +++ b/encodings/zstd/src/zstd_buffers/mod.rs @@ -589,6 +589,7 @@ mod tests { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); crate::initialize(&session); + vortex_aggregates::initialize(&session); session }); diff --git a/vortex-aggregates/src/count/grouped.rs b/vortex-aggregates/src/count/grouped.rs index cb363ace387..0309c5499d3 100644 --- a/vortex-aggregates/src/count/grouped.rs +++ b/vortex-aggregates/src/count/grouped.rs @@ -42,7 +42,7 @@ impl DynGroupedAggregateKernel for CountGroupedKernel { /// Count each valid group from the element validity mask. /// /// The [`Count`] partial dtype is non-nullable `U64`. If any outer group is invalid, this returns -/// `Ok(None)` so [`GroupedAccumulator`](crate::aggregate_fn::GroupedAccumulator) falls back to +/// `Ok(None)` so [`GroupedAccumulator`](vortex_array::aggregate_fn::GroupedAccumulator) falls back to /// flushing the empty accumulator state (`0`) for null groups. pub(super) fn try_grouped_count( groups: &GroupedArray, diff --git a/vortex-aggregates/src/is_sorted/mod.rs b/vortex-aggregates/src/is_sorted/mod.rs index 29b01c67722..42670b79fd5 100644 --- a/vortex-aggregates/src/is_sorted/mod.rs +++ b/vortex-aggregates/src/is_sorted/mod.rs @@ -77,6 +77,13 @@ fn is_sorted_impl(array: &ArrayRef, strict: bool, ctx: &mut ExecutionCtx) -> Vor return Ok(value); } + // Null-dtype arrays are all null, so they are sorted (strictly only when len <= 1, handled above). + if matches!(array.dtype(), DType::Null) { + let result = !strict; + cache_is_sorted(array, strict, result); + return Ok(result); + } + // Unsupported dtypes, such as structs and lists, are reported as unsorted. if IsSorted .return_dtype(&IsSortedOptions { strict }, array.dtype()) @@ -631,6 +638,7 @@ mod tests { use vortex_array::arrays::DecimalArray; use vortex_array::arrays::DictArray; use vortex_array::arrays::ListViewArray; + use vortex_array::arrays::NullArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::runend::RunEnd; @@ -1026,4 +1034,42 @@ mod tests { assert!(!is_sorted(&chunked, &mut ctx)?); Ok(()) } + + #[rstest] + #[case::empty(0, None, true, true)] + #[case::single(1, Some(true), true, true)] + #[case::multiple(3, Some(true), true, false)] + fn null_array_sorted_and_constant_stats( + #[case] len: usize, + #[case] expected_constant: Option, + #[case] expected_sorted: bool, + #[case] expected_strict_sorted: bool, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let array = NullArray::new(len).into_array(); + + assert_eq!(is_sorted(&array, &mut ctx)?, expected_sorted); + assert_eq!(is_strict_sorted(&array, &mut ctx)?, expected_strict_sorted); + + let fresh = NullArray::new(len).into_array(); + assert_eq!( + fresh + .statistics() + .compute_as::(Stat::IsConstant, &mut ctx), + expected_constant + ); + assert_eq!( + fresh + .statistics() + .compute_as::(Stat::IsSorted, &mut ctx), + Some(expected_sorted) + ); + assert_eq!( + fresh + .statistics() + .compute_as::(Stat::IsStrictSorted, &mut ctx), + Some(expected_strict_sorted) + ); + Ok(()) + } } diff --git a/vortex-array/src/compute/conformance/consistency.rs b/vortex-array/src/compute/conformance/consistency.rs index b045e6796e6..86f7205adbc 100644 --- a/vortex-array/src/compute/conformance/consistency.rs +++ b/vortex-array/src/compute/conformance/consistency.rs @@ -1300,7 +1300,8 @@ pub(crate) fn test_scalar_probe_consistency(array: &ArrayRef, ctx: &mut Executio /// - **Symmetry**: Ensures proper ordering relationships when operands are swapped /// /// ## Aggregate Operations -/// - **Slice/Aggregate**: Verifies aggregates on sliced arrays match canonical +/// - **Slice/Aggregate**: Verifies aggregates on sliced arrays match canonical (when the session +/// registers aggregates via `vortex_aggregates::initialize`) /// /// ## Identity Operations /// - **Filter Identity**: All-true mask preserves the array diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 6259fd63e26..5340cc73f90 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -17,6 +17,7 @@ use super::StatsSetIntoIter; use super::TypedStatsSetRef; use crate::ArrayRef; use crate::ExecutionCtx; +use crate::dtype::DType; use crate::scalar::Scalar; use crate::scalar::ScalarValue; use crate::stats::Precision; @@ -257,6 +258,24 @@ impl StatsSetRef<'_> { // Null counts come from validity, which every array exposes directly. Stat::NullCount => return Ok(array.invalid_count(ctx).ok().map(Into::into)), Stat::IsConstant if array.is_empty() => return Ok(None), + // Null-dtype arrays are all null, so constancy and sortedness follow from length alone. + Stat::IsConstant if matches!(array.dtype(), DType::Null) => { + self.set(Stat::IsConstant, Precision::exact(true)); + return Ok(Some(true.into())); + } + Stat::IsSorted if matches!(array.dtype(), DType::Null) => { + self.set(Stat::IsSorted, Precision::exact(true)); + if array.len() <= 1 { + self.set(Stat::IsStrictSorted, Precision::exact(true)); + } + return Ok(Some(true.into())); + } + Stat::IsStrictSorted if matches!(array.dtype(), DType::Null) => { + let value = array.len() <= 1; + self.set(Stat::IsSorted, Precision::exact(true)); + self.set(Stat::IsStrictSorted, Precision::exact(value)); + return Ok(Some(value.into())); + } _ => {} } if stat.dtype(array.dtype()).is_none() { diff --git a/vortex-expr/src/stats/stat_fn.rs b/vortex-expr/src/stats/stat_fn.rs index add234a33f1..009615ce112 100644 --- a/vortex-expr/src/stats/stat_fn.rs +++ b/vortex-expr/src/stats/stat_fn.rs @@ -204,12 +204,12 @@ mod tests { use std::sync::LazyLock; use rstest::rstest; + use vortex_aggregates::null_count::NullCount; + use vortex_aggregates::sum::Sum; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::EmptyOptions; use vortex_array::aggregate_fn::NumericalAggregateOpts; - use vortex_array::aggregate_fn::fns::null_count::NullCount; - use vortex_array::aggregate_fn::fns::sum::Sum; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; From e98a661da32f7071939b47170711b77a251c4d36 Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 1 Dec 2026 14:49:28 +0000 Subject: [PATCH 14/27] Remove stat_aggregates, rename framework_tests, and restore pushdown doctest - Rename `vortex-aggregates/src/framework_tests` (along with `combined_tests` and `grouped_tests`) to `vortex-aggregates/src/tests`. - Restore the `ExtensionStoragePushdown` doctest in `vortex-array/src/aggregate_fn/storage_pushdown.rs`. - Remove `vortex-array/src/aggregate_fn/stat_aggregates.rs` and restore aggregate IDs, `IsSortedOptions`, `sum_decimal_dtype`, `has_nan_values`, and `UncompressedSizeInBytes`/`All*` checks to their home modules. Signed-off-by: Robert Kruszewski --- encodings/fsst/Cargo.toml | 2 +- .../src/compute/uncompressed_size_in_bytes.rs | 4 +- encodings/fsst/src/lib.rs | 5 +- vortex-aggregates/src/all_nan/mod.rs | 5 +- vortex-aggregates/src/all_non_nan/mod.rs | 5 +- vortex-aggregates/src/all_non_null/mod.rs | 5 +- vortex-aggregates/src/all_null/mod.rs | 5 +- vortex-aggregates/src/is_constant/mod.rs | 5 +- vortex-aggregates/src/is_sorted/mod.rs | 39 ++++- vortex-aggregates/src/lib.rs | 6 +- vortex-aggregates/src/max/mod.rs | 5 +- vortex-aggregates/src/min/mod.rs | 5 +- vortex-aggregates/src/min_max/mod.rs | 13 +- vortex-aggregates/src/nan_count/mod.rs | 5 +- vortex-aggregates/src/null_count/mod.rs | 5 +- vortex-aggregates/src/sum/mod.rs | 20 ++- .../{framework_tests => tests}/accumulator.rs | 0 .../chunked_kernel.rs | 0 .../{combined_tests.rs => tests/combined.rs} | 0 .../core_consistency.rs | 0 .../extension_validation.rs | 0 .../{grouped_tests.rs => tests/grouped.rs} | 0 .../listview_is_constant.rs | 0 .../src/{framework_tests => tests}/mod.rs | 4 +- .../src/{framework_tests => tests}/proto.rs | 0 .../src/{framework_tests => tests}/stats.rs | 0 .../storage_pushdown.rs | 0 .../struct_is_constant.rs | 0 .../union_uncompressed_size.rs | 0 .../src/uncompressed_size_in_bytes/mod.rs | 12 +- vortex-array/src/aggregate_fn/mod.rs | 1 - .../src/aggregate_fn/stat_aggregates.rs | 156 ------------------ .../src/aggregate_fn/storage_pushdown.rs | 46 +++++- .../src/arrays/primitive/integer_bounds.rs | 8 +- vortex-array/src/stats/stat.rs | 96 +++++++++-- vortex-array/src/stats/stats_set.rs | 10 +- vortex-expr/src/stats/stat_fn.rs | 13 +- 37 files changed, 248 insertions(+), 232 deletions(-) rename vortex-aggregates/src/{framework_tests => tests}/accumulator.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/chunked_kernel.rs (100%) rename vortex-aggregates/src/{combined_tests.rs => tests/combined.rs} (100%) rename vortex-aggregates/src/{framework_tests => tests}/core_consistency.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/extension_validation.rs (100%) rename vortex-aggregates/src/{grouped_tests.rs => tests/grouped.rs} (100%) rename vortex-aggregates/src/{framework_tests => tests}/listview_is_constant.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/mod.rs (76%) rename vortex-aggregates/src/{framework_tests => tests}/proto.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/stats.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/storage_pushdown.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/struct_is_constant.rs (100%) rename vortex-aggregates/src/{framework_tests => tests}/union_uncompressed_size.rs (100%) delete mode 100644 vortex-array/src/aggregate_fn/stat_aggregates.rs diff --git a/encodings/fsst/Cargo.toml b/encodings/fsst/Cargo.toml index 410ebbc8a2f..5f1fe26af98 100644 --- a/encodings/fsst/Cargo.toml +++ b/encodings/fsst/Cargo.toml @@ -20,6 +20,7 @@ num-traits = { workspace = true } prost = { workspace = true } rand = { workspace = true, optional = true } simdutf8 = { workspace = true } +vortex-aggregates = { workspace = true } vortex-array = { workspace = true } vortex-buffer = { workspace = true } vortex-error = { workspace = true } @@ -37,7 +38,6 @@ hegeltest = { workspace = true } mimalloc = { workspace = true } rand = { workspace = true } rstest = { workspace = true } -vortex-aggregates = { workspace = true } vortex-array = { workspace = true, features = ["_test-harness"] } vortex-expr = { workspace = true } diff --git a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs index d9a2fca7886..6f8f1fe83b1 100644 --- a/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs +++ b/encodings/fsst/src/compute/uncompressed_size_in_bytes.rs @@ -4,13 +4,13 @@ use std::mem::size_of; use num_traits::ToPrimitive; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::ArrayRef; use vortex_array::ArrayView; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::kernels::DynAggregateKernel; -use vortex_array::aggregate_fn::stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::PrimitiveArray; use vortex_array::arrays::varbinview::BinaryView; @@ -36,7 +36,7 @@ impl DynAggregateKernel for FsstUncompressedSizeKernel { batch: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult> { - if aggregate_fn.id() != *UNCOMPRESSED_SIZE_IN_BYTES_ID { + if !aggregate_fn.is::() { return Ok(None); } diff --git a/encodings/fsst/src/lib.rs b/encodings/fsst/src/lib.rs index e2c9f0fc696..1bbf6558e70 100644 --- a/encodings/fsst/src/lib.rs +++ b/encodings/fsst/src/lib.rs @@ -27,9 +27,10 @@ mod tests; pub use array::*; pub use compress::*; +use vortex_aggregates::uncompressed_size_in_bytes::UncompressedSizeInBytes; use vortex_array::ArrayVTable; +use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::session::AggregateFnSessionExt; -use vortex_array::aggregate_fn::stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID; use vortex_array::session::ArraySessionExt; use vortex_session::VortexSession; @@ -39,7 +40,7 @@ pub fn initialize(session: &VortexSession) { kernel::initialize(session); session.aggregate_fns().register_aggregate_kernel( FSST.id(), - Some(*UNCOMPRESSED_SIZE_IN_BYTES_ID), + Some(UncompressedSizeInBytes.id()), &compute::uncompressed_size_in_bytes::FsstUncompressedSizeKernel, ); rules::register_parent_rules(session); diff --git a/vortex-aggregates/src/all_nan/mod.rs b/vortex-aggregates/src/all_nan/mod.rs index d1cd4e3d073..ec4b9d56714 100644 --- a/vortex-aggregates/src/all_nan/mod.rs +++ b/vortex-aggregates/src/all_nan/mod.rs @@ -8,12 +8,12 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::nan_count::columnar_nan_count; use crate::nan_count::nan_count; @@ -36,7 +36,8 @@ impl AggregateFnVTable for AllNan { type Partial = bool; fn id(&self) -> AggregateFnId { - *stat_aggregates::ALL_NAN_ID + static ID: CachedId = CachedId::new("vortex.all_nan"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/all_non_nan/mod.rs b/vortex-aggregates/src/all_non_nan/mod.rs index 93b9c582e73..d13403740a9 100644 --- a/vortex-aggregates/src/all_non_nan/mod.rs +++ b/vortex-aggregates/src/all_non_nan/mod.rs @@ -8,12 +8,12 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::nan_count::columnar_nan_count; use crate::nan_count::nan_count; @@ -36,7 +36,8 @@ impl AggregateFnVTable for AllNonNan { type Partial = bool; fn id(&self) -> AggregateFnId { - *stat_aggregates::ALL_NON_NAN_ID + static ID: CachedId = CachedId::new("vortex.all_non_nan"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/all_non_null/mod.rs b/vortex-aggregates/src/all_non_null/mod.rs index 97dbd789fdf..5b8f635ad1f 100644 --- a/vortex-aggregates/src/all_non_null/mod.rs +++ b/vortex-aggregates/src/all_non_null/mod.rs @@ -9,12 +9,12 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; /// Compute whether every value in an array is non-null. /// @@ -27,7 +27,8 @@ impl AggregateFnVTable for AllNonNull { type Partial = bool; fn id(&self) -> AggregateFnId { - *stat_aggregates::ALL_NON_NULL_ID + static ID: CachedId = CachedId::new("vortex.all_non_null"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/all_null/mod.rs b/vortex-aggregates/src/all_null/mod.rs index 3025c6458c1..44d1f9a2f87 100644 --- a/vortex-aggregates/src/all_null/mod.rs +++ b/vortex-aggregates/src/all_null/mod.rs @@ -9,12 +9,12 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability; use vortex_array::scalar::Scalar; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; /// Compute whether every value in an array is null. /// @@ -27,7 +27,8 @@ impl AggregateFnVTable for AllNull { type Partial = bool; fn id(&self) -> AggregateFnId { - *stat_aggregates::ALL_NULL_ID + static ID: CachedId = CachedId::new("vortex.all_null"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/is_constant/mod.rs b/vortex-aggregates/src/is_constant/mod.rs index 8ebf3921d02..d0798ed2288 100644 --- a/vortex-aggregates/src/is_constant/mod.rs +++ b/vortex-aggregates/src/is_constant/mod.rs @@ -24,7 +24,6 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::arrays::Constant; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; @@ -43,6 +42,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_mask::Mask; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use self::bool::check_bool_constant; use self::decimal::check_decimal_constant; @@ -250,7 +250,8 @@ impl AggregateFnVTable for IsConstant { type Partial = IsConstantPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::IS_CONSTANT_ID + static ID: CachedId = CachedId::new("vortex.is_constant"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/is_sorted/mod.rs b/vortex-aggregates/src/is_sorted/mod.rs index 42670b79fd5..e577bb37153 100644 --- a/vortex-aggregates/src/is_sorted/mod.rs +++ b/vortex-aggregates/src/is_sorted/mod.rs @@ -7,6 +7,9 @@ mod fixed_size_list; mod primitive; mod varbin; +use std::fmt; +use std::fmt::Display; +use std::fmt::Formatter; use std::mem; use vortex_array::ArrayRef; @@ -19,8 +22,6 @@ use vortex_array::aggregate_fn::AggregateArgs; use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; -use vortex_array::aggregate_fn::stat_aggregates; -pub use vortex_array::aggregate_fn::stat_aggregates::IsSortedOptions; use vortex_array::builtins::ArrayBuiltins; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; @@ -32,7 +33,9 @@ use vortex_array::stats::Stat; use vortex_array::stats::StatsProviderExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use self::bool::check_bool_sorted; use self::decimal::check_decimal_sorted; @@ -232,12 +235,42 @@ pub fn make_is_sorted_partial_dtype(element_dtype: &DType) -> DType { ) } +/// Options for the `is_sorted` aggregate function. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct IsSortedOptions { + /// If true, check for strictly ascending order (no duplicates). + pub strict: bool, +} + +impl IsSortedOptions { + /// Serialize these options to metadata bytes: one byte, `1` for strict and `0` otherwise. + pub fn serialize(&self) -> Vec { + vec![u8::from(self.strict)] + } + + /// Deserialize these options from metadata bytes written by [`IsSortedOptions::serialize`]. + pub fn deserialize(metadata: &[u8]) -> VortexResult { + match metadata { + [0] => Ok(Self { strict: false }), + [1] => Ok(Self { strict: true }), + _ => vortex_bail!("invalid is_sorted options metadata {metadata:?}"), + } + } +} + +impl Display for IsSortedOptions { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "strict={}", self.strict) + } +} + impl AggregateFnVTable for IsSorted { type Options = IsSortedOptions; type Partial = IsSortedPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::IS_SORTED_ID + static ID: CachedId = CachedId::new("vortex.is_sorted"); + *ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/lib.rs b/vortex-aggregates/src/lib.rs index 6979691d228..e4d36240e22 100644 --- a/vortex-aggregates/src/lib.rs +++ b/vortex-aggregates/src/lib.rs @@ -59,11 +59,7 @@ pub mod uncompressed_size_in_bytes; mod widen; #[cfg(test)] -mod combined_tests; -#[cfg(test)] -mod framework_tests; -#[cfg(test)] -mod grouped_tests; +mod tests; /// Register this crate's aggregate functions and kernels with the given session. pub fn initialize(session: &VortexSession) { diff --git a/vortex-aggregates/src/max/mod.rs b/vortex-aggregates/src/max/mod.rs index a3791d14022..4d036e9c032 100644 --- a/vortex-aggregates/src/max/mod.rs +++ b/vortex-aggregates/src/max/mod.rs @@ -10,7 +10,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::partial_ord::partial_max; use vortex_array::scalar::Scalar; @@ -21,6 +20,7 @@ use vortex_array::stats::StatsProviderExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::min_max::MinMax; use crate::min_max::columnar_min_max; @@ -83,7 +83,8 @@ impl AggregateFnVTable for Max { type Partial = MaxPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::MAX_ID + static ID: CachedId = CachedId::new("vortex.max"); + *ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/min/mod.rs b/vortex-aggregates/src/min/mod.rs index 25763d5a0ce..f8fd3534e36 100644 --- a/vortex-aggregates/src/min/mod.rs +++ b/vortex-aggregates/src/min/mod.rs @@ -10,7 +10,6 @@ use vortex_array::aggregate_fn::AggregateFnRef; use vortex_array::aggregate_fn::AggregateFnSatisfaction; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::partial_ord::partial_min; use vortex_array::scalar::Scalar; @@ -21,6 +20,7 @@ use vortex_array::stats::StatsProviderExt; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::min_max::MinMax; use crate::min_max::columnar_min_max; @@ -83,7 +83,8 @@ impl AggregateFnVTable for Min { type Partial = MinPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::MIN_ID + static ID: CachedId = CachedId::new("vortex.min"); + *ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/min_max/mod.rs b/vortex-aggregates/src/min_max/mod.rs index b83f356a5c3..f04acc2dc8f 100644 --- a/vortex-aggregates/src/min_max/mod.rs +++ b/vortex-aggregates/src/min_max/mod.rs @@ -22,8 +22,6 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::stat_aggregates; -use vortex_array::aggregate_fn::stat_aggregates::has_nan_values; use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; @@ -42,6 +40,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_error::vortex_panic; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use self::bool::accumulate_bool; use self::decimal::accumulate_decimal; @@ -337,12 +336,20 @@ fn minmax_compute_supported_dtype(input_dtype: &DType) -> bool { ) || is_fixed_size_bytes(input_dtype) } +pub(crate) fn has_nan_values(dtype: &DType) -> bool { + match dtype { + DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()), + _ => dtype.is_float(), + } +} + impl AggregateFnVTable for MinMax { type Options = NumericalAggregateOpts; type Partial = MinMaxPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::MIN_MAX_ID + static ID: CachedId = CachedId::new("vortex.min_max"); + *ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/nan_count/mod.rs b/vortex-aggregates/src/nan_count/mod.rs index 6c73b2ce2ab..f97b35dcadc 100644 --- a/vortex-aggregates/src/nan_count/mod.rs +++ b/vortex-aggregates/src/nan_count/mod.rs @@ -14,7 +14,6 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; @@ -26,6 +25,7 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_bail; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use self::primitive::accumulate_primitive; @@ -100,7 +100,8 @@ impl AggregateFnVTable for NanCount { type Partial = u64; fn id(&self) -> AggregateFnId { - *stat_aggregates::NAN_COUNT_ID + static ID: CachedId = CachedId::new("vortex.nan_count"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/null_count/mod.rs b/vortex-aggregates/src/null_count/mod.rs index b7de267d994..1056ca6d077 100644 --- a/vortex-aggregates/src/null_count/mod.rs +++ b/vortex-aggregates/src/null_count/mod.rs @@ -11,7 +11,6 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; use vortex_array::dtype::PType; @@ -22,6 +21,7 @@ use vortex_array::stats::StatsProvider; use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; /// Return the number of null values in an array. pub fn null_count(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { @@ -53,7 +53,8 @@ impl AggregateFnVTable for NullCount { type Partial = u64; fn id(&self) -> AggregateFnId { - *stat_aggregates::NULL_COUNT_ID + static ID: CachedId = CachedId::new("vortex.null_count"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { diff --git a/vortex-aggregates/src/sum/mod.rs b/vortex-aggregates/src/sum/mod.rs index f04f532f3fd..ae3f736f983 100644 --- a/vortex-aggregates/src/sum/mod.rs +++ b/vortex-aggregates/src/sum/mod.rs @@ -17,8 +17,9 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::dtype::DType; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::MAX_PRECISION; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::scalar::DecimalValue; @@ -33,6 +34,7 @@ use vortex_error::vortex_bail; use vortex_error::vortex_ensure; use vortex_error::vortex_panic; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; pub(crate) use self::bool::accumulate_bool; pub(crate) use self::constant::multiply_constant; @@ -73,14 +75,24 @@ pub fn sum(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { #[derive(Clone, Debug)] pub struct Sum; -pub use vortex_array::aggregate_fn::stat_aggregates::sum_decimal_dtype; +// Both Spark and DataFusion use this heuristic. +// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 +// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 +/// Returns the decimal dtype a sum over `input` widens to. +pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { + DecimalDType::new( + u8::min(MAX_PRECISION, input.precision() + 10), + input.scale(), + ) +} impl AggregateFnVTable for Sum { type Options = NumericalAggregateOpts; type Partial = SumPartial; fn id(&self) -> AggregateFnId { - *stat_aggregates::SUM_ID + static ID: CachedId = CachedId::new("vortex.sum"); + *ID } fn serialize(&self, options: &Self::Options) -> VortexResult>> { @@ -96,7 +108,7 @@ impl AggregateFnVTable for Sum { } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - stat_aggregates::sum_return_dtype(input_dtype) + Stat::Sum.dtype(input_dtype) } fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { diff --git a/vortex-aggregates/src/framework_tests/accumulator.rs b/vortex-aggregates/src/tests/accumulator.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/accumulator.rs rename to vortex-aggregates/src/tests/accumulator.rs diff --git a/vortex-aggregates/src/framework_tests/chunked_kernel.rs b/vortex-aggregates/src/tests/chunked_kernel.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/chunked_kernel.rs rename to vortex-aggregates/src/tests/chunked_kernel.rs diff --git a/vortex-aggregates/src/combined_tests.rs b/vortex-aggregates/src/tests/combined.rs similarity index 100% rename from vortex-aggregates/src/combined_tests.rs rename to vortex-aggregates/src/tests/combined.rs diff --git a/vortex-aggregates/src/framework_tests/core_consistency.rs b/vortex-aggregates/src/tests/core_consistency.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/core_consistency.rs rename to vortex-aggregates/src/tests/core_consistency.rs diff --git a/vortex-aggregates/src/framework_tests/extension_validation.rs b/vortex-aggregates/src/tests/extension_validation.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/extension_validation.rs rename to vortex-aggregates/src/tests/extension_validation.rs diff --git a/vortex-aggregates/src/grouped_tests.rs b/vortex-aggregates/src/tests/grouped.rs similarity index 100% rename from vortex-aggregates/src/grouped_tests.rs rename to vortex-aggregates/src/tests/grouped.rs diff --git a/vortex-aggregates/src/framework_tests/listview_is_constant.rs b/vortex-aggregates/src/tests/listview_is_constant.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/listview_is_constant.rs rename to vortex-aggregates/src/tests/listview_is_constant.rs diff --git a/vortex-aggregates/src/framework_tests/mod.rs b/vortex-aggregates/src/tests/mod.rs similarity index 76% rename from vortex-aggregates/src/framework_tests/mod.rs rename to vortex-aggregates/src/tests/mod.rs index 6c27515bd17..3772111f30c 100644 --- a/vortex-aggregates/src/framework_tests/mod.rs +++ b/vortex-aggregates/src/tests/mod.rs @@ -1,12 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Tests of the `vortex_array::aggregate_fn` framework that need concrete aggregate functions. +//! Aggregate framework and cross-encoding tests. mod accumulator; mod chunked_kernel; +mod combined; mod core_consistency; mod extension_validation; +mod grouped; mod listview_is_constant; mod proto; mod stats; diff --git a/vortex-aggregates/src/framework_tests/proto.rs b/vortex-aggregates/src/tests/proto.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/proto.rs rename to vortex-aggregates/src/tests/proto.rs diff --git a/vortex-aggregates/src/framework_tests/stats.rs b/vortex-aggregates/src/tests/stats.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/stats.rs rename to vortex-aggregates/src/tests/stats.rs diff --git a/vortex-aggregates/src/framework_tests/storage_pushdown.rs b/vortex-aggregates/src/tests/storage_pushdown.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/storage_pushdown.rs rename to vortex-aggregates/src/tests/storage_pushdown.rs diff --git a/vortex-aggregates/src/framework_tests/struct_is_constant.rs b/vortex-aggregates/src/tests/struct_is_constant.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/struct_is_constant.rs rename to vortex-aggregates/src/tests/struct_is_constant.rs diff --git a/vortex-aggregates/src/framework_tests/union_uncompressed_size.rs b/vortex-aggregates/src/tests/union_uncompressed_size.rs similarity index 100% rename from vortex-aggregates/src/framework_tests/union_uncompressed_size.rs rename to vortex-aggregates/src/tests/union_uncompressed_size.rs diff --git a/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs index 4829ffdd49b..0a2d549f422 100644 --- a/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs +++ b/vortex-aggregates/src/uncompressed_size_in_bytes/mod.rs @@ -36,8 +36,6 @@ use vortex_array::aggregate_fn::AggregateFnId; use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::EmptyOptions; -use vortex_array::aggregate_fn::stat_aggregates; -use vortex_array::aggregate_fn::stat_aggregates::supports_uncompressed_size_in_bytes; use vortex_array::arrays::Constant; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::ListView; @@ -45,7 +43,6 @@ use vortex_array::arrays::map::MapArraySlotsExt; use vortex_array::arrays::varbinview::BinaryView; use vortex_array::dtype::DType; use vortex_array::dtype::Nullability::NonNullable; -use vortex_array::dtype::PType; use vortex_array::scalar::Scalar; use vortex_array::stats::Precision; use vortex_array::stats::Stat; @@ -56,6 +53,7 @@ use vortex_error::vortex_bail; use vortex_error::vortex_err; use vortex_mask::Mask; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; /// Return the uncompressed size of an array in bytes. /// @@ -103,7 +101,7 @@ pub struct UncompressedSizeInBytes; impl UncompressedSizeInBytes { /// Whether arrays of `dtype` can be measured. Variant arrays cannot. pub fn supports_dtype(dtype: &DType) -> bool { - supports_uncompressed_size_in_bytes(dtype) + Stat::UncompressedSizeInBytes.dtype(dtype).is_some() } } @@ -112,7 +110,8 @@ impl AggregateFnVTable for UncompressedSizeInBytes { type Partial = u64; fn id(&self) -> AggregateFnId { - *stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID + static ID: CachedId = CachedId::new("vortex.uncompressed_size_in_bytes"); + *ID } fn serialize(&self, _options: &Self::Options) -> VortexResult>> { @@ -128,8 +127,7 @@ impl AggregateFnVTable for UncompressedSizeInBytes { } fn return_dtype(&self, _options: &Self::Options, input_dtype: &DType) -> Option { - supports_uncompressed_size_in_bytes(input_dtype) - .then_some(DType::Primitive(PType::U64, NonNullable)) + Stat::UncompressedSizeInBytes.dtype(input_dtype) } fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option { diff --git a/vortex-array/src/aggregate_fn/mod.rs b/vortex-array/src/aggregate_fn/mod.rs index 781092d917f..0d99dd36e22 100644 --- a/vortex-array/src/aggregate_fn/mod.rs +++ b/vortex-array/src/aggregate_fn/mod.rs @@ -42,7 +42,6 @@ pub mod fns; pub mod kernels; pub mod proto; pub mod session; -pub mod stat_aggregates; /// A unique identifier for an aggregate function. pub type AggregateFnId = Id; diff --git a/vortex-array/src/aggregate_fn/stat_aggregates.rs b/vortex-array/src/aggregate_fn/stat_aggregates.rs deleted file mode 100644 index 703b0470871..00000000000 --- a/vortex-array/src/aggregate_fn/stat_aggregates.rs +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright the Vortex contributors - -//! Identifiers and options of the aggregate functions that back array statistics. -//! -//! [`Stat`](crate::stats::Stat) names each of these aggregates by ID and options, and -//! array statistics are computed by resolving them through the session's -//! [`AggregateFnSession`](crate::aggregate_fn::session::AggregateFnSession). The -//! implementations themselves can therefore be registered from any crate. - -use std::fmt; -use std::fmt::Display; -use std::fmt::Formatter; - -use vortex_error::VortexResult; -use vortex_error::vortex_bail; -use vortex_session::registry::CachedId; - -use crate::dtype::DType; -use crate::dtype::DecimalDType; -use crate::dtype::MAX_PRECISION; -use crate::dtype::Nullability; -use crate::dtype::PType; - -/// ID of the aggregate computing the minimum, the `Min` statistic. -pub static MIN_ID: CachedId = CachedId::new("vortex.min"); -/// ID of the aggregate computing the minimum and maximum together, the `Min` and `Max` statistics -/// in one pass. -pub static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); -/// ID of the aggregate computing the maximum, the `Max` statistic. -pub static MAX_ID: CachedId = CachedId::new("vortex.max"); -/// ID of the aggregate computing the sum, the `Sum` statistic. -pub static SUM_ID: CachedId = CachedId::new("vortex.sum"); -/// ID of the aggregate counting nulls, the `NullCount` statistic. -pub static NULL_COUNT_ID: CachedId = CachedId::new("vortex.null_count"); -/// ID of the aggregate counting NaN values, the `NaNCount` statistic. -pub static NAN_COUNT_ID: CachedId = CachedId::new("vortex.nan_count"); -/// ID of the aggregate measuring uncompressed size, the `UncompressedSizeInBytes` statistic. -pub static UNCOMPRESSED_SIZE_IN_BYTES_ID: CachedId = - CachedId::new("vortex.uncompressed_size_in_bytes"); -/// ID of the aggregate checking constancy, the `IsConstant` statistic. -pub static IS_CONSTANT_ID: CachedId = CachedId::new("vortex.is_constant"); -/// ID of the aggregate checking sortedness, the `IsSorted` and `IsStrictSorted` statistics. -pub static IS_SORTED_ID: CachedId = CachedId::new("vortex.is_sorted"); -/// ID of the aggregate checking that every value is null. -pub static ALL_NULL_ID: CachedId = CachedId::new("vortex.all_null"); -/// ID of the aggregate checking that no value is null. -pub static ALL_NON_NULL_ID: CachedId = CachedId::new("vortex.all_non_null"); -/// ID of the aggregate checking that every value is NaN. -pub static ALL_NAN_ID: CachedId = CachedId::new("vortex.all_nan"); -/// ID of the aggregate checking that no value is NaN. -pub static ALL_NON_NAN_ID: CachedId = CachedId::new("vortex.all_non_nan"); - -/// Options for the `is_sorted` aggregate function. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct IsSortedOptions { - /// If true, check for strictly ascending order (no duplicates). - pub strict: bool, -} - -impl IsSortedOptions { - /// Serialize these options to metadata bytes: one byte, `1` for strict and `0` otherwise. - pub fn serialize(&self) -> Vec { - vec![u8::from(self.strict)] - } - - /// Deserialize these options from metadata bytes written by [`IsSortedOptions::serialize`]. - pub fn deserialize(metadata: &[u8]) -> VortexResult { - match metadata { - [0] => Ok(Self { strict: false }), - [1] => Ok(Self { strict: true }), - _ => vortex_bail!("invalid is_sorted options metadata {metadata:?}"), - } - } -} - -impl Display for IsSortedOptions { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - write!(f, "strict={}", self.strict) - } -} - -/// The return dtype of the `vortex.sum` aggregate over `input_dtype`, or `None` if summing that -/// dtype is unsupported. -/// -/// A sum that overflows is null, so every result dtype is nullable. -pub fn sum_return_dtype(input_dtype: &DType) -> Option { - use Nullability::Nullable; - - Some(match input_dtype { - DType::Bool(_) => DType::Primitive(PType::U64, Nullable), - DType::Primitive(ptype, _) => match ptype { - PType::U8 | PType::U16 | PType::U32 | PType::U64 => { - DType::Primitive(PType::U64, Nullable) - } - PType::I8 | PType::I16 | PType::I32 | PType::I64 => { - DType::Primitive(PType::I64, Nullable) - } - // Float sums cannot overflow, but all-null floats still sum to null. - PType::F16 | PType::F32 | PType::F64 => DType::Primitive(PType::F64, Nullable), - }, - DType::Decimal(decimal_dtype, _) => { - DType::Decimal(sum_decimal_dtype(decimal_dtype), Nullable) - } - _ => return None, - }) -} - -// Both Spark and DataFusion use this heuristic. -// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 -// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 -/// Returns the decimal dtype a sum over `input` widens to. -pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { - DecimalDType::new( - u8::min(MAX_PRECISION, input.precision() + 10), - input.scale(), - ) -} - -/// Whether the uncompressed size of an array of `dtype` can be measured. -pub fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { - match dtype { - DType::FixedSizeBinary(..) => false, - DType::Null - | DType::Bool(_) - | DType::Primitive(..) - | DType::Decimal(..) - | DType::Utf8(_) - | DType::Binary(_) => true, - DType::List(element_dtype, _) | DType::FixedSizeList(element_dtype, ..) => { - supports_uncompressed_size_in_bytes(element_dtype) - } - DType::Map(map_dtype, _) => { - supports_uncompressed_size_in_bytes(&map_dtype.key_dtype()) - && supports_uncompressed_size_in_bytes(&map_dtype.value_dtype()) - } - DType::Struct(fields, _) => fields - .fields() - .all(|field| supports_uncompressed_size_in_bytes(&field)), - DType::Union(variants, _) => variants - .variants() - .all(|variant| supports_uncompressed_size_in_bytes(&variant)), - DType::Variant(_) => false, - DType::Extension(ext_dtype) => { - supports_uncompressed_size_in_bytes(ext_dtype.storage_dtype()) - } - } -} - -/// Whether `dtype` can hold NaN values: floats, and extension types stored as floats. -pub fn has_nan_values(dtype: &DType) -> bool { - match dtype { - DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()), - _ => dtype.is_float(), - } -} diff --git a/vortex-array/src/aggregate_fn/storage_pushdown.rs b/vortex-array/src/aggregate_fn/storage_pushdown.rs index ab07efbf3c6..402ff1d4bc8 100644 --- a/vortex-array/src/aggregate_fn/storage_pushdown.rs +++ b/vortex-array/src/aggregate_fn/storage_pushdown.rs @@ -64,8 +64,50 @@ use crate::scalar::Scalar; /// /// # Example /// -/// `vortex_aggregates::register_storage_ordered` registers the `is_sorted` and `min_max` aggregates -/// this way for the temporal extension types. +/// Timestamps compare like their `i64` storage, so `is_sorted` can be pushed down. Register the +/// pair once on the session, then bind it like any other aggregate: +/// +/// ``` +/// # use vortex_aggregates::is_sorted::IsSorted; +/// # use vortex_aggregates::is_sorted::IsSortedOptions; +/// # use vortex_array::IntoArray; +/// # use vortex_session::VortexSession; +/// # use vortex_array::VortexSessionExecute; +/// # use vortex_array::aggregate_fn::Accumulator; +/// # use vortex_array::aggregate_fn::DynAccumulator; +/// # use vortex_array::aggregate_fn::ExtensionStoragePushdown; +/// # use vortex_array::aggregate_fn::session::AggregateFnSessionExt; +/// # use vortex_array::arrays::ExtensionArray; +/// # use vortex_array::arrays::PrimitiveArray; +/// # use vortex_array::dtype::DType; +/// # use vortex_array::dtype::Nullability; +/// # use vortex_array::extension::datetime::TimeUnit; +/// # use vortex_array::extension::datetime::Timestamp; +/// # fn main() -> vortex_error::VortexResult<()> { +/// let session = VortexSession::empty(); +/// +/// // Register `vortex.is_sorted[vortex.timestamp]`. +/// let is_sorted = ExtensionStoragePushdown::new(IsSorted, Timestamp); +/// session.aggregate_fns().register(is_sorted.clone()); +/// +/// // Aggregate a timestamp column through its storage. +/// let ext_dtype = Timestamp::new(TimeUnit::Milliseconds, Nullability::NonNullable).erased(); +/// let column = ExtensionArray::new( +/// ext_dtype.clone(), +/// PrimitiveArray::from_iter([1_000i64, 2_000, 3_000]).into_array(), +/// ) +/// .into_array(); +/// +/// let mut acc = Accumulator::try_new( +/// is_sorted, +/// IsSortedOptions { strict: true }, +/// DType::Extension(ext_dtype), +/// )?; +/// acc.accumulate(&column, &mut session.create_execution_ctx())?; +/// assert!(bool::try_from(&acc.finish()?)?); +/// # Ok(()) +/// # } +/// ``` #[derive(Clone, Debug)] pub struct ExtensionStoragePushdown { aggregate: A, diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index a36474d6e7e..31e10f2044b 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -14,13 +14,13 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; +use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::ExecutionCtx; use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::NumericalAggregateOpts; use crate::aggregate_fn::session::AggregateFnSessionExt; -use crate::aggregate_fn::stat_aggregates; use crate::arrays::PrimitiveArray; use crate::arrays::primitive::PrimitiveArrayExt; use crate::match_each_integer_ptype; @@ -143,11 +143,9 @@ fn ensure_int(array: &ArrayRef) -> VortexResult<()> { /// Resolves the `min_max` aggregate, skipping NaNs like the `Min` and `Max` statistics, if the /// session registers one. fn resolve_min_max(ctx: &ExecutionCtx) -> VortexResult> { + static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); let session = ctx.session(); - let Some(plugin) = session - .aggregate_fns() - .find_plugin(&stat_aggregates::MIN_MAX_ID) - else { + let Some(plugin) = session.aggregate_fns().find_plugin(&MIN_MAX_ID) else { return Ok(None); }; plugin diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index b6e279367c7..fc399054010 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -11,15 +11,17 @@ use num_enum::IntoPrimitive; use num_enum::TryFromPrimitive; use vortex_error::VortexResult; use vortex_session::VortexSession; +use vortex_session::registry::CachedId; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::NumericalAggregateOpts; use crate::aggregate_fn::session::AggregateFnSessionExt; -use crate::aggregate_fn::stat_aggregates; -use crate::aggregate_fn::stat_aggregates::IsSortedOptions; use crate::dtype::DType; +use crate::dtype::DecimalDType; +use crate::dtype::MAX_PRECISION; use crate::dtype::Nullability::NonNullable; +use crate::dtype::Nullability::Nullable; use crate::dtype::PType; use crate::stats::LowerBound; use crate::stats::Precision; @@ -172,39 +174,50 @@ impl Stat { Self::Min => data_type.clone(), Self::NullCount => DType::Primitive(PType::U64, NonNullable), Self::UncompressedSizeInBytes => { - return stat_aggregates::supports_uncompressed_size_in_bytes(data_type) + return supports_uncompressed_size_in_bytes(data_type) .then_some(DType::Primitive(PType::U64, NonNullable)); } Self::NaNCount => { return matches!(data_type, DType::Primitive(ptype, _) if ptype.is_float()) .then_some(DType::Primitive(PType::U64, NonNullable)); } - Self::Sum => return stat_aggregates::sum_return_dtype(data_type), + Self::Sum => return sum_return_dtype(data_type), }) } /// The ID of the aggregate function that computes this statistic. pub fn aggregate_fn_id(&self) -> AggregateFnId { + static IS_CONSTANT_ID: CachedId = CachedId::new("vortex.is_constant"); + static IS_SORTED_ID: CachedId = CachedId::new("vortex.is_sorted"); + static MAX_ID: CachedId = CachedId::new("vortex.max"); + static MIN_ID: CachedId = CachedId::new("vortex.min"); + static NULL_COUNT_ID: CachedId = CachedId::new("vortex.null_count"); + static UNCOMPRESSED_SIZE_IN_BYTES_ID: CachedId = + CachedId::new("vortex.uncompressed_size_in_bytes"); + static SUM_ID: CachedId = CachedId::new("vortex.sum"); + static NAN_COUNT_ID: CachedId = CachedId::new("vortex.nan_count"); + **match self { - Self::IsConstant => &stat_aggregates::IS_CONSTANT_ID, - Self::IsSorted | Self::IsStrictSorted => &stat_aggregates::IS_SORTED_ID, - Self::Max => &stat_aggregates::MAX_ID, - Self::Min => &stat_aggregates::MIN_ID, - Self::NullCount => &stat_aggregates::NULL_COUNT_ID, - Self::UncompressedSizeInBytes => &stat_aggregates::UNCOMPRESSED_SIZE_IN_BYTES_ID, - Self::Sum => &stat_aggregates::SUM_ID, - Self::NaNCount => &stat_aggregates::NAN_COUNT_ID, + Self::IsConstant => &IS_CONSTANT_ID, + Self::IsSorted | Self::IsStrictSorted => &IS_SORTED_ID, + Self::Max => &MAX_ID, + Self::Min => &MIN_ID, + Self::NullCount => &NULL_COUNT_ID, + Self::UncompressedSizeInBytes => &UNCOMPRESSED_SIZE_IN_BYTES_ID, + Self::Sum => &SUM_ID, + Self::NaNCount => &NAN_COUNT_ID, } } /// The serialized options the aggregate function computing this statistic is bound to. /// - /// Min/max/sum statistics skip NaN values. + /// Min/max/sum statistics skip NaN values, and `vortex.is_sorted` encodes `strict` as a single + /// `0`/`1` byte. pub fn aggregate_fn_options(&self) -> Vec { match self { Self::Max | Self::Min | Self::Sum => NumericalAggregateOpts::skip_nans().serialize(), - Self::IsSorted => IsSortedOptions { strict: false }.serialize(), - Self::IsStrictSorted => IsSortedOptions { strict: true }.serialize(), + Self::IsSorted => vec![0], + Self::IsStrictSorted => vec![1], Self::IsConstant | Self::NullCount | Self::NaNCount | Self::UncompressedSizeInBytes => { vec![] } @@ -272,6 +285,59 @@ impl Display for Stat { } } +fn sum_return_dtype(input_dtype: &DType) -> Option { + Some(match input_dtype { + DType::Bool(_) => DType::Primitive(PType::U64, Nullable), + DType::Primitive(ptype, _) => match ptype { + PType::U8 | PType::U16 | PType::U32 | PType::U64 => { + DType::Primitive(PType::U64, Nullable) + } + PType::I8 | PType::I16 | PType::I32 | PType::I64 => { + DType::Primitive(PType::I64, Nullable) + } + // Float sums cannot overflow, but all-null floats still sum to null. + PType::F16 | PType::F32 | PType::F64 => DType::Primitive(PType::F64, Nullable), + }, + DType::Decimal(decimal_dtype, _) => DType::Decimal( + DecimalDType::new( + u8::min(MAX_PRECISION, decimal_dtype.precision() + 10), + decimal_dtype.scale(), + ), + Nullable, + ), + _ => return None, + }) +} + +fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { + match dtype { + DType::FixedSizeBinary(..) => false, + DType::Null + | DType::Bool(_) + | DType::Primitive(..) + | DType::Decimal(..) + | DType::Utf8(_) + | DType::Binary(_) => true, + DType::List(element_dtype, _) | DType::FixedSizeList(element_dtype, ..) => { + supports_uncompressed_size_in_bytes(element_dtype) + } + DType::Map(map_dtype, _) => { + supports_uncompressed_size_in_bytes(&map_dtype.key_dtype()) + && supports_uncompressed_size_in_bytes(&map_dtype.value_dtype()) + } + DType::Struct(fields, _) => fields + .fields() + .all(|field| supports_uncompressed_size_in_bytes(&field)), + DType::Union(variants, _) => variants + .variants() + .all(|variant| supports_uncompressed_size_in_bytes(&variant)), + DType::Variant(_) => false, + DType::Extension(ext_dtype) => { + supports_uncompressed_size_in_bytes(ext_dtype.storage_dtype()) + } + } +} + #[cfg(test)] mod test { use std::sync::LazyLock; diff --git a/vortex-array/src/stats/stats_set.rs b/vortex-array/src/stats/stats_set.rs index 92c8e9a15f1..8ed89171bdc 100644 --- a/vortex-array/src/stats/stats_set.rs +++ b/vortex-array/src/stats/stats_set.rs @@ -14,7 +14,6 @@ use vortex_error::VortexResult; use vortex_error::vortex_err; use vortex_error::vortex_panic; -use crate::aggregate_fn::stat_aggregates::has_nan_values; use crate::dtype::DType; use crate::scalar::Scalar; use crate::scalar::ScalarValue; @@ -617,6 +616,13 @@ impl MutTypedStatsSetRef<'_, '_> { } } +fn has_nan_values(dtype: &DType) -> bool { + match dtype { + DType::Extension(ext_dtype) => has_nan_values(ext_dtype.storage_dtype()), + _ => dtype.is_float(), + } +} + #[cfg(test)] mod test { @@ -624,7 +630,7 @@ mod test { use smallvec::smallvec; use vortex_error::VortexResult; - use crate::aggregate_fn::stat_aggregates::has_nan_values; + use super::has_nan_values; use crate::dtype::DType; use crate::dtype::DecimalDType; use crate::dtype::MAX_PRECISION; diff --git a/vortex-expr/src/stats/stat_fn.rs b/vortex-expr/src/stats/stat_fn.rs index 009615ce112..7b55ab23993 100644 --- a/vortex-expr/src/stats/stat_fn.rs +++ b/vortex-expr/src/stats/stat_fn.rs @@ -6,11 +6,14 @@ use std::fmt::Display; use std::fmt::Formatter; +use vortex_aggregates::all_nan::AllNan; +use vortex_aggregates::all_non_nan::AllNonNan; +use vortex_aggregates::all_non_null::AllNonNull; +use vortex_aggregates::all_null::AllNull; use vortex_array::ArrayRef; use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::aggregate_fn::AggregateFnRef; -use vortex_array::aggregate_fn::stat_aggregates; use vortex_array::arrays::ConstantArray; use vortex_array::dtype::DType; use vortex_array::kernel::SupportsFn; @@ -150,7 +153,7 @@ fn stat_array( dtype: DType, len: usize, ) -> VortexResult { - let value = if aggregate_fn.id() == *stat_aggregates::ALL_NULL_ID { + let value = if aggregate_fn.is::() { let len = u64::try_from(len)?; match array.statistics().get_as::(Stat::NullCount) { Precision::Exact(count) => Some(count == len), @@ -158,14 +161,14 @@ fn stat_array( Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.id() == *stat_aggregates::ALL_NON_NULL_ID { + } else if aggregate_fn.is::() { match array.statistics().get_as::(Stat::NullCount) { Precision::Exact(count) => Some(count == 0), Precision::Inexact(0) => Some(true), Precision::Inexact(_) | Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.id() == *stat_aggregates::ALL_NAN_ID { + } else if aggregate_fn.is::() { let len = u64::try_from(len)?; match array.statistics().get_as::(Stat::NaNCount) { Precision::Exact(count) => Some(count == len), @@ -173,7 +176,7 @@ fn stat_array( Precision::Absent => None, } .map(ScalarValue::Bool) - } else if aggregate_fn.id() == *stat_aggregates::ALL_NON_NAN_ID { + } else if aggregate_fn.is::() { match array.statistics().get_as::(Stat::NaNCount) { Precision::Exact(count) => Some(count == 0), Precision::Inexact(0) => Some(true), From 6e8397b15a6366d6267a7620100a687c77fb939c Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 1 Dec 2026 16:39:33 +0000 Subject: [PATCH 15/27] Cache resolved stat aggregates and fast-path bitmap valid_count - Cache bound stat aggregate functions in AggregateFnSession so compute_stat and integer_bounds do not serialize and deserialize protobuf options or re-allocate AggregateFnRef and AggregateDTypes on every uncached lookup. - Add AggregateFnRef::aggregate to run single-array aggregations on the stack without boxing DynAccumulator, and avoid protobuf serialization in Stat::from_aggregate_fn for built-in option types. - Count canonical host BoolArray validities directly in ArrayRef::valid_count while caching Stat::Sum, addressing the null_count_run_end and sparse_null_count benchmark regressions. - Cover RunEnd and Widen in core_encodings_aggregate_consistency. Signed-off-by: Robert Kruszewski --- .../src/tests/core_consistency.rs | 22 ++++++++- vortex-aggregates/src/tests/stats.rs | 29 ++++++++++++ vortex-array/src/aggregate_fn/accumulator.rs | 9 ++++ vortex-array/src/aggregate_fn/erased.rs | 10 +++- vortex-array/src/aggregate_fn/session.rs | 38 +++++++++++++++ vortex-array/src/aggregate_fn/typed.rs | 41 +++++++++++++++-- vortex-array/src/aggregate_fn/vtable.rs | 8 ++++ vortex-array/src/array/erased.rs | 34 ++++++++++---- .../src/arrays/primitive/integer_bounds.rs | 15 +++--- vortex-array/src/stats/array.rs | 4 +- vortex-array/src/stats/stat.rs | 46 ++++++++++++++----- 11 files changed, 218 insertions(+), 38 deletions(-) diff --git a/vortex-aggregates/src/tests/core_consistency.rs b/vortex-aggregates/src/tests/core_consistency.rs index 38f4ede76b0..ceb9b0ac191 100644 --- a/vortex-aggregates/src/tests/core_consistency.rs +++ b/vortex-aggregates/src/tests/core_consistency.rs @@ -16,8 +16,12 @@ use vortex_array::arrays::ChunkedArray; use vortex_array::arrays::ConstantArray; use vortex_array::arrays::DictArray; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::WidenArray; +use vortex_array::arrays::runend::RunEnd; use vortex_array::compute::conformance::consistency::test_slice_aggregate_consistency; +use vortex_array::dtype::PType; use vortex_buffer::buffer; +use vortex_error::VortexResult; use vortex_session::VortexSession; static SESSION: LazyLock = LazyLock::new(|| { @@ -48,6 +52,22 @@ static SESSION: LazyLock = LazyLock::new(|| { ]) .into_array() )] -fn core_encodings_aggregate_consistency(#[case] array: ArrayRef) { +#[case::runend( + RunEnd::try_new( + buffer![2u32, 5, 7].into_array(), + buffer![10i32, -3, 42].into_array(), + &mut SESSION.create_execution_ctx(), + )? + .into_array() +)] +#[case::widen( + WidenArray::try_new( + buffer![10i8, -3, 42, 7, -1, 0, 15].into_array(), + PType::I32.into(), + )? + .into_array() +)] +fn core_encodings_aggregate_consistency(#[case] array: ArrayRef) -> VortexResult<()> { test_slice_aggregate_consistency(&array, &mut SESSION.create_execution_ctx()); + Ok(()) } diff --git a/vortex-aggregates/src/tests/stats.rs b/vortex-aggregates/src/tests/stats.rs index 24a629e3bdd..d0d3ffefa67 100644 --- a/vortex-aggregates/src/tests/stats.rs +++ b/vortex-aggregates/src/tests/stats.rs @@ -22,8 +22,11 @@ use vortex_array::dtype::PType; use vortex_array::scalar::ScalarValue; use vortex_array::stats::Precision; use vortex_array::stats::Stat; +use vortex_array::stats::StatsProviderExt; use vortex_array::validity::Validity; +use vortex_error::VortexExpect; use vortex_error::VortexResult; +use vortex_error::vortex_bail; use vortex_session::VortexSession; static SESSION: LazyLock = LazyLock::new(|| { @@ -132,3 +135,29 @@ fn merge_sortedness_computed_chunks( assert_eq!(merged.get(Stat::IsSorted), expected); Ok(()) } + +#[test] +fn valid_count_caches_sum_on_bool_validity() -> VortexResult<()> { + let array = PrimitiveArray::from_option_iter([Some(10i32), None, Some(20), Some(30), None]) + .into_array(); + let mut ctx = VortexSession::empty().create_execution_ctx(); + assert_eq!(array.valid_count(&mut ctx)?, 3); + assert_eq!(array.invalid_count(&mut ctx)?, 2); + + let Validity::Array(validity) = array.validity()? else { + vortex_bail!("expected array-backed validity"); + }; + assert_eq!( + validity.statistics().get_as::(Stat::Sum), + Precision::exact(3u64) + ); + + let first = Stat::Sum + .resolve_aggregate_fn(&SESSION)? + .vortex_expect("Sum registered"); + let second = Stat::Sum + .resolve_aggregate_fn(&SESSION)? + .vortex_expect("Sum registered"); + assert_eq!(first, second); + Ok(()) +} diff --git a/vortex-array/src/aggregate_fn/accumulator.rs b/vortex-array/src/aggregate_fn/accumulator.rs index 1eb483f6989..ecc8cde6b2a 100644 --- a/vortex-array/src/aggregate_fn/accumulator.rs +++ b/vortex-array/src/aggregate_fn/accumulator.rs @@ -53,7 +53,16 @@ impl Accumulator { /// them again for every batch. pub fn from_dtypes(vtable: V, options: V::Options, dtypes: AggregateDTypes) -> Self { let aggregate_fn = AggregateFn::new(vtable.clone(), options.clone()).erased(); + Self::from_bound(vtable, options, aggregate_fn, dtypes) + } + /// Build an accumulator reusing an already-bound [`AggregateFnRef`]. + pub(super) fn from_bound( + vtable: V, + options: V::Options, + aggregate_fn: AggregateFnRef, + dtypes: AggregateDTypes, + ) -> Self { Self { vtable, options, diff --git a/vortex-array/src/aggregate_fn/erased.rs b/vortex-array/src/aggregate_fn/erased.rs index c512ea81b7e..acfd13b568e 100644 --- a/vortex-array/src/aggregate_fn/erased.rs +++ b/vortex-array/src/aggregate_fn/erased.rs @@ -14,6 +14,8 @@ use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_utils::debug_with::DebugWith; +use crate::ArrayRef; +use crate::ExecutionCtx; use crate::aggregate_fn::AccumulatorRef; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnSatisfaction; @@ -23,6 +25,7 @@ use crate::aggregate_fn::options::AggregateFnOptions; use crate::aggregate_fn::typed::AggregateFnInner; use crate::aggregate_fn::typed::DynAggregateFn; use crate::dtype::DType; +use crate::scalar::Scalar; /// A type-erased aggregate function, pairing a vtable with bound options behind a trait object. /// @@ -96,7 +99,12 @@ impl AggregateFnRef { /// Create an accumulator for streaming aggregation. pub fn accumulator(&self, input_dtype: &DType) -> VortexResult { - self.0.accumulator(input_dtype) + self.0.accumulator(self, input_dtype) + } + + /// Compute the aggregate over a single array without boxing an accumulator. + pub fn aggregate(&self, array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { + self.0.aggregate(self, array, ctx) } /// Create a grouped accumulator for grouped streaming aggregation. diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 959d9a4b7b8..1e53c92df84 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -4,14 +4,17 @@ use std::any::Any; use std::sync::Arc; +use vortex_error::VortexResult; use vortex_session::ArcSwapMap; use vortex_session::SessionExt; use vortex_session::SessionGuard; use vortex_session::SessionVar; +use vortex_session::VortexSession; use vortex_utils::aliases::hash_map::HashMap; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnPluginRef; +use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::AggregateFnVTable; use crate::aggregate_fn::fns::all_non_distinct::AllNonDistinct; use crate::aggregate_fn::kernels::DynAggregateKernel; @@ -29,6 +32,7 @@ use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate; #[derive(Clone, Debug)] pub struct AggregateFnSession { registry: AggregateFnRegistry, + bound_fns: BoundAggregateFnCache, kernels: AggregateKernelRegistry, grouped_kernels: GroupedKernelRegistry, @@ -47,9 +51,14 @@ impl SessionVar for AggregateFnSession { type AggregateKernelKey = (ArrayId, Option); type GroupedEncodingKernelKey = (ArrayId, AggregateFnId); +type BoundAggregateFnKey = (AggregateFnId, &'static [u8]); /// Registry of aggregate function plugins, keyed by aggregate function id. type AggregateFnRegistry = ArcSwapMap; +/// Cache of bound aggregate functions resolved from static option bytes, paired with the plugin +/// instance they were deserialized from so re-registering an ID invalidates the entry. +type BoundAggregateFnCache = + ArcSwapMap; /// Registry of aggregate kernels, keyed by encoding and optional aggregate function. type AggregateKernelRegistry = ArcSwapMap; /// Registry of encoding-agnostic grouped aggregate kernels, keyed by aggregate function id. @@ -62,6 +71,7 @@ impl Default for AggregateFnSession { fn default() -> Self { let this = Self { registry: AggregateFnRegistry::default(), + bound_fns: BoundAggregateFnCache::default(), kernels: AggregateKernelRegistry::default(), grouped_kernels: GroupedKernelRegistry::default(), grouped_encoding_kernels: GroupedEncodingKernelRegistry::default(), @@ -83,6 +93,34 @@ impl AggregateFnSession { self.registry.get(id) } + /// Resolves and caches the bound [`AggregateFnRef`] for `(id, options)` from the currently + /// registered plugin. + pub(crate) fn resolve_bound( + &self, + id: AggregateFnId, + options: &'static [u8], + session: &VortexSession, + ) -> VortexResult> { + let key = (id, options); + if let Some((cached, bound_fn)) = self.bound_fns.get(&key) + && self.is_current_plugin(id, &cached) + { + return Ok(Some(bound_fn)); + } + + let Some(plugin) = self.find_plugin(&id) else { + return Ok(None); + }; + let bound_fn = plugin.deserialize(options, session)?; + self.bound_fns.insert(key, (plugin, bound_fn.clone())); + Ok(Some(bound_fn)) + } + + fn is_current_plugin(&self, id: AggregateFnId, cur: &AggregateFnPluginRef) -> bool { + self.registry + .read(|r| r.get(&id).is_some_and(|p| Arc::ptr_eq(p, cur))) + } + /// Register an aggregate function vtable in the session, replacing any existing vtable with /// the same ID. pub fn register(&self, vtable: V) { diff --git a/vortex-array/src/aggregate_fn/typed.rs b/vortex-array/src/aggregate_fn/typed.rs index f5a3e8e5d84..4a63ca40bc9 100644 --- a/vortex-array/src/aggregate_fn/typed.rs +++ b/vortex-array/src/aggregate_fn/typed.rs @@ -21,6 +21,8 @@ use std::sync::OnceLock; use vortex_error::VortexResult; +use crate::ArrayRef; +use crate::ExecutionCtx; use crate::aggregate_fn::Accumulator; use crate::aggregate_fn::AccumulatorRef; use crate::aggregate_fn::AggregateDTypes; @@ -28,9 +30,11 @@ use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::AggregateFnSatisfaction; use crate::aggregate_fn::AggregateFnVTable; +use crate::aggregate_fn::DynAccumulator; use crate::aggregate_fn::GroupedAccumulator; use crate::aggregate_fn::GroupedAccumulatorRef; use crate::dtype::DType; +use crate::scalar::Scalar; /// An object-safe, sealed trait for bound aggregate function dispatch. /// @@ -44,7 +48,17 @@ pub(super) trait DynAggregateFn: 'static + Send + Sync + super::sealed::Sealed { fn can_satisfy(&self, requested: &AggregateFnRef) -> AggregateFnSatisfaction; fn return_dtype(&self, input_dtype: &DType) -> Option; fn state_dtype(&self, input_dtype: &DType) -> Option; - fn accumulator(&self, input_dtype: &DType) -> VortexResult; + fn accumulator( + &self, + self_ref: &AggregateFnRef, + input_dtype: &DType, + ) -> VortexResult; + fn aggregate( + &self, + self_ref: &AggregateFnRef, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult; fn accumulator_grouped(&self, input_dtype: &DType) -> VortexResult; fn options_serialize(&self) -> VortexResult>>; @@ -123,14 +137,35 @@ impl DynAggregateFn for AggregateFnInner { V::partial_dtype(&self.vtable, &self.options, input_dtype) } - fn accumulator(&self, input_dtype: &DType) -> VortexResult { - Ok(Box::new(Accumulator::from_dtypes( + fn accumulator( + &self, + self_ref: &AggregateFnRef, + input_dtype: &DType, + ) -> VortexResult { + Ok(Box::new(Accumulator::from_bound( self.vtable.clone(), self.options.clone(), + self_ref.clone(), self.resolve_dtypes(input_dtype)?, ))) } + fn aggregate( + &self, + self_ref: &AggregateFnRef, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult { + let mut accumulator = Accumulator::from_bound( + self.vtable.clone(), + self.options.clone(), + self_ref.clone(), + self.resolve_dtypes(array.dtype())?, + ); + accumulator.accumulate(array, ctx)?; + accumulator.finish() + } + fn accumulator_grouped(&self, input_dtype: &DType) -> VortexResult { Ok(Box::new(GroupedAccumulator::from_dtypes( self.vtable.clone(), diff --git a/vortex-array/src/aggregate_fn/vtable.rs b/vortex-array/src/aggregate_fn/vtable.rs index 42d0946a0ee..5847ea80840 100644 --- a/vortex-array/src/aggregate_fn/vtable.rs +++ b/vortex-array/src/aggregate_fn/vtable.rs @@ -6,6 +6,7 @@ use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::hash::Hash; +use std::sync::LazyLock; use prost::Message; use vortex_error::VortexResult; @@ -320,6 +321,13 @@ impl NumericalAggregateOpts { .encode_to_vec() } + /// Cached serialized bytes for [`Self::skip_nans`]. + pub(crate) fn skip_nans_bytes() -> &'static [u8] { + static BYTES: LazyLock> = + LazyLock::new(|| NumericalAggregateOpts::skip_nans().serialize()); + &BYTES + } + /// Deserialize these options from protobuf-encoded metadata bytes. pub fn deserialize(metadata: &[u8]) -> VortexResult { let opts = pb::NumericalAggregateOpts::decode(metadata)?; diff --git a/vortex-array/src/array/erased.rs b/vortex-array/src/array/erased.rs index e3e8d87ce2d..cbaaf388604 100644 --- a/vortex-array/src/array/erased.rs +++ b/vortex-array/src/array/erased.rs @@ -37,6 +37,7 @@ use crate::array::ArraySlots; use crate::array::DynArrayData; use crate::array::probe::ArrayProbe; use crate::array::probe::RepeatedArrayProbe; +use crate::arrays::Bool; use crate::arrays::BoolArray; use crate::arrays::Constant; use crate::arrays::DictArray; @@ -385,15 +386,30 @@ impl ArrayRef { Validity::NonNullable | Validity::AllValid => len, Validity::AllInvalid => 0, // The number of valid rows is the number of `true` values in the validity array, which - // its `Sum` statistic gives. Count the bitmap if the session has no `Sum` aggregate. - Validity::Array(a) => match a - .statistics() - .compute_stat(Stat::Sum, ctx)? - .and_then(|sum| sum.as_primitive().as_::()) - { - Some(count) => count, - None => a.execute::(ctx)?.to_bit_buffer().true_count(), - }, + // its `Sum` statistic gives. Count canonical host bitmaps directly and fall back to + // decoding if the session has no `Sum` aggregate. + Validity::Array(a) => { + if let Precision::Exact(count) = a.statistics().get_as::(Stat::Sum) { + count + } else if let Some(bools) = a.as_opt::() + && a.is_host() + && !a.dtype().is_nullable() + { + let count = bools.to_bit_buffer().true_count(); + a.statistics() + .set(Stat::Sum, Precision::exact(count as u64)); + count + } else { + match a + .statistics() + .compute_stat(Stat::Sum, ctx)? + .and_then(|sum| sum.as_primitive().as_::()) + { + Some(count) => count, + None => a.execute::(ctx)?.to_bit_buffer().true_count(), + } + } + } }; vortex_ensure!(count <= len, "Valid count exceeds array length"); diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index 31e10f2044b..661089e113c 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -62,9 +62,7 @@ pub fn integer_bounds( if let Some(min_max) = resolve_min_max(ctx)? && min_max.return_dtype(array.dtype()).is_some() { - let mut accumulator = min_max.accumulator(array.dtype())?; - accumulator.accumulate(array, ctx)?; - let result = accumulator.finish()?; + let result = min_max.aggregate(array, ctx)?; if result.is_null() { return Ok(None); } @@ -145,12 +143,11 @@ fn ensure_int(array: &ArrayRef) -> VortexResult<()> { fn resolve_min_max(ctx: &ExecutionCtx) -> VortexResult> { static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); let session = ctx.session(); - let Some(plugin) = session.aggregate_fns().find_plugin(&MIN_MAX_ID) else { - return Ok(None); - }; - plugin - .deserialize(&NumericalAggregateOpts::skip_nans().serialize(), session) - .map(Some) + session.aggregate_fns().resolve_bound( + *MIN_MAX_ID, + NumericalAggregateOpts::skip_nans_bytes(), + session, + ) } fn bounds_from(array: &ArrayRef, min: &Scalar, max: &Scalar) -> Option { diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 5340cc73f90..5c9cfb79b58 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -290,9 +290,7 @@ impl StatsSetRef<'_> { if aggregate_fn.return_dtype(array.dtype()).is_none() { return Ok(None); } - let mut accumulator = aggregate_fn.accumulator(array.dtype())?; - accumulator.accumulate(array, ctx)?; - let result = accumulator.finish()?; + let result = aggregate_fn.aggregate(array, ctx)?; if result.is_null() { return Ok(None); } diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index fc399054010..ef4dde4b29f 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -15,6 +15,7 @@ use vortex_session::registry::CachedId; use crate::aggregate_fn::AggregateFnId; use crate::aggregate_fn::AggregateFnRef; +use crate::aggregate_fn::EmptyOptions; use crate::aggregate_fn::NumericalAggregateOpts; use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::dtype::DType; @@ -214,12 +215,16 @@ impl Stat { /// Min/max/sum statistics skip NaN values, and `vortex.is_sorted` encodes `strict` as a single /// `0`/`1` byte. pub fn aggregate_fn_options(&self) -> Vec { + self.aggregate_fn_options_slice().to_vec() + } + + fn aggregate_fn_options_slice(&self) -> &'static [u8] { match self { - Self::Max | Self::Min | Self::Sum => NumericalAggregateOpts::skip_nans().serialize(), - Self::IsSorted => vec![0], - Self::IsStrictSorted => vec![1], + Self::Max | Self::Min | Self::Sum => NumericalAggregateOpts::skip_nans_bytes(), + Self::IsSorted => &[0], + Self::IsStrictSorted => &[1], Self::IsConstant | Self::NullCount | Self::NaNCount | Self::UncompressedSizeInBytes => { - vec![] + &[] } } } @@ -231,12 +236,11 @@ impl Stat { &self, session: &VortexSession, ) -> VortexResult> { - let Some(plugin) = session.aggregate_fns().find_plugin(&self.aggregate_fn_id()) else { - return Ok(None); - }; - plugin - .deserialize(&self.aggregate_fn_options(), session) - .map(Some) + session.aggregate_fns().resolve_bound( + self.aggregate_fn_id(), + self.aggregate_fn_options_slice(), + session, + ) } /// Return the statistic represented by `aggregate_fn`, if it has a legacy stat slot. @@ -256,8 +260,26 @@ impl Stat { ] .into_iter() .find(|stat| stat.aggregate_fn_id() == id)?; - let options = aggregate_fn.options().serialize().ok()??; - (options == stat.aggregate_fn_options()).then_some(stat) + let options = aggregate_fn.options(); + let matches_options = match stat { + Self::Min | Self::Max | Self::Sum => { + match options.as_any().downcast_ref::() { + Some(opts) => opts.skip_nans, + None => { + options.serialize().ok()??.as_slice() == stat.aggregate_fn_options_slice() + } + } + } + Self::NullCount | Self::NaNCount | Self::UncompressedSizeInBytes => { + if options.as_any().is::() { + true + } else { + options.serialize().ok()??.as_slice() == stat.aggregate_fn_options_slice() + } + } + Self::IsConstant | Self::IsSorted | Self::IsStrictSorted => unreachable!(), + }; + matches_options.then_some(stat) } pub fn name(&self) -> &str { From 737d728bf5db961bb7bbe4754e02560829290b71 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 18:15:19 +0000 Subject: [PATCH 16/27] Try session min_max aggregate in bool_bounds before decoding Signed-off-by: Will Manning Co-Authored-By: Will Manning --- encodings/sparse/src/compute/min_max.rs | 58 +++++++++++++++++++++++++ vortex-array/src/arrays/bool/bounds.rs | 52 +++++++++++++++++++--- 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/encodings/sparse/src/compute/min_max.rs b/encodings/sparse/src/compute/min_max.rs index 29850b4d251..0f070eb3faf 100644 --- a/encodings/sparse/src/compute/min_max.rs +++ b/encodings/sparse/src/compute/min_max.rs @@ -68,9 +68,15 @@ mod tests { use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::aggregate_fn::NumericalAggregateOpts; + use vortex_array::arrays::BoolArray; + use vortex_array::arrays::bool::BoolBounds; + use vortex_array::arrays::bool::bool_bounds; + use vortex_array::dtype::DType; + use vortex_array::dtype::Nullability; use vortex_array::scalar::Scalar; use vortex_array::session::ArraySessionExt; use vortex_buffer::buffer; + use vortex_error::VortexResult; use vortex_session::VortexSession; use crate::Sparse; @@ -114,4 +120,56 @@ mod tests { .unwrap(); assert_eq!(kernel, canonical); } + + #[test] + fn bool_bounds_via_sparse_min_max() -> VortexResult<()> { + let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); + initialize(&session); + let mut ctx = session.create_execution_ctx(); + + let all_true = Sparse::try_new( + buffer![1u64, 5].into_array(), + BoolArray::from_iter([true, true]).into_array(), + 10, + Scalar::from(true), + &mut ctx, + )? + .into_array(); + assert_eq!( + bool_bounds(&all_true, &mut ctx)?, + Some(BoolBounds { + all_true: true, + any_true: true, + }) + ); + + let mixed = Sparse::try_new( + buffer![3u64].into_array(), + BoolArray::from_iter([false]).into_array(), + 10, + Scalar::from(true), + &mut ctx, + )? + .into_array(); + assert_eq!( + bool_bounds(&mixed, &mut ctx)?, + Some(BoolBounds { + all_true: false, + any_true: true, + }) + ); + + let all_null = Sparse::try_new( + buffer![0u64].into_array(), + BoolArray::from_iter([None::]).into_array(), + 10, + Scalar::null(DType::Bool(Nullability::Nullable)), + &mut ctx, + )? + .into_array(); + assert_eq!(bool_bounds(&all_null, &mut ctx)?, None); + + Ok(()) + } } diff --git a/vortex-array/src/arrays/bool/bounds.rs b/vortex-array/src/arrays/bool/bounds.rs index f79149e3ac0..7f279bb1bd6 100644 --- a/vortex-array/src/arrays/bool/bounds.rs +++ b/vortex-array/src/arrays/bool/bounds.rs @@ -1,18 +1,25 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright the Vortex contributors -//! Whether a boolean array is all true or contains a true value, computed directly from its bits. +//! Whether a boolean array is all true or contains a true value. //! -//! Validity checks need these answers for every array. They are computed here without the -//! aggregate function registry, so they work with any session. Exact cached `Min`/`Max` -//! statistics are used when present, and computed answers are written back to the cache. +//! Validity checks need these answers for every array. Exact cached `Min`/`Max` statistics are +//! used when present; otherwise the session's `vortex.min_max` aggregate is tried first so +//! encoding kernels (such as `Sparse` and `RunEnd`) can answer without decoding the bitmap. When +//! the session registers no `min_max` aggregate, the array is executed to a [`BoolArray`] and +//! scanned directly, and computed answers are written back to the cache. +use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; +use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::ExecutionCtx; +use crate::aggregate_fn::AggregateFnRef; +use crate::aggregate_fn::NumericalAggregateOpts; +use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::arrays::BoolArray; use crate::arrays::bool::BoolArrayExt; use crate::stats::Precision; @@ -32,7 +39,8 @@ pub struct BoolBounds { /// /// # Errors /// -/// Fails if `array` is not a boolean array, or if it cannot be executed to a [`BoolArray`]. +/// Fails if `array` is not a boolean array, or if computing its `min_max` aggregate or executing +/// it to a [`BoolArray`] fails. pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { vortex_ensure!( array.dtype().is_boolean(), @@ -47,6 +55,30 @@ pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult(ctx)?; let values = bools.to_bit_buffer(); let (valid, true_count) = match BoolArrayExt::validity(&bools).execute_mask(bools.len(), ctx)? { @@ -70,6 +102,16 @@ pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult VortexResult> { + static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); + let session = ctx.session(); + session.aggregate_fns().resolve_bound( + *MIN_MAX_ID, + NumericalAggregateOpts::skip_nans_bytes(), + session, + ) +} + #[cfg(test)] mod tests { use std::sync::LazyLock; From af189f21b857428aae8f364fe0a511f3fedbedf4 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 18:39:14 +0000 Subject: [PATCH 17/27] Fix rustdoc links and initialize aggregates in rle_decode bench Signed-off-by: Will Manning Co-Authored-By: Will Manning --- encodings/fastlanes/benches/rle_decode.rs | 1 + vortex-aggregates/src/is_constant/supported.rs | 2 +- vortex-array/src/aggregate_fn/session.rs | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/encodings/fastlanes/benches/rle_decode.rs b/encodings/fastlanes/benches/rle_decode.rs index 12a2cc0611d..6bbd8df975f 100644 --- a/encodings/fastlanes/benches/rle_decode.rs +++ b/encodings/fastlanes/benches/rle_decode.rs @@ -57,6 +57,7 @@ static SESSION: LazyLock = LazyLock::new(|| { .with::() .with::() .with::(); + vortex_aggregates::initialize(&session); vortex_fastlanes::initialize(&session); session }); diff --git a/vortex-aggregates/src/is_constant/supported.rs b/vortex-aggregates/src/is_constant/supported.rs index d0f3a2ba40a..0c1e05a8cbd 100644 --- a/vortex-aggregates/src/is_constant/supported.rs +++ b/vortex-aggregates/src/is_constant/supported.rs @@ -18,7 +18,7 @@ use vortex_array::scalar_fn::builtin::compare::comparable; /// map checks instead compare their elements with [`Compare`], so they require [`comparable`] /// elements, keys, and values. Union and variant arrays have no constant check. /// -/// [`Compare`]: crate::scalar_fn::builtin::compare::Compare +/// [`Compare`]: vortex_array::scalar_fn::builtin::compare::Compare /// [`is_constant`]: super::is_constant pub fn supports_is_constant(dtype: &DType) -> bool { match dtype { diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 1e53c92df84..5354d334150 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -28,7 +28,7 @@ use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate; /// /// The default session registers the built-in aggregate functions and kernels. Additional /// aggregate functions and kernels may be registered by extensions when they are added to a -/// [`VortexSession`](vortex_session::VortexSession). +/// [`VortexSession`]. #[derive(Clone, Debug)] pub struct AggregateFnSession { registry: AggregateFnRegistry, From 280fa589f30849cef563c77e5eef821a5d70ac69 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 19:14:16 +0000 Subject: [PATCH 18/27] Address roborev findings: typed bounded_min/max check, shared session_min_max, MinMax golden proto test Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-aggregates/src/max/mod.rs | 3 +- vortex-aggregates/src/min/mod.rs | 3 +- vortex-aggregates/src/tests/proto.rs | 4 + vortex-array/src/arrays/bool/bounds.rs | 46 +++-------- .../src/arrays/primitive/integer_bounds.rs | 81 ++++++++++++------- vortex-array/src/arrays/primitive/mod.rs | 2 + 6 files changed, 73 insertions(+), 66 deletions(-) diff --git a/vortex-aggregates/src/max/mod.rs b/vortex-aggregates/src/max/mod.rs index 4d036e9c032..886b86e861c 100644 --- a/vortex-aggregates/src/max/mod.rs +++ b/vortex-aggregates/src/max/mod.rs @@ -22,6 +22,7 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; +use crate::bounded_max::BoundedMax; use crate::min_max::MinMax; use crate::min_max::columnar_min_max; use crate::min_max::min_max; @@ -115,7 +116,7 @@ impl AggregateFnVTable for Max { .is_some_and(|other| other == options) { AggregateFnSatisfaction::Exact - } else if requested.id().as_str() == "vortex.bounded_max" && options.skip_nans { + } else if requested.is::() && options.skip_nans { // A NaN-including maximum may be NaN, which is not a usable upper bound. AggregateFnSatisfaction::Approximate } else { diff --git a/vortex-aggregates/src/min/mod.rs b/vortex-aggregates/src/min/mod.rs index f8fd3534e36..c4853f56636 100644 --- a/vortex-aggregates/src/min/mod.rs +++ b/vortex-aggregates/src/min/mod.rs @@ -22,6 +22,7 @@ use vortex_error::VortexResult; use vortex_session::VortexSession; use vortex_session::registry::CachedId; +use crate::bounded_min::BoundedMin; use crate::min_max::MinMax; use crate::min_max::columnar_min_max; use crate::min_max::min_max; @@ -115,7 +116,7 @@ impl AggregateFnVTable for Min { .is_some_and(|other| other == options) { AggregateFnSatisfaction::Exact - } else if requested.id().as_str() == "vortex.bounded_min" && options.skip_nans { + } else if requested.is::() && options.skip_nans { // A NaN-including minimum may be NaN, which is not a usable lower bound. AggregateFnSatisfaction::Approximate } else { diff --git a/vortex-aggregates/src/tests/proto.rs b/vortex-aggregates/src/tests/proto.rs index bace8acf0a3..6a12e198786 100644 --- a/vortex-aggregates/src/tests/proto.rs +++ b/vortex-aggregates/src/tests/proto.rs @@ -34,6 +34,7 @@ use crate::last::Last; use crate::max::Max; use crate::mean::Mean; use crate::min::Min; +use crate::min_max::MinMax; use crate::null_count::NullCount; use crate::sum::Sum; @@ -166,6 +167,8 @@ fn aggregate_fn_serde() { #[case(Sum.bind(NumericalAggregateOpts::include_nans()))] #[case(Count.bind(NumericalAggregateOpts::skip_nans()))] #[case(Count.bind(NumericalAggregateOpts::include_nans()))] +#[case(MinMax.bind(NumericalAggregateOpts::skip_nans()))] +#[case(MinMax.bind(NumericalAggregateOpts::include_nans()))] fn numeric_aggregate_options_round_trip(#[case] agg_fn: AggregateFnRef) -> VortexResult<()> { assert_round_trip(agg_fn) } @@ -252,6 +255,7 @@ fn unknown_aggregate_fn_id_allow_unknown() { #[case::count(Count.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0cvortex.count\x12\x02\x08\x01".as_slice())] #[case::min(Min.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.min\x12\x02\x08\x01".as_slice())] #[case::max(Max.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0avortex.max\x12\x02\x08\x01".as_slice())] +#[case::min_max(MinMax.bind(NumericalAggregateOpts::skip_nans()), b"\x0a\x0evortex.min_max\x12\x02\x08\x01".as_slice())] #[case::first(First.bind(EmptyOptions), b"\x0a\x0cvortex.first\x12\x00".as_slice())] #[case::last(Last.bind(EmptyOptions), b"\x0a\x0bvortex.last\x12\x00".as_slice())] #[case::null_count(NullCount.bind(EmptyOptions), b"\x0a\x11vortex.null_count\x12\x00".as_slice())] diff --git a/vortex-array/src/arrays/bool/bounds.rs b/vortex-array/src/arrays/bool/bounds.rs index 7f279bb1bd6..de806a36401 100644 --- a/vortex-array/src/arrays/bool/bounds.rs +++ b/vortex-array/src/arrays/bool/bounds.rs @@ -9,19 +9,16 @@ //! the session registers no `min_max` aggregate, the array is executed to a [`BoolArray`] and //! scanned directly, and computed answers are written back to the cache. -use vortex_error::VortexExpect; use vortex_error::VortexResult; use vortex_error::vortex_ensure; use vortex_mask::Mask; -use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; -use crate::aggregate_fn::NumericalAggregateOpts; -use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::arrays::BoolArray; use crate::arrays::bool::BoolArrayExt; +use crate::arrays::primitive::SessionMinMax; +use crate::arrays::primitive::session_min_max; use crate::stats::Precision; use crate::stats::Stat; use crate::stats::StatsProviderExt; @@ -57,26 +54,17 @@ pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult return Ok(None), + SessionMinMax::Bounds(min, max) => { + if let (Some(all_true), Some(any_true)) = (min.as_bool().value(), max.as_bool().value()) + { + stats.set(Stat::Min, Precision::exact(all_true)); + stats.set(Stat::Max, Precision::exact(any_true)); + return Ok(Some(BoolBounds { all_true, any_true })); + } } + SessionMinMax::Unsupported => {} } let bools = array.clone().execute::(ctx)?; @@ -102,16 +90,6 @@ pub fn bool_bounds(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult VortexResult> { - static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); - let session = ctx.session(); - session.aggregate_fns().resolve_bound( - *MIN_MAX_ID, - NumericalAggregateOpts::skip_nans_bytes(), - session, - ) -} - #[cfg(test)] mod tests { use std::sync::LazyLock; diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index 661089e113c..66a10a6f6a5 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -18,7 +18,6 @@ use vortex_session::registry::CachedId; use crate::ArrayRef; use crate::ExecutionCtx; -use crate::aggregate_fn::AggregateFnRef; use crate::aggregate_fn::NumericalAggregateOpts; use crate::aggregate_fn::session::AggregateFnSessionExt; use crate::arrays::PrimitiveArray; @@ -59,32 +58,22 @@ pub fn integer_bounds( } // Compute both extrema in one pass with the session's `min_max` aggregate. - if let Some(min_max) = resolve_min_max(ctx)? - && min_max.return_dtype(array.dtype()).is_some() - { - let result = min_max.aggregate(array, ctx)?; - if result.is_null() { - return Ok(None); - } - let min = result - .as_struct() - .field_by_idx(0) - .vortex_expect("min_max has a min field"); - let max = result - .as_struct() - .field_by_idx(1) - .vortex_expect("min_max has a max field"); - if let Some(bounds) = bounds_from(array, &min, &max) { - if let (Some(min), Some(max)) = (min.value(), max.value()) { - stats.set(Stat::Min, Precision::Exact(min.clone())); - stats.set(Stat::Max, Precision::Exact(max.clone())); + match session_min_max(array, ctx)? { + SessionMinMax::Empty => return Ok(None), + SessionMinMax::Bounds(min, max) => { + if let Some(bounds) = bounds_from(array, &min, &max) { + if let (Some(min), Some(max)) = (min.value(), max.value()) { + stats.set(Stat::Min, Precision::Exact(min.clone())); + stats.set(Stat::Max, Precision::Exact(max.clone())); + } + // Cache the null count too, as computing the `Min` and `Max` statistics does. + if stats.get(Stat::NullCount).as_exact().is_none() { + stats.set(Stat::NullCount, Precision::exact(array.invalid_count(ctx)?)); + } + return Ok(Some(bounds)); } - // Cache the null count too, as computing the `Min` and `Max` statistics does. - if stats.get(Stat::NullCount).as_exact().is_none() { - stats.set(Stat::NullCount, Precision::exact(array.invalid_count(ctx)?)); - } - return Ok(Some(bounds)); } + SessionMinMax::Unsupported => {} } Ok(scan_array(array, ctx)?.map(|scanned| IntegerBounds { @@ -138,16 +127,48 @@ fn ensure_int(array: &ArrayRef) -> VortexResult<()> { Ok(()) } -/// Resolves the `min_max` aggregate, skipping NaNs like the `Min` and `Max` statistics, if the -/// session registers one. -fn resolve_min_max(ctx: &ExecutionCtx) -> VortexResult> { +/// Outcome of running the session's `vortex.min_max` aggregate on an array. +pub(crate) enum SessionMinMax { + /// The session has no `vortex.min_max` aggregate registered, or it does not support the dtype. + Unsupported, + /// The aggregate ran and reported no valid values. + Empty, + /// The aggregate ran and returned `(min, max)` scalars. + Bounds(Scalar, Scalar), +} + +/// Evaluates the session's `vortex.min_max` aggregate (skipping NaNs) if registered and supported +/// for `array`'s dtype. +pub(crate) fn session_min_max( + array: &ArrayRef, + ctx: &mut ExecutionCtx, +) -> VortexResult { static MIN_MAX_ID: CachedId = CachedId::new("vortex.min_max"); let session = ctx.session(); - session.aggregate_fns().resolve_bound( + let Some(min_max) = session.aggregate_fns().resolve_bound( *MIN_MAX_ID, NumericalAggregateOpts::skip_nans_bytes(), session, - ) + )? + else { + return Ok(SessionMinMax::Unsupported); + }; + if min_max.return_dtype(array.dtype()).is_none() { + return Ok(SessionMinMax::Unsupported); + } + let result = min_max.aggregate(array, ctx)?; + if result.is_null() { + return Ok(SessionMinMax::Empty); + } + let min = result + .as_struct() + .field_by_idx(0) + .vortex_expect("min_max has a min field"); + let max = result + .as_struct() + .field_by_idx(1) + .vortex_expect("min_max has a max field"); + Ok(SessionMinMax::Bounds(min, max)) } fn bounds_from(array: &ArrayRef, min: &Scalar, max: &Scalar) -> Option { diff --git a/vortex-array/src/arrays/primitive/mod.rs b/vortex-array/src/arrays/primitive/mod.rs index 59f36ec8495..a7c32876c0d 100644 --- a/vortex-array/src/arrays/primitive/mod.rs +++ b/vortex-array/src/arrays/primitive/mod.rs @@ -11,9 +11,11 @@ pub use array::PrimitiveSlots; pub use array::chunk_range; pub use array::patch_chunk; pub use integer_bounds::IntegerBounds; +pub(crate) use integer_bounds::SessionMinMax; pub use integer_bounds::integer_bounds; pub use integer_bounds::integer_is_sorted; pub use integer_bounds::integer_is_strict_sorted; +pub(crate) use integer_bounds::session_min_max; pub use vtable::PrimitiveArray; pub(crate) mod compute; From 35af79c731c6777200162d30dd374836662f6aa9 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 20:13:13 +0000 Subject: [PATCH 19/27] Address roborev findings: update AggregateFnSession doc comment and deduplicate sum_decimal_dtype Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-aggregates/src/sum/mod.rs | 13 +------------ vortex-array/src/aggregate_fn/session.rs | 7 +++++-- vortex-array/src/stats/stat.rs | 21 ++++++++++++++------- 3 files changed, 20 insertions(+), 21 deletions(-) diff --git a/vortex-aggregates/src/sum/mod.rs b/vortex-aggregates/src/sum/mod.rs index ae3f736f983..a0ba2c5e622 100644 --- a/vortex-aggregates/src/sum/mod.rs +++ b/vortex-aggregates/src/sum/mod.rs @@ -18,8 +18,6 @@ use vortex_array::aggregate_fn::AggregateFnVTable; use vortex_array::aggregate_fn::DynAccumulator; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::dtype::DType; -use vortex_array::dtype::DecimalDType; -use vortex_array::dtype::MAX_PRECISION; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; use vortex_array::scalar::DecimalValue; @@ -75,16 +73,7 @@ pub fn sum(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { #[derive(Clone, Debug)] pub struct Sum; -// Both Spark and DataFusion use this heuristic. -// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 -// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 -/// Returns the decimal dtype a sum over `input` widens to. -pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { - DecimalDType::new( - u8::min(MAX_PRECISION, input.precision() + 10), - input.scale(), - ) -} +pub use vortex_array::stats::sum_decimal_dtype; impl AggregateFnVTable for Sum { type Options = NumericalAggregateOpts; diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index 5354d334150..dc4923d0bb4 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -26,8 +26,11 @@ use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate; /// Session state for aggregate functions and encoding-specific aggregate kernels. /// -/// The default session registers the built-in aggregate functions and kernels. Additional -/// aggregate functions and kernels may be registered by extensions when they are added to a +/// The default session registers only the `all_non_distinct` aggregate and the `Chunked` +/// aggregate kernel. Sessions that compute statistics (such as `Min`, `Max`, `Sum`, or +/// `IsSorted`) must register the built-in aggregates via `vortex_aggregates::initialize`, +/// `VortexSessionDefault`, or `vortex_file::register_default_encodings`. Additional aggregate +/// functions and kernels may be registered by extensions when they are added to a /// [`VortexSession`]. #[derive(Clone, Debug)] pub struct AggregateFnSession { diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index ef4dde4b29f..7edaa51ccd1 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -307,6 +307,17 @@ impl Display for Stat { } } +// Both Spark and DataFusion use this heuristic. +// - https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66 +// - https://github.com/apache/datafusion/blob/4153adf2c0f6e317ef476febfdc834208bd46622/datafusion/functions-aggregate/src/sum.rs#L188 +/// Returns the decimal dtype a sum over `input` widens to. +pub fn sum_decimal_dtype(input: &DecimalDType) -> DecimalDType { + DecimalDType::new( + u8::min(MAX_PRECISION, input.precision() + 10), + input.scale(), + ) +} + fn sum_return_dtype(input_dtype: &DType) -> Option { Some(match input_dtype { DType::Bool(_) => DType::Primitive(PType::U64, Nullable), @@ -320,13 +331,9 @@ fn sum_return_dtype(input_dtype: &DType) -> Option { // Float sums cannot overflow, but all-null floats still sum to null. PType::F16 | PType::F32 | PType::F64 => DType::Primitive(PType::F64, Nullable), }, - DType::Decimal(decimal_dtype, _) => DType::Decimal( - DecimalDType::new( - u8::min(MAX_PRECISION, decimal_dtype.precision() + 10), - decimal_dtype.scale(), - ), - Nullable, - ), + DType::Decimal(decimal_dtype, _) => { + DType::Decimal(sum_decimal_dtype(decimal_dtype), Nullable) + } _ => return None, }) } From b86d40fad99a2f3562bf4a726d27bb8b536d6cec Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 20:55:27 +0000 Subject: [PATCH 20/27] Initialize vortex_aggregates in zigzag array test session Signed-off-by: Will Manning Co-Authored-By: Will Manning --- encodings/zigzag/src/array/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/encodings/zigzag/src/array/mod.rs b/encodings/zigzag/src/array/mod.rs index 8c1397d6114..e266aadc5e8 100644 --- a/encodings/zigzag/src/array/mod.rs +++ b/encodings/zigzag/src/array/mod.rs @@ -301,6 +301,7 @@ mod test { static SESSION: LazyLock = LazyLock::new(|| { let session = VortexSession::empty(); + vortex_aggregates::initialize(&session); crate::initialize(&session); session }); From e010c2da01e4ac1f39e72e72fb7f90d0d7e0a8a8 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 22:13:03 +0000 Subject: [PATCH 21/27] Restore accumulator_sum_v2 bench and update codspeed_bench_counts.json Signed-off-by: Will Manning Co-Authored-By: Will Manning --- scripts/codspeed_bench_counts.json | 4 ++-- .../benches/accumulator_construction.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/codspeed_bench_counts.json b/scripts/codspeed_bench_counts.json index cf30ba30ddc..5986d61e0fb 100644 --- a/scripts/codspeed_bench_counts.json +++ b/scripts/codspeed_bench_counts.json @@ -8,7 +8,7 @@ "write_compression": 3 }, "vortex-aggregates": { - "accumulator_construction": 1, + "accumulator_construction": 2, "aggregate_definedness": 6, "aggregate_grouped": 18, "aggregate_max": 15, @@ -60,7 +60,7 @@ "run_end_sum": 1, "run_end_take": 5, "scalar_at_struct": 2, - "scalar_construction": 10, + "scalar_construction": 8, "scalar_fn_probe": 8, "scalar_subtract": 0, "search_sorted": 1, diff --git a/vortex-aggregates/benches/accumulator_construction.rs b/vortex-aggregates/benches/accumulator_construction.rs index 1a0c00302b0..610393c5e4b 100644 --- a/vortex-aggregates/benches/accumulator_construction.rs +++ b/vortex-aggregates/benches/accumulator_construction.rs @@ -11,6 +11,7 @@ use divan::Bencher; use divan::counter::ItemsCount; use mimalloc::MiMalloc; use vortex_aggregates::count::Count; +use vortex_aggregates::sum_v2::SumV2; use vortex_array::aggregate_fn::AggregateFnVTableExt; use vortex_array::aggregate_fn::NumericalAggregateOpts; use vortex_array::dtype::DType; @@ -38,6 +39,17 @@ fn struct8_dtype() -> DType { ) } +#[divan::bench] +fn accumulator_sum_v2(bencher: Bencher) { + let dtype = DType::Primitive(PType::I64, Nullability::Nullable); + let aggregate_fn = SumV2.bind(NumericalAggregateOpts::default()); + bencher.counter(ItemsCount::new(N)).bench_local(|| { + for _ in 0..N { + black_box(aggregate_fn.accumulator(black_box(&dtype)).unwrap()); + } + }); +} + #[divan::bench] fn accumulator_count_struct8(bencher: Bencher) { let dtype = struct8_dtype(); From 3ee5dd2f28530d8deb7b39cf541596aed4623c1a Mon Sep 17 00:00:00 2001 From: Will Manning Date: Tue, 1 Dec 2026 23:12:41 +0000 Subject: [PATCH 22/27] Canonicalize array once in test_cast_to_primitive before scanning bounds Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/compute/conformance/cast.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/vortex-array/src/compute/conformance/cast.rs b/vortex-array/src/compute/conformance/cast.rs index 694b6419370..c0051c1e1e5 100644 --- a/vortex-array/src/compute/conformance/cast.rs +++ b/vortex-array/src/compute/conformance/cast.rs @@ -6,6 +6,7 @@ use vortex_error::VortexResult; use vortex_error::vortex_panic; use crate::ArrayRef; +use crate::Canonical; use crate::ExecutionCtx; use crate::IntoArray; use crate::RecursiveCanonical; @@ -223,9 +224,14 @@ fn test_cast_to_primitive( test_round_trip: bool, ctx: &mut ExecutionCtx, ) { - let out_of_range = (0..array.len()) + let canonical = array + .clone() + .execute::(ctx) + .vortex_expect("canonical execution should succeed in conformance test") + .into_array(); + let out_of_range = (0..canonical.len()) .map(|idx| { - array + canonical .execute_scalar(idx, ctx) .vortex_expect("scalar_at should succeed in conformance test") }) From 9748e0b7bf972e49d58c5224cb295601332ef6a3 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 2 Dec 2026 00:13:21 +0000 Subject: [PATCH 23/27] Expand core_encodings_aggregate_consistency to cover all core encodings plus sliced/filtered inputs Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../src/tests/core_consistency.rs | 120 +++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/vortex-aggregates/src/tests/core_consistency.rs b/vortex-aggregates/src/tests/core_consistency.rs index ceb9b0ac191..b6a9422a8e8 100644 --- a/vortex-aggregates/src/tests/core_consistency.rs +++ b/vortex-aggregates/src/tests/core_consistency.rs @@ -12,16 +12,33 @@ use rstest::rstest; use vortex_array::ArrayRef; 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::DecimalArray; use vortex_array::arrays::DictArray; +use vortex_array::arrays::ExtensionArray; +use vortex_array::arrays::ListArray; +use vortex_array::arrays::Patched; use vortex_array::arrays::PrimitiveArray; +use vortex_array::arrays::StructArray; +use vortex_array::arrays::VarBinArray; +use vortex_array::arrays::VarBinViewArray; use vortex_array::arrays::WidenArray; use vortex_array::arrays::runend::RunEnd; use vortex_array::compute::conformance::consistency::test_slice_aggregate_consistency; +use vortex_array::dtype::DecimalDType; +use vortex_array::dtype::FieldNames; +use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +use vortex_array::dtype::i256; +use vortex_array::extension::datetime::Date; +use vortex_array::extension::datetime::TimeUnit; +use vortex_array::patches::Patches; +use vortex_array::validity::Validity; use vortex_buffer::buffer; use vortex_error::VortexResult; +use vortex_mask::Mask; use vortex_session::VortexSession; static SESSION: LazyLock = LazyLock::new(|| { @@ -37,6 +54,55 @@ static SESSION: LazyLock = LazyLock::new(|| { .into_array() )] #[case::float_with_nan(buffer![1.5f64, f64::NAN, -2.0, 8.25, f64::NAN, 0.0, 3.5].into_array())] +#[case::nullable_bool( + BoolArray::from_iter([Some(true), None, Some(false), Some(true), None, Some(false), Some(true)]) + .into_array() +)] +#[case::decimal_i128( + DecimalArray::new( + buffer![100i128, -50, 250, 0, 75, -10, 400], + DecimalDType::new(20, 2), + Validity::from_iter([true, true, false, true, true, false, true]), + &mut SESSION.create_execution_ctx(), + ) + .into_array() +)] +#[case::decimal_i256( + DecimalArray::new( + buffer![ + i256::from_i128(1000), + i256::from_i128(-500), + i256::from_i128(2500), + i256::from_i128(0), + i256::from_i128(750), + i256::from_i128(-100), + i256::from_i128(4000), + ], + DecimalDType::new(50, 4), + Validity::from_iter([true, false, true, true, false, true, true]), + &mut SESSION.create_execution_ctx(), + ) + .into_array() +)] +#[case::varbin( + VarBinArray::from_iter( + [Some("delta"), None, Some("alpha"), Some("gamma"), None, Some("beta"), Some("epsilon")], + vortex_array::dtype::DType::Utf8(Nullability::Nullable), + ) + .into_array() +)] +#[case::varbinview( + VarBinViewArray::from_iter_nullable_str([ + Some("delta"), + None, + Some("a_much_longer_string_for_outline_view"), + Some("gamma"), + None, + Some("beta"), + Some("another_long_outline_string_value"), + ]) + .into_array() +)] #[case::constant(ConstantArray::new(7i64, 9).into_array())] #[case::dict( DictArray::new( @@ -67,7 +133,59 @@ static SESSION: LazyLock = LazyLock::new(|| { )? .into_array() )] +#[case::patched( + Patched::from_array_and_patches( + buffer![1i32, 2, 3, 4, 5, 6, 7].into_array(), + &Patches::new( + 7, + 0, + buffer![1u32, 4].into_array(), + buffer![100i32, -50].into_array(), + None, + &mut SESSION.create_execution_ctx(), + )?, + &mut SESSION.create_execution_ctx(), + )? + .into_array() +)] +#[case::extension( + ExtensionArray::new( + Date::new(TimeUnit::Days, Nullability::Nullable).erased(), + PrimitiveArray::from_option_iter([Some(10i32), None, Some(2), Some(30), None, Some(5), Some(15)]) + .into_array(), + ) + .into_array() +)] +#[case::struct_array( + StructArray::try_new( + FieldNames::from(["a", "b"]), + vec![ + buffer![5i32, 1, 9, 3, 7, 2, 8].into_array(), + BoolArray::from_iter([true, false, true, true, false, false, true]).into_array(), + ], + 7, + Validity::from_iter([true, false, true, true, true, false, true]), + )? + .into_array() +)] +#[case::list( + ListArray::try_new( + buffer![1i32, 2, 3, 4, 5, 6, 7, 8].into_array(), + buffer![0u32, 2, 2, 4, 5, 6, 7, 8].into_array(), + Validity::from_iter([true, false, true, true, false, true, true]), + &mut SESSION.create_execution_ctx(), + )? + .into_array() +)] fn core_encodings_aggregate_consistency(#[case] array: ArrayRef) -> VortexResult<()> { - test_slice_aggregate_consistency(&array, &mut SESSION.create_execution_ctx()); + let mut ctx = SESSION.create_execution_ctx(); + test_slice_aggregate_consistency(&array, &mut ctx); + + let sliced = array.slice(1..array.len() - 1)?; + test_slice_aggregate_consistency(&sliced, &mut ctx); + + let mask = Mask::from_iter((0..array.len()).map(|i| i % 2 == 0)); + let filtered = array.filter(mask)?; + test_slice_aggregate_consistency(&filtered, &mut ctx); Ok(()) } From 0fe57cfd41ff0a4e84869df0e5c8daa98c92f53c Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 2 Dec 2026 01:21:52 +0000 Subject: [PATCH 24/27] Trim bound-aggregate lookup and dtype resolution overhead in compute_stat Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/aggregate_fn/erased.rs | 10 +++++ vortex-array/src/aggregate_fn/session.rs | 18 ++++---- vortex-array/src/aggregate_fn/typed.rs | 45 +++++++++++++++++++ .../src/arrays/primitive/integer_bounds.rs | 5 +-- vortex-array/src/stats/array.rs | 5 +-- vortex-session/src/arc_swap_map.rs | 12 +++++ 6 files changed, 81 insertions(+), 14 deletions(-) diff --git a/vortex-array/src/aggregate_fn/erased.rs b/vortex-array/src/aggregate_fn/erased.rs index acfd13b568e..fc24b40a6f3 100644 --- a/vortex-array/src/aggregate_fn/erased.rs +++ b/vortex-array/src/aggregate_fn/erased.rs @@ -107,6 +107,16 @@ impl AggregateFnRef { self.0.aggregate(self, array, ctx) } + /// Compute the aggregate over a single array if its dtype is supported, returning `Ok(None)` + /// otherwise. + pub(crate) fn try_aggregate( + &self, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + self.0.try_aggregate(self, array, ctx) + } + /// Create a grouped accumulator for grouped streaming aggregation. pub fn accumulator_grouped(&self, input_dtype: &DType) -> VortexResult { self.0.accumulator_grouped(input_dtype) diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index dc4923d0bb4..ffce232d866 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -58,10 +58,11 @@ type BoundAggregateFnKey = (AggregateFnId, &'static [u8]); /// Registry of aggregate function plugins, keyed by aggregate function id. type AggregateFnRegistry = ArcSwapMap; -/// Cache of bound aggregate functions resolved from static option bytes, paired with the plugin -/// instance they were deserialized from so re-registering an ID invalidates the entry. -type BoundAggregateFnCache = - ArcSwapMap; +/// Cache of bound aggregate functions resolved from static option bytes. +/// +/// Entries for an aggregate ID are invalidated by [`AggregateFnSession::register`] whenever its +/// plugin is replaced. +type BoundAggregateFnCache = ArcSwapMap; /// Registry of aggregate kernels, keyed by encoding and optional aggregate function. type AggregateKernelRegistry = ArcSwapMap; /// Registry of encoding-agnostic grouped aggregate kernels, keyed by aggregate function id. @@ -105,9 +106,7 @@ impl AggregateFnSession { session: &VortexSession, ) -> VortexResult> { let key = (id, options); - if let Some((cached, bound_fn)) = self.bound_fns.get(&key) - && self.is_current_plugin(id, &cached) - { + if let Some(bound_fn) = self.bound_fns.get(&key) { return Ok(Some(bound_fn)); } @@ -115,7 +114,9 @@ impl AggregateFnSession { return Ok(None); }; let bound_fn = plugin.deserialize(options, session)?; - self.bound_fns.insert(key, (plugin, bound_fn.clone())); + if self.is_current_plugin(id, &plugin) { + self.bound_fns.insert(key, bound_fn.clone()); + } Ok(Some(bound_fn)) } @@ -130,6 +131,7 @@ impl AggregateFnSession { let id = vtable.id(); let pluginref = Arc::new(vtable) as AggregateFnPluginRef; self.registry.insert(id, pluginref); + self.bound_fns.retain(|(cached_id, _), _| *cached_id != id); } /// Returns the aggregate kernel registered for `array_id` and `agg_fn_id`, if any. diff --git a/vortex-array/src/aggregate_fn/typed.rs b/vortex-array/src/aggregate_fn/typed.rs index 4a63ca40bc9..fdc5731c9c9 100644 --- a/vortex-array/src/aggregate_fn/typed.rs +++ b/vortex-array/src/aggregate_fn/typed.rs @@ -59,6 +59,12 @@ pub(super) trait DynAggregateFn: 'static + Send + Sync + super::sealed::Sealed { array: &ArrayRef, ctx: &mut ExecutionCtx, ) -> VortexResult; + fn try_aggregate( + &self, + self_ref: &AggregateFnRef, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult>; fn accumulator_grouped(&self, input_dtype: &DType) -> VortexResult; fn options_serialize(&self) -> VortexResult>>; @@ -87,6 +93,26 @@ pub(super) struct AggregateFnInner { } impl AggregateFnInner { + fn try_resolve_dtypes(&self, input_dtype: &DType) -> Option { + if let Some(dtypes) = self.resolved.get() { + if dtypes.dtype == *input_dtype { + return Some(dtypes.clone()); + } + return AggregateDTypes::try_new(&self.vtable, &self.options, input_dtype.clone()).ok(); + } + + let dtypes = + AggregateDTypes::try_new(&self.vtable, &self.options, input_dtype.clone()).ok()?; + + // Another thread may have filled the cache first, possibly for another input dtype. + let cached = self.resolved.get_or_init(|| dtypes.clone()); + if cached.dtype == *input_dtype { + return Some(cached.clone()); + } + + Some(dtypes) + } + /// The dtypes of this aggregate over `input_dtype`, reusing the cached dtypes if they match. fn resolve_dtypes(&self, input_dtype: &DType) -> VortexResult { if let Some(dtypes) = self.resolved.get() { @@ -166,6 +192,25 @@ impl DynAggregateFn for AggregateFnInner { accumulator.finish() } + fn try_aggregate( + &self, + self_ref: &AggregateFnRef, + array: &ArrayRef, + ctx: &mut ExecutionCtx, + ) -> VortexResult> { + let Some(dtypes) = self.try_resolve_dtypes(array.dtype()) else { + return Ok(None); + }; + let mut accumulator = Accumulator::from_bound( + self.vtable.clone(), + self.options.clone(), + self_ref.clone(), + dtypes, + ); + accumulator.accumulate(array, ctx)?; + accumulator.finish().map(Some) + } + fn accumulator_grouped(&self, input_dtype: &DType) -> VortexResult { Ok(Box::new(GroupedAccumulator::from_dtypes( self.vtable.clone(), diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index 66a10a6f6a5..fbe36b38bfc 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -153,10 +153,9 @@ pub(crate) fn session_min_max( else { return Ok(SessionMinMax::Unsupported); }; - if min_max.return_dtype(array.dtype()).is_none() { + let Some(result) = min_max.try_aggregate(array, ctx)? else { return Ok(SessionMinMax::Unsupported); - } - let result = min_max.aggregate(array, ctx)?; + }; if result.is_null() { return Ok(SessionMinMax::Empty); } diff --git a/vortex-array/src/stats/array.rs b/vortex-array/src/stats/array.rs index 5c9cfb79b58..47677ad35b0 100644 --- a/vortex-array/src/stats/array.rs +++ b/vortex-array/src/stats/array.rs @@ -287,10 +287,9 @@ impl StatsSetRef<'_> { let Some(aggregate_fn) = stat.resolve_aggregate_fn(ctx.session())? else { return Ok(None); }; - if aggregate_fn.return_dtype(array.dtype()).is_none() { + let Some(result) = aggregate_fn.try_aggregate(array, ctx)? else { return Ok(None); - } - let result = aggregate_fn.aggregate(array, ctx)?; + }; if result.is_null() { return Ok(None); } diff --git a/vortex-session/src/arc_swap_map.rs b/vortex-session/src/arc_swap_map.rs index 63023e5cccc..de14953c22b 100644 --- a/vortex-session/src/arc_swap_map.rs +++ b/vortex-session/src/arc_swap_map.rs @@ -132,6 +132,18 @@ impl ArcSwapMap { }); } + /// Retain only the entries specified by the predicate. + pub fn retain(&self, f: impl Fn(&K, &V) -> bool) + where + K: Clone, + V: Clone, + S: Clone, + { + self.modify(|map| { + map.retain(|k, v| f(k, v)); + }); + } + /// Insert `value` under `key` only if no value is stored there yet. /// /// Returns `true` if `value` was inserted, or `false` if a value was already From 8ca8c4189ca6d47f8b66549c3a88e4022c7b26ed Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 2 Dec 2026 02:13:23 +0000 Subject: [PATCH 25/27] Serialize AggregateFnSession cache updates with register Signed-off-by: Will Manning Co-Authored-By: Will Manning --- vortex-array/src/aggregate_fn/session.rs | 250 ++++++++++++++++++++++- 1 file changed, 248 insertions(+), 2 deletions(-) diff --git a/vortex-array/src/aggregate_fn/session.rs b/vortex-array/src/aggregate_fn/session.rs index ffce232d866..0b6763b79ab 100644 --- a/vortex-array/src/aggregate_fn/session.rs +++ b/vortex-array/src/aggregate_fn/session.rs @@ -4,6 +4,7 @@ use std::any::Any; use std::sync::Arc; +use parking_lot::Mutex; use vortex_error::VortexResult; use vortex_session::ArcSwapMap; use vortex_session::SessionExt; @@ -36,6 +37,10 @@ use crate::arrays::chunked::compute::aggregate::ChunkedArrayAggregate; pub struct AggregateFnSession { registry: AggregateFnRegistry, bound_fns: BoundAggregateFnCache, + /// Serializes `registry` updates with `bound_fns` cache mutations so a concurrent `resolve_bound` + /// miss cannot re-insert a bound function for a plugin that `register` has already replaced. + /// Hot cache hits in `resolve_bound` read `bound_fns` lock-free. + bound_fns_write_lock: Arc>, kernels: AggregateKernelRegistry, grouped_kernels: GroupedKernelRegistry, @@ -76,6 +81,7 @@ impl Default for AggregateFnSession { let this = Self { registry: AggregateFnRegistry::default(), bound_fns: BoundAggregateFnCache::default(), + bound_fns_write_lock: Arc::new(Mutex::new(())), kernels: AggregateKernelRegistry::default(), grouped_kernels: GroupedKernelRegistry::default(), grouped_encoding_kernels: GroupedEncodingKernelRegistry::default(), @@ -114,8 +120,11 @@ impl AggregateFnSession { return Ok(None); }; let bound_fn = plugin.deserialize(options, session)?; - if self.is_current_plugin(id, &plugin) { - self.bound_fns.insert(key, bound_fn.clone()); + { + let _guard = self.bound_fns_write_lock.lock(); + if self.is_current_plugin(id, &plugin) { + self.bound_fns.insert(key, bound_fn.clone()); + } } Ok(Some(bound_fn)) } @@ -130,6 +139,7 @@ impl AggregateFnSession { pub fn register(&self, vtable: V) { let id = vtable.id(); let pluginref = Arc::new(vtable) as AggregateFnPluginRef; + let _guard = self.bound_fns_write_lock.lock(); self.registry.insert(id, pluginref); self.bound_fns.retain(|(cached_id, _), _| *cached_id != id); } @@ -298,3 +308,239 @@ pub trait AggregateFnSessionExt: SessionExt { } } impl AggregateFnSessionExt for S {} + +#[cfg(test)] +mod tests { + use vortex_error::VortexExpect; + use vortex_error::VortexResult; + use vortex_session::VortexSession; + use vortex_session::registry::CachedId; + + use crate::ArrayRef; + use crate::Columnar; + use crate::ExecutionCtx; + use crate::aggregate_fn::AggregateArgs; + use crate::aggregate_fn::AggregateFnId; + use crate::aggregate_fn::AggregateFnVTable; + use crate::aggregate_fn::EmptyOptions; + use crate::aggregate_fn::session::AggregateFnSessionExt; + use crate::dtype::DType; + use crate::dtype::Nullability; + use crate::scalar::Scalar; + + fn shared_test_id() -> AggregateFnId { + static ID: CachedId = CachedId::new("vortex.test.resolve_bound_invalidation"); + *ID + } + + #[derive(Clone, Debug)] + struct FirstVTable; + + impl AggregateFnVTable for FirstVTable { + type Options = EmptyOptions; + type Partial = (); + + fn id(&self) -> AggregateFnId { + shared_test_id() + } + + fn serialize(&self, _options: &Self::Options) -> VortexResult>> { + Ok(Some(vec![])) + } + + fn deserialize( + &self, + _metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + Ok(EmptyOptions) + } + + fn return_dtype(&self, _options: &Self::Options, _input_dtype: &DType) -> Option { + Some(DType::Bool(Nullability::NonNullable)) + } + + fn partial_dtype(&self, _options: &Self::Options, _input_dtype: &DType) -> Option { + Some(DType::Bool(Nullability::NonNullable)) + } + + fn empty_partial(&self, _args: AggregateArgs<'_, Self::Options>) -> VortexResult<()> { + Ok(()) + } + + fn accumulate( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &mut (), + _batch: &Columnar, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + Ok(()) + } + + fn merge_partials( + &self, + _args: AggregateArgs<'_, Self::Options>, + _left: (), + _right: (), + ) -> VortexResult<()> { + Ok(()) + } + + fn to_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &(), + ) -> VortexResult { + Ok(Scalar::bool(false, Nullability::NonNullable)) + } + + fn partial_from_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _scalar: &Scalar, + ) -> VortexResult<()> { + Ok(()) + } + + fn is_saturated(&self, _args: AggregateArgs<'_, Self::Options>, _partial: &()) -> bool { + false + } + + fn finalize( + &self, + _args: AggregateArgs<'_, Self::Options>, + states: ArrayRef, + ) -> VortexResult { + Ok(states) + } + + fn finalize_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &(), + ) -> VortexResult { + Ok(Scalar::bool(false, Nullability::NonNullable)) + } + } + + #[derive(Clone, Debug)] + struct SecondVTable; + + impl AggregateFnVTable for SecondVTable { + type Options = EmptyOptions; + type Partial = (); + + fn id(&self) -> AggregateFnId { + shared_test_id() + } + + fn serialize(&self, _options: &Self::Options) -> VortexResult>> { + Ok(Some(vec![])) + } + + fn deserialize( + &self, + _metadata: &[u8], + _session: &VortexSession, + ) -> VortexResult { + Ok(EmptyOptions) + } + + fn return_dtype(&self, _options: &Self::Options, _input_dtype: &DType) -> Option { + Some(DType::Bool(Nullability::NonNullable)) + } + + fn partial_dtype(&self, _options: &Self::Options, _input_dtype: &DType) -> Option { + Some(DType::Bool(Nullability::NonNullable)) + } + + fn empty_partial(&self, _args: AggregateArgs<'_, Self::Options>) -> VortexResult<()> { + Ok(()) + } + + fn accumulate( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &mut (), + _batch: &Columnar, + _ctx: &mut ExecutionCtx, + ) -> VortexResult<()> { + Ok(()) + } + + fn merge_partials( + &self, + _args: AggregateArgs<'_, Self::Options>, + _left: (), + _right: (), + ) -> VortexResult<()> { + Ok(()) + } + + fn to_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &(), + ) -> VortexResult { + Ok(Scalar::bool(true, Nullability::NonNullable)) + } + + fn partial_from_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _scalar: &Scalar, + ) -> VortexResult<()> { + Ok(()) + } + + fn is_saturated(&self, _args: AggregateArgs<'_, Self::Options>, _partial: &()) -> bool { + false + } + + fn finalize( + &self, + _args: AggregateArgs<'_, Self::Options>, + states: ArrayRef, + ) -> VortexResult { + Ok(states) + } + + fn finalize_scalar( + &self, + _args: AggregateArgs<'_, Self::Options>, + _partial: &(), + ) -> VortexResult { + Ok(Scalar::bool(true, Nullability::NonNullable)) + } + } + + #[test] + fn resolve_bound_tracks_registration_and_replacement() -> VortexResult<()> { + let session = VortexSession::empty(); + let id = shared_test_id(); + + assert!( + session + .aggregate_fns() + .resolve_bound(id, &[], &session)? + .is_none() + ); + + session.aggregate_fns().register(FirstVTable); + let first = session + .aggregate_fns() + .resolve_bound(id, &[], &session)? + .vortex_expect("registered first vtable"); + assert!(first.is::()); + + session.aggregate_fns().register(SecondVTable); + let second = session + .aggregate_fns() + .resolve_bound(id, &[], &session)? + .vortex_expect("registered replacement vtable"); + assert!(second.is::()); + + Ok(()) + } +} From 39f542245c5846cac488f6fe5b97377776056e65 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 2 Dec 2026 03:13:29 +0000 Subject: [PATCH 26/27] Align integer_bounds sortedness scan with IsSorted null ordering Signed-off-by: Will Manning Co-Authored-By: Will Manning --- .../src/arrays/primitive/integer_bounds.rs | 158 +++++++++++------- 1 file changed, 94 insertions(+), 64 deletions(-) diff --git a/vortex-array/src/arrays/primitive/integer_bounds.rs b/vortex-array/src/arrays/primitive/integer_bounds.rs index fbe36b38bfc..862213f1118 100644 --- a/vortex-array/src/arrays/primitive/integer_bounds.rs +++ b/vortex-array/src/arrays/primitive/integer_bounds.rs @@ -76,13 +76,10 @@ pub fn integer_bounds( SessionMinMax::Unsupported => {} } - Ok(scan_array(array, ctx)?.map(|scanned| IntegerBounds { - min: scanned.min, - max: scanned.max, - })) + Ok(scan_array(array, ctx)?.bounds) } -/// Returns whether the valid values of `array` are in non-decreasing order. +/// Returns whether `array` is in non-decreasing order, with nulls sorting before all valid values. /// /// # Errors /// @@ -92,7 +89,7 @@ pub fn integer_is_sorted(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResu sortedness(array, Stat::IsSorted, ctx) } -/// Returns whether the valid values of `array` are in strictly increasing order. +/// Returns whether `array` is in strictly increasing order, with at most one leading null. /// /// # Errors /// @@ -111,11 +108,11 @@ fn sortedness(array: &ArrayRef, stat: Stat, ctx: &mut ExecutionCtx) -> VortexRes { return Ok(sorted); } - // An array without valid values is trivially sorted. - Ok(scan_array(array, ctx)?.is_none_or(|scanned| match stat { + let scanned = scan_array(array, ctx)?; + Ok(match stat { Stat::IsStrictSorted => scanned.is_strict_sorted, _ => scanned.is_sorted, - })) + }) } fn ensure_int(array: &ArrayRef) -> VortexResult<()> { @@ -183,17 +180,16 @@ fn as_i128(array: &ArrayRef, scalar: &Scalar) -> Option { }) } -/// The bounds and sortedness of the valid values of an integer array, widened to `i128`. +/// The bounds and sortedness of an integer array, widened to `i128`. struct ScannedBounds { - min: i128, - max: i128, + bounds: Option, is_sorted: bool, is_strict_sorted: bool, } -/// Executes `array` to a [`PrimitiveArray`] and scans its valid values once, caching `Min`, `Max` -/// and `NullCount`. Returns `None` if `array` has no valid values. -fn scan_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult> { +/// Executes `array` to a [`PrimitiveArray`] and scans its elements once, caching `Min`, `Max` +/// and `NullCount`. +fn scan_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult { let primitive = array.clone().execute::(ctx)?; let mask = PrimitiveArrayExt::validity(&primitive).execute_mask(primitive.len(), ctx)?; @@ -204,60 +200,73 @@ fn scan_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult(), &mask) else { - return Ok(None); - }; - stats.set(Stat::Min, Precision::exact(scanned.min)); - stats.set(Stat::Max, Precision::exact(scanned.max)); - Ok(Some(ScannedBounds { - min: i128::from(scanned.min), - max: i128::from(scanned.max), + let scanned = scan(primitive.as_slice::

(), &mask); + let bounds = scanned.bounds.map(|(min, max)| { + stats.set(Stat::Min, Precision::exact(min)); + stats.set(Stat::Max, Precision::exact(max)); + IntegerBounds { + min: i128::from(min), + max: i128::from(max), + } + }); + Ok(ScannedBounds { + bounds, is_sorted: scanned.is_sorted, is_strict_sorted: scanned.is_strict_sorted, - })) + }) }) } -/// The bounds of the values selected by a mask, in the values' own type. +/// The bounds and sortedness of an array's elements, in the values' own type. struct Scanned

{ - min: P, - max: P, + bounds: Option<(P, P)>, is_sorted: bool, is_strict_sorted: bool, } -/// Returns the minimum, maximum and sortedness of the values selected by `mask`. -fn scan(values: &[P], mask: &Mask) -> Option> { - let mut valid = values - .iter() - .enumerate() - .filter(|(idx, _)| match mask { +/// Returns the minimum and maximum of valid values and the sortedness of all elements, +/// ordering nulls before all valid values to match the `IsSorted` and `IsStrictSorted` aggregates. +fn scan(values: &[P], mask: &Mask) -> Scanned

{ + let mut elements = values.iter().enumerate().map(|(idx, &value)| { + let valid = match mask { Mask::AllTrue(_) => true, Mask::AllFalse(_) => false, - Mask::Values(values) => values.value(*idx), - }) - .map(|(_, value)| *value); - - let first = valid.next()?; - let mut scanned = Scanned { - min: first, - max: first, - is_sorted: true, - is_strict_sorted: true, + Mask::Values(bits) => bits.value(idx), + }; + valid.then_some(value) + }); + + let Some(first) = elements.next() else { + return Scanned { + bounds: None, + is_sorted: true, + is_strict_sorted: true, + }; }; + + let mut bounds = first.map(|value| (value, value)); + let mut is_sorted = true; + let mut is_strict_sorted = true; let mut prev = first; - for value in valid { - if value < scanned.min { - scanned.min = value; - } - if value > scanned.max { - scanned.max = value; + for current in elements { + if let Some(value) = current { + bounds = match bounds { + Some((min, max)) => Some(( + if value < min { value } else { min }, + if value > max { value } else { max }, + )), + None => Some((value, value)), + }; } - scanned.is_sorted &= prev <= value; - scanned.is_strict_sorted &= prev < value; - prev = value; + is_sorted &= prev <= current; + is_strict_sorted &= prev < current; + prev = current; + } + Scanned { + bounds, + is_sorted, + is_strict_sorted, } - Some(scanned) } #[cfg(test)] @@ -303,28 +312,49 @@ mod tests { } #[test] - fn scan_skips_nulls() -> VortexResult<()> { - let array = - PrimitiveArray::from_option_iter([Some(5i64), None, Some(-3), None]).into_array(); + fn scan_orders_nulls_first() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); + + let interleaved = + PrimitiveArray::from_option_iter([Some(5i64), None, Some(6)]).into_array(); assert_eq!( - integer_bounds(&array, &mut ctx)?, - Some(IntegerBounds { min: -3, max: 5 }) + integer_bounds(&interleaved, &mut ctx)?, + Some(IntegerBounds { min: 5, max: 6 }) ); - assert!(!integer_is_sorted(&array, &mut ctx)?); + assert!(!integer_is_sorted(&interleaved, &mut ctx)?); + assert!(!integer_is_strict_sorted(&interleaved, &mut ctx)?); assert_eq!( - array.statistics().get_as::(Stat::NullCount), - Precision::exact(2usize) + interleaved.statistics().get_as::(Stat::NullCount), + Precision::exact(1usize) ); + + let single_leading_null = + PrimitiveArray::from_option_iter([None, Some(5i64), Some(6)]).into_array(); + assert!(integer_is_sorted(&single_leading_null, &mut ctx)?); + assert!(integer_is_strict_sorted(&single_leading_null, &mut ctx)?); + + let two_leading_nulls = + PrimitiveArray::from_option_iter([None, None, Some(5i64)]).into_array(); + assert!(integer_is_sorted(&two_leading_nulls, &mut ctx)?); + assert!(!integer_is_strict_sorted(&two_leading_nulls, &mut ctx)?); + Ok(()) } #[test] fn all_null_array_has_no_bounds_and_is_sorted() -> VortexResult<()> { - let array = PrimitiveArray::from_option_iter([None::, None]).into_array(); let mut ctx = SESSION.create_execution_ctx(); - assert_eq!(integer_bounds(&array, &mut ctx)?, None); - assert!(integer_is_strict_sorted(&array, &mut ctx)?); + + let single_null = PrimitiveArray::from_option_iter([None::]).into_array(); + assert_eq!(integer_bounds(&single_null, &mut ctx)?, None); + assert!(integer_is_sorted(&single_null, &mut ctx)?); + assert!(integer_is_strict_sorted(&single_null, &mut ctx)?); + + let two_nulls = PrimitiveArray::from_option_iter([None::, None]).into_array(); + assert_eq!(integer_bounds(&two_nulls, &mut ctx)?, None); + assert!(integer_is_sorted(&two_nulls, &mut ctx)?); + assert!(!integer_is_strict_sorted(&two_nulls, &mut ctx)?); + Ok(()) } From 2be4d73d8a4597c8d516cd9529b83700fe40e9d1 Mon Sep 17 00:00:00 2001 From: Will Manning Date: Wed, 2 Dec 2026 04:13:46 +0000 Subject: [PATCH 27/27] Move aggregate-dependent stats tests to vortex-aggregates Signed-off-by: Will Manning Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- vortex-aggregates/src/tests/stats.rs | 43 +++++++++++++++++++ .../src/arrays/constant/vtable/canonical.rs | 31 ------------- vortex-array/src/stats/stat.rs | 16 ------- 3 files changed, 43 insertions(+), 47 deletions(-) diff --git a/vortex-aggregates/src/tests/stats.rs b/vortex-aggregates/src/tests/stats.rs index d0d3ffefa67..5044efee2ab 100644 --- a/vortex-aggregates/src/tests/stats.rs +++ b/vortex-aggregates/src/tests/stats.rs @@ -19,9 +19,11 @@ use vortex_array::dtype::DType; use vortex_array::dtype::FieldNames; use vortex_array::dtype::Nullability; use vortex_array::dtype::PType; +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::StatsProviderExt; use vortex_array::validity::Validity; use vortex_error::VortexExpect; @@ -161,3 +163,44 @@ fn valid_count_caches_sum_on_bool_validity() -> VortexResult<()> { assert_eq!(first, second); Ok(()) } + +#[test] +fn test_canonicalize_propagates_stats() -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let scalar = Scalar::bool(true, Nullability::NonNullable); + let const_array = ConstantArray::new(scalar, 4).into_array(); + let stats = const_array + .statistics() + .compute_all(&all::().collect_vec(), &mut ctx)?; + let canonical = const_array.execute::(&mut ctx)?.into_array(); + let canonical_stats = canonical.statistics(); + + let stats_ref = stats.as_typed_ref(canonical.dtype()); + + for stat in all::() { + if stat.dtype(canonical.dtype()).is_none() { + continue; + } + assert!( + !stats_ref.get(stat).is_absent(), + "stat {stat} should be computed" + ); + assert_eq!( + canonical_stats.get(stat), + stats_ref.get(stat), + "stat mismatch {stat}" + ); + } + Ok(()) +} + +#[test] +fn min_of_nulls_is_not_panic() -> VortexResult<()> { + assert!(Stat::Min.resolve_aggregate_fn(&SESSION)?.is_some()); + let min = PrimitiveArray::from_option_iter::([None, None, None, None]) + .statistics() + .compute_as::(Stat::Min, &mut SESSION.create_execution_ctx()); + + assert_eq!(min, None); + Ok(()) +} diff --git a/vortex-array/src/arrays/constant/vtable/canonical.rs b/vortex-array/src/arrays/constant/vtable/canonical.rs index 05d5cfef90e..768588468bf 100644 --- a/vortex-array/src/arrays/constant/vtable/canonical.rs +++ b/vortex-array/src/arrays/constant/vtable/canonical.rs @@ -547,8 +547,6 @@ mod tests { use std::sync::Arc; use std::sync::LazyLock; - use enum_iterator::all; - use itertools::Itertools; use rstest::rstest; use vortex_buffer::buffer; use vortex_error::VortexExpect; @@ -557,7 +555,6 @@ mod tests { use vortex_session::VortexSession; use crate::ArrayRef; - use crate::Canonical; use crate::IntoArray; use crate::VortexSessionExecute; use crate::arrays::BoolArray; @@ -588,8 +585,6 @@ mod tests { 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. @@ -633,32 +628,6 @@ mod tests { assert_arrays_eq!(const_array, expected, &mut ctx); } - #[test] - fn test_canonicalize_propagates_stats() -> VortexResult<()> { - let mut ctx = SESSION.create_execution_ctx(); - let scalar = Scalar::bool(true, Nullability::NonNullable); - let const_array = ConstantArray::new(scalar, 4).into_array(); - let stats = const_array - .statistics() - .compute_all(&all::().collect_vec(), &mut ctx)?; - let canonical = const_array.execute::(&mut ctx)?.into_array(); - let canonical_stats = canonical.statistics(); - - let stats_ref = stats.as_typed_ref(canonical.dtype()); - - for stat in all::() { - if stat.dtype(canonical.dtype()).is_none() { - continue; - } - assert_eq!( - canonical_stats.get(stat), - stats_ref.get(stat), - "stat mismatch {stat}" - ); - } - Ok(()) - } - #[test] fn test_canonicalize_scalar_values() { let mut ctx = SESSION.create_execution_ctx(); diff --git a/vortex-array/src/stats/stat.rs b/vortex-array/src/stats/stat.rs index 7edaa51ccd1..12cb19fc738 100644 --- a/vortex-array/src/stats/stat.rs +++ b/vortex-array/src/stats/stat.rs @@ -369,26 +369,10 @@ fn supports_uncompressed_size_in_bytes(dtype: &DType) -> bool { #[cfg(test)] mod test { - use std::sync::LazyLock; - use enum_iterator::all; - use vortex_session::VortexSession; - use crate::VortexSessionExecute; - use crate::arrays::PrimitiveArray; use crate::stats::Stat; - static SESSION: LazyLock = LazyLock::new(VortexSession::empty); - - #[test] - fn min_of_nulls_is_not_panic() { - let min = PrimitiveArray::from_option_iter::([None, None, None, None]) - .statistics() - .compute_as::(Stat::Min, &mut SESSION.create_execution_ctx()); - - assert_eq!(min, None); - } - #[test] fn has_same_dtype_as_array() { assert!(Stat::Min.has_same_dtype_as_array());