Repository navigation
Conversation
…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
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
stddev,stdvar(and*_over_time) and SQLSTDDEV*/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.ExactKind::SumOfSquaredDeviations(count, running mean, sum of squared deviations; Welford update, Chan merge, 24 bytes) read through a newVarianceReadout(sample/population variance/stddev) onFinalizeExactAccumulator.stddev_over_timeandstdvar_over_timeof the same rows read the same chain (testsvariance_states::*).Review guide
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.crates/types/src/summary_type/parameters.rs(kind, readout,measure),crates/executor/src/summary_kernels/moments.rs(Welford + Chan merge, moved out ofoperators/aggregate/columnar.rs),crates/executor/src/summary_kernels/exact.rs(state, evaluation, merge).crates/executor/src/operators/summary/mod.rsandphysical_planner/mod.rs(evaluation nullability),crates/types/src/ir/operator/agg_intent.rs(StdDev/Variance output nullable for a sample or a nullable input) andcrates/types/src/ir/schema/aggregate_schema.rs(a global StdDev/Variance is nullable, as a global MIN/MAX is: SQLvar_popover no rows is NULL).variance_readout: Noneadded to everyFinalizeExactAccumulator/ExactEvaluationliteral in tests; one extra argument toExactAccumulator::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;data10,000 gauge series sampled every 100 ms.AggregateoverTimeRange(1h)each step (no other candidate)SummaryTumblingWindowChain[SumOfSquaredDeviations]kept at ingestion, merged per step, finalized withPopulationStdDevandPopulationVarianceServes 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) gainssum of squared deviations: count (u64), mean (f64), sum_squared_deviations (f64), 24 bytes, no presence word (empty = count 0). The serde form ofScalarStategains variantSumOfSquaredDeviations { count, mean, sum_squared_deviations }.Usage (as
variance_states::stddev_and_stdvar_of_the_same_rows_share_one_chainruns it):Algorithm changes
Exact variance state (new)
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.Moments::add):n += 1; d = x − mean; mean += d/n; M2 += d·(x − mean)(same ops as the rawAggregate, 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/norM2/(n−1), sqrt for stddev;None(SQL NULL) for n = 0, or n < 2 for a sample.ExactMergeOperationsPerState, per-row exact update); no per-kind calibration.Why not
[Sum, Count, SumOfSquares]sharing avg's states: each exact state finalizes to one f64 and avg combines finalized columns with aBinaryOp; 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
variance_readoutas a separate serde-defaulted field (not a rename ofcounter_readout) to keep plan files compatible.Verification
Run on a build host (not an experiment host) at the PR head.
asap-executor --lib summary_kernels::exactasap-executor --test executor tumbling_window_chain exact_state_columnsasap-stage1-pass1-per-computation-candidates --libaggregate_without_realization_is_not_a_targetnow usesgroupasap-types(all)asap-stage1-pass2-reuse-candidatesSummaryMergeasap-integration-testsvariance_states,per_series_exact_execution,sql_relational_executionstdvar_over_timee2e; SQLstddev_samp/var_pop/stddevwith NULLs vs DuckDBintegration,planner,planner-cli,cost,devtools), clippy, fmtpass2_promql::rollup::a_standard_deviation_rolls_up_the_finer_state(wasdoes_not_roll_up; now 1 rollup),promql_binary_arithmetic_keeps_an_unsupported_arm_exactusesmad_over_time| review fix (global
var_pop/stddev_popover 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_nullpass; 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