Skip to content

feat: exact sum-of-squared-deviations state keeps stddev and variance at ingestion - #1560

Draft
zzylol wants to merge 5 commits into
feat/sil-intentfrom
feat/exact-sum-of-squares
Draft

zzylol wants to merge 5 commits into
feat/sil-intentfrom
feat/exact-sum-of-squares

Conversation

@zzylol

@zzylol zzylol commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: stddev, stdvar (and *_over_time) and SQL STDDEV*/VAR* had no exact accumulator, so Pass 1 offered only raw execution: stddev_over_time(data[1h]) every 15 s over 10,000 series at 10 Hz rescanned an hour of samples each step.
  • Change: a new exact, mergeable state ExactKind::SumOfSquaredDeviations (count, running mean, sum of squared deviations; Welford update, Chan merge, 24 bytes) read through a new VarianceReadout (sample/population variance/stddev) on FinalizeExactAccumulator.
  • Effect: that workload now plans one tumbling-window chain of these states at ingestion; stddev_over_time and stdvar_over_time of the same rows read the same chain (tests variance_states::*).

Review guide

  • Base: feat/sil-intent (feat(sil): plan SIL intents: parse/check, lowering, hole guard, planning modes, group latency (L_G) #1553); this is a draft stacked on it.
  • Read first: crates/types/src/summary_type/parameters.rs (kind, readout, measure), crates/executor/src/summary_kernels/moments.rs (Welford + Chan merge, moved out of operators/aggregate/columnar.rs), crates/executor/src/summary_kernels/exact.rs (state, evaluation, merge).
  • Careful: crates/executor/src/operators/summary/mod.rs and physical_planner/mod.rs (evaluation nullability), crates/types/src/ir/operator/agg_intent.rs (StdDev/Variance output nullable for a sample or a nullable input) and crates/types/src/ir/schema/aggregate_schema.rs (a global StdDev/Variance is nullable, as a global MIN/MAX is: SQL var_pop over no rows is NULL).
  • Mechanical: variance_readout: None added to every FinalizeExactAccumulator/ExactEvaluation literal in tests; one extra argument to ExactAccumulator::evaluation, ScalarState::evaluation, exact_evaluation.

Behavior: before → after

Workload: PromQL stddev_over_time(data[1h]), stdvar_over_time(data[1h]), avg_over_time(data[1h]), each exact, every 15 s; data 10,000 gauge series sampled every 100 ms.

before after
stddev / stdvar raw Aggregate over TimeRange(1h) each step (no other candidate) one SummaryTumblingWindowChain[SumOfSquaredDeviations] kept at ingestion, merged per step, finalized with PopulationStdDev and PopulationVariance
avg Sum + Count chains unchanged (Sum + Count chains)

Serves the eval's "sketch/state benefit" need: variance queries can now be served from ingestion-time state like sums.

Interfaces

crates/types/src/summary_type/parameters.rs

 /// An exact, mergeable accumulator family. The type stays; this PR adds a variant.
 pub enum ExactKind {
     Sum,
     Count,
     Min,
     Max,
     Counter,
     IRate,
+    /// Count, running mean and sum of squared deviations (Welford's M2), merged by
+    /// Chan's formula; read through a `VarianceReadout`. 24 sealed bytes.
+    SumOfSquaredDeviations,
 }
 /// Parameters per exact kind (none carry any). The type stays; one variant added.
 pub enum ExactParams {
     Sum,
     Count,
     Min,
     Max,
     Counter,
     IRate,
+    SumOfSquaredDeviations,
 }
+/// What a finalize reads from a `SumOfSquaredDeviations` state: variance over
+/// n − 1 (sample) or n (population), or its square root. New type.
+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 answering `AggIntent::StdDev`/`Variance`; `None` for any other intent.
+    pub fn for_intent(intent: &AggIntent) -> Option<Self>;
+    /// Divides by n rather than n − 1.
+    pub fn population(self) -> bool;
+    /// Reads the square root.
+    pub fn standard_deviation(self) -> bool;
+}

crates/types/src/ir/operator/asap.rs

 /// The type stays; this PR adds a field to one variant.
 pub enum ASAPOp<C> {
     FinalizeExactAccumulator {
         child: C,
         /// For a Counter state, rate or increase; `None` otherwise.
         counter_readout: Option<CounterReadout>,
+        /// For a SumOfSquaredDeviations state, which variance/stddev it reads; `None`
+        /// otherwise (serde default, omitted when `None`, so old plan files read back).
+        variance_readout: Option<VarianceReadout>,
     },
 }

