diff --git a/vortex-expr/src/stats/derive.rs b/vortex-expr/src/stats/derive.rs new file mode 100644 index 00000000000..73f70b8b472 --- /dev/null +++ b/vortex-expr/src/stats/derive.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Session-registered derivations of a scalar function's result statistics from the statistics +//! of its inputs. +//! +//! Stats rewrite rules bound sub-expressions of a predicate, such as the min and max of +//! `cast(col)` in `cast(col) > 5`. Statistics are stored only for columns, so a statistic of +//! `cast(col)` must be expressed in terms of the statistics of `col`. A [`StatDerivation`] +//! registered for a scalar function says how. + +use std::fmt::Debug; +use std::sync::Arc; + +use vortex_array::aggregate_fn::AggregateFnRef; +use vortex_array::expr::BoundExpression; +use vortex_array::scalar_fn::ScalarFnId; +use vortex_session::VortexSession; + +use crate::stats::bound; +use crate::stats::session::StatsSessionExt; + +/// Shared reference to a statistic derivation. +pub type StatDerivationRef = Arc; + +/// Expresses the statistics of a scalar function's result in terms of the statistics of its +/// inputs. +/// +/// At most one derivation is registered per scalar function. When one is registered, it decides +/// every statistic of expressions rooted at that function: stats rewrites never read a statistic +/// stored for such an expression itself. +pub trait StatDerivation: Debug + Send + Sync + 'static { + /// Returns the scalar function id whose statistics this derivation describes. + fn scalar_fn_id(&self) -> ScalarFnId; + + /// Expresses the statistic `aggregate_fn` of `expr`, whose root scalar function id is + /// [`Self::scalar_fn_id`], as an expression over statistics of other expressions. + /// + /// Returns `None` when the statistic cannot be known from statistics. + fn derive_stat( + &self, + expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + session: &VortexSession, + ) -> Option; +} + +/// Expresses the statistic `aggregate_fn` of `expr` as an expression over the statistics that +/// can be read for the current scope. +/// +/// If a [`StatDerivation`] is registered for the root scalar function of `expr`, it decides the +/// statistic. Otherwise this is a reference to `aggregate_fn` of `expr` itself. Returns `None` +/// when the statistic cannot be known, for example when the aggregate does not support the dtype +/// of `expr`. +pub fn stat_expr( + expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + session: &VortexSession, +) -> Option { + if let Some(scalar_fn) = expr.as_scalar() + && let Some(derivation) = session.stats().stat_derivation_for(scalar_fn.id()) + { + return derivation.derive_stat(expr, aggregate_fn, session); + } + + // The aggregate may not support the expression's dtype, e.g. min/max over structs, + // even when the predicate itself is well-typed. Such stats cannot be lowered later, + // so do not reference them in the rewrite. + aggregate_fn + .return_dtype(expr.dtype()) + .is_some() + .then(|| bound::stat(expr.clone(), aggregate_fn.clone())) +} + +#[cfg(test)] +mod tests { + 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; + use vortex_array::expr::BoundExpression; + use vortex_array::expr::bound::lit; + use vortex_array::expr::col; + use vortex_array::scalar_fn::ScalarFnId; + use vortex_array::scalar_fn::ScalarFnVTable; + use vortex_error::VortexResult; + use vortex_functions::byte_length::ByteLength; + use vortex_functions::expr::byte_length; + use vortex_session::VortexSession; + + use super::StatDerivation; + use super::stat_expr; + use crate::stats::session::StatsSessionExt; + + /// Bounds the max byte length of every value by a fixed length, and knows no other statistic. + #[derive(Debug)] + struct MaxByteLength(u64); + + impl StatDerivation for MaxByteLength { + fn scalar_fn_id(&self) -> ScalarFnId { + ByteLength.id() + } + + fn derive_stat( + &self, + _expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + _session: &VortexSession, + ) -> Option { + aggregate_fn.is::().then(|| lit(self.0)) + } + } + + fn byte_length_of_column() -> VortexResult { + byte_length(col("s")).bind(&DType::Struct( + StructFields::from_iter([("s", DType::Utf8(Nullability::NonNullable))]), + Nullability::NonNullable, + )) + } + + #[test] + fn registered_derivation_decides_every_statistic() -> VortexResult<()> { + let session = VortexSession::empty(); + session.stats().register_stat_derivation(MaxByteLength(8)); + let expr = byte_length_of_column()?; + + assert_eq!( + stat_expr( + &expr, + &Max.bind(NumericalAggregateOpts::skip_nans()), + &session + ), + Some(lit(8u64)) + ); + // The derivation knows no min, and no stored min of `byte_length(s)` is read instead. + assert_eq!( + stat_expr( + &expr, + &Min.bind(NumericalAggregateOpts::skip_nans()), + &session + ), + None + ); + Ok(()) + } + + #[test] + fn later_registration_replaces_earlier() -> VortexResult<()> { + let session = VortexSession::empty(); + session.stats().register_stat_derivation(MaxByteLength(8)); + session.stats().register_stat_derivation(MaxByteLength(16)); + + assert_eq!( + stat_expr( + &byte_length_of_column()?, + &Max.bind(NumericalAggregateOpts::skip_nans()), + &session + ), + Some(lit(16u64)) + ); + Ok(()) + } +} diff --git a/vortex-expr/src/stats/mod.rs b/vortex-expr/src/stats/mod.rs index 71d9ebb1c49..c5df8698b44 100644 --- a/vortex-expr/src/stats/mod.rs +++ b/vortex-expr/src/stats/mod.rs @@ -17,6 +17,7 @@ pub use expr::sum; pub use session::*; pub mod bind; +pub mod derive; pub mod expr; pub mod rewrite; pub mod session; diff --git a/vortex-expr/src/stats/rewrite/builtins.rs b/vortex-expr/src/stats/rewrite/builtins.rs index 47714c31bf0..b62850d74ad 100644 --- a/vortex-expr/src/stats/rewrite/builtins.rs +++ b/vortex-expr/src/stats/rewrite/builtins.rs @@ -6,10 +6,15 @@ use std::cmp::Ordering; 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::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::expr::BoundExpression; use vortex_array::expr::bound::and; @@ -24,7 +29,6 @@ use vortex_array::expr::bound::lt; use vortex_array::expr::bound::lt_eq; use vortex_array::expr::bound::or; use vortex_array::expr::bound::or_collect; -use vortex_array::expr::stats::Stat; use vortex_array::scalar::Scalar; use vortex_array::scalar::StringLike; use vortex_array::scalar_fn::EmptyOptions; @@ -56,7 +60,8 @@ use vortex_functions::lower_bound::LowerBound; use vortex_functions::lower_bound::LowerBoundKind; use vortex_session::VortexSession; -use crate::stats::bound::stat; +use crate::stats::derive::StatDerivation; +use crate::stats::derive::stat_expr; use crate::stats::rewrite::StatsRewriteRule; use crate::stats::rewrite::dynamic_expression::StatsProof; use crate::stats::rewrite::dynamic_expression::dynamic_stats_proof; @@ -87,6 +92,9 @@ pub(crate) fn register_builtins(session: &StatsSession) { session.register_rewrite(DynamicComparisonNanCountStatsRewrite); session.register_rewrite(DynamicComparisonAllNonNanStatsRewrite); session.register_rewrite(DynamicExpressionStatsRewrite); + session.register_stat_derivation(LiteralStatDerivation); + session.register_stat_derivation(CastStatDerivation); + session.register_stat_derivation(LowerStatDerivation); } fn row_count() -> BoundExpression { @@ -120,6 +128,117 @@ impl StatsRewriteRule for LiteralStatsRewrite { } } +/// A literal's statistics are its value. A statistic that is not meaningful for the literal, such +/// as `NaNCount` over a non-float value, is unknown rather than read from the literal. +#[derive(Debug)] +struct LiteralStatDerivation; + +impl StatDerivation for LiteralStatDerivation { + fn scalar_fn_id(&self) -> ScalarFnId { + Literal.id() + } + + fn derive_stat( + &self, + expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + _session: &VortexSession, + ) -> Option { + let scalar = expr.as_::(); + if aggregate_fn.is::() || aggregate_fn.is::() { + return Some(lit(scalar.clone())); + } + if aggregate_fn.is::() { + return Some(lit(if scalar.is_null() { 1u64 } else { 0u64 })); + } + if aggregate_fn.is::() { + return Some(lit(scalar.is_null())); + } + if aggregate_fn.is::() { + return Some(lit(!scalar.is_null())); + } + let value = scalar.as_primitive_opt()?; + if !value.ptype().is_float() { + return None; + } + if aggregate_fn.is::() { + return Some(lit(if value.is_nan() { 1u64 } else { 0u64 })); + } + // Whether a null is NaN is unknown, so only a non-null value answers these. + if scalar.is_null() { + return None; + } + if aggregate_fn.is::() { + return Some(lit(value.is_nan())); + } + if aggregate_fn.is::() { + return Some(lit(!value.is_nan())); + } + None + } +} + +/// Derives the statistics of `cast(input)` from the statistics of `input`. +#[derive(Debug)] +struct CastStatDerivation; + +impl StatDerivation for CastStatDerivation { + fn scalar_fn_id(&self) -> ScalarFnId { + Cast.id() + } + + fn derive_stat( + &self, + expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + session: &VortexSession, + ) -> Option { + let input = expr.child(0); + if aggregate_fn.is::() || aggregate_fn.is::() { + return stat_expr(input, aggregate_fn, session) + .map(|stat| cast(stat, expr.as_::().clone())); + } + // A cast keeps NaNs as NaNs. It changes the sum's dtype and the size of each value, so + // neither carries over from the input. + if aggregate_fn.is::() { + return stat_expr(input, aggregate_fn, session); + } + None + } +} + +/// Bounds the statistics of `lower(input)` from the byte-ordered min/max of `input`. +#[derive(Debug)] +struct LowerStatDerivation; + +impl StatDerivation for LowerStatDerivation { + fn scalar_fn_id(&self) -> ScalarFnId { + Lower.id() + } + + fn derive_stat( + &self, + expr: &BoundExpression, + aggregate_fn: &AggregateFnRef, + session: &VortexSession, + ) -> Option { + let input = expr.child(0); + let kind = if aggregate_fn.is::() { + LowerBoundKind::Min + } else if aggregate_fn.is::() { + LowerBoundKind::Max + } else if aggregate_fn.is::() { + // Lowercasing maps nulls to nulls and values to values. + return null_count(input, session); + } else { + return None; + }; + LowerBound + .try_new_bound_expr(kind, [min(input, session)?, max(input, session)?]) + .ok() + } +} + /// Bool literal predicate value fn literal_truth(expr: &BoundExpression) -> Option { expr.as_::().as_bool_opt().and_then(|b| b.value()) @@ -136,9 +255,9 @@ impl StatsRewriteRule for CompareNanCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - compare_falsify::(expr) + compare_falsify::(expr, session) } } @@ -153,9 +272,9 @@ impl StatsRewriteRule for CompareAllNonNanStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - compare_falsify::(expr) + compare_falsify::(expr, session) } } @@ -195,6 +314,7 @@ impl StatsRewriteRule for BooleanAllNonNanStatsRewrite { fn compare_falsify( expr: &BoundExpression, + session: &VortexSession, ) -> VortexResult> { let operator = expr.as_::(); let lhs = expr.child(0); @@ -202,42 +322,49 @@ fn compare_falsify( Ok(match operator { CompareOperator::Eq => { - let left = min(lhs).zip(max(rhs)).map(|(a, b)| gt(a, b)); - let right = min(rhs).zip(max(lhs)).map(|(a, b)| gt(a, b)); + let left = min(lhs, session) + .zip(max(rhs, session)) + .map(|(a, b)| gt(a, b)); + let right = min(rhs, session) + .zip(max(lhs, session)) + .map(|(a, b)| gt(a, b)); or_collect(left.into_iter().chain(right)) - .map(|value_predicate| with_non_nan_guards::

