diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 1ea07c071..b802d4784 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -2783,6 +2783,7 @@ fn a_finalize_charges_each_group_its_measured_time() { let finalize = node(Payload::ASAP(ASAPOp::FinalizeExactAccumulator { child: 0, counter_readout: None, + variance_readout: None, })); let usage = node_resource_usage_and_cost( &finalize, @@ -3787,6 +3788,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { let finalize = node(Payload::ASAP(ASAPOp::FinalizeExactAccumulator { child: 0, counter_readout: None, + variance_readout: None, })); check( "FinalizeExactAccumulator", diff --git a/crates/devtools/tests/viewer_contract.rs b/crates/devtools/tests/viewer_contract.rs index c25fbe004..84de61e3a 100644 --- a/crates/devtools/tests/viewer_contract.rs +++ b/crates/devtools/tests/viewer_contract.rs @@ -188,6 +188,7 @@ fn asap_samples() -> Vec> { ASAPOp::FinalizeExactAccumulator { child: (), counter_readout: None, + variance_readout: None, }, ASAPOp::MaintainPopulation { child: (), diff --git a/crates/executor/src/capability/mod.rs b/crates/executor/src/capability/mod.rs index f9d51ed96..d643f2050 100644 --- a/crates/executor/src/capability/mod.rs +++ b/crates/executor/src/capability/mod.rs @@ -368,13 +368,16 @@ pub fn validate_exact_evaluation( validate_native_family(family)?; use planner_types::summary_type::ExactKind as E; // `validate_native_family` admits only exact families with a kernel. - // A counter state is read as `rate` or `increase`; no other exact - // state takes a counter readout. + // A counter state is read as `rate` or `increase`, a sum of squared + // deviations as a variance or standard deviation; no other exact + // state takes a readout. let supported = matches!( family, SummaryFamilyType::ExactAggregate(kind, _) if *kind == evaluation.statistic ) && (evaluation.statistic == E::Counter) - == evaluation.counter_readout.is_some(); + == evaluation.counter_readout.is_some() + && (evaluation.statistic == E::SumOfSquaredDeviations) + == evaluation.variance_readout.is_some(); if !supported { return Err(Error::Invalid( "evaluation is not implemented for this summary family".into(), diff --git a/crates/executor/src/evaluation.rs b/crates/executor/src/evaluation.rs index df0139e19..ce68fc205 100644 --- a/crates/executor/src/evaluation.rs +++ b/crates/executor/src/evaluation.rs @@ -1,7 +1,7 @@ //! Evaluations over merged exact summary states. use crate::summary_kernels::exact::ExactAccumulator; use crate::AggregateCore; -use planner_types::summary_type::{CounterReadout, ExactKind}; +use planner_types::summary_type::{CounterReadout, ExactKind, VarianceReadout}; use std::sync::Arc; fn merge_exact_states( @@ -38,12 +38,15 @@ pub fn insufficient_counter_raw_data_samples( } /// Merge already selected exact tumbling windows and read one population, a -/// counter as `counter_readout`. `None` means the population is absent from -/// the result: a counter with too few samples, or an empty MIN/MAX. +/// counter as `counter_readout`, a sum of squared deviations as +/// `variance_readout`. `None` means the population is absent from the +/// result: a counter with too few samples, an empty MIN/MAX, or a variance +/// with too few values (SQL's NULL). pub fn exact_evaluation( states: impl IntoIterator>, statistic: ExactKind, counter_readout: Option, + variance_readout: Option, range_ms: Option<(i64, i64)>, key: Option<&[String]>, ) -> Result, String> { @@ -52,7 +55,7 @@ pub fn exact_evaluation( return Ok(None); } merged - .evaluation(statistic, counter_readout, range_ms, key) + .evaluation(statistic, counter_readout, variance_readout, range_ms, key) .map_err(|error| error.to_string()) } @@ -83,6 +86,7 @@ mod counter_tests { kind, (kind == ExactKind::Counter).then_some(CounterReadout::Rate), None, + None, key.as_deref() ) .unwrap(), @@ -101,16 +105,18 @@ mod counter_tests { let read = Some(CounterReadout::Rate); let one = [Arc::new(state.clone()) as Arc]; assert_eq!( - exact_evaluation(one, rate, read, Some((0, 60_000)), None).unwrap(), + exact_evaluation(one, rate, read, None, Some((0, 60_000)), None).unwrap(), None ); state.update(None, 20., 20_000); let two = || [Arc::new(state.clone()) as Arc]; - assert!(exact_evaluation(two(), rate, read, Some((0, 60_000)), None) - .unwrap() - .is_some()); - assert!(exact_evaluation(two(), rate, read, Some((60_000, 0)), None).is_err()); - assert!(exact_evaluation([], rate, read, Some((0, 60_000)), None).is_err()); + assert!( + exact_evaluation(two(), rate, read, None, Some((0, 60_000)), None) + .unwrap() + .is_some() + ); + assert!(exact_evaluation(two(), rate, read, None, Some((60_000, 0)), None).is_err()); + assert!(exact_evaluation([], rate, read, None, Some((0, 60_000)), None).is_err()); } // An irate state reads PromQL `irate` from its last two samples: a @@ -129,6 +135,7 @@ mod counter_tests { None, None, None, + None, ) }; // (8 - 5) over the last 10 s. @@ -143,6 +150,8 @@ mod counter_tests { state.update(None, 1., 0); Arc::new(state) as Arc }; - assert!(exact_evaluation([state(), state()], ExactKind::IRate, None, None, None).is_err()); + assert!( + exact_evaluation([state(), state()], ExactKind::IRate, None, None, None, None).is_err() + ); } } diff --git a/crates/executor/src/operators/aggregate/columnar.rs b/crates/executor/src/operators/aggregate/columnar.rs index 83b595104..8b36f7ce1 100644 --- a/crates/executor/src/operators/aggregate/columnar.rs +++ b/crates/executor/src/operators/aggregate/columnar.rs @@ -11,6 +11,7 @@ use crate::operators::common::{row_chunks, Workspace}; use crate::operators::group_table::GroupTable; use crate::operators::{Kind, Operator}; use crate::runtime::{Cooperative, Input, RunContext}; +use crate::summary_kernels::moments::Moments; use crate::values::arrow_columns::float64_array; use crate::values::arrow_columns::{self, ColumnDepth}; use crate::values::{Batch, SchemaRef, Value}; @@ -24,37 +25,6 @@ fn invalid(message: &str) -> Error { Error::Invalid(message.into()) } -/// Welford's running count, mean and sum of squared deviations from the -/// mean (its M2), as Prometheus `stddev`/`stdvar` and DataFusion's variance -/// update them: the same operations, so the same rounding. The values 1, 2 -/// and 4 give count 3, mean 7/3 and a sum of squared deviations of 14/3. -#[derive(Clone, Copy, Default)] -struct Moments { - count: u64, - mean: f64, - sum_squared_deviations: f64, -} - -impl Moments { - fn add(&mut self, value: f64) { - self.count += 1; - let delta = value - self.mean; - self.mean += delta / self.count as f64; - self.sum_squared_deviations += delta * (value - self.mean); - } - - /// The variance over n (`population`) or n - 1; `None` with no value, - /// or one value of a sample. 1, 2 and 4: 14/9, or 7/3 for a sample. - fn variance(&self, population: bool) -> Option { - let divisor = if population { - self.count - } else { - self.count.saturating_sub(1) - }; - (divisor > 0).then(|| self.sum_squared_deviations / divisor as f64) - } -} - /// DataFusion's `corr` state, Welford's update over pairs: the count, both /// inputs' running means and sums of squared deviations, and the /// co-moment (the sum of products of both deviations). The pairs (1, 3), diff --git a/crates/executor/src/operators/range_function.rs b/crates/executor/src/operators/range_function.rs index d75d7d51b..572cefe68 100644 --- a/crates/executor/src/operators/range_function.rs +++ b/crates/executor/src/operators/range_function.rs @@ -581,6 +581,7 @@ mod tests { [Arc::new(state) as Arc], ExactKind::Counter, Some(readout), + None, Some((start, end)), None, ) diff --git a/crates/executor/src/operators/summary/mod.rs b/crates/executor/src/operators/summary/mod.rs index af69b86fb..3edc5ece8 100644 --- a/crates/executor/src/operators/summary/mod.rs +++ b/crates/executor/src/operators/summary/mod.rs @@ -333,17 +333,27 @@ impl Operator { } else { DataType::Float64 }; - // A state-only row represents the global population. Its extrema may - // be empty, just like an ordinary ungrouped MIN/MAX aggregate. - let nullable = fields.len() == 1 - && matches!( - fields[state].dtype, - SummaryFamilyType::ExactAggregate( - planner_types::summary_type::ExactKind::Min - | planner_types::summary_type::ExactKind::Max, - _ - ) - ); + // A state-only row represents the global population. Its extrema and + // variance may be empty, just like an ordinary ungrouped MIN/MAX or + // VAR_POP aggregate. A sample variance is NULL with fewer than two + // values (SQL), in any group; a grouped population one only with none + // ([`Self::with_nullable_value`]). + let sample_variance = matches!( + &query, + SummaryEvaluation::Exact(evaluation) + if evaluation.variance_readout.is_some_and(|readout| !readout.population()) + ); + let nullable = sample_variance + || fields.len() == 1 + && matches!( + fields[state].dtype, + SummaryFamilyType::ExactAggregate( + planner_types::summary_type::ExactKind::Min + | planner_types::summary_type::ExactKind::Max + | planner_types::summary_type::ExactKind::SumOfSquaredDeviations, + _ + ) + ); fields[state] = result_field("value", result_type, nullable); Ok(Self { kind: Kind::Evaluation { state, query }, @@ -354,7 +364,7 @@ impl Operator { } /// Whether a per-group build of `family` takes values of `dtype`: every /// family takes Float64; an exact count any type (it counts values); an -/// exact sum, min or max also Int64 (SQL integer columns; each value as its +/// exact sum, min, max or sum of squared deviations also Int64 (SQL integer columns; each value as its /// exact Float64, refused beyond ±2^53); a sketch also takes Int64 (a numeric sketch as its exact Float64, a /// distinct count as an integer item); a distinct count (KMV, HLL) also /// takes Utf8, and UnivMon Utf8 and Bool. @@ -364,7 +374,10 @@ fn accepts_update_type(family: &SummaryFamilyType, dtype: &DataType) -> bool { return match family { SummaryFamilyType::ExactAggregate(ExactKind::Count, _) => true, SummaryFamilyType::ExactAggregate( - ExactKind::Sum | ExactKind::Min | ExactKind::Max, + ExactKind::Sum + | ExactKind::Min + | ExactKind::Max + | ExactKind::SumOfSquaredDeviations, _, ) => matches!(dtype, DataType::Float64 | DataType::Int64), _ => *dtype == DataType::Float64, @@ -402,6 +415,27 @@ impl Operator { } } +impl Operator { + /// This exact evaluation with a nullable value, where the Planner types + /// it so: a population variance over a nullable SQL column is NULL for a + /// group whose values are all NULL. + pub fn with_nullable_value(mut self) -> Result { + let Kind::Evaluation { + state, + query: SummaryEvaluation::Exact(_), + } = &self.kind + else { + return Err(invalid( + "a nullable exact value requires an exact evaluation", + )); + }; + let mut fields = self.output.fields.clone(); + fields[*state].nullable = true; + self.output = schema(fields); + Ok(self) + } +} + impl Operator { /// This exact SUM, MIN or MAX evaluation ([`Self::evaluation`] of an /// exact family) with an Int64 value, as SQL types the aggregate of an @@ -1473,7 +1507,11 @@ fn evaluate_states( )); } match record - .evaluation(evaluation.counter_readout, range_ms) + .evaluation( + evaluation.counter_readout, + evaluation.variance_readout, + range_ms, + ) .map_err(|e| Error::Operator(e.to_string()))? { // An Int64 sum, min or max (`with_whole_exact_value`): its diff --git a/crates/executor/src/physical_planner/mod.rs b/crates/executor/src/physical_planner/mod.rs index 57e3b0445..725a331c3 100644 --- a/crates/executor/src/physical_planner/mod.rs +++ b/crates/executor/src/physical_planner/mod.rs @@ -1251,7 +1251,9 @@ fn bind_operation( }; match &node.payload { Payload::ASAP(ASAPOp::FinalizeExactAccumulator { - counter_readout, .. + counter_readout, + variance_readout, + .. }) => { let state = summary_column(input)?; let statistic = match &input.fields[state].dtype { @@ -1264,6 +1266,7 @@ fn bind_operation( SummaryEvaluation::Exact(ExactEvaluation { statistic, counter_readout: *counter_readout, + variance_readout: *variance_readout, lookback_ms: None, offset_ms: 0, }), @@ -1273,6 +1276,11 @@ fn bind_operation( // the state column in place. let declared_whole = node.output_schema.fields.get(state).map(|f| &f.dtype) == Some(&FieldDataType::Plain(DataType::Int64)); + let declared_nullable = node + .output_schema + .fields + .get(state) + .is_some_and(|f| f.nullable); match statistic { planner_types::summary_type::ExactKind::Sum | planner_types::summary_type::ExactKind::Min @@ -1281,6 +1289,11 @@ fn bind_operation( { evaluation.with_whole_exact_value() } + planner_types::summary_type::ExactKind::SumOfSquaredDeviations + if declared_nullable => + { + evaluation.with_nullable_value() + } _ => Ok(evaluation), } } diff --git a/crates/executor/src/summary_kernels/exact.rs b/crates/executor/src/summary_kernels/exact.rs index 661ee4480..12777412b 100644 --- a/crates/executor/src/summary_kernels/exact.rs +++ b/crates/executor/src/summary_kernels/exact.rs @@ -1,9 +1,10 @@ //! Exact summary state identified by Planner family, independent of keyed layout. use super::increase::IncreaseAccumulator; +use super::moments::Moments; use crate::summary_kernels::traits::{aggregate_core_object_methods, downcast_peer}; use crate::AggregateCore; use planner_types::ir::schema::FieldDataType as SummaryFamilyType; -use planner_types::summary_type::{CounterReadout, ExactKind, ExactParams}; +use planner_types::summary_type::{CounterReadout, ExactKind, ExactParams, VarianceReadout}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -25,6 +26,9 @@ pub(crate) enum ScalarState { /// PromQL `irate`: the last two samples, `(time, value)`, the newer /// second. Samples arrive in increasing time. LastTwoSamples([Option<(i64, f64)>; 2]), + /// A standard deviation's or variance's count, mean and sum of squared + /// deviations. + SumOfSquaredDeviations(Moments), } /// Both the family and population layout survive persistence. One counter @@ -85,6 +89,10 @@ pub struct ExactEvaluation { /// `None` for every other state. #[serde(default, skip_serializing_if = "Option::is_none")] pub counter_readout: Option, + /// For a `SumOfSquaredDeviations` state, which variance or standard + /// deviation it reads; `None` for every other state. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variance_readout: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub lookback_ms: Option, #[serde(default, skip_serializing_if = "is_zero")] @@ -98,11 +106,13 @@ fn is_zero(ms: &i64) -> bool { impl ExactAccumulator { /// Read one population. An empty MIN/MAX population reads as `None`. /// `range_ms` extrapolates a counter to that evaluation range, read as - /// `counter_readout`. + /// `counter_readout`; a sum of squared deviations is read as + /// `variance_readout`. pub fn evaluation( &self, statistic: ExactKind, counter_readout: Option, + variance_readout: Option, range_ms: Option<(i64, i64)>, key: Option<&[String]>, ) -> Result, Error> { @@ -114,7 +124,7 @@ impl ExactAccumulator { (None, None) => &self.scalar, _ => return Err("evaluation population differs from installed layout".into()), }; - state.evaluation(counter_readout, range_ms) + state.evaluation(counter_readout, variance_readout, range_ms) } /// The earliest sample time of a counter state, over @@ -172,6 +182,10 @@ impl ExactAccumulator { SummaryFamilyType::ExactAggregate(K::IRate, P::IRate) => { ScalarState::LastTwoSamples([None; 2]) } + SummaryFamilyType::ExactAggregate( + K::SumOfSquaredDeviations, + P::SumOfSquaredDeviations, + ) => ScalarState::SumOfSquaredDeviations(Moments::default()), _ => return Err(format!("unsupported exact Planner family: {family:?}")), }; Ok(Self { @@ -284,17 +298,34 @@ impl ScalarState { *older = newer.replace((timestamp_ms, value)); } } + ScalarState::SumOfSquaredDeviations(moments) => moments.add(value), } } /// The population's value; `range_ms` extrapolates a counter, read as - /// `counter_readout` (a counter needs one). An empty MIN/MAX reads as - /// `None`. + /// `counter_readout` (a counter needs one); a sum of squared deviations + /// is read as `variance_readout` (it needs one, and no other state + /// takes one). An empty MIN/MAX reads as `None`, as does a variance + /// with no value or a sample variance with one (SQL's NULL). pub(crate) fn evaluation( &self, counter_readout: Option, + variance_readout: Option, range_ms: Option<(i64, i64)>, ) -> Result, Error> { + if let ScalarState::SumOfSquaredDeviations(moments) = self { + let readout = variance_readout + .ok_or("a sum of squared deviations is read with a variance readout")?; + let variance = moments.variance(readout.population()); + return Ok(if readout.standard_deviation() { + variance.map(f64::sqrt) + } else { + variance + }); + } + if variance_readout.is_some() { + return Err("only a sum of squared deviations takes a variance readout".into()); + } match self { ScalarState::Sum { sum, compensation, .. @@ -313,6 +344,7 @@ impl ScalarState { Ok(super::increase::instant_rate(*previous, *last)) } ScalarState::LastTwoSamples(_) => Err("irate population lacks two samples".into()), + ScalarState::SumOfSquaredDeviations(_) => unreachable!("read above"), } } @@ -423,6 +455,9 @@ fn merge_scalar(left: &ScalarState, right: &ScalarState) -> Result { return Err("irate states do not merge".into()) } + (ScalarState::SumOfSquaredDeviations(a), ScalarState::SumOfSquaredDeviations(b)) => { + ScalarState::SumOfSquaredDeviations(a.merge(b).ok_or("exact count overflow")?) + } _ => return Err("exact scalar state families differ".into()), }) } @@ -482,7 +517,7 @@ mod tests { restored.merge_from(&negative).unwrap(); assert_eq!( restored - .evaluation(ExactKind::Sum, None, None, None) + .evaluation(ExactKind::Sum, None, None, None, None) .unwrap(), Some(1.0) ); @@ -495,12 +530,14 @@ mod tests { state.update(None, f64::INFINITY, 0); state.update(None, 1.0, 0); assert_eq!( - state.evaluation(ExactKind::Sum, None, None, None).unwrap(), + state + .evaluation(ExactKind::Sum, None, None, None, None) + .unwrap(), Some(f64::INFINITY) ); state.update(None, f64::NEG_INFINITY, 0); assert!(state - .evaluation(ExactKind::Sum, None, None, None) + .evaluation(ExactKind::Sum, None, None, None, None) .unwrap() .unwrap() .is_nan()); @@ -517,7 +554,7 @@ mod tests { assert_eq!(restored.family(), &sum()); assert_eq!( restored - .evaluation(ExactKind::Sum, None, None, Some(&key)) + .evaluation(ExactKind::Sum, None, None, None, Some(&key)) .unwrap(), Some(2.5) ); @@ -536,7 +573,13 @@ mod tests { } let read = |state: &ExactAccumulator, readout| { state - .evaluation(ExactKind::Counter, Some(readout), Some((0, 60_000)), None) + .evaluation( + ExactKind::Counter, + Some(readout), + None, + Some((0, 60_000)), + None, + ) .unwrap() .unwrap() }; @@ -549,7 +592,7 @@ mod tests { assert!((increase - 13.5).abs() < 1e-12, "{increase}"); assert!((rate - 0.225).abs() < 1e-12, "{rate}"); assert!(state - .evaluation(ExactKind::Counter, None, Some((0, 60_000)), None) + .evaluation(ExactKind::Counter, None, None, Some((0, 60_000)), None) .is_err()); let json = serde_json::to_string(&state).unwrap(); for old_name in ["Rate", "Increase"] { @@ -598,4 +641,215 @@ mod tests { }; assert!(decode(&payload).is_err()); } + + fn moments() -> SummaryFamilyType { + SummaryFamilyType::exact(ExactKind::SumOfSquaredDeviations) + } + + const READOUTS: [VarianceReadout; 4] = [ + VarianceReadout::SampleVariance, + VarianceReadout::PopulationVariance, + VarianceReadout::SampleStdDev, + VarianceReadout::PopulationStdDev, + ]; + + /// One sum-of-squared-deviations state over `values`. + fn moments_of(values: impl IntoIterator) -> ExactAccumulator { + let mut state = ExactAccumulator::new(moments(), false).unwrap(); + for value in values { + state.update(None, value, 0); + } + state + } + + fn read(state: &ExactAccumulator, readout: VarianceReadout) -> Option { + state + .evaluation( + ExactKind::SumOfSquaredDeviations, + None, + Some(readout), + None, + None, + ) + .unwrap() + } + + fn merged(a: &ExactAccumulator, b: &ExactAccumulator) -> ExactAccumulator { + let mut merged = a.clone(); + merged.merge_from(b).unwrap(); + merged + } + + /// `n` values `1e9 + k / 1024` with `k` a pseudo-random integer in + /// [-1024, 1024]: a mean of about 1e9 and a variance of about 1/3, each + /// value exact in an f64. Also the `k`s, for the exact variance. + fn large_mean_small_variance(n: usize) -> (Vec, Vec) { + let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; + let ks: Vec = (0..n) + .map(|_| { + seed = seed + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + ((seed >> 33) % 2_049) as i64 - 1_024 + }) + .collect(); + let values = ks.iter().map(|&k| 1e9 + k as f64 / 1_024.0).collect(); + (values, ks) + } + + /// The exact variance of `1e9 + k / 1024` over `ks`, by integer + /// arithmetic (the shift by 1e9 does not change it): `(n Σk² − (Σk)²) / + /// (n · divisor) / 1024²`, rounded once to f64. + fn exact_variance(ks: &[i64], population: bool) -> f64 { + let n = ks.len() as i128; + let sum: i128 = ks.iter().map(|&k| k as i128).sum(); + let sum_of_squares: i128 = ks.iter().map(|&k| (k as i128) * (k as i128)).sum(); + let divisor = if population { n } else { n - 1 }; + let numerator = n * sum_of_squares - sum * sum; + numerator as f64 / (n * divisor) as f64 / (1_024.0 * 1_024.0) + } + + fn assert_close(actual: f64, expected: f64, relative: f64, what: &str) { + assert!( + (actual - expected).abs() <= relative * expected.abs(), + "{what}: {actual} vs {expected}" + ); + } + + // Adversarial data, a mean of 1e9 and a variance of 1/3, built in four + // tumbling windows and merged: every readout matches the exact variance + // (integer arithmetic) to 1e-6. Welford's relative error grows as + // ε · mean / σ (here 2.2e-16 · 1.7e9 ≈ 4e-7: each deviation is taken + // from a mean rounded to its ulp, 1.2e-7), the same as the raw + // `Aggregate`'s, which updates alike. The naive formula over the same values, + // (Σx² − (Σx)²/n) / (n − 1), even with compensated sums, is off by more + // than 1%: Σx² is about 1e22, so its rounding alone swamps n · 1/3. + #[test] + fn merged_variance_matches_exact_two_pass_on_a_large_mean_and_small_variance() { + let (values, ks) = large_mean_small_variance(10_000); + let windows: Vec = values + .chunks(2_500) + .map(|window| moments_of(window.iter().copied())) + .collect(); + let mut state = windows[0].clone(); + for window in &windows[1..] { + state.merge_from(window).unwrap(); + } + for population in [false, true] { + let exact = exact_variance(&ks, population); + let (variance, stddev) = if population { + ( + VarianceReadout::PopulationVariance, + VarianceReadout::PopulationStdDev, + ) + } else { + ( + VarianceReadout::SampleVariance, + VarianceReadout::SampleStdDev, + ) + }; + assert_close(read(&state, variance).unwrap(), exact, 1e-6, "variance"); + assert_close(read(&state, stddev).unwrap(), exact.sqrt(), 1e-6, "stddev"); + } + let (mut sum, mut sum_compensation) = (0.0, 0.0); + let (mut squares, mut squares_compensation) = (0.0, 0.0); + for &value in &values { + compensated_add(&mut sum, &mut sum_compensation, value); + compensated_add(&mut squares, &mut squares_compensation, value * value); + } + let n = values.len() as f64; + let (sum, squares) = (sum + sum_compensation, squares + squares_compensation); + let naive = (squares - sum * sum / n) / (n - 1.0); + let exact = exact_variance(&ks, false); + assert!( + (naive - exact).abs() > 0.01 * exact, + "naive {naive} vs exact {exact}" + ); + } + + // Chan's merge is associative and has the empty state as identity, to + // rounding: three states of different sizes and means merged either way + // round, and the state of all values built in one pass, read alike to + // 1e-12 for every readout; merging an empty state changes nothing. + #[test] + fn merge_is_associative_and_matches_one_pass() { + let a: Vec = (0..37).map(|i| 1e6 + f64::from(i) * 0.25).collect(); + let b: Vec = (0..5).map(|i| -3.0 + f64::from(i * i)).collect(); + let c: Vec = (0..101).map(|i| 1e-3 * f64::from(i % 7)).collect(); + let [sa, sb, sc] = [&a, &b, &c].map(|values| moments_of(values.iter().copied())); + let left = merged(&merged(&sa, &sb), &sc); + let right = merged(&sa, &merged(&sb, &sc)); + let one_pass = moments_of(a.iter().chain(&b).chain(&c).copied()); + let empty = moments_of([]); + for readout in READOUTS { + let expected = read(&one_pass, readout).unwrap(); + assert_close(read(&left, readout).unwrap(), expected, 1e-12, "left"); + assert_close(read(&right, readout).unwrap(), expected, 1e-12, "right"); + assert_eq!(read(&merged(&sa, &empty), readout), read(&sa, readout)); + assert_eq!(read(&merged(&empty, &sa), readout), read(&sa, readout)); + } + } + + // SQL semantics: no value reads NULL (`None`) for every readout; one + // value has population variance and stddev 0 and no sample variance + // or stddev (NULL); 1, 2 and 4 have population variance 14/9 and + // sample variance 7/3, and their square roots. + #[test] + fn sample_and_population_readouts_follow_sql() { + let empty = moments_of([]); + for readout in READOUTS { + assert_eq!(read(&empty, readout), None, "{readout:?}"); + } + let one = moments_of([5.0]); + assert_eq!(read(&one, VarianceReadout::PopulationVariance), Some(0.0)); + assert_eq!(read(&one, VarianceReadout::PopulationStdDev), Some(0.0)); + assert_eq!(read(&one, VarianceReadout::SampleVariance), None); + assert_eq!(read(&one, VarianceReadout::SampleStdDev), None); + let three = moments_of([1.0, 2.0, 4.0]); + for (readout, expected) in [ + (VarianceReadout::PopulationVariance, 14.0 / 9.0), + (VarianceReadout::SampleVariance, 7.0 / 3.0), + (VarianceReadout::PopulationStdDev, (14.0f64 / 9.0).sqrt()), + (VarianceReadout::SampleStdDev, (7.0f64 / 3.0).sqrt()), + ] { + assert_close(read(&three, readout).unwrap(), expected, 1e-15, "1, 2, 4"); + } + } + + // A NaN or infinite value makes every readout NaN, as Prometheus' + // `stdvar_over_time` gives. + #[test] + fn a_nan_or_infinite_value_reads_nan() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let state = moments_of([1.0, bad, 3.0]); + for readout in READOUTS { + assert!(read(&state, readout).unwrap().is_nan(), "{bad} {readout:?}"); + } + } + } + + // The state is read only with a variance readout, and a variance + // readout reads no other state; it survives persistence. + #[test] + fn a_variance_readout_reads_only_the_sum_of_squared_deviations() { + let state = moments_of([1.0, 2.0, 4.0]); + let kind = ExactKind::SumOfSquaredDeviations; + assert!(state.evaluation(kind, None, None, None, None).is_err()); + let mut plain_sum = ExactAccumulator::new(sum(), false).unwrap(); + plain_sum.update(None, 1.0, 0); + assert!(plain_sum + .evaluation( + ExactKind::Sum, + None, + Some(VarianceReadout::SampleVariance), + None, + None + ) + .is_err()); + let bytes = rmp_serde::to_vec_named(&state).unwrap(); + let restored: ExactAccumulator = rmp_serde::from_slice(&bytes).unwrap(); + for readout in READOUTS { + assert_eq!(read(&restored, readout), read(&state, readout)); + } + } } diff --git a/crates/executor/src/summary_kernels/factory/mod.rs b/crates/executor/src/summary_kernels/factory/mod.rs index e03ec6ff6..fcdd84d94 100644 --- a/crates/executor/src/summary_kernels/factory/mod.rs +++ b/crates/executor/src/summary_kernels/factory/mod.rs @@ -93,11 +93,12 @@ pub(crate) fn finite_input(value: f64) -> Result<(), String> { } } -/// The input rule of an exact accumulator of `kind`. A sum, count, min -/// or max takes any value with PromQL's semantics, since a division by -/// zero upstream gives one (`q / 0` is +Inf, `0 / 0` NaN): a sum that sees -/// NaN, or +Inf and -Inf, is NaN; a count counts the value; min and max -/// skip NaN unless every value is NaN. A stale marker is not a value +/// The input rule of an exact accumulator of `kind`. A sum, count, min, +/// max or sum of squared deviations takes any value with PromQL's +/// semantics, since a division by zero upstream gives one (`q / 0` is +Inf, +/// `0 / 0` NaN): a sum that sees NaN, or +Inf and -Inf, is NaN; a count +/// counts the value; min and max skip NaN unless every value is NaN; a +/// variance that sees NaN or an infinity is NaN. A stale marker is not a value /// ([`not_a_stale_marker`]). A counter's rate or increase needs finite /// samples ([`finite_input`]). pub(crate) fn exact_accumulator_input( @@ -106,9 +107,11 @@ pub(crate) fn exact_accumulator_input( ) -> Result<(), String> { use planner_types::summary_type::ExactKind; match kind { - ExactKind::Sum | ExactKind::Count | ExactKind::Min | ExactKind::Max => { - not_a_stale_marker(value) - } + ExactKind::Sum + | ExactKind::Count + | ExactKind::Min + | ExactKind::Max + | ExactKind::SumOfSquaredDeviations => not_a_stale_marker(value), ExactKind::Counter | ExactKind::IRate => finite_input(value), } } diff --git a/crates/executor/src/summary_kernels/factory/tests.rs b/crates/executor/src/summary_kernels/factory/tests.rs index 49edb56d2..cf5944b71 100644 --- a/crates/executor/src/summary_kernels/factory/tests.rs +++ b/crates/executor/src/summary_kernels/factory/tests.rs @@ -131,7 +131,7 @@ fn exact_accumulators_take_non_finite_values_as_promql_does() { .downcast_ref::() .expect("an exact state"); exact - .evaluation(kind, None, None, None) + .evaluation(kind, None, None, None, None) .map_err(|error| error.to_string()) }; let (inf, nan) = (f64::INFINITY, f64::NAN); diff --git a/crates/executor/src/summary_kernels/mod.rs b/crates/executor/src/summary_kernels/mod.rs index 4d7787cc5..560a0fbeb 100644 --- a/crates/executor/src/summary_kernels/mod.rs +++ b/crates/executor/src/summary_kernels/mod.rs @@ -8,6 +8,7 @@ pub mod hydra_cms; pub mod hydra_kll; pub mod increase; pub mod kmv; +pub(crate) mod moments; pub mod univmon; pub use count_min_sketch::*; diff --git a/crates/executor/src/summary_kernels/moments.rs b/crates/executor/src/summary_kernels/moments.rs new file mode 100644 index 000000000..855f3de16 --- /dev/null +++ b/crates/executor/src/summary_kernels/moments.rs @@ -0,0 +1,63 @@ +//! Welford's running count, mean and sum of squared deviations, and Chan's +//! merge of two: the state of an exact `Aggregate`'s standard deviation or +//! variance and of an exact sum-of-squared-deviations accumulator. +use serde::{Deserialize, Serialize}; + +/// Welford's running count, mean and sum of squared deviations from the +/// mean (its M2), as Prometheus `stddev`/`stdvar` and DataFusion's variance +/// update them: the same operations, so the same rounding. The values 1, 2 +/// and 4 give count 3, mean 7/3 and a sum of squared deviations of 14/3. +/// Deviations are taken from the running mean, so they stay of the +/// variance's size however large the mean: summing squares instead +/// (`Σx² − (Σx)²/n`) cancels catastrophically. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)] +pub(crate) struct Moments { + pub(crate) count: u64, + pub(crate) mean: f64, + pub(crate) sum_squared_deviations: f64, +} + +impl Moments { + pub(crate) fn add(&mut self, value: f64) { + self.count += 1; + let delta = value - self.mean; + self.mean += delta / self.count as f64; + self.sum_squared_deviations += delta * (value - self.mean); + } + + /// The moments of both inputs' values, by Chan et al.'s pairwise + /// update: with `d` the difference of the means and `n = a + b` values, + /// the mean moves by `d · b / n` and the sum of squared deviations is + /// both sums plus `d² · a · b / n`. Exact in real arithmetic, so + /// associative to rounding; an empty input leaves the other unchanged. + /// `None` when the count overflows. + pub(crate) fn merge(&self, other: &Self) -> Option { + if other.count == 0 { + return Some(*self); + } + if self.count == 0 { + return Some(*other); + } + let count = self.count.checked_add(other.count)?; + let (a, b, n) = (self.count as f64, other.count as f64, count as f64); + let delta = other.mean - self.mean; + Some(Self { + count, + mean: self.mean + delta * (b / n), + sum_squared_deviations: self.sum_squared_deviations + + other.sum_squared_deviations + + delta * delta * (a * b / n), + }) + } + + /// The variance over n (`population`) or n - 1; `None` with no value, + /// or one value of a sample. 1, 2 and 4: 14/9, or 7/3 for a sample. + pub(crate) fn variance(&self, population: bool) -> Option { + let divisor = if population { + self.count + } else { + self.count.saturating_sub(1) + }; + (divisor > 0).then(|| self.sum_squared_deviations / divisor as f64) + } +} diff --git a/crates/executor/src/summary_kernels/state_column_updater/tests.rs b/crates/executor/src/summary_kernels/state_column_updater/tests.rs index 202545b84..66ddf6053 100644 --- a/crates/executor/src/summary_kernels/state_column_updater/tests.rs +++ b/crates/executor/src/summary_kernels/state_column_updater/tests.rs @@ -43,7 +43,7 @@ fn an_exact_sum_column_takes_non_finite_values() { let GroupStates::Exact { states, .. } = &updater.states else { unreachable!() }; - let read = |group: usize| states[group].evaluation(None, None).unwrap().unwrap(); + let read = |group: usize| states[group].evaluation(None, None, None).unwrap().unwrap(); assert_eq!(read(0), f64::INFINITY); assert!(read(1).is_nan()); let rate = FieldDataType::ExactAggregate(ExactKind::Counter, ExactParams::Counter); @@ -184,7 +184,9 @@ fn sealed_ten_thousand_series_answer_alike_and_hold_less() { ( readouts .iter() - .map(|&readout| format!("{:?}", state.evaluation(readout, Some((0, 15_000))))) + .map(|&readout| { + format!("{:?}", state.evaluation(readout, None, Some((0, 15_000)))) + }) .collect::>(), state.insufficient_counter_raw_data_samples(), format!("{state:?}"), @@ -227,6 +229,10 @@ fn the_planner_prices_each_sealed_exact_state_at_its_size() { (ExactKind::Max, ExactParams::Max), (ExactKind::Counter, ExactParams::Counter), (ExactKind::IRate, ExactParams::IRate), + ( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + ), ] { let family = FieldDataType::ExactAggregate(kind, parameters); let mut updater = StateColumnUpdater::new(&family, None).unwrap(); diff --git a/crates/executor/src/values/batch/tests.rs b/crates/executor/src/values/batch/tests.rs index 5322f25af..3900e8cfb 100644 --- a/crates/executor/src/values/batch/tests.rs +++ b/crates/executor/src/values/batch/tests.rs @@ -291,6 +291,7 @@ fn a_batch_from_columns_holds_sealed_states_and_labels() { None, None, None, + None, ) .unwrap() .unwrap() @@ -438,6 +439,7 @@ fn a_selective_filter_compacts_its_state_column() { None, None, None, + None, ) .unwrap() .unwrap() @@ -513,6 +515,7 @@ fn concat_of_different_exact_columns_keeps_records() { None, None, None, + None, ) .unwrap() .unwrap() diff --git a/crates/executor/src/values/mapped_states.rs b/crates/executor/src/values/mapped_states.rs index 10b66f1b0..3a25fa820 100644 --- a/crates/executor/src/values/mapped_states.rs +++ b/crates/executor/src/values/mapped_states.rs @@ -404,6 +404,7 @@ pub(crate) fn state_view_bytes( /// | MIN, MAX | presence word, `value` (f64) | /// | counter (rate, increase) | presence word, `starting_value` (f64), `starting_timestamp` (i64), `last_seen_value` (f64), `last_seen_timestamp` (i64), `total_increase` (f64), `sample_count` (u64) | /// | irate | twice (older first): presence word, `timestamp` (i64), `value` (f64) | +/// | sum of squared deviations | `count` (u64), `mean`, `sum_squared_deviations` (f64); empty: count 0 | pub(crate) fn exact_record_bytes(record: &ScalarState) -> Vec { let mut out = Vec::with_capacity(56); let mut word = |value: u64| out.extend_from_slice(&value.to_le_bytes()); @@ -442,6 +443,11 @@ pub(crate) fn exact_record_bytes(record: &ScalarState) -> Vec { word(value.to_bits()); } } + ScalarState::SumOfSquaredDeviations(moments) => { + word(moments.count); + word(moments.mean.to_bits()); + word(moments.sum_squared_deviations.to_bits()); + } } out } @@ -454,6 +460,7 @@ fn record_size(kind: ExactKind) -> usize { ExactKind::Min | ExactKind::Max => 16, ExactKind::Counter => 56, ExactKind::IRate => 48, + ExactKind::SumOfSquaredDeviations => 24, } } @@ -461,7 +468,7 @@ fn record_size(kind: ExactKind) -> usize { fn presence_offsets(kind: ExactKind) -> &'static [usize] { match kind { ExactKind::Sum => &[16], - ExactKind::Count => &[], + ExactKind::Count | ExactKind::SumOfSquaredDeviations => &[], ExactKind::Min | ExactKind::Max | ExactKind::Counter => &[0], ExactKind::IRate => &[0, 24], } @@ -553,6 +560,13 @@ impl MappedRecords { }; ScalarState::LastTwoSamples([sample(0), sample(24)]) } + ExactKind::SumOfSquaredDeviations => { + ScalarState::SumOfSquaredDeviations(crate::summary_kernels::moments::Moments { + count: u64_at(record, 0), + mean: f64_at(record, 8), + sum_squared_deviations: f64_at(record, 16), + }) + } } } } diff --git a/crates/executor/src/values/state_column.rs b/crates/executor/src/values/state_column.rs index 014e4958b..c9338625c 100644 --- a/crates/executor/src/values/state_column.rs +++ b/crates/executor/src/values/state_column.rs @@ -5,6 +5,7 @@ use super::mapped_states::{ }; use crate::summary_kernels::exact::{ExactAccumulator, ScalarState}; use crate::summary_kernels::increase::IncreaseAccumulator; +use crate::summary_kernels::moments::Moments; use crate::AggregateCore; use arrow::buffer::BooleanBuffer; use planner_types::ir::schema::FieldDataType; @@ -41,7 +42,8 @@ pub(crate) enum StateStorage { /// One kernel object per state: sketches, and states read from rows. Objects(Vec>), /// One fixed-size numeric record per state, for an exact accumulator - /// (sum, count, min, max, rate, increase) of one population: one + /// (sum, count, min, max, rate, increase, sum of squared deviations) of + /// one population: one /// contiguous buffer, no allocation per state. Exact(ExactRecords), /// Sketch states in their view layout, read through read-only views @@ -69,6 +71,8 @@ pub(crate) enum ExactRecords { Counter(Optional), /// irate: the last two samples. LastTwoSamples(Box<[LastTwoSamples]>), + /// A variance's count, mean and sum of squared deviations. + SumOfSquaredDeviations(Box<[Moments]>), /// Records of any exact kind in their view layout, in bytes something /// outside the run holds ([`StateColumn::from_views`]). Mapped(MappedRecords), @@ -173,6 +177,15 @@ impl ExactRecords { }) .collect(), ), + ExactKind::SumOfSquaredDeviations => Self::SumOfSquaredDeviations( + states + .into_iter() + .map(|state| match state { + ScalarState::SumOfSquaredDeviations(moments) => moments, + _ => wrong(), + }) + .collect(), + ), } } @@ -192,6 +205,9 @@ impl ExactRecords { Self::Max(records) => ScalarState::Max(records.get(index)), Self::Counter(records) => ScalarState::Counter(records.get(index)), Self::LastTwoSamples(records) => ScalarState::LastTwoSamples(records[index]), + Self::SumOfSquaredDeviations(records) => { + ScalarState::SumOfSquaredDeviations(records[index]) + } Self::Mapped(records) => records.get(index), } } @@ -204,6 +220,7 @@ impl ExactRecords { Self::Min(records) | Self::Max(records) => records.values.len(), Self::Counter(records) => records.values.len(), Self::LastTwoSamples(records) => records.len(), + Self::SumOfSquaredDeviations(records) => records.len(), Self::Mapped(records) => records.len(), } } @@ -216,6 +233,7 @@ impl ExactRecords { Self::Min(records) | Self::Max(records) => records.memory_bytes(), Self::Counter(records) => records.memory_bytes(), Self::LastTwoSamples(records) => std::mem::size_of_val(&**records), + Self::SumOfSquaredDeviations(records) => std::mem::size_of_val(&**records), // Held outside the run; `StateColumn::from_views` sizes them. Self::Mapped(_) => 0, } diff --git a/crates/executor/tests/exact_state_columns.rs b/crates/executor/tests/exact_state_columns.rs index 2ff1df298..122be0846 100644 --- a/crates/executor/tests/exact_state_columns.rs +++ b/crates/executor/tests/exact_state_columns.rs @@ -4,7 +4,9 @@ use asap_executor::operators::{Operator, SummaryEvaluation}; use asap_executor::plan::PhysicalDAG; use asap_executor::planner::ir::schema::{DataType, Field, FieldDataType, Schema}; -use asap_executor::planner::summary_type::{CounterReadout, ExactKind, ExactParams}; +use asap_executor::planner::summary_type::{ + CounterReadout, ExactKind, ExactParams, VarianceReadout, +}; use asap_executor::runtime::{Limits, RunContext, Scope}; use asap_executor::summary_kernels::exact::ExactEvaluation; use asap_executor::values::{Batch, SchemaRef, Value}; @@ -90,20 +92,34 @@ fn run(operator: Operator, inputs: Vec) -> Vec { // or one of each), row for row. #[test] fn exact_records_merge_and_evaluate_as_kernel_objects_do() { - for (kind, params, counter_readout) in [ - (ExactKind::Sum, ExactParams::Sum, None), - (ExactKind::Count, ExactParams::Count, None), - (ExactKind::Min, ExactParams::Min, None), - (ExactKind::Max, ExactParams::Max, None), + for (kind, params, counter_readout, variance_readout) in [ + (ExactKind::Sum, ExactParams::Sum, None, None), + (ExactKind::Count, ExactParams::Count, None, None), + (ExactKind::Min, ExactParams::Min, None, None), + (ExactKind::Max, ExactParams::Max, None, None), ( ExactKind::Counter, ExactParams::Counter, Some(CounterReadout::Increase), + None, ), ( ExactKind::Counter, ExactParams::Counter, Some(CounterReadout::Rate), + None, + ), + ( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + None, + Some(VarianceReadout::SampleStdDev), + ), + ( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + None, + Some(VarianceReadout::PopulationVariance), ), ] { let family = FieldDataType::ExactAggregate(kind, params); @@ -132,6 +148,7 @@ fn exact_records_merge_and_evaluate_as_kernel_objects_do() { SummaryEvaluation::Exact(ExactEvaluation { statistic: kind, counter_readout, + variance_readout, lookback_ms: None, offset_ms: 0, }), @@ -159,7 +176,7 @@ fn exact_records_merge_and_evaluate_as_kernel_objects_do() { } } -/// An exact SUM, MIN or MAX state takes an Int64 value column (SQL's integer +/// An exact SUM, MIN, MAX or sum-of-squared-deviations state takes an Int64 value column (SQL's integer /// columns), each value as its exact Float64: per series 1+4, 2+5, 3+6. #[test] fn exact_states_take_int64_values() { @@ -176,10 +193,17 @@ fn exact_states_take_int64_values() { .map(|i: i64| vec![Value::Utf8(format!("s{}", i % 3).into()), Value::Int64(i)]) .collect(); let batch = Batch::try_new(schema.clone(), rows).unwrap(); - for (kind, params, expected) in [ - (ExactKind::Sum, ExactParams::Sum, [9.0, 5.0, 7.0]), - (ExactKind::Min, ExactParams::Min, [3.0, 1.0, 2.0]), - (ExactKind::Max, ExactParams::Max, [6.0, 4.0, 5.0]), + for (kind, params, variance_readout, expected) in [ + (ExactKind::Sum, ExactParams::Sum, None, [9.0, 5.0, 7.0]), + (ExactKind::Min, ExactParams::Min, None, [3.0, 1.0, 2.0]), + (ExactKind::Max, ExactParams::Max, None, [6.0, 4.0, 5.0]), + // 3 and 6, 1 and 4, 2 and 5: each a population variance of 2.25. + ( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + Some(VarianceReadout::PopulationVariance), + [2.25, 2.25, 2.25], + ), ] { let family = FieldDataType::ExactAggregate(kind, params); let build = @@ -192,6 +216,7 @@ fn exact_states_take_int64_values() { SummaryEvaluation::Exact(ExactEvaluation { statistic: kind, counter_readout: None, + variance_readout, lookback_ms: None, offset_ms: 0, }), @@ -210,3 +235,88 @@ fn exact_states_take_int64_values() { assert_eq!(values, expected, "{kind:?}"); } } + +/// A sum-of-squared-deviations state skips NULL values and reads as SQL +/// does: series `a` holds 1, NULL and 3 (sample stddev √2, population +/// variance 1), `b` only NULL (no value: NULL for both) and `c` one value +/// (sample stddev NULL, population variance 0). +#[test] +fn a_sum_of_squared_deviations_skips_nulls_and_reads_sql_nulls() { + let schema: SchemaRef = Arc::new(Schema { + fields: vec![ + field("series", DataType::Utf8), + Field { + name: "value".into(), + dtype: FieldDataType::Plain(DataType::Float64), + nullable: true, + }, + ], + time_index: None, + unique_keys: vec![], + closed: false, + }); + let row = |series: &str, value: Option| { + vec![ + Value::Utf8(series.into()), + value.map_or(Value::Null, Value::Float64), + ] + }; + let batch = Batch::try_new( + schema.clone(), + vec![ + row("a", Some(1.0)), + row("a", None), + row("b", None), + row("a", Some(3.0)), + row("c", Some(5.0)), + ], + ) + .unwrap(); + let family = FieldDataType::ExactAggregate( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + ); + let build = Operator::per_group_summary_build(schema, family, None, 1, None, vec![0]).unwrap(); + let states = run(build, vec![batch]); + for (readout, expected) in [ + ( + VarianceReadout::SampleStdDev, + [Value::Float64(2f64.sqrt()), Value::Null, Value::Null], + ), + ( + VarianceReadout::PopulationVariance, + [Value::Float64(1.0), Value::Null, Value::Float64(0.0)], + ), + ] { + let evaluation = Operator::evaluation( + states[0].schema().clone(), + 1, + SummaryEvaluation::Exact(ExactEvaluation { + statistic: ExactKind::SumOfSquaredDeviations, + counter_readout: None, + variance_readout: Some(readout), + lookback_ms: None, + offset_ms: 0, + }), + ) + .unwrap() + // As the Planner types a variance of a nullable column. + .with_nullable_value() + .unwrap(); + let mut rows: Vec<(String, Value)> = run(evaluation, states.clone()) + .iter() + .flat_map(|b| b.to_rows()) + .map(|row| match &row[0] { + Value::Utf8(s) => (s.to_string(), row[1].clone()), + other => panic!("{other:?}"), + }) + .collect(); + rows.sort_by(|a, b| a.0.cmp(&b.0)); + let values: Vec = rows.into_iter().map(|(_, v)| v).collect(); + assert_eq!( + format!("{values:?}"), + format!("{expected:?}"), + "{readout:?}" + ); + } +} diff --git a/crates/executor/tests/multi_level_window_chains.rs b/crates/executor/tests/multi_level_window_chains.rs index 1198df65a..9719e3c9d 100644 --- a/crates/executor/tests/multi_level_window_chains.rs +++ b/crates/executor/tests/multi_level_window_chains.rs @@ -128,6 +128,7 @@ fn finalized_merge(windows: Rc, built: Built) -> Rc node(Operator::ASAP(match built { Built::Sum | Built::Max => ASAPOp::FinalizeExactAccumulator { counter_readout: None, + variance_readout: None, child: merged, }, Built::DDSketchP99 | Built::KllP99 => ASAPOp::SummaryEstimate { diff --git a/crates/executor/tests/physical_dag.rs b/crates/executor/tests/physical_dag.rs index cdca6e6af..9b8ba2c05 100644 --- a/crates/executor/tests/physical_dag.rs +++ b/crates/executor/tests/physical_dag.rs @@ -204,6 +204,7 @@ fn summary_construction_merge_and_evaluation_at_both_phases() { asap_executor::summary_kernels::exact::ExactEvaluation { statistic: ExactKind::Sum, counter_readout: None, + variance_readout: None, lookback_ms: None, offset_ms: 0, }, @@ -543,6 +544,7 @@ fn exact_state_and_family_validation() { asap_executor::summary_kernels::exact::ExactEvaluation { statistic: ExactKind::Sum, counter_readout: None, + variance_readout: None, lookback_ms: None, offset_ms: 0, }, @@ -674,6 +676,7 @@ fn empty_exact_count_is_an_integer_state_evaluation() { asap_executor::summary_kernels::exact::ExactEvaluation { statistic: ExactKind::Count, counter_readout: None, + variance_readout: None, lookback_ms: None, offset_ms: 0, }, @@ -693,6 +696,55 @@ fn empty_exact_count_is_an_integer_state_evaluation() { assert!(matches!(run(&dag, 2, query())[0][0], Value::Int64(0))); } +// A global SQL population variance over no rows reads NULL: the empty +// global group's sum-of-squared-deviations state has no value, and its +// state-only row is nullable as a global MIN/MAX's is. +#[test] +fn empty_global_population_variance_reads_null() { + let input = schema(&[("value", DataType::Float64, false)]); + let build = Operator::per_group_summary_build( + input.clone(), + FieldDataType::ExactAggregate( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + ), + None, + 0, + None, + vec![], + ) + .unwrap() + .with_emit_empty_global(true, None) + .unwrap(); + let read = Operator::evaluation( + build.schema(), + 0, + asap_executor::operators::SummaryEvaluation::Exact( + asap_executor::summary_kernels::exact::ExactEvaluation { + statistic: ExactKind::SumOfSquaredDeviations, + counter_readout: None, + variance_readout: Some( + asap_executor::planner::summary_type::VarianceReadout::PopulationVariance, + ), + lookback_ms: None, + offset_ms: 0, + }, + ), + ) + .unwrap(); + let mut dag = PhysicalDAG::default(); + dag.add( + 0, + vec![], + Operator::source(input, vec![]).unwrap(), + Lifetime::None, + ) + .unwrap(); + dag.add(1, vec![0], build, Lifetime::None).unwrap(); + dag.add(2, vec![1], read, Lifetime::None).unwrap(); + assert!(matches!(run(&dag, 2, query())[0][0], Value::Null)); +} + // Float extrema have the same NaN behavior as the exact summary kernels. #[test] fn extrema_preserve_numeric_values_in_the_presence_of_nan() { diff --git a/crates/executor/tests/physical_semantics.rs b/crates/executor/tests/physical_semantics.rs index 704325ca4..2cc18889e 100644 --- a/crates/executor/tests/physical_semantics.rs +++ b/crates/executor/tests/physical_semantics.rs @@ -1245,6 +1245,7 @@ fn counter_tumbling_windows_merge_in_any_order() { Some(planner_types::summary_type::CounterReadout::Increase), None, None, + None, ) .unwrap() .unwrap() @@ -1351,6 +1352,7 @@ fn empty_exact_summary_extrema_agree_with_ordinary_aggregation() { asap_executor::summary_kernels::exact::ExactEvaluation { statistic: kind, counter_readout: None, + variance_readout: None, lookback_ms: None, offset_ms: 0, }, @@ -1539,6 +1541,7 @@ fn filtered_summary_build_keeps_empty_groups() { ASAPOp::FinalizeExactAccumulator { child: 0, counter_readout: None, + variance_readout: None, }, (DataType::Int64, false), ["a 1", "b 0", "c 1"], diff --git a/crates/executor/tests/precompute_population.rs b/crates/executor/tests/precompute_population.rs index 8115b2e36..da033829b 100644 --- a/crates/executor/tests/precompute_population.rs +++ b/crates/executor/tests/precompute_population.rs @@ -149,6 +149,7 @@ fn try_state_dag( payload: PhysicalASAPOperatorPayload::ASAP(ASAPOp::FinalizeExactAccumulator { child: read_id - 1, counter_readout: None, + variance_readout: None, }), output_state: ExecutionDataState::INGESTION_ROWS, lifetime: Default::default(), diff --git a/crates/executor/tests/promql_binary.rs b/crates/executor/tests/promql_binary.rs index c8ed51182..82aa68033 100644 --- a/crates/executor/tests/promql_binary.rs +++ b/crates/executor/tests/promql_binary.rs @@ -393,6 +393,7 @@ fn stored_series_evaluations_support_filters_and_sets() { PhysicalASAPOperatorPayload::ASAP(ASAPOp::FinalizeExactAccumulator { child: id - 2, counter_readout: None, + variance_readout: None, }) } _ => PhysicalASAPOperatorPayload::NonASAP( diff --git a/crates/executor/tests/promql_values.rs b/crates/executor/tests/promql_values.rs index af1a5a9e3..c5e7c9cb7 100644 --- a/crates/executor/tests/promql_values.rs +++ b/crates/executor/tests/promql_values.rs @@ -224,6 +224,7 @@ fn compile_exact_evaluation( SummaryEvaluation::Exact(ExactEvaluation { statistic, counter_readout, + variance_readout: None, lookback_ms: is_counter.then_some(lookback_ms), offset_ms: 0, }), diff --git a/crates/executor/tests/raw_scan.rs b/crates/executor/tests/raw_scan.rs index 47f9063f2..4e4ece71e 100644 --- a/crates/executor/tests/raw_scan.rs +++ b/crates/executor/tests/raw_scan.rs @@ -862,6 +862,7 @@ fn windowed_count_plan(shift_ms: Option) -> PhysicalASAPDAG { PhysicalASAPOperatorPayload::ASAP(ASAPOp::FinalizeExactAccumulator { child: 3, counter_readout: None, + variance_readout: None, }), &value, ExecutionDataState::QUERY_ROWS, diff --git a/crates/executor/tests/tumbling_window_chain.rs b/crates/executor/tests/tumbling_window_chain.rs index 0e48de390..52433a97b 100644 --- a/crates/executor/tests/tumbling_window_chain.rs +++ b/crates/executor/tests/tumbling_window_chain.rs @@ -14,7 +14,7 @@ use planner_types::ir::scalar::ColumnRef; use planner_types::ir::schema::FieldDataType; use planner_types::ir::{ASAPOp, NonASAPOp, Operator, OperatorNode, QueryRoot, TimeRangeKind}; use planner_types::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; -use planner_types::summary_type::{ExactKind, ExactParams, SummaryUpdate}; +use planner_types::summary_type::{ExactKind, ExactParams, SummaryUpdate, VarianceReadout}; use std::collections::BTreeMap; use std::rc::Rc; use std::sync::Arc; @@ -59,6 +59,7 @@ fn finalized_sum(states: Rc) -> Rc { node(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: states, counter_readout: None, + variance_readout: None, })) } @@ -438,3 +439,127 @@ fn a_time_shift_at_end_evaluates_its_input_at_the_requests_end() { direct_sums(2 * HOUR_MS - 5 * MINUTE_MS, 2 * HOUR_MS) ); } + +/// The sample (`population` false) or population variance per job of the +/// samples in `(start, end]`, computed directly in two passes. +fn direct_variances(start: i64, end: i64, population: bool) -> BTreeMap { + let mut values: BTreeMap> = BTreeMap::new(); + for (job, t, value) in samples() { + if start < t && t <= end { + values.entry(job.to_string()).or_default().push(value); + } + } + values + .into_iter() + .map(|(job, values)| { + let n = values.len() as f64; + let mean = values.iter().sum::() / n; + let squared_deviations: f64 = values.iter().map(|v| (v - mean) * (v - mean)).sum(); + let divisor = if population { n } else { n - 1.0 }; + (job, squared_deviations / divisor) + }) + .collect() +} + +// `stddev` and `stdvar` of the last hour per job, both read from one chain +// of 10-minute sum-of-squared-deviations windows built at ingestion: at +// T = 4h the query merges the six windows of `(3h, 4h]` once and reads the +// sample standard deviation and the population variance from them, equal +// (to 1e-12) to the two-pass values over the raw samples. +#[test] +fn a_sum_of_squared_deviations_chain_built_at_ingestion_answers_stddev_and_stdvar() { + let moments = FieldDataType::ExactAggregate( + ExactKind::SumOfSquaredDeviations, + ExactParams::SumOfSquaredDeviations, + ); + let chain = node(Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: scan(), + summary_type: moments, + input: SummaryUpdate::column(ColumnRef::SampleValue), + reduction: Reduction::by(vec![0]), + filter: None, + tumbling_window_width_ms: WIDTH_MS as u64, + })); + let merged = node(Operator::ASAP(ASAPOp::SummaryMerge { + children: vec![range(HOUR_MS, chain.clone())], + group_by: None, + })); + let read_as = |readout| { + node(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { + child: merged.clone(), + counter_readout: None, + variance_readout: Some(readout), + })) + }; + let stddev = read_as(VarianceReadout::SampleStdDev); + let stdvar = read_as(VarianceReadout::PopulationVariance); + let (mut dag, nodes) = + planner_types::test_support::forwarders::physical_asap_dag_at_query_time_with_node_ids(&[ + QueryRoot::Operator(stddev.clone()), + QueryRoot::Operator(stdvar.clone()), + ]) + .unwrap(); + let chain_id = id_of(&nodes, &chain); + dag.nodes + .iter_mut() + .find(|node| node.id == chain_id) + .unwrap() + .retention_ms = Some(HOUR_MS as u64); + let roots = [id_of(&nodes, &stddev) as u64, id_of(&nodes, &stdvar) as u64]; + let views = views_at(&mut dag, &[chain_id as u64]).unwrap(); + let refresh = compile(&dag, &[], &[chain_id as u64]).unwrap(); + let query = compile(&dag, &views, &roots).unwrap(); + let mut store = Arc::new(store_with_samples()); + let schema = Arc::new( + dag.nodes + .iter() + .find(|node| node.id == chain_id) + .unwrap() + .output_schema + .clone(), + ); + for window_end in (1..=4 * HOUR_MS / WIDTH_MS).map(|i| i * WIDTH_MS) { + let context = RunContext::new( + Scope::Ingestion { + window_start_ms: window_end - WIDTH_MS, + window_end_ms: window_end, + }, + Limits::default(), + ) + .unwrap(); + let rows = { + let refresh = refresh.instantiate(store.clone()).unwrap(); + run(&refresh, &[chain_id as u64], context).remove(0) + }; + let batch = Batch::try_new(schema.clone(), rows).unwrap(); + Arc::get_mut(&mut store) + .unwrap() + .append_materialized_view(&views[0], (window_end - WIDTH_MS, window_end), vec![batch]) + .unwrap(); + } + let evaluation_time_ms = 4 * HOUR_MS; + let context = RunContext::new(Scope::Query { evaluation_time_ms }, Limits::default()).unwrap(); + let answers = { + let query = query.instantiate(store).unwrap(); + run(&query, &roots, context) + }; + let start = evaluation_time_ms - HOUR_MS; + let sample_stddevs: BTreeMap = direct_variances(start, evaluation_time_ms, false) + .into_iter() + .map(|(job, variance)| (job, variance.sqrt())) + .collect(); + let population_variances = direct_variances(start, evaluation_time_ms, true); + for (answer, expected) in [ + (sums_of(answers[0].clone()), sample_stddevs), + (sums_of(answers[1].clone()), population_variances), + ] { + assert_eq!(answer.len(), 2, "{answer:?}"); + for (job, value) in &expected { + let read = answer[job]; + assert!( + (read - value).abs() <= 1e-12 * value, + "{job}: {read} vs {value}" + ); + } + } +} diff --git a/crates/integration-tests/src/lib.rs b/crates/integration-tests/src/lib.rs index 98af742ba..f0e4a6224 100644 --- a/crates/integration-tests/src/lib.rs +++ b/crates/integration-tests/src/lib.rs @@ -366,6 +366,7 @@ pub mod planning { ExactKind::Max, ExactKind::Counter, ExactKind::IRate, + ExactKind::SumOfSquaredDeviations, ]; for kind in &exact { match kind { @@ -374,7 +375,8 @@ pub mod planning { | ExactKind::Min | ExactKind::Max | ExactKind::Counter - | ExactKind::IRate => {} + | ExactKind::IRate + | ExactKind::SumOfSquaredDeviations => {} } } // Every family, and no family (`sketch` and `exact` both `None`). diff --git a/crates/integration-tests/tests/main.rs b/crates/integration-tests/tests/main.rs index 0210d3849..dafe4e942 100644 --- a/crates/integration-tests/tests/main.rs +++ b/crates/integration-tests/tests/main.rs @@ -49,4 +49,5 @@ mod stage3_objective; mod state_views; mod storage_costs; mod time_range; +mod variance_states; mod view_state_key; diff --git a/crates/integration-tests/tests/operator_design_examples.rs b/crates/integration-tests/tests/operator_design_examples.rs index 9f8d9d658..fb2967b69 100644 --- a/crates/integration-tests/tests/operator_design_examples.rs +++ b/crates/integration-tests/tests/operator_design_examples.rs @@ -88,6 +88,7 @@ async fn sql_sum_projection_before_and_after_summary_rewrite() { asap_types::ir::Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, }), node.schema.clone(), )); diff --git a/crates/integration-tests/tests/pass2_promql/rollup.rs b/crates/integration-tests/tests/pass2_promql/rollup.rs index 01b55413b..2efe61194 100644 --- a/crates/integration-tests/tests/pass2_promql/rollup.rs +++ b/crates/integration-tests/tests/pass2_promql/rollup.rs @@ -117,10 +117,12 @@ fn different_per_series_functions_do_not_roll_up() { assert_eq!(rollup_count(&memo), 0); } +/// A standard deviation's sum-of-squared-deviations state by (job) +/// merges the finer state by (job, instance), as a sum's state does. #[test] -fn a_standard_deviation_does_not_roll_up() { +fn a_standard_deviation_rolls_up_the_finer_state() { let memo = pass2_memo(&["stddev by (job) (m)", "stddev by (job, instance) (m)"]); - assert_eq!(rollup_count(&memo), 0); + assert_eq!(rollup_count(&memo), 1); } #[test] diff --git a/crates/integration-tests/tests/per_series_exact_execution.rs b/crates/integration-tests/tests/per_series_exact_execution.rs index f02ec5e39..23d0e3a38 100644 --- a/crates/integration-tests/tests/per_series_exact_execution.rs +++ b/crates/integration-tests/tests/per_series_exact_execution.rs @@ -438,6 +438,7 @@ fn planned_exact_range_functions_execute() { (200.0f64 / 3.0).sqrt(), Some(0.0), ), + ("stdvar_over_time(x[5m])", 5.25, 200.0 / 3.0, Some(0.0)), ("mad_over_time(x[5m])", 1.5, 10.0, Some(0.0)), ("present_over_time(x[5m])", 1.0, 1.0, Some(1.0)), ] { diff --git a/crates/integration-tests/tests/promql_to_post_asap.rs b/crates/integration-tests/tests/promql_to_post_asap.rs index 162c4fd72..12cf4a696 100644 --- a/crates/integration-tests/tests/promql_to_post_asap.rs +++ b/crates/integration-tests/tests/promql_to_post_asap.rs @@ -247,11 +247,11 @@ fn promql_binary_arithmetic_preserves_both_scalar_operand_orders() { } } -/// An arm with no summary (`stddev_over_time`) stays plain exact work while +/// An arm with no summary (`mad_over_time`) stays plain exact work while /// the other arm still binds its exact accumulator. #[test] fn promql_binary_arithmetic_keeps_an_unsupported_arm_exact() { - let root = lower_and_realize_summaries("rate(a[1m]) + stddev_over_time(b[1m])"); + let root = lower_and_realize_summaries("rate(a[1m]) + mad_over_time(b[1m])"); let Some(NonASAPOp::BinaryOp { lhs, rhs, .. }) = root.non_asap() else { panic!("expected BinaryOp, got {:?}", root.operator); }; diff --git a/crates/integration-tests/tests/sql_relational_execution.rs b/crates/integration-tests/tests/sql_relational_execution.rs index c3302c480..cf6bc946d 100644 --- a/crates/integration-tests/tests/sql_relational_execution.rs +++ b/crates/integration-tests/tests/sql_relational_execution.rs @@ -344,3 +344,38 @@ fn sort_by_an_expression() { false, ); } + +// `STDDEV_SAMP`, `VAR_POP` and `STDDEV` per `k` skip NULLs and read NULL +// where SQL does: g1's x (1, 5, 2) has sample stddev √(13/3) and +// population variance 26/9, its v (3, 1, 3) stddev √(4/3); g2's x (NULL, +// 9) has one value, so no sample stddev (NULL) and population variance 0, +// its v (2, 7) stddev √12.5. Values within 1e-12 of DuckDB's. +#[test] +fn stddev_and_variance_follow_sql() { + let query = "SELECT k, stddev_samp(x), var_pop(x), stddev(v) FROM t GROUP BY k"; + let rows = sql(query, true); + let expected = [ + ( + "g1", + Some((13.0f64 / 3.0).sqrt()), + 26.0 / 9.0, + (4.0f64 / 3.0).sqrt(), + ), + ("g2", None, 0.0, 12.5f64.sqrt()), + ]; + assert_eq!(rows.len(), expected.len(), "{query}: {rows:?}"); + let close = |value: &Value, expected: f64| matches!(value, Value::Float64(v) if (v - expected).abs() <= 1e-12 * expected.abs().max(1.0)); + for (row, (k, stddev_samp_x, var_pop_x, stddev_v)) in rows.iter().zip(expected) { + assert_eq!( + format!("{:?}", row[0]), + format!("{:?}", text(k)), + "{query}: {rows:?}" + ); + match stddev_samp_x { + Some(expected) => assert!(close(&row[1], expected), "{query}: {rows:?}"), + None => assert!(matches!(row[1], Value::Null), "{query}: {rows:?}"), + } + assert!(close(&row[2], var_pop_x), "{query}: {rows:?}"); + assert!(close(&row[3], stddev_v), "{query}: {rows:?}"); + } +} diff --git a/crates/integration-tests/tests/variance_states.rs b/crates/integration-tests/tests/variance_states.rs new file mode 100644 index 000000000..79e074934 --- /dev/null +++ b/crates/integration-tests/tests/variance_states.rs @@ -0,0 +1,123 @@ +//! A standard deviation or variance kept at ingestion: Pass 1 offers one +//! exact sum-of-squared-deviations state (count, mean and the sum of +//! squared deviations from it) for `stddev`, `stdvar` and their +//! `*_over_time` forms, so a repeating long-range read is answered from a +//! tumbling-window chain of those states, merged like a sum's, instead of +//! from raw samples; `stddev` and `stdvar` of the same rows read one chain. +use asap_planner::{ + plan_installable, FrontendInput, InstallablePlan, PlanningModels, PlanningWorkload, UserInput, +}; +use asap_types::ir::schema::FieldDataType; +use asap_types::ir::{ASAPOp, Operator}; +use asap_types::summary_type::{ExactKind, VarianceReadout}; + +/// `queries`, each every 15 s over the last hour of `data` (10,000 gauge +/// series at 10 Hz), exactly. +fn workload(queries: &[&str]) -> PlanningWorkload { + let entries: Vec = queries + .iter() + .map(|query| { + serde_json::json!({ + "demand": {"fixed_interval_at": {"evaluation_phase": 0, "interval": 15000}}, + "predictability": {"predictable": {"known_at": null}}, + "query": query, + "range_evaluation": null, + "requirements": {"accuracy": {"max_error": 0.0, "failure_probability": 0.0}, + "max_latency_ms": null} + }) + }) + .collect(); + serde_json::from_value(serde_json::json!({ + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 100000.0}}, + "sources": {"data": {"metric_type": "gauge", "sample_interval": 100, + "series_count": 10000}}}, + "query_workload": {"language": "promql", "query_batch": null, + "repeating_queries": entries} + })) + .unwrap() +} + +async fn planned(queries: &[&str]) -> InstallablePlan { + let workload = workload(queries); + plan_installable(UserInput::new( + &workload, + FrontendInput::Promql, + PlanningModels::builtin(), + )) + .await + .unwrap() + .0 +} + +/// The plan's tumbling-window chains of exact `kind` states. +fn chains_of(plan: &InstallablePlan, kind: ExactKind) -> usize { + plan.dag + .nodes + .iter() + .filter(|node| { + matches!( + &node.payload, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + summary_type: FieldDataType::ExactAggregate(chained, _), + .. + }) if *chained == kind + ) + }) + .count() +} + +/// The variance readouts the plan's finalizes read. +fn variance_readouts(plan: &InstallablePlan) -> Vec { + let mut readouts: Vec<_> = plan + .dag + .nodes + .iter() + .filter_map(|node| match &node.payload { + Operator::ASAP(ASAPOp::FinalizeExactAccumulator { + variance_readout, .. + }) => *variance_readout, + _ => None, + }) + .collect(); + readouts.sort_by_key(|readout| format!("{readout:?}")); + readouts +} + +/// `stddev_over_time(data[1h])` every 15 s keeps a chain of +/// sum-of-squared-deviations states at ingestion and reads the population +/// standard deviation from it, rather than scanning an hour of samples +/// every step; the plan compiles. +#[tokio::test] +async fn a_repeating_stddev_over_time_keeps_a_chain_at_ingestion() { + let plan = planned(&["stddev_over_time(data[1h])"]).await; + assert_eq!(chains_of(&plan, ExactKind::SumOfSquaredDeviations), 1); + assert_eq!( + variance_readouts(&plan), + vec![VarianceReadout::PopulationStdDev] + ); + plan.check_compiles().unwrap(); +} + +/// `stddev_over_time` and `stdvar_over_time` of the same hour share one +/// chain, each finalized with its own readout; `avg_over_time` beside them +/// is kept at ingestion too, from its own sum and count states. +#[tokio::test] +async fn stddev_and_stdvar_of_the_same_rows_share_one_chain() { + let plan = planned(&[ + "stddev_over_time(data[1h])", + "stdvar_over_time(data[1h])", + "avg_over_time(data[1h])", + ]) + .await; + assert_eq!(chains_of(&plan, ExactKind::SumOfSquaredDeviations), 1); + assert_eq!( + variance_readouts(&plan), + vec![ + VarianceReadout::PopulationStdDev, + VarianceReadout::PopulationVariance + ] + ); + assert_eq!(chains_of(&plan, ExactKind::Sum), 1); + assert_eq!(chains_of(&plan, ExactKind::Count), 1); + plan.check_compiles().unwrap(); +} diff --git a/crates/planner/src/installable/tests.rs b/crates/planner/src/installable/tests.rs index 45e783092..665e4fc61 100644 --- a/crates/planner/src/installable/tests.rs +++ b/crates/planner/src/installable/tests.rs @@ -122,6 +122,7 @@ fn chain_plan( let root = node(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: merged, counter_readout: None, + variance_readout: None, })); let (mut dag, nodes) = asap_types::test_support::forwarders::physical_asap_dag_at_query_time_with_node_ids(&[ diff --git a/crates/stage1-pass1-per-computation-candidates/src/candidates/measure_output.rs b/crates/stage1-pass1-per-computation-candidates/src/candidates/measure_output.rs index f684c95aa..aa0efbe1e 100644 --- a/crates/stage1-pass1-per-computation-candidates/src/candidates/measure_output.rs +++ b/crates/stage1-pass1-per-computation-candidates/src/candidates/measure_output.rs @@ -13,7 +13,9 @@ use asap_types::ir::{ ProjectItem, ScalarExpr, }; use asap_types::stages::{Memo, MemoGroupId}; -use asap_types::summary_type::{CounterReadout, ExactKind, SketchStatistic, SummaryInputExpr}; +use asap_types::summary_type::{ + CounterReadout, ExactKind, SketchStatistic, SummaryInputExpr, VarianceReadout, +}; use super::pending::{add_candidate, commit_pending, Pending}; use super::SingleMeasure; @@ -44,6 +46,7 @@ pub(super) fn measure_output( Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: pending.push(memo, build)?, counter_readout: CounterReadout::for_intent(measure.intent), + variance_readout: VarianceReadout::for_intent(measure.intent), }) } HowToComputeAggregateMeasure::Summary(algorithm) => { @@ -100,6 +103,7 @@ pub(super) fn measure_output( Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: sum, counter_readout: None, + variance_readout: None, }), )?; let count = pending.push( @@ -107,6 +111,7 @@ pub(super) fn measure_output( Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: count, counter_readout: None, + variance_readout: None, }), )?; if memo.groups()[measure.unfiltered_input.0 as usize] diff --git a/crates/stage1-pass1-per-computation-candidates/src/computation_targets.rs b/crates/stage1-pass1-per-computation-candidates/src/computation_targets.rs index 1b1ff4df2..433424182 100644 --- a/crates/stage1-pass1-per-computation-candidates/src/computation_targets.rs +++ b/crates/stage1-pass1-per-computation-candidates/src/computation_targets.rs @@ -40,8 +40,8 @@ use crate::{expression, schema, PerComputationCandidateError}; pub(crate) enum HowToComputeAggregateMeasure { /// One or more exact mergeable accumulator states, by accumulator kind, /// finalized and combined into the measure: one state for `sum`, - /// `count`, `min`, `max`, `rate`, `irate` and `increase`; `[Sum, Count]`, - /// divided, for `avg`. + /// `count`, `min`, `max`, `rate`, `irate`, `increase`, `stddev` and + /// `stdvar`/`variance`; `[Sum, Count]`, divided, for `avg`. ExactAccumulator(Vec), /// A sketch algorithm: its state group gets one build candidate per /// configuration of the algorithm's predefined list (`parameter_list`). @@ -108,6 +108,12 @@ pub(crate) fn ways_to_compute_intent(intent: &AggIntent) -> Vec vec![ExactKind::Counter], AggIntent::IRate => vec![ExactKind::IRate], AggIntent::Avg { .. } => vec![ExactKind::Sum, ExactKind::Count], + // One state holds the count, mean and squared deviations each + // variant reads, so `stddev` and `stdvar` (sample or population) + // of the same rows share it; it skips NULLs as they do. + AggIntent::StdDev { .. } | AggIntent::Variance { .. } => { + vec![ExactKind::SumOfSquaredDeviations] + } _ => vec![], }; let mut choices = Vec::new(); diff --git a/crates/stage1-pass1-per-computation-candidates/src/tests/candidates.rs b/crates/stage1-pass1-per-computation-candidates/src/tests/candidates.rs index da25b49ff..a4a7c8679 100644 --- a/crates/stage1-pass1-per-computation-candidates/src/tests/candidates.rs +++ b/crates/stage1-pass1-per-computation-candidates/src/tests/candidates.rs @@ -60,6 +60,7 @@ fn exact_accumulator_is_a_state_group_and_a_finalize() { let finalize = Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, }); let finalize_groups = groups_where(&memo, |e| *e == finalize); assert!(candidates_of(&memo, s).iter().any(|c| { diff --git a/crates/stage1-pass1-per-computation-candidates/src/tests/intents.rs b/crates/stage1-pass1-per-computation-candidates/src/tests/intents.rs index 17ed56b00..f3cd093dd 100644 --- a/crates/stage1-pass1-per-computation-candidates/src/tests/intents.rs +++ b/crates/stage1-pass1-per-computation-candidates/src/tests/intents.rs @@ -85,3 +85,32 @@ fn a_count_offers_no_count_sketch() { &HowToComputeAggregateMeasure::Summary(SketchAlgorithm::CountSketch) )); } + +/// A standard deviation or variance, sample or population, lists one exact +/// sum-of-squared-deviations state (it holds the count and mean too), so +/// `stddev`, `stdvar` and SQL's four variants over the same rows share it +/// and it can be kept at ingestion and merged like a sum. No summary is +/// offered. +#[test] +fn stddev_and_variance_list_the_sum_of_squared_deviations_state() { + for population in [false, true] { + for intent in [ + AggIntent::StdDev { + col: Some(0), + population, + }, + AggIntent::Variance { + col: None, + population, + }, + ] { + assert_eq!( + ways_to_compute_intent(&intent), + vec![HowToComputeAggregateMeasure::ExactAccumulator(vec![ + ExactKind::SumOfSquaredDeviations + ])], + "{intent:?}" + ); + } + } +} diff --git a/crates/stage1-pass1-per-computation-candidates/src/tests/targets.rs b/crates/stage1-pass1-per-computation-candidates/src/tests/targets.rs index 6fa30bb42..e72340ac1 100644 --- a/crates/stage1-pass1-per-computation-candidates/src/tests/targets.rs +++ b/crates/stage1-pass1-per-computation-candidates/src/tests/targets.rs @@ -41,25 +41,22 @@ fn multi_measure_aggregate_has_one_target_per_measure() { } /// An aggregate with no realization besides exact execution (no -/// accumulator, no summary: `stddev`) is not a target. +/// accumulator, no summary: `group`) is not a target. #[test] fn aggregate_without_realization_is_not_a_target() { let mut memo = Memo::new(&DataWorkload::default()); let rows = selector(&mut memo, TimeRangeKind::Instant, "m", &[]); - let stddev = aggregate_group( + let group = aggregate_group( &mut memo, rows, Reduction::by(vec![]), - vec![AggIntent::StdDev { - col: None, - population: true, - }], + vec![AggIntent::Group], None, ); - query(&mut memo, stddev, None); + query(&mut memo, group, None); assert!(computation_targets(&memo, &[]).unwrap().is_empty()); let memo = pass1_memo(memo, &[]).unwrap(); - assert_eq!(candidates_of(&memo, stddev).len(), 1); + assert_eq!(candidates_of(&memo, group).len(), 1); } /// An aggregate several queries read, or a scalar root reads twice, is one diff --git a/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs b/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs index 3c9275622..4d2f1663c 100644 --- a/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs +++ b/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs @@ -43,6 +43,7 @@ pub fn exact_state( Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, }), ); (state, finalized) diff --git a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/filters.rs b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/filters.rs index bce264f21..c526fbb49 100644 --- a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/filters.rs +++ b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/filters.rs @@ -230,6 +230,7 @@ fn a_compensating_filter_over_a_sql_table_has_sql_semantics() { Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, }), ); query(&mut memo, root, Some(AccuracyTarget::exact())); diff --git a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/measures.rs b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/measures.rs index 68e9004df..dc310ac12 100644 --- a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/measures.rs +++ b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/measures.rs @@ -1,4 +1,5 @@ -//! The measures that roll up: a sum and a count as a sum. +//! The measures that roll up: a sum and a count as a sum, and a +//! sum-of-squared-deviations state as a regrouping merge. use asap_types::accuracy::AccuracyTarget; use asap_types::ir::operator::arguments::Reduction; use asap_types::ir::operator::AggIntent; @@ -6,7 +7,7 @@ use asap_types::ir::schema::FieldDataType; use asap_types::ir::{ASAPOp, NonASAPOp, Operator}; use asap_types::stages::{Memo, OriginOfCandidateForMemoGroup}; -use asap_types::summary_type::{CounterReadout, ExactKind}; +use asap_types::summary_type::{CounterReadout, ExactKind, VarianceReadout}; use asap_types::workload::DataWorkload; use crate::test_fixtures::*; @@ -37,6 +38,7 @@ fn a_coarse_exact_sum_rolls_up_the_finer_sum() { Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: rate, counter_readout: Some(CounterReadout::Rate), + variance_readout: None, }), ); let sum_by = |memo: &mut Memo, keys: Vec, name: &str| { @@ -112,3 +114,46 @@ fn a_coarse_count_rolls_up_the_finer_count_as_a_sum() { })] ); } + +/// `stddev by (job) (x[1m])`'s state rolls up the finer `stdvar by (job, +/// instance) (x[1m])`'s: one sum-of-squared-deviations state per (job, +/// instance) merges into one per job (Chan's merge of count, mean and sum +/// of squared deviations), as a sum's state would. +#[test] +fn a_coarse_sum_of_squared_deviations_merges_the_finer_states_by_its_keys() { + let mut memo = Memo::new(&DataWorkload::default()); + let input = scan_group(&mut memo, "x", &["job", "instance"], vec![]); + let window = group(&mut memo, range(60_000, input)); + let moments = FieldDataType::exact(ExactKind::SumOfSquaredDeviations); + let state_read_as = |memo: &mut Memo, keys: Vec, readout| { + let state = group( + memo, + state_grouped_by(moments.clone(), Reduction::by(keys), window), + ); + let finalized = group( + memo, + Operator::ASAP(ASAPOp::FinalizeExactAccumulator { + child: state, + counter_readout: None, + variance_readout: Some(readout), + }), + ); + query(memo, finalized, Some(AccuracyTarget::exact())); + state + }; + let fine = state_read_as(&mut memo, vec![2, 3], VarianceReadout::PopulationVariance); + let coarse = state_read_as(&mut memo, vec![2], VarianceReadout::PopulationStdDev); + let logical = pass2(memo, &[entry(60_000), entry(60_000)]); + let rollups: Vec<_> = candidates_of(&logical.memo, coarse) + .iter() + .filter(|c| c.origin == OriginOfCandidateForMemoGroup::Rollup) + .map(|c| c.expression.operator.clone()) + .collect(); + assert_eq!( + rollups, + vec![Operator::ASAP(ASAPOp::SummaryMerge { + children: vec![fine], + group_by: Some(vec![0]), + })] + ); +} diff --git a/crates/types/src/ir/operator/agg_intent.rs b/crates/types/src/ir/operator/agg_intent.rs index 9c90f4fb7..47bdcf045 100644 --- a/crates/types/src/ir/operator/agg_intent.rs +++ b/crates/types/src/ir/operator/agg_intent.rs @@ -620,8 +620,16 @@ impl AggIntent { AggIntent::Min { .. } => col("min", input.dtype.clone(), input.nullable), AggIntent::Max { .. } => col("max", input.dtype.clone(), input.nullable), AggIntent::Avg { .. } => col("avg", DataType::Float64, false), - AggIntent::StdDev { .. } => col("stddev", DataType::Float64, false), - AggIntent::Variance { .. } => col("variance", DataType::Float64, false), + // Nullable for a sample (SQL reads NULL for fewer than two + // values) and over a nullable input (no non-NULL value: NULL); + // a population over non-NULL values (PromQL's) has a value in + // every group. + AggIntent::StdDev { population, .. } => { + col("stddev", DataType::Float64, !population || input.nullable) + } + AggIntent::Variance { population, .. } => { + col("variance", DataType::Float64, !population || input.nullable) + } // Nullable: correlation is undefined for fewer than two pairs where // both inputs are non-null, and for a zero-variance input. AggIntent::PearsonCorr { .. } => col("corr", DataType::Float64, true), diff --git a/crates/types/src/ir/operator/asap.rs b/crates/types/src/ir/operator/asap.rs index b53c1e42e..c4a3aa188 100644 --- a/crates/types/src/ir/operator/asap.rs +++ b/crates/types/src/ir/operator/asap.rs @@ -17,7 +17,9 @@ use crate::ir::schema::aggregate_schema::{aggregate_output, OutputColumnSource}; use crate::ir::schema::{ColumnId, DataType, Field, FieldDataType, Schema}; use crate::ir::SchemaDerivationError; use crate::summary_type::SummaryTypeCapability; -use crate::summary_type::{CounterReadout, SketchStatistic, SummaryInputExpr, SummaryUpdate}; +use crate::summary_type::{ + CounterReadout, SketchStatistic, SummaryInputExpr, SummaryUpdate, VarianceReadout, +}; /// Why an ASAP operator cannot be used yet. pub const UNIMPLEMENTED_ASAP_OP: &str = @@ -54,6 +56,12 @@ pub enum ASAPOp> { /// counter state answers both; `None` for every other state. #[serde(default, skip_serializing_if = "Option::is_none")] counter_readout: Option, + /// For a [`SumOfSquaredDeviations`](crate::summary_type::ExactKind::SumOfSquaredDeviations) + /// state, which value it reads (sample or population variance or + /// standard deviation), so one state answers all four; `None` for + /// every other state. + #[serde(default, skip_serializing_if = "Option::is_none")] + variance_readout: Option, }, /// Maintain the full declared population, including membership changes. MaintainPopulation { @@ -216,9 +224,11 @@ impl ASAPOp { FinalizeExactAccumulator { child, counter_readout, + variance_readout, } => FinalizeExactAccumulator { child: f(child), counter_readout: *counter_readout, + variance_readout: *variance_readout, }, MaintainPopulation { child, population } => MaintainPopulation { child: f(child), @@ -374,10 +384,16 @@ impl ASAPOp { FinalizeExactAccumulator { child, counter_readout, + variance_readout, } => { // A rollup finalizes as the coarse build it stands for. if let Some((build, schema)) = rolled_up_build(child) { - return finalized_schema(Some(&build), &schema, *counter_readout); + return finalized_schema( + Some(&build), + &schema, + *counter_readout, + *variance_readout, + ); } // The windows a `TimeRange` over a chain selects, merged, // finalize as the chain's build over that range. @@ -385,6 +401,7 @@ impl ASAPOp { summary_build(child).as_ref(), child.schema(), *counter_readout, + *variance_readout, )? } MaintainPopulation { child, .. } => child.schema().clone(), @@ -601,6 +618,7 @@ impl ASAPOp { FinalizeExactAccumulator { child, counter_readout, + variance_readout, } => { needs_state(child, "FinalizeExactAccumulator")?; if child @@ -613,14 +631,16 @@ impl ASAPOp { "FinalizeExactAccumulator requires exact accumulator state".into(), )); } - // A counter state is read as `rate` or `increase`; no other - // exact state takes a counter readout. + // A counter state is read as `rate` or `increase`, a sum of + // squared deviations as a variance or standard deviation; + // no other exact state takes a readout. if child.schema().fields.iter().any(|f| { matches!(&f.dtype, FieldDataType::ExactAggregate(kind, _) - if kind.measure(None, *counter_readout).is_none()) + if kind.measure(None, *counter_readout, *variance_readout).is_none()) }) { return Err(SchemaDerivationError::InvalidScalarSignature( - "a counter state's finalize needs a counter readout, and only it takes one" + "a counter state's finalize needs a counter readout, a sum of squared \ + deviations' a variance readout, and no other state takes one" .into(), )); } @@ -882,20 +902,21 @@ fn chain_schema( /// The exact `Aggregate` that finalizing the state `build` builds (a /// `SummaryAgg` or `SummaryTumblingWindowChain` of an exact summary type) -/// with `counter_readout` computes, over the build's input: the build's +/// with `counter_readout` or `variance_readout` computes, over the build's input: the build's /// reduction, one unnamed measure (the kind's [`ExactKind::measure`] of the /// column the build reads, `None` for an input that is no column), filtered /// by the build's filter. For a chain it is the aggregate of one window, /// whose value column a finalize outputs. `Ok(None)` for any other build. -/// Errors when the build's column does not resolve, or when -/// `counter_readout` does not fit the kind (a counter needs one, any other -/// kind takes none). Example: finalizing `SummaryAgg[Counter](m[5m])` with +/// Errors when the build's column does not resolve, or when a readout +/// does not fit the kind (a counter needs a counter readout, a sum of +/// squared deviations a variance readout, any other kind takes none). Example: finalizing `SummaryAgg[Counter](m[5m])` with /// `CounterReadout::Rate` computes `Aggregate(Rate)` over `m[5m]`. /// /// [`ExactKind::measure`]: crate::summary_type::ExactKind::measure pub(crate) fn finalized_aggregate( build: &ASAPOp, counter_readout: Option, + variance_readout: Option, ) -> Result>, SchemaDerivationError> { let (ASAPOp::SummaryAgg { child: source, @@ -922,11 +943,15 @@ pub(crate) fn finalized_aggregate( ), _ => None, }; - let measure = kind.measure(column, counter_readout).ok_or_else(|| { - SchemaDerivationError::InvalidScalarSignature( - "an exact state's finalize reads a counter readout only from a counter".into(), - ) - })?; + let measure = kind + .measure(column, counter_readout, variance_readout) + .ok_or_else(|| { + SchemaDerivationError::InvalidScalarSignature( + "an exact state's finalize reads a counter readout only from a counter, and a \ + variance readout only from a sum of squared deviations" + .into(), + ) + })?; Ok(Some(NonASAPOp::Aggregate { child: source.clone(), reduction: reduction.clone(), @@ -942,14 +967,16 @@ pub(crate) fn finalized_aggregate( /// The schema `FinalizeExactAccumulator` derives over state of /// `state_schema` that `build` (the state's `SummaryAgg`, if any) builds: /// each exact aggregate replaced by the value it finalizes to -/// ([`finalized_aggregate`]), a counter state read as `counter_readout`. +/// ([`finalized_aggregate`]), a counter state read as `counter_readout`, a +/// sum of squared deviations as `variance_readout`. fn finalized_schema( build: Option<&ASAPOp>, state_schema: &Schema, counter_readout: Option, + variance_readout: Option, ) -> Result { let aggregate = build - .map(|build| finalized_aggregate(build, counter_readout)) + .map(|build| finalized_aggregate(build, counter_readout, variance_readout)) .transpose()? .flatten(); let value_result = match &aggregate { diff --git a/crates/types/src/ir/schema/aggregate_schema.rs b/crates/types/src/ir/schema/aggregate_schema.rs index d65a7e0f7..88858e989 100644 --- a/crates/types/src/ir/schema/aggregate_schema.rs +++ b/crates/types/src/ir/schema/aggregate_schema.rs @@ -193,9 +193,18 @@ pub(crate) fn aggregate_output( let input_column = measure_input_column(in_schema, intent); let in_col = input_column.map_or(&probe, |id| &in_schema.fields[id]); let mut out = intent.output_column(in_col); - // A global extremum emits NULL for an empty input, even if its input - // column is non-nullable. Grouped extrema only emit existing groups. - if by.is_empty() && matches!(intent, AggIntent::Min { .. } | AggIntent::Max { .. }) { + // A global extremum, standard deviation or variance emits NULL for an + // empty input, even if its input column is non-nullable. Grouped + // ones only emit existing groups. + if by.is_empty() + && matches!( + intent, + AggIntent::Min { .. } + | AggIntent::Max { .. } + | AggIntent::StdDev { .. } + | AggIntent::Variance { .. } + ) + { out.nullable = true; } if let Some((arg, _)) = intent @@ -723,6 +732,46 @@ mod tests { } } + // A global standard deviation or variance is NULL over no rows, as a + // global MIN/MAX is, even of a NOT NULL column: SQL `SELECT var_pop(v) + // FROM w WHERE v > 100` with no row matching gives one NULL row. A + // grouped population one over a NOT NULL column has a value in every + // group. + #[test] + fn a_global_variance_is_nullable_over_a_not_null_column() { + let input = Schema::new(vec![ + col("g", DataType::Utf8, false), + col("v", DataType::Float64, false), + ]); + for measure in [ + AggIntent::Variance { + col: Some(1), + population: true, + }, + AggIntent::StdDev { + col: Some(1), + population: true, + }, + ] { + let global = aggregate_output_schema( + &input, + &Reduction::by(vec![]), + std::slice::from_ref(&measure), + &[], + ) + .unwrap(); + assert!(global.fields.last().unwrap().nullable, "{measure:?}"); + let grouped = aggregate_output_schema( + &input, + &Reduction::by(vec![0]), + std::slice::from_ref(&measure), + &[], + ) + .unwrap(); + assert!(!grouped.fields.last().unwrap().nullable, "{measure:?}"); + } + } + #[test] fn aggregate_strips_time_and_keeps_unique_keys() { let input = Schema::with_time_index( diff --git a/crates/types/src/ir/schema/mod.rs b/crates/types/src/ir/schema/mod.rs index a2f6e805e..ee7c8b663 100644 --- a/crates/types/src/ir/schema/mod.rs +++ b/crates/types/src/ir/schema/mod.rs @@ -163,6 +163,7 @@ impl FieldDataType { ExactKind::Max => ExactParams::Max, ExactKind::Counter => ExactParams::Counter, ExactKind::IRate => ExactParams::IRate, + ExactKind::SumOfSquaredDeviations => ExactParams::SumOfSquaredDeviations, }; FieldDataType::ExactAggregate(kind, params) } diff --git a/crates/types/src/stages/logical/group/aggregate_coverage.rs b/crates/types/src/stages/logical/group/aggregate_coverage.rs index 54df6e5a0..3d25210e3 100644 --- a/crates/types/src/stages/logical/group/aggregate_coverage.rs +++ b/crates/types/src/stages/logical/group/aggregate_coverage.rs @@ -235,6 +235,7 @@ pub(super) fn aggregate_coverage<'m>( Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child, counter_readout, + variance_readout, }) => { let operator = child.operator(); let Operator::ASAP( @@ -257,7 +258,9 @@ pub(super) fn aggregate_coverage<'m>( }; // The group's schema derived from the same aggregate, so this // does too: an error here is a caller bug. - let Ok(Some(mut aggregate)) = finalized_aggregate(build, *counter_readout) else { + let Ok(Some(mut aggregate)) = + finalized_aggregate(build, *counter_readout, *variance_readout) + else { debug_assert!(false, "a finalize whose schema derives has an aggregate"); return Err(CoverageError::NoCoverage); }; @@ -269,7 +272,7 @@ pub(super) fn aggregate_coverage<'m>( // `finalized_aggregate` made this kind's measure with // this readout, so one exists without a column too. measures[0] = kind - .measure(None, *counter_readout) + .measure(None, *counter_readout, *variance_readout) .expect("a measure for this kind and readout"); } // No filter list when unfiltered. diff --git a/crates/types/src/stages/logical/group/column_properties.rs b/crates/types/src/stages/logical/group/column_properties.rs index d4a2fcd6f..071c81acd 100644 --- a/crates/types/src/stages/logical/group/column_properties.rs +++ b/crates/types/src/stages/logical/group/column_properties.rs @@ -530,9 +530,10 @@ fn asap_columns(op: &ASAPOp>, output: &Schema) -> Vec readout_columns(child, output, |state, summary_type| match summary_type { FieldDataType::ExactAggregate(kind, _) => kind - .measure(None, *counter_readout) + .measure(None, *counter_readout, *variance_readout) .map_or(Unknown, |measure| measure_sign(&measure, state)), FieldDataType::SummarySample(kind, params) => sampling_finalized_sign(kind, params), FieldDataType::Wavelet(kind, params) => wavelet_finalized_sign(kind, params), diff --git a/crates/types/src/summary_type/capability.rs b/crates/types/src/summary_type/capability.rs index 6fed20978..13071f516 100644 --- a/crates/types/src/summary_type/capability.rs +++ b/crates/types/src/summary_type/capability.rs @@ -204,7 +204,9 @@ impl SummaryTypeCapability { let (merge_inputs, readouts): (_, &'static [(StatisticKind, MergedError)]) = match summary_type { FieldDataType::ExactAggregate(kind, _) => match kind { - E::Sum | E::Count => (Some(Disjoint), &[]), + // Chan's merge of count, mean and squared deviations + // adds disjoint inputs, as a sum's does. + E::Sum | E::Count | E::SumOfSquaredDeviations => (Some(Disjoint), &[]), E::Min | E::Max => (Some(MayOverlap), &[]), // The counter accumulator joins time-ordered windows with // reset handling (`IncreaseAccumulator::merge_pair`). diff --git a/crates/types/src/summary_type/mod.rs b/crates/types/src/summary_type/mod.rs index 3a03bd2c7..9348d25fb 100644 --- a/crates/types/src/summary_type/mod.rs +++ b/crates/types/src/summary_type/mod.rs @@ -22,8 +22,8 @@ pub use family::SummaryFamily; pub use parameter_lists::parameter_list; pub use parameters::{ CounterReadout, ExactKind, ExactParams, HydraParams, SamplingKind, SamplingParams, - SketchParameterRange, SketchParams, StatModelKind, StatModelParams, WaveletKind, WaveletParams, - KLL_MAX_K, + SketchParameterRange, SketchParams, StatModelKind, StatModelParams, VarianceReadout, + WaveletKind, WaveletParams, KLL_MAX_K, }; pub use statistic::SketchStatistic; pub use update::{EntityIdentity, SummaryInputExpr, SummaryUpdate}; diff --git a/crates/types/src/summary_type/parameters.rs b/crates/types/src/summary_type/parameters.rs index d2ec6ada3..12becbbec 100644 --- a/crates/types/src/summary_type/parameters.rs +++ b/crates/types/src/summary_type/parameters.rs @@ -24,6 +24,20 @@ pub enum ExactKind { Counter, /// Instant-rate accumulator retaining the final two timestamped samples. IRate, + /// A count, a running mean and the sum of squared deviations from it + /// (Welford's M2), merged by Chan's pairwise formula; read through a + /// [`VarianceReadout`] as the sample or population variance or standard + /// deviation, so `stddev`, `stdvar` and SQL's four variants over the + /// same rows share one state. It keeps the mean, not a sum of squares: + /// the variance from Σx², Σx and n, `(Σx² − (Σx)²/n) / (n − 1)`, + /// subtracts two numbers of size n·mean² to get one of size n·variance, + /// so a mean of 1e9 and a variance of 1 loses every digit (Σx² ≈ n·1e18 + /// rounds to about n·100), with or without compensated sums. Deviations + /// from the running mean stay of the variance's size: the relative + /// error grows only as ε · mean / σ (4e-7 for a mean of 1e9 and σ of + /// 0.58), as the raw `Aggregate`'s Welford update does. Example: 1, 2 + /// and 4 hold count 3, mean 7/3 and 14/3. + SumOfSquaredDeviations, } impl ExactKind { @@ -34,7 +48,8 @@ impl ExactKind { /// per group. Sum: the compensated sum and whether it saw a sample (24); /// count (8); min and max: the value and a validity bit (9); a counter: /// its two samples, increase and sample count, and a validity bit (49); - /// irate: the last two samples (48). + /// irate: the last two samples (48); a sum of squared deviations: its + /// count, mean and sum (24; an empty one has count 0). pub fn sealed_state_bytes(self) -> u64 { match self { ExactKind::Sum => 24, @@ -42,6 +57,7 @@ impl ExactKind { ExactKind::Min | ExactKind::Max => 9, ExactKind::Counter => 49, ExactKind::IRate => 48, + ExactKind::SumOfSquaredDeviations => 24, } } } @@ -80,28 +96,95 @@ impl CounterReadout { } } +/// What a finalize reads from a [`ExactKind::SumOfSquaredDeviations`] +/// state: the variance over n − 1 (sample) or n (population), or its +/// square root. Example: 1, 2 and 4 read as sample variance 7/3 and +/// population variance 14/9. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum VarianceReadout { + /// SQL `VAR_SAMP`, `VARIANCE`. + SampleVariance, + /// SQL `VAR_POP`; PromQL `stdvar`, `stdvar_over_time`. + PopulationVariance, + /// SQL `STDDEV_SAMP`, `STDDEV`. + SampleStdDev, + /// SQL `STDDEV_POP`; PromQL `stddev`, `stddev_over_time`. + PopulationStdDev, +} + +impl VarianceReadout { + /// The readout that answers `intent`: one for `AggIntent::StdDev` and + /// `AggIntent::Variance`, sample or population; `None` for any other. + pub fn for_intent(intent: &crate::ir::operator::AggIntent) -> Option { + use crate::ir::operator::AggIntent; + Some(match intent { + AggIntent::StdDev { + population: false, .. + } => Self::SampleStdDev, + AggIntent::StdDev { + population: true, .. + } => Self::PopulationStdDev, + AggIntent::Variance { + population: false, .. + } => Self::SampleVariance, + AggIntent::Variance { + population: true, .. + } => Self::PopulationVariance, + _ => return None, + }) + } + + /// Whether it divides by n (population) rather than n − 1 (sample). + pub fn population(self) -> bool { + matches!(self, Self::PopulationVariance | Self::PopulationStdDev) + } + + /// Whether it reads the standard deviation (the variance's square root). + pub fn standard_deviation(self) -> bool { + matches!(self, Self::SampleStdDev | Self::PopulationStdDev) + } + + /// The aggregate this readout computes of input column `col`. + fn measure(self, col: Option) -> crate::ir::operator::AggIntent { + use crate::ir::operator::AggIntent; + let population = self.population(); + if self.standard_deviation() { + AggIntent::StdDev { col, population } + } else { + AggIntent::Variance { col, population } + } + } +} + impl ExactKind { /// The aggregate an exact accumulator of this kind finalizes to, of /// input column `column` (`None`: the sample value), read with - /// `counter_readout`: `ExactKind::Counter` with `CounterReadout::Rate` - /// finalizes to what `AggIntent::Rate` computes, and - /// `ExactKind::Sum.measure(Some(2), None)` to `AggIntent::Sum { col: - /// Some(2) }`. `None` when the readout does not fit the kind: a - /// `Counter` needs one, any other kind takes none. + /// `counter_readout` or `variance_readout`: `ExactKind::Counter` with + /// `CounterReadout::Rate` finalizes to what `AggIntent::Rate` computes, + /// `ExactKind::Sum.measure(Some(2), None, None)` to `AggIntent::Sum { + /// col: Some(2) }`. `None` when a readout does not fit the kind: a + /// `Counter` needs a counter readout, a `SumOfSquaredDeviations` a + /// variance readout, any other kind takes none. pub(crate) fn measure( self, column: Option, counter_readout: Option, + variance_readout: Option, ) -> Option { use crate::ir::operator::AggIntent; - match (self, counter_readout) { - (ExactKind::Counter, Some(readout)) => Some(readout.measure()), - (ExactKind::Counter, None) | (_, Some(_)) => None, - (ExactKind::Sum, None) => Some(AggIntent::Sum { col: column }), - (ExactKind::Min, None) => Some(AggIntent::Min { col: column }), - (ExactKind::Max, None) => Some(AggIntent::Max { col: column }), - (ExactKind::Count, None) => Some(AggIntent::Count), - (ExactKind::IRate, None) => Some(AggIntent::IRate), + match (self, counter_readout, variance_readout) { + (ExactKind::Counter, Some(readout), None) => Some(readout.measure()), + (ExactKind::SumOfSquaredDeviations, None, Some(readout)) => { + Some(readout.measure(column)) + } + (ExactKind::Counter | ExactKind::SumOfSquaredDeviations, _, _) + | (_, Some(_), _) + | (_, _, Some(_)) => None, + (ExactKind::Sum, None, None) => Some(AggIntent::Sum { col: column }), + (ExactKind::Min, None, None) => Some(AggIntent::Min { col: column }), + (ExactKind::Max, None, None) => Some(AggIntent::Max { col: column }), + (ExactKind::Count, None, None) => Some(AggIntent::Count), + (ExactKind::IRate, None, None) => Some(AggIntent::IRate), } } @@ -114,7 +197,7 @@ impl ExactKind { pub fn tracks_counter_increase(&self) -> bool { match self { Self::Counter | Self::IRate => true, - Self::Sum | Self::Min | Self::Max | Self::Count => false, + Self::Sum | Self::Min | Self::Max | Self::Count | Self::SumOfSquaredDeviations => false, } } } @@ -131,6 +214,7 @@ pub enum ExactParams { Max, Counter, IRate, + SumOfSquaredDeviations, } /// The largest KLL `k` `asap_sketchlib` builds: it silently caps a larger diff --git a/crates/types/tests/coverage_finalize.rs b/crates/types/tests/coverage_finalize.rs index cb61654f6..e0a7ac2d3 100644 --- a/crates/types/tests/coverage_finalize.rs +++ b/crates/types/tests/coverage_finalize.rs @@ -9,7 +9,10 @@ use asap_types::ir::scalar::ColumnRef; use asap_types::ir::schema::FieldDataType; use asap_types::ir::{ASAPOp, ExprSemantics, Operator, Predicate}; use asap_types::stages::{AggregateCoverage, Memo, MemoGroupId}; -use asap_types::summary_type::{CounterReadout, ExactKind, SummaryInputExpr, SummaryUpdate}; +use asap_types::summary_type::{ + CounterReadout, ExactKind, SummaryInputExpr, SummaryTypeCapability, SummaryUpdate, + VarianceReadout, +}; use asap_types::test_support::memo_builders::{candidate, group, scan_group}; use asap_types::test_support::memo_fixtures::{ aggregate, aggregate_with, compare, range, state, state_grouped_by, @@ -33,6 +36,18 @@ fn finalize(child: MemoGroupId, counter_readout: Option) -> Oper Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child, counter_readout, + variance_readout: None, + }) +} +/// `child`'s sum-of-squared-deviations state read as `variance_readout`. +fn finalize_variance( + child: MemoGroupId, + variance_readout: Option, +) -> Operator { + Operator::ASAP(ASAPOp::FinalizeExactAccumulator { + child, + counter_readout: None, + variance_readout, }) } /// `Scan m` (label `pod`) and `m[5m]`. @@ -230,3 +245,118 @@ fn a_finalized_state_of_a_constant_input_has_coverage_only_when_it_counts() { assert!(coverage(&memo, direct_count).is_some()); assert_eq!(coverage(&memo, count), coverage(&memo, direct_count)); } + +/// `stddev_over_time`, `stdvar_over_time` and SQL's sample and population +/// `stddev`/`variance` of `m[5m]` all finalize one sum-of-squared-deviations +/// state: each readout covers what its aggregate over the same rows covers, +/// so the four share one state. +#[test] +fn every_variance_readout_covers_what_its_aggregate_covers() { + let (mut memo, last_5m) = memo_over_last_5m(); + let moments = add( + &mut memo, + state( + FieldDataType::exact(ExactKind::SumOfSquaredDeviations), + last_5m, + ), + ); + for population in [false, true] { + for measure in [ + AggIntent::StdDev { + col: None, + population, + }, + AggIntent::Variance { + col: None, + population, + }, + ] { + let readout = VarianceReadout::for_intent(&measure).expect("a variance readout"); + let direct = add( + &mut memo, + aggregate(Reduction::PerEntity, measure.clone(), last_5m), + ); + let finalized = add(&mut memo, finalize_variance(moments, Some(readout))); + assert!(coverage(&memo, direct).is_some(), "{measure:?}"); + assert_eq!( + coverage(&memo, finalized), + coverage(&memo, direct), + "{measure:?}" + ); + } + } +} + +/// A sum-of-squared-deviations state is read only through a variance +/// readout, and a variance readout fits no other state: both finalizes +/// are refused. +#[test] +fn a_variance_readout_fits_only_the_sum_of_squared_deviations() { + let (mut memo, last_5m) = memo_over_last_5m(); + let moments = add( + &mut memo, + state( + FieldDataType::exact(ExactKind::SumOfSquaredDeviations), + last_5m, + ), + ); + assert!(memo + .find_or_add_group(finalize_variance(moments, None)) + .is_err()); + let sum = add( + &mut memo, + state(FieldDataType::exact(ExactKind::Sum), last_5m), + ); + assert!(memo + .find_or_add_group(finalize_variance( + sum, + Some(VarianceReadout::PopulationStdDev) + )) + .is_err()); +} + +/// The state is a count, a mean and the sum of squared deviations from it +/// (8 bytes each, no validity bit: an empty state has count 0); like a sum +/// it merges disjoint inputs and so rolls groups up. Only the four +/// standard-deviation and variance aggregates have a readout. +#[test] +fn the_sum_of_squared_deviations_state_is_24_bytes_and_merges_groups() { + assert_eq!(ExactKind::SumOfSquaredDeviations.sealed_state_bytes(), 24); + assert!(SummaryTypeCapability::merges_groups(&FieldDataType::exact( + ExactKind::SumOfSquaredDeviations + ))); + for (intent, readout) in [ + ( + AggIntent::StdDev { + col: Some(1), + population: false, + }, + Some(VarianceReadout::SampleStdDev), + ), + ( + AggIntent::StdDev { + col: None, + population: true, + }, + Some(VarianceReadout::PopulationStdDev), + ), + ( + AggIntent::Variance { + col: None, + population: false, + }, + Some(VarianceReadout::SampleVariance), + ), + ( + AggIntent::Variance { + col: None, + population: true, + }, + Some(VarianceReadout::PopulationVariance), + ), + (AggIntent::Avg { col: None }, None), + (AggIntent::Sum { col: None }, None), + ] { + assert_eq!(VarianceReadout::for_intent(&intent), readout, "{intent:?}"); + } +} diff --git a/crates/types/tests/memo_group_properties.rs b/crates/types/tests/memo_group_properties.rs index f67a2f5ed..931d60085 100644 --- a/crates/types/tests/memo_group_properties.rs +++ b/crates/types/tests/memo_group_properties.rs @@ -943,6 +943,7 @@ fn a_finalized_exact_accumulator_has_its_aggregates_sign() { Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: g3, counter_readout, + variance_readout: None, }), ); signs(&memo, g4)[VALUE] @@ -1013,6 +1014,7 @@ fn a_finalized_exact_state_outputs_its_aggregates_value_column() { Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, }), ); memo.groups()[finalize.0 as usize] diff --git a/crates/types/tests/physical_asap_dag.rs b/crates/types/tests/physical_asap_dag.rs index 25e738eb3..5a1fc1b7a 100644 --- a/crates/types/tests/physical_asap_dag.rs +++ b/crates/types/tests/physical_asap_dag.rs @@ -34,6 +34,7 @@ fn plan() -> Rc { OperatorNode::new_shared(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: Rc::new(state), counter_readout: None, + variance_readout: None, })) .unwrap() } @@ -46,6 +47,7 @@ fn batch_shares_the_summary_and_keeps_one_root_per_query() { let second = OperatorNode::new_shared(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, })) .unwrap(); let roots: Vec = [first, second] @@ -382,6 +384,7 @@ fn plan_with_threshold(threshold: f64) -> PhysicalASAPDAG { let root = OperatorNode::new_shared(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state, counter_readout: None, + variance_readout: None, })) .unwrap(); asap_types::test_support::forwarders::physical_asap_dag_at_query_time(&root).unwrap() diff --git a/crates/types/tests/schema_rebuilding.rs b/crates/types/tests/schema_rebuilding.rs index 3539af8f0..6efe07689 100644 --- a/crates/types/tests/schema_rebuilding.rs +++ b/crates/types/tests/schema_rebuilding.rs @@ -187,6 +187,7 @@ fn summary_transitions_preserve_structural_metadata() { let finalized = OperatorNode::new_shared(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state.clone(), counter_readout: None, + variance_readout: None, })) .unwrap(); assert_eq!(finalized.schema.unique_keys, state.schema.unique_keys); diff --git a/crates/types/tests/structure_contract.rs b/crates/types/tests/structure_contract.rs index a9acac71a..f7b9c13a3 100644 --- a/crates/types/tests/structure_contract.rs +++ b/crates/types/tests/structure_contract.rs @@ -155,7 +155,8 @@ fn state_evaluations_and_passthrough_keep_their_contracts() { .is_ok()); assert!(validate_asap_inputs(&ASAPOp::FinalizeExactAccumulator { child: state, - counter_readout: None + counter_readout: None, + variance_readout: None, }) .is_err()); } diff --git a/crates/types/tests/tumbling_window_chain.rs b/crates/types/tests/tumbling_window_chain.rs index a53b164d5..4e5261249 100644 --- a/crates/types/tests/tumbling_window_chain.rs +++ b/crates/types/tests/tumbling_window_chain.rs @@ -249,6 +249,7 @@ fn merged_windows_are_the_build_over_the_selected_range() { Operator::ASAP(ASAPOp::FinalizeExactAccumulator { child: state.clone(), counter_readout: None, + variance_readout: None, }) } else { Operator::ASAP(ASAPOp::SummaryEstimate {