crates/executor/src/summary_kernels/exact.rs, crates/executor/src/evaluation.rs, crates/executor/src/operators/summary/mod.rs

 /// Planned evaluation of an exact summary. The type stays; one field added.
 pub struct ExactEvaluation {
     pub statistic: ExactKind,
     pub counter_readout: Option<CounterReadout>,
+    /// For a SumOfSquaredDeviations state, the readout; `None` otherwise (serde default).
+    pub variance_readout: Option<VarianceReadout>,
     pub lookback_ms: Option<i64>,
     pub offset_ms: i64,
 }
 impl ExactAccumulator {
     /// Read one population.
-    pub fn evaluation(&self, statistic: ExactKind, counter_readout: Option<CounterReadout>, range_ms: Option<(i64, i64)>, key: Option<&[String]>) -> Result<Option<f64>, Error>;
+    pub fn evaluation(&self, statistic: ExactKind, counter_readout: Option<CounterReadout>, variance_readout: Option<VarianceReadout>, range_ms: Option<(i64, i64)>, key: Option<&[String]>) -> Result<Option<f64>, Error>;
 }
 /// Merge exact windows and read one population.
-pub fn exact_evaluation(states: impl IntoIterator<Item = Arc<dyn AggregateCore>>, statistic: ExactKind, counter_readout: Option<CounterReadout>, range_ms: Option<(i64, i64)>, key: Option<&[String]>) -> Result<Option<f64>, String>;
+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>;
 impl Operator {
+    /// This exact evaluation with a nullable value (a population variance over a
+    /// nullable SQL column); the physical planner calls it where the Planner types it so.
+    pub fn with_nullable_value(self) -> Result<Self, Error>;
 }

Wire/file formats: the persisted exact record ("view layout", exact_record_bytes) gains sum of squared deviations: count (u64), mean (f64), sum_squared_deviations (f64), 24 bytes, no presence word (empty = count 0). The serde form of ScalarState gains variant SumOfSquaredDeviations { count, mean, sum_squared_deviations }.

Usage (as variance_states::stddev_and_stdvar_of_the_same_rows_share_one_chain runs it):

// The workload: three exact PromQL queries every 15 s over 10,000 series at 10 Hz.
let workload = workload(&["stddev_over_time(data[1h])", "stdvar_over_time(data[1h])", "avg_over_time(data[1h])"]);
// Stage 0 lowers each to Aggregate{StdDev|Variance|Avg, population: true} over TimeRange(1h);
// Pass 1 (`ways_to_compute_intent`) lists ExactAccumulator([SumOfSquaredDeviations]) for the first two,
// built by `measure_output` as SummaryAgg[SumOfSquaredDeviations] + FinalizeExactAccumulator
// { variance_readout: Some(PopulationStdDev | PopulationVariance) } — both share the one SummaryAgg group;
// Pass 2 offers its tumbling-window chain (merge rule Disjoint); Stage 3 selects it.
let plan = plan_installable(UserInput::new(&workload, FrontendInput::Promql, PlanningModels::builtin())).await?.0;
// One chain of SumOfSquaredDeviations, two finalizes reading it, avg on its own Sum and Count chains.
assert_eq!(chains_of(&plan, ExactKind::SumOfSquaredDeviations), 1);
assert_eq!(variance_readouts(&plan), [PopulationStdDev, PopulationVariance]);
plan.check_compiles()?; // the executor compiles the chain, merge and both finalizes

Algorithm changes

Exact variance state (new)

  • Problem: no ingestion-time realization of stddev/variance. The obvious state (Σx, Σx², n) is numerically unsound: on 10,000 values 1e9 + k/1024 (variance 1/3) the formula (Σx² − (Σx)²/n)/(n−1) with Kahan–Neumaier sums is off by more than 1% (test asserts; in practice >100%), because Σx² ≈ 1e22 rounds to far more than n·variance.
  • After: state = (n, mean, M2). Update (Moments::add): n += 1; d = x − mean; mean += d/n; M2 += d·(x − mean) (same ops as the raw Aggregate, so the same rounding as Prometheus/DataFusion). Merge (Moments::merge, Chan et al.): d = mean_b − mean_a; n = a + b; mean = mean_a + d·b/n; M2 = M2_a + M2_b + d²·a·b/n; empty side is the identity. Finalize: M2/n or M2/(n−1), sqrt for stddev; None (SQL NULL) for n = 0, or n < 2 for a sample.
  • Correctness: exact in real arithmetic, so associative to rounding (test: three uneven states merged both ways vs one pass, 1e-12); relative error ε·mean/σ, matched against an exact integer-arithmetic variance to 1e-6 on mean 1e9 / σ 0.58 (observed 8e-8); NaN/±Inf → NaN.
  • Complexity: O(1) per update and per merge, 24 bytes per group (Sum 24, Count 8). Cost model: priced by the generic exact constants (ExactMergeOperationsPerState, per-row exact update); no per-kind calibration.
  • Limits: not bitwise identical to the raw one-pass result after merges (to rounding only).

Why not [Sum, Count, SumOfSquares] sharing avg's states: each exact state finalizes to one f64 and avg combines finalized columns with a BinaryOp; doing the same for variance subtracts two finalized f64s and cancels as above. Keeping (n, mean, M2) in one state makes the readout local and sound; the cost is that avg + stddev of the same rows keep Sum + Count + this state (8 + 24 + 24 bytes/group) instead of sharing Sum/Count.