([lhs, rhs], value_predicate)) + .map(|value_predicate| { + with_non_nan_guards::

([lhs, rhs], value_predicate, session) + }) .transpose()? .flatten() } - CompareOperator::NotEq => min(lhs) - .zip(max(rhs)) - .zip(max(lhs).zip(min(rhs))) + CompareOperator::NotEq => min(lhs, session) + .zip(max(rhs, session)) + .zip(max(lhs, session).zip(min(rhs, session))) .map(|((min_lhs, max_rhs), (max_lhs, min_rhs))| { with_non_nan_guards::

( [lhs, rhs], and(eq(min_lhs, max_rhs), eq(max_lhs, min_rhs)), + session, ) }) .transpose()? .flatten(), - CompareOperator::Gt => max(lhs) - .zip(min(rhs)) - .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], lt_eq(a, b))) + CompareOperator::Gt => max(lhs, session) + .zip(min(rhs, session)) + .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], lt_eq(a, b), session)) .transpose()? .flatten(), - CompareOperator::Gte => max(lhs) - .zip(min(rhs)) - .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], lt(a, b))) + CompareOperator::Gte => max(lhs, session) + .zip(min(rhs, session)) + .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], lt(a, b), session)) .transpose()? .flatten(), - CompareOperator::Lt => min(lhs) - .zip(max(rhs)) - .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], gt_eq(a, b))) + CompareOperator::Lt => min(lhs, session) + .zip(max(rhs, session)) + .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], gt_eq(a, b), session)) .transpose()? .flatten(), - CompareOperator::Lte => min(lhs) - .zip(max(rhs)) - .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], gt(a, b))) + CompareOperator::Lte => min(lhs, session) + .zip(max(rhs, session)) + .map(|(a, b)| with_non_nan_guards::

([lhs, rhs], gt(a, b), session)) .transpose()? .flatten(), }) @@ -312,17 +439,17 @@ impl StatsRewriteRule for IsNullNullCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(null_count(expr.child(0)).map(|null_count| eq(null_count, lit(0u64)))) + Ok(null_count(expr.child(0), session).map(|null_count| eq(null_count, lit(0u64)))) } fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(null_count(expr.child(0)).map(|null_count| eq(null_count, row_count()))) + Ok(null_count(expr.child(0), session).map(|null_count| eq(null_count, row_count()))) } } @@ -337,9 +464,9 @@ impl StatsRewriteRule for IsNullAllNonNullStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_non_null(expr.child(0)))) + Ok(all_non_null(expr.child(0), session)) } } @@ -354,9 +481,9 @@ impl StatsRewriteRule for IsNullAllNullStatsRewrite { fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_null(expr.child(0)))) + Ok(all_null(expr.child(0), session)) } } @@ -371,17 +498,17 @@ impl StatsRewriteRule for IsNotNullNullCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(null_count(expr.child(0)).map(|null_count| eq(null_count, row_count()))) + Ok(null_count(expr.child(0), session).map(|null_count| eq(null_count, row_count()))) } fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(null_count(expr.child(0)).map(|null_count| eq(null_count, lit(0u64)))) + Ok(null_count(expr.child(0), session).map(|null_count| eq(null_count, lit(0u64)))) } } @@ -396,9 +523,9 @@ impl StatsRewriteRule for IsNotNullAllNullStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_null(expr.child(0)))) + Ok(all_null(expr.child(0), session)) } } @@ -413,9 +540,9 @@ impl StatsRewriteRule for IsNotNullAllNonNullStatsRewrite { fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_non_null(expr.child(0)))) + Ok(all_non_null(expr.child(0), session)) } } @@ -432,17 +559,17 @@ impl StatsRewriteRule for IsNanNaNCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(nan_count(expr.child(0)).map(|nan_count| eq(nan_count, lit(0u64)))) + Ok(nan_count(expr.child(0), session).map(|nan_count| eq(nan_count, lit(0u64)))) } fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(nan_count(expr.child(0)).map(|nan_count| eq(nan_count, row_count()))) + Ok(nan_count(expr.child(0), session).map(|nan_count| eq(nan_count, row_count()))) } } @@ -459,9 +586,9 @@ impl StatsRewriteRule for IsNanAllNonNanStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_non_nan(expr.child(0)))) + Ok(all_non_nan(expr.child(0), session)) } } @@ -478,9 +605,9 @@ impl StatsRewriteRule for IsNanAllNanStatsRewrite { fn satisfy( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - Ok(Some(all_nan(expr.child(0)))) + Ok(all_nan(expr.child(0), session)) } } @@ -495,7 +622,7 @@ impl StatsRewriteRule for LikeStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { let like_options = expr.as_::(); if like_options.negated || like_options.case_insensitive { @@ -512,8 +639,8 @@ impl StatsRewriteRule for LikeStatsRewrite { let source = expr.child(0); Ok(match LikeVariant::from_str(pattern) { Some(LikeVariant::Exact(text)) => { - min(source) - .zip(max(source)) + min(source, session) + .zip(max(source, session)) .map(|(source_min, source_max)| { or( gt(source_min, lit(text.as_ref())), @@ -525,8 +652,8 @@ impl StatsRewriteRule for LikeStatsRewrite { let Some(successor) = prefix.to_string().increment().ok() else { return Ok(None); }; - min(source) - .zip(max(source)) + min(source, session) + .zip(max(source, session)) .map(|(source_min, source_max)| { or( gt_eq(source_min, lit(successor)), @@ -550,9 +677,9 @@ impl StatsRewriteRule for ListContainsNanCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - list_contains_falsify::(expr) + list_contains_falsify::(expr, session) } } @@ -567,9 +694,9 @@ impl StatsRewriteRule for ListContainsAllNonNanStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - list_contains_falsify::(expr) + list_contains_falsify::(expr, session) } } @@ -598,6 +725,7 @@ fn non_null_bounds(elements: &[Scalar]) -> Option<(&Scalar, &Scalar)> { fn list_contains_falsify( expr: &BoundExpression, + session: &VortexSession, ) -> VortexResult> { let list = expr.child(0); let needle = expr.child(1); @@ -615,10 +743,10 @@ fn list_contains_falsify( return Ok(P::EMIT_UNGUARDED_REWRITES.then(|| lit(true))); } - let Some(value_max) = max(needle) else { + let Some(value_max) = max(needle, session) else { return Ok(None); }; - let Some(value_min) = min(needle) else { + let Some(value_min) = min(needle, session) else { return Ok(None); }; @@ -638,7 +766,7 @@ fn list_contains_falsify( })) }; value_predicate - .map(|value_predicate| with_non_nan_guards::

([needle], value_predicate)) + .map(|value_predicate| with_non_nan_guards::

([needle], value_predicate, session)) .transpose() .map(Option::flatten) } @@ -654,9 +782,9 @@ impl StatsRewriteRule for DynamicComparisonNanCountStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - dynamic_comparison_falsify::(expr) + dynamic_comparison_falsify::(expr, session) } } @@ -671,24 +799,25 @@ impl StatsRewriteRule for DynamicComparisonAllNonNanStatsRewrite { fn falsify( &self, expr: &BoundExpression, - _session: &VortexSession, + session: &VortexSession, ) -> VortexResult> { - dynamic_comparison_falsify::(expr) + dynamic_comparison_falsify::(expr, session) } } fn dynamic_comparison_falsify( expr: &BoundExpression, + session: &VortexSession, ) -> VortexResult> { let dynamic = expr.as_::(); let lhs = expr.child(0); let Some((operator, lhs_stat)) = (match dynamic.operator() { CompareOperator::Eq | CompareOperator::NotEq => None, - CompareOperator::Gt => max(lhs).map(|lhs_stat| (CompareOperator::Lte, lhs_stat)), - CompareOperator::Gte => max(lhs).map(|lhs_stat| (CompareOperator::Lt, lhs_stat)), - CompareOperator::Lt => min(lhs).map(|lhs_stat| (CompareOperator::Gte, lhs_stat)), - CompareOperator::Lte => min(lhs).map(|lhs_stat| (CompareOperator::Gt, lhs_stat)), + CompareOperator::Gt => max(lhs, session).map(|lhs_stat| (CompareOperator::Lte, lhs_stat)), + CompareOperator::Gte => max(lhs, session).map(|lhs_stat| (CompareOperator::Lt, lhs_stat)), + CompareOperator::Lt => min(lhs, session).map(|lhs_stat| (CompareOperator::Gte, lhs_stat)), + CompareOperator::Lte => min(lhs, session).map(|lhs_stat| (CompareOperator::Gt, lhs_stat)), }) else { return Ok(None); }; @@ -697,39 +826,48 @@ fn dynamic_comparison_falsify( dynamic.with_operator(operator, !dynamic.default()), lhs_stat, ); - with_non_nan_guards::

([lhs], value_predicate) + with_non_nan_guards::

([lhs], value_predicate, session) } -fn min(expr: &BoundExpression) -> Option { - stat_expr(expr, Stat::Min) +// Statistics follow NaN-skipping semantics, so min and max request it explicitly. +fn min(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr( + expr, + &Min.bind(NumericalAggregateOpts::skip_nans()), + session, + ) } -fn max(expr: &BoundExpression) -> Option { - stat_expr(expr, Stat::Max) +fn max(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr( + expr, + &Max.bind(NumericalAggregateOpts::skip_nans()), + session, + ) } -fn null_count(expr: &BoundExpression) -> Option { - stat_expr(expr, Stat::NullCount) +fn null_count(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &NullCount.bind(AggregateEmptyOptions), session) } -fn nan_count(expr: &BoundExpression) -> Option { - stat_expr(expr, Stat::NaNCount) +fn nan_count(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &NanCount.bind(AggregateEmptyOptions), session) } -fn all_null(expr: &BoundExpression) -> BoundExpression { - stat_fn(expr.clone(), AllNull.bind(AggregateEmptyOptions)) +fn all_null(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &AllNull.bind(AggregateEmptyOptions), session) } -fn all_non_null(expr: &BoundExpression) -> BoundExpression { - stat_fn(expr.clone(), AllNonNull.bind(AggregateEmptyOptions)) +fn all_non_null(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &AllNonNull.bind(AggregateEmptyOptions), session) } -fn all_nan(expr: &BoundExpression) -> BoundExpression { - stat_fn(expr.clone(), AllNan.bind(AggregateEmptyOptions)) +fn all_nan(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &AllNan.bind(AggregateEmptyOptions), session) } -fn all_non_nan(expr: &BoundExpression) -> BoundExpression { - stat_fn(expr.clone(), AllNonNan.bind(AggregateEmptyOptions)) +fn all_non_nan(expr: &BoundExpression, session: &VortexSession) -> Option { + stat_expr(expr, &AllNonNan.bind(AggregateEmptyOptions), session) } enum NanCheck { @@ -741,7 +879,7 @@ enum NanCheck { trait NonNanProof { const EMIT_UNGUARDED_REWRITES: bool; - fn check(expr: &BoundExpression) -> VortexResult; + fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult; } struct NanCountProof; @@ -749,8 +887,8 @@ struct NanCountProof; impl NonNanProof for NanCountProof { const EMIT_UNGUARDED_REWRITES: bool = true; - fn check(expr: &BoundExpression) -> VortexResult { - non_nan_check(expr, |expr| match stat_expr(expr, Stat::NaNCount) { + fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult { + non_nan_check(expr, |expr| match nan_count(expr, session) { Some(nan_count) => NanCheck::Check(eq(nan_count, lit(0u64))), None => NanCheck::Unavailable, }) @@ -762,9 +900,10 @@ struct AllNonNanProof; impl NonNanProof for AllNonNanProof { const EMIT_UNGUARDED_REWRITES: bool = false; - fn check(expr: &BoundExpression) -> VortexResult { - non_nan_check(expr, |expr| { - NanCheck::Check(stat_fn(expr.clone(), AllNonNan.bind(AggregateEmptyOptions))) + fn check(expr: &BoundExpression, session: &VortexSession) -> VortexResult { + non_nan_check(expr, |expr| match all_non_nan(expr, session) { + Some(all_non_nan) => NanCheck::Check(all_non_nan), + None => NanCheck::Unavailable, }) } } @@ -806,43 +945,14 @@ fn has_nans(dtype: &DType) -> bool { dtype.is_float() } -fn stat_expr(expr: &BoundExpression, stat: Stat) -> Option { - if let Some(literal) = literal_stat(expr, stat) { - return Some(literal); - } - - // `literal_stat` handled every stat that is defined for literals. If it returned - // `None`, the requested stat is not meaningful for this literal, such as - // `NaNCount` over a non-float value, so do not manufacture `stat(literal, ...)`. - if expr.is::() { - return None; - } - - if let Some(dtype) = expr.as_opt::() { - return cast_stat(expr.child(0), dtype, stat); - } - - if expr.is::() { - return lower_stat(expr.child(0), stat); - } - - let aggregate_fn = stat.aggregate_fn()?; - // The aggregate may not support the expression's dtype, e.g. min/max over structs, - // even when the predicate itself is well-typed. Such stats cannot be lowered later, - // so do not reference them in the rewrite. - aggregate_fn - .return_dtype(expr.dtype()) - .is_some() - .then(|| stat_fn(expr.clone(), aggregate_fn)) -} - fn with_non_nan_guards<'a, P: NonNanProof>( exprs: impl IntoIterator, value_predicate: BoundExpression, + session: &VortexSession, ) -> VortexResult> { let mut nan_checks = Vec::new(); for expr in exprs { - match P::check(expr)? { + match P::check(expr, session)? { NanCheck::NotNeeded => {} NanCheck::Check(check) => nan_checks.push(check), NanCheck::Unavailable => return Ok(None), @@ -860,53 +970,6 @@ fn with_non_nan_guards<'a, P: NonNanProof>( }) } -fn literal_stat(expr: &BoundExpression, stat: Stat) -> Option { - let scalar = expr.as_opt::()?; - match stat { - Stat::Min | Stat::Max => Some(lit(scalar.clone())), - Stat::NullCount => Some(lit(if scalar.is_null() { 1u64 } else { 0u64 })), - Stat::NaNCount => { - let value = scalar.as_primitive_opt()?; - if !value.ptype().is_float() { - return None; - } - - Some(lit(if value.is_nan() { 1u64 } else { 0u64 })) - } - Stat::IsConstant - | Stat::IsSorted - | Stat::IsStrictSorted - | Stat::Sum - | Stat::UncompressedSizeInBytes => None, - } -} - -fn cast_stat(expr: &BoundExpression, dtype: &DType, stat: Stat) -> Option { - match stat { - Stat::Min | Stat::Max => stat_expr(expr, stat).map(|stat| cast(stat, dtype.clone())), - Stat::NaNCount | Stat::Sum | Stat::UncompressedSizeInBytes => stat_expr(expr, stat), - Stat::NullCount | Stat::IsConstant | Stat::IsSorted | Stat::IsStrictSorted => None, - } -} - -/// Bounds `lower(input)` from the byte-ordered min/max of `input`. -fn lower_stat(input: &BoundExpression, stat: Stat) -> Option { - let kind = match stat { - Stat::Min => LowerBoundKind::Min, - Stat::Max => LowerBoundKind::Max, - // Lowercasing maps nulls to nulls and values to values. - Stat::NullCount => return null_count(input), - _ => return None, - }; - LowerBound - .try_new_bound_expr(kind, [min(input)?, max(input)?]) - .ok() -} - -fn stat_fn(expr: BoundExpression, aggregate_fn: AggregateFnRef) -> BoundExpression { - stat(expr, aggregate_fn) -} - #[cfg(test)] mod tests { use std::sync::Arc; @@ -1225,10 +1288,10 @@ mod tests { )) ); - // NaN literals fold through the nan_count stat. + // NaN literals fold through the nan_count and all_non_nan stats. assert_rewrite_eq!( falsify(&is_nan(lit(f32::NAN)))?, - Some(or(eq(lit(1u64), lit(0u64)), all_non_nan(&lit(f32::NAN)))) + Some(or(eq(lit(1u64), lit(0u64)), lit(false))) ); Ok(()) } @@ -1250,7 +1313,7 @@ mod tests { satisfy(&is_nan(lit(f32::NAN)))?, Some(or( eq(lit(1u64), RowCount.new_expr(EmptyOptions, [])), - all_nan(&lit(f32::NAN)), + lit(true), )) ); Ok(()) diff --git a/vortex-expr/src/stats/session.rs b/vortex-expr/src/stats/session.rs index edc5de15c08..e8a56d10a7a 100644 --- a/vortex-expr/src/stats/session.rs +++ b/vortex-expr/src/stats/session.rs @@ -13,6 +13,8 @@ use vortex_session::SessionGuard; use vortex_session::SessionVar; use vortex_utils::aliases::hash_map::HashMap; +use crate::stats::derive::StatDerivation; +use crate::stats::derive::StatDerivationRef; use crate::stats::rewrite::StatsRewriteRule; use crate::stats::rewrite::StatsRewriteRuleRef; use crate::stats::rewrite::register_builtins; @@ -23,12 +25,14 @@ type StatsRewriteRuleSet = Arc<[StatsRewriteRuleRef]>; #[derive(Clone, Debug)] pub struct StatsSession { rewrite_rules: Arc>>, + stat_derivations: Arc>>, } impl Default for StatsSession { fn default() -> Self { let this = Self { rewrite_rules: Arc::new(RwLock::new(HashMap::default())), + stat_derivations: Arc::new(RwLock::new(HashMap::default())), }; register_builtins(&this); this @@ -60,6 +64,29 @@ impl StatsSession { ) -> Option { self.rewrite_rules.read().get(&scalar_fn_id).cloned() } + + /// Register how the statistics of a scalar function's result derive from its inputs'. + /// + /// This replaces any derivation already registered for that function, including a builtin + /// one, so a plugin can refine how a function's statistics are derived. + pub fn register_stat_derivation(&self, derivation: D) { + self.register_stat_derivation_ref(Arc::new(derivation)); + } + + /// Register a shared statistic derivation. See [`Self::register_stat_derivation`]. + pub fn register_stat_derivation_ref(&self, derivation: StatDerivationRef) { + self.stat_derivations + .write() + .insert(derivation.scalar_fn_id(), derivation); + } + + /// Return the statistic derivation registered for `scalar_fn_id`. + pub(crate) fn stat_derivation_for( + &self, + scalar_fn_id: ScalarFnId, + ) -> Option { + self.stat_derivations.read().get(&scalar_fn_id).cloned() + } } impl SessionVar for StatsSession {