Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/cost/src/node/usage/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions crates/devtools/tests/viewer_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ fn asap_samples() -> Vec<ASAPOp<()>> {
ASAPOp::FinalizeExactAccumulator {
child: (),
counter_readout: None,
variance_readout: None,
},
ASAPOp::MaintainPopulation {
child: (),
Expand Down
9 changes: 6 additions & 3 deletions crates/executor/src/capability/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
31 changes: 20 additions & 11 deletions crates/executor/src/evaluation.rs
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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<Item = Arc<dyn AggregateCore>>,
statistic: ExactKind,
counter_readout: Option<CounterReadout>,
variance_readout: Option<VarianceReadout>,
range_ms: Option<(i64, i64)>,
key: Option<&[String]>,
) -> Result<Option<f64>, String> {
Expand All @@ -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())
}

Expand Down Expand Up @@ -83,6 +86,7 @@ mod counter_tests {
kind,
(kind == ExactKind::Counter).then_some(CounterReadout::Rate),
None,
None,
key.as_deref()
)
.unwrap(),
Expand All @@ -101,16 +105,18 @@ mod counter_tests {
let read = Some(CounterReadout::Rate);
let one = [Arc::new(state.clone()) as Arc<dyn AggregateCore>];
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<dyn AggregateCore>];
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
Expand All @@ -129,6 +135,7 @@ mod counter_tests {
None,
None,
None,
None,
)
};
// (8 - 5) over the last 10 s.
Expand All @@ -143,6 +150,8 @@ mod counter_tests {
state.update(None, 1., 0);
Arc::new(state) as Arc<dyn AggregateCore>
};
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()
);
}
}
32 changes: 1 addition & 31 deletions crates/executor/src/operators/aggregate/columnar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<f64> {
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),
Expand Down
1 change: 1 addition & 0 deletions crates/executor/src/operators/range_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ mod tests {
[Arc::new(state) as Arc<dyn AggregateCore>],
ExactKind::Counter,
Some(readout),
None,
Some((start, end)),
None,
)
Expand Down
66 changes: 52 additions & 14 deletions crates/executor/src/operators/summary/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand All @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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<Self, Error> {
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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion crates/executor/src/physical_planner/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
}),
Expand All @@ -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
Expand All @@ -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),
}
}
Expand Down
Loading