Decisions and open questions

  • Decided (2026-12-03, this PR, per approved design latitude "pick and justify"): Welford/Chan (count, mean, M2) instead of Σx²; variance_readout as a separate serde-defaulted field (not a rename of counter_readout) to keep plan files compatible.
  • Needs reviewer decision: none.

Verification

Run on a build host (not an experiment host) at the PR head.

scope result notes
asap-executor --lib summary_kernels::exact 11 passed new: adversarial large mean vs exact integer variance; associativity; SQL sample/population NULLs; NaN/Inf; readout fit + persistence
asap-executor --test executor tumbling_window_chain exact_state_columns 8 passed new: chain of 10-min windows built at ingestion answers sample stddev and population variance vs two-pass (1e-12); records vs objects for two readouts; Int64 input; NULL skipping
asap-stage1-pass1-per-computation-candidates --lib 42 passed new: StdDev/Variance list the state; aggregate_without_realization_is_not_a_target now uses group
asap-types (all) passed new: four readouts cover their aggregates; readout/kind mismatch refused; 24 bytes, merges groups
asap-stage1-pass2-reuse-candidates passed new: coarse state rolls up the finer by a regrouping SummaryMerge
asap-integration-tests variance_states, per_series_exact_execution, sql_relational_execution 24 passed new: repeating stddev keeps a chain; stddev+stdvar share one chain; stdvar_over_time e2e; SQL stddev_samp/var_pop/stddev with NULLs vs DuckDB
wider (integration, planner, planner-cli, cost, devtools), clippy, fmt all passed; clippy -D warnings clean on changed crates; fmt clean two old-behavior tests updated: pass2_promql::rollup::a_standard_deviation_rolls_up_the_finer_state (was does_not_roll_up; now 1 rollup), promql_binary_arithmetic_keeps_an_unsupported_arm_exact uses mad_over_time

| review fix (global var_pop/stddev_pop over a NOT NULL column, no rows → NULL) | aggregate_schema::a_global_variance_is_nullable_over_a_not_null_column, physical_dag::empty_global_population_variance_reads_null pass; types, executor, pass 1, pass 2, integration, planner, planner-cli, cost suites rerun with no failure; clippy clean | tests committed before the fix; I did not run them against the pre-fix code separately |

Follow-ups

  • The state's cost is priced by the generic exact constants and is not measured. Remeasure and add measured-table rows (review IMPORTANT-2).

  • Data plane: a compact codec for the new exact record kind (draft stacked on the backend PR it builds on, linked from there).

  • Deferred: per-kind measured cost constants; design-doc tables listing exact kinds (asap-primitive-schema.md) still list the old kinds.

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi

zzylol and others added 2 commits December 3, 2026 19:29
…nce at ingestion (failing)

Tests for an exact, mergeable state of a count, a mean and the sum of
squared deviations from it (ExactKind::SumOfSquaredDeviations), read
through a VarianceReadout as the sample or population standard deviation
or variance: Pass 1 lists it for StdDev/Variance; its finalize covers
the aggregate it reads; Pass 2 rolls finer states up by a regrouping
merge; the executor's Chan merge is associative and matches an exact
(integer) variance on a mean of 1e9 and a variance of 1/3, where the
naive sum-of-squares formula is off by more than 1%; NULLs are skipped
and SQL NULLs read; a chain built at ingestion answers stddev and stdvar;
a repeating stddev_over_time keeps the chain, shared with stdvar_over_time.

They fail to compile: the kind and readout do not exist yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
… at ingestion

ExactKind::SumOfSquaredDeviations holds a count, a running mean and the
sum of squared deviations from it (Welford), merged by Chan's pairwise
formula (disjoint inputs, like a sum), 24 bytes sealed. A new
VarianceReadout on FinalizeExactAccumulator (and ExactEvaluation) reads it
as the sample or population variance or standard deviation, so PromQL
stddev/stdvar(_over_time) and SQL's stddev/variance variants over the
same rows share one state. Pass 1 lists it for StdDev/Variance; Pass 2
chains and rolls it up through the generic capability row; the executor
builds, merges, seals (view record: count, mean, M2) and finalizes it,
skipping NULLs and reading SQL NULL for no value or one sample value.

The mean, not a sum of squares, is kept: (Σx² − (Σx)²/n)/(n − 1) cancels
catastrophically (a mean of 1e9 and a variance of 1/3 is off by >100%
even with compensated sums); Welford's error is ε·mean/σ (here 4e-7).

StdDev/Variance output columns are nullable for a sample or a nullable
input, as SQL reads them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
@zzylol zzylol added enhancement New feature or request optimizer Workload optimization and plan selection testing Corpus, regression, differential, or benchmark tests labels Dec 3, 2026
zzylol and others added 3 commits December 3, 2026 23:16
…nsupported-arm example

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
…s reads NULL (failing)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
… MIN/MAX is

SQL var_pop/stddev_pop over a NOT NULL column with no row read one NULL
row; the state path errored (empty exact population) because the
finalized column was typed non-nullable. Grouped population variants
over NOT NULL columns stay non-nullable (every emitted group has a value).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request optimizer Workload optimization and plan selection testing Corpus, regression, differential, or benchmark tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant