feat(promql): partial state and merge for native float aggregates

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
Dennis Zhuang
2026-10-21 16:36:12 +08:00
parent 6106fb0bc8
commit 5ab3f899b0
3 changed files with 645 additions and 26 deletions
+47 -26
View File
@@ -16,9 +16,14 @@
//! is keyed by absolute grid index, never by local row number; sparse state and trimmed output
//! do not expand the full grid.
mod state;
#[cfg(test)]
mod tests;
pub use state::{
AccumulatorState, FloatMerger, PartialAggregate, PartialGroup, StateField, merge_count_values,
};
use std::cmp::Reverse;
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, BinaryHeap, HashMap};
@@ -33,7 +38,7 @@ use crate::map::{drop_empty_labels, validate_float_series, validate_scalar};
use crate::range_eval::quantile;
/// Float aggregations without a parameter.
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AggregateOp {
Sum,
Count,
@@ -139,30 +144,39 @@ impl FloatAggregator {
/// The result of every group, in the order the groups first appeared.
pub fn finish(self) -> Result<Vec<Series>> {
let width = self.schema.fields.len();
let mut builder = GridSeriesBuilder::try_new(self.schema)?;
let mut output = Vec::with_capacity(self.groups.len());
let mut row = Vec::with_capacity(width);
for group in self.groups {
// One builder serves every group, so each result series starts explicitly.
builder.begin_series();
for (&block, states) in &group.blocks {
// The last block can extend past the grid; only points with a sample are pushed.
for (offset, point) in states.chunks_exact(width).enumerate() {
if !point.iter().any(|state| state.seen) {
continue;
}
row.clear();
row.extend(point.iter().map(|state| state.finish(self.op)));
builder.push(block * BLOCK_POINTS + offset, &row)?;
}
}
output.extend(builder.finish(group.metric)?);
}
Ok(output)
finish_groups(self.schema, self.op, self.groups)
}
}
/// Turns the state of `groups` into result series, in group order.
fn finish_groups(
schema: Arc<SeriesSchema>,
op: AggregateOp,
groups: Vec<Group>,
) -> Result<Vec<Series>> {
let width = schema.fields.len();
let mut builder = GridSeriesBuilder::try_new(schema)?;
let mut output = Vec::with_capacity(groups.len());
let mut row = Vec::with_capacity(width);
for group in groups {
// One builder serves every group, so each result series starts explicitly.
builder.begin_series();
for (&block, states) in &group.blocks {
// The last block can extend past the grid; only points with a sample are pushed.
for (offset, point) in states.chunks_exact(width).enumerate() {
if !point.iter().any(|state| state.seen) {
continue;
}
row.clear();
row.extend(point.iter().map(|state| state.finish(op)));
builder.push(block * BLOCK_POINTS + offset, &row)?;
}
}
output.extend(builder.finish(group.metric)?);
}
Ok(output)
}
/// `quantile(q, v)`, with `q` read at each grid point from an unlabelled single-field scalar on
/// the same grid, as Prometheus evaluates the parameter at every step. A point where `q` has no
/// value has no result; `q` outside `[0, 1]` or NaN gives what Prometheus' `quantile` gives.
@@ -301,7 +315,7 @@ pub fn count_values(
let mut group_index = HashMap::new();
// Counts are kept per point that has one, not in blocks: a gauge with distinct values makes
// about one group per sample.
let mut groups: Vec<(MetricName, BTreeMap<usize, Vec<f64>>)> = Vec::new();
let mut groups: Counts = Vec::new();
for series in input {
// Equal bits format to the same label value, so each distinct value of a series
// resolves its group once.
@@ -333,9 +347,16 @@ pub fn count_values(
}
}
}
count_series(schema, groups)
}
/// Counts per point and field: one series per label set, a count of 0 being no sample.
type Counts = Vec<(MetricName, BTreeMap<usize, Vec<f64>>)>;
fn count_series(schema: &Arc<SeriesSchema>, groups: Counts) -> Result<Vec<Series>> {
let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
let mut output = Vec::with_capacity(groups.len());
let mut row = Vec::with_capacity(width);
let mut row = Vec::with_capacity(schema.fields.len());
for (metric, counts) in groups {
builder.begin_series();
for (point, counts) in counts {
@@ -523,7 +544,6 @@ impl FloatState {
*self = Self {
seen: true,
value: match op {
AggregateOp::Group => 1.0,
// The running sum of squared deviations; Prometheus starts it at NaN for a
// non-finite first sample.
AggregateOp::Stddev | AggregateOp::Stdvar if !sample.is_finite() => f64::NAN,
@@ -590,7 +610,8 @@ impl FloatState {
AggregateOp::Avg if self.incremental_mean => self.mean + self.compensation,
AggregateOp::Avg => self.value / self.count + self.compensation / self.count,
AggregateOp::Count => self.count,
AggregateOp::Min | AggregateOp::Max | AggregateOp::Group => self.value,
AggregateOp::Min | AggregateOp::Max => self.value,
AggregateOp::Group => 1.0,
AggregateOp::Stdvar => self.value / self.count,
AggregateOp::Stddev => (self.value / self.count).sqrt(),
})
+339
View File
@@ -0,0 +1,339 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Partial aggregation: the state one execution partition folds its series into, and the merge
//! of such states into the final result.
//!
//! A merge regroups the operations of a serial fold, so floating-point results differ from
//! [`aggregate_float`](crate::aggregate::aggregate_float) by rounding. The same reassociation can
//! also move an overflow of finite values: a serial `sum` of `[1e308, 1e308, -1e308]` is `+Inf`,
//! while the merge of `[1e308]` and `[1e308, -1e308]` is finite. Explicit NaN and infinite inputs
//! follow the same rules as the serial fold. Where the serial fold keeps the first of two equal
//! values, as `min` and `max` do for `0` and `-0`, a merge keeps the one merged first.
use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use datafusion::error::{DataFusionError, Result};
use datatypes::series::MetricName;
use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
use crate::aggregate::{
AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, LabelKey, count_series,
finish_groups, kahan_inc, label_key,
};
use crate::map::validate_float_series;
/// A component of [`AccumulatorState`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateField {
/// The running sum (`sum`, and `avg` until it switches to a mean), the extreme (`min`,
/// `max`), or the sum of squared deviations (`stddev`, `stdvar`).
Value,
/// The running mean (`avg` once switched, `stddev`, `stdvar`).
Mean,
/// The Kahan compensation of `Value`, or of `Mean` once `avg` has switched.
Compensation,
/// The number of samples folded in.
Count,
/// Whether `avg` has switched from a sum to a mean, which it does when the sum overflows.
IncrementalMean,
}
impl AggregateOp {
/// The components the state of this aggregation carries; the others are unused and need not
/// be stored. `group` has none: a state that exists has a value of 1.
pub fn state_fields(self) -> &'static [StateField] {
use StateField::*;
match self {
Self::Sum => &[Value, Compensation],
Self::Count => &[Count],
Self::Avg => &[Value, Mean, Compensation, Count, IncrementalMean],
Self::Min | Self::Max => &[Value],
Self::Group => &[],
Self::Stddev | Self::Stdvar => &[Value, Mean, Count],
}
}
}
/// The state of one field of one group at one grid point.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct AccumulatorState {
pub value: f64,
pub mean: f64,
pub compensation: f64,
pub count: f64,
pub incremental_mean: bool,
}
/// The state of one group: its points in ascending order, each with one state per field, `None`
/// where no sample of that field was folded in.
#[derive(Clone, Debug)]
pub struct PartialGroup {
pub metric: MetricName,
pub points: Vec<(usize, Vec<Option<AccumulatorState>>)>,
}
/// The state of one execution partition, with its groups in the order they first appeared.
#[derive(Clone, Debug)]
pub struct PartialAggregate {
pub op: AggregateOp,
pub groups: Vec<PartialGroup>,
}
impl FloatAggregator {
/// The state folded so far, for a merge with the state of other partitions.
pub fn finish_partial(self) -> PartialAggregate {
let width = self.schema.fields.len();
let groups = self
.groups
.into_iter()
.map(|group| {
let mut points = Vec::new();
for (&block, states) in &group.blocks {
for (offset, point) in states.chunks_exact(width).enumerate() {
if point.iter().any(|state| state.seen) {
points.push((
block * BLOCK_POINTS + offset,
point.iter().map(|state| state.partial()).collect(),
));
}
}
}
PartialGroup {
metric: group.metric,
points,
}
})
.collect();
PartialAggregate {
op: self.op,
groups,
}
}
}
/// Merges the partial states of one aggregation into its result. Groups are identified by their
/// full label set, already grouped by the partitions, and keep the order they first arrive in.
pub struct FloatMerger {
schema: Arc<SeriesSchema>,
op: AggregateOp,
group_index: HashMap<LabelKey, usize>,
groups: Vec<Group>,
}
impl FloatMerger {
pub fn try_new(schema: &Arc<SeriesSchema>, op: AggregateOp) -> Result<Self> {
if schema.eval_grid.is_none() {
return Err(DataFusionError::Execution(
"Aggregate requires an evaluated grid".into(),
));
}
Ok(Self {
schema: schema.clone(),
op,
group_index: HashMap::new(),
groups: Vec::new(),
})
}
/// Merges the state of one partition. A partial that does not fit this merge, by its
/// aggregation, field count or grid positions, fails and leaves the merge unchanged.
pub fn merge(&mut self, partial: PartialAggregate) -> Result<()> {
let width = self.schema.fields.len();
let points = self
.schema
.eval_grid
.as_ref()
.expect("checked at construction")
.timestamps()
.len();
if partial.op != self.op {
return Err(DataFusionError::Execution(format!(
"cannot merge {:?} state into {:?}",
partial.op, self.op
)));
}
for group in &partial.groups {
for (point, states) in &group.points {
if *point >= points || states.len() != width {
return Err(DataFusionError::Execution(
"aggregate state does not match the grid or fields of the merge".into(),
));
}
}
}
for group in partial.groups {
let index = match self.group_index.entry(label_key(&group.metric)) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
self.groups.push(Group {
metric: group.metric,
blocks: BTreeMap::new(),
});
*entry.insert(self.groups.len() - 1)
}
};
let blocks = &mut self.groups[index].blocks;
for (point, states) in group.points {
let block = blocks.entry(point / BLOCK_POINTS).or_insert_with(|| {
vec![FloatState::default(); BLOCK_POINTS * width].into_boxed_slice()
});
let offset = (point % BLOCK_POINTS) * width;
for (slot, state) in block[offset..offset + width].iter_mut().zip(states) {
if let Some(state) = state {
slot.merge(self.op, FloatState::from_partial(state));
}
}
}
}
Ok(())
}
/// The result of every group, in the order the groups first arrived.
pub fn finish(self) -> Result<Vec<Series>> {
finish_groups(self.schema, self.op, self.groups)
}
}
impl FloatState {
fn partial(&self) -> Option<AccumulatorState> {
self.seen.then_some(AccumulatorState {
value: self.value,
mean: self.mean,
compensation: self.compensation,
count: self.count,
incremental_mean: self.incremental_mean,
})
}
fn from_partial(state: AccumulatorState) -> Self {
Self {
seen: true,
value: state.value,
mean: state.mean,
compensation: state.compensation,
count: state.count,
incremental_mean: state.incremental_mean,
}
}
/// Folds the state of another partition into this one.
fn merge(&mut self, op: AggregateOp, other: Self) {
if !self.seen {
*self = other;
return;
}
match op {
AggregateOp::Sum => {
// The error of adding the two sums goes into the compensation with theirs.
let (value, compensation) = kahan_inc(other.value, self.value, self.compensation);
self.value = value;
self.compensation = compensation + other.compensation;
}
AggregateOp::Count => self.count += other.count,
AggregateOp::Group => {}
AggregateOp::Max => {
if self.value < other.value || self.value.is_nan() {
self.value = other.value;
}
}
AggregateOp::Min => {
if self.value > other.value || self.value.is_nan() {
self.value = other.value;
}
}
AggregateOp::Avg => self.merge_avg(other),
AggregateOp::Stddev | AggregateOp::Stdvar => {
// Chan et al.'s pairwise update. `delta * (delta * weight)` keeps the product
// finite where it is: `delta²` alone overflows for `[0]` and `[1.5e154]`, whose
// merged sum of squares is finite.
let count = self.count + other.count;
let delta = other.mean - self.mean;
let weight = self.count * other.count / count;
self.mean += delta * (other.count / count);
self.value = self.value + other.value + delta * (delta * weight);
self.count = count;
}
}
}
/// Adds the sums while they stay finite, and otherwise continues with the count-weighted
/// mean, as the serial update switches to an incremental mean once its sum overflows.
fn merge_avg(&mut self, other: Self) {
let count = self.count + other.count;
if !self.incremental_mean && !other.incremental_mean {
let (value, compensation) = kahan_inc(other.value, self.value, self.compensation);
if !value.is_infinite() {
self.value = value;
self.compensation = compensation + other.compensation;
self.count = count;
return;
}
}
let (mean, compensation) = self.mean_form();
let (other_mean, other_compensation) = other.mean_form();
let (weight, other_weight) = (self.count / count, other.count / count);
(self.mean, self.compensation) = kahan_inc(
other_mean * other_weight,
mean * weight,
compensation * weight + other_compensation * other_weight,
);
self.incremental_mean = true;
self.count = count;
}
/// The mean and its compensation, converting a sum as the serial update does on switching.
fn mean_form(&self) -> (f64, f64) {
if self.incremental_mean {
(self.mean, self.compensation)
} else {
(self.value / self.count, self.compensation / self.count)
}
}
}
/// Merges `count_values` results of several partitions. Each partial already carries its full
/// output label set, value label included, so series with one label set add their counts point
/// by point and field by field.
pub fn merge_count_values(
schema: &Arc<SeriesSchema>,
partials: impl IntoIterator<Item = Series>,
) -> Result<Vec<Series>> {
let width = schema.fields.len();
let mut group_index: HashMap<LabelKey, usize> = HashMap::new();
let mut groups: Counts = Vec::new();
for series in partials {
validate_float_series(schema, &series)?;
let index = match group_index.entry(label_key(&series.metric)) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
groups.push((series.metric.clone(), BTreeMap::new()));
*entry.insert(groups.len() - 1)
}
};
for (field_index, field) in series.fields.iter().enumerate() {
for ((point, _), sample) in series.time.positions().zip(field.iter()) {
if let SampleRef::Float(count) = sample {
groups[index]
.1
.entry(point)
.or_insert_with(|| vec![0.0; width])[field_index] += count;
}
}
}
}
count_series(schema, groups)
}
+259
View File
@@ -20,6 +20,10 @@ use datatypes::series::histogram::HistogramBatchBuilder;
use datatypes::series::samples::{FieldSpec, Samples, SeriesFields};
use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use super::*;
use crate::golden::{assert_result, cases};
use crate::grid_series::reference::{Labels, piece_ranges};
@@ -1021,3 +1025,258 @@ fn quantile_over_one_point_members_reads_each_member_at_its_point() {
let expected: Vec<Option<f64>> = (0..128).map(|point| Some(point as f64)).collect();
assert_eq!(values_of(&output, 0, 128), (0, expected));
}
/// A float sample for the partial tests: ordinary values, repeats, signed zeros, NaN and
/// infinities, but no finite values large enough to overflow when regrouped.
fn partial_sample(rng: &mut StdRng) -> f64 {
match rng.random_range(0..20) {
0 => f64::NAN,
1 => f64::INFINITY,
2 => f64::NEG_INFINITY,
3 => 0.0,
4 => -0.0,
5..=8 => rng.random_range(0..4) as f64,
_ => (rng.random::<f64>() - 0.5) * 2e6,
}
}
/// Every valued (point, field) of `output` by rendered label set.
fn flatten(output: &[Series]) -> BTreeMap<String, BTreeMap<(usize, usize), f64>> {
let mut flat: BTreeMap<String, BTreeMap<(usize, usize), f64>> = BTreeMap::new();
for series in output {
let points = flat.entry(format!("{:?}", series.metric)).or_default();
for (field, samples) in series.fields.iter().enumerate() {
for ((point, _), sample) in series.time.positions().zip(samples.iter()) {
if let SampleRef::Float(value) = sample {
assert!(points.insert((point, field), value).is_none());
}
}
}
}
flat
}
fn assert_flat_close(
actual: &[Series],
expected: &[Series],
epsilon: f64,
context: &dyn std::fmt::Display,
) {
let (actual, expected) = (flatten(actual), flatten(expected));
assert_eq!(
actual.keys().collect::<Vec<_>>(),
expected.keys().collect::<Vec<_>>(),
"{context}"
);
for (labels, expected) in &expected {
let actual = &actual[labels];
assert_eq!(
actual.keys().collect::<Vec<_>>(),
expected.keys().collect::<Vec<_>>(),
"{context} {labels}"
);
for (key, &value) in expected {
assert!(
crate::grid_series::reference::close(actual[key], value, epsilon),
"{context} {labels} {key:?}: merged {} serial {value}",
actual[key]
);
}
}
}
/// Partial states merged in any partition and merge order give the serial result, within the
/// rounding a regrouped fold may change: the same groups, points and fields, the same NaN and
/// infinities. Each partial keeps only the components its aggregation declares, so the layout
/// in `state_fields` is all a merge needs.
#[test]
fn partials_merge_to_the_serial_result() {
const OPS: [AggregateOp; 8] = [
AggregateOp::Sum,
AggregateOp::Count,
AggregateOp::Avg,
AggregateOp::Min,
AggregateOp::Max,
AggregateOp::Group,
AggregateOp::Stddev,
AggregateOp::Stdvar,
];
let strip = |op: AggregateOp, state: &mut AccumulatorState| {
let kept = op.state_fields();
let mut stripped = AccumulatorState::default();
for field in kept {
match field {
StateField::Value => stripped.value = state.value,
StateField::Mean => stripped.mean = state.mean,
StateField::Compensation => stripped.compensation = state.compensation,
StateField::Count => stripped.count = state.count,
StateField::IncrementalMean => stripped.incremental_mean = state.incremental_mean,
}
}
*state = stripped;
};
for seed in 0..300 {
let mut rng = StdRng::seed_from_u64(seed);
let fields: Vec<String> = (0..rng.random_range(1..=3))
.map(|field| format!("f{field}"))
.collect();
let names: Vec<&str> = fields.iter().map(String::as_str).collect();
let schema = schema_with_grid_len(&names, rng.random_range(1..80));
let points = schema.eval_grid.as_ref().unwrap().timestamps().len();
let mut builder = GridSeriesBuilder::try_new(schema.clone()).unwrap();
let mut series = Vec::new();
for index in 0..rng.random_range(1..12) {
builder.begin_series();
for point in 0..points {
let row: Vec<Option<f64>> = (0..names.len())
.map(|_| rng.random_bool(0.6).then(|| partial_sample(&mut rng)))
.collect();
builder.push(point, &row).unwrap();
}
let job = ["x", "y"][rng.random_range(0..2)];
let index = index.to_string();
series.extend(
builder
.finish(metric("m", &[("job", job), ("i", &index)]))
.unwrap(),
);
}
let parts: Vec<usize> = series.iter().map(|_| rng.random_range(0..4)).collect();
let mut order: Vec<usize> = (0..4).collect();
order.shuffle(&mut rng);
let grouping = if rng.random_bool(0.5) {
Grouping::By(&["job"])
} else {
Grouping::Without(&["i"])
};
for op in OPS {
let serial = aggregate_float(&schema, &series, op, grouping).unwrap();
let mut merger = FloatMerger::try_new(&schema, op).unwrap();
for &part in &order {
let mut aggregator = FloatAggregator::try_new(&schema, op, grouping).unwrap();
for (series, _) in series.iter().zip(&parts).filter(|(_, p)| **p == part) {
aggregator.update(series).unwrap();
}
let mut partial = aggregator.finish_partial();
for group in &mut partial.groups {
for (_, states) in &mut group.points {
states
.iter_mut()
.flatten()
.for_each(|state| strip(op, state));
}
}
merger.merge(partial).unwrap();
}
let merged = merger.finish().unwrap();
assert_flat_close(&merged, &serial, 1e-10, &format!("seed {seed} {op:?}"));
}
let serial = count_values(&schema, &series, "value", grouping).unwrap();
let partials = order.iter().flat_map(|&part| {
let members: Vec<Series> = series
.iter()
.zip(&parts)
.filter(|(_, p)| **p == part)
.map(|(series, _)| series.clone())
.collect();
count_values(&schema, &members, "value", grouping).unwrap()
});
let merged = merge_count_values(&schema, partials).unwrap();
assert_flat_close(&merged, &serial, 0.0, &format!("seed {seed} count_values"));
}
}
/// Adding two partial sums can lose low bits, which go into the compensation: `1` survives
/// between `1e100` and `-1e100` in three partials as it does in the serial fold.
#[test]
fn a_sum_merge_keeps_the_error_of_adding_partial_sums() {
let schema = schema(&["value"]);
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
for value in [1e100, 1.0, -1e100] {
let mut aggregator =
FloatAggregator::try_new(&schema, AggregateOp::Sum, Grouping::By(&[])).unwrap();
aggregator
.update(&input(&schema, metric("m", &[]), 0, &[vec![Some(value)]]))
.unwrap();
merger.merge(aggregator.finish_partial()).unwrap();
}
assert_eq!(
values_of(&merger.finish().unwrap(), 0, 128),
(0, vec![Some(1.0)])
);
}
/// Merging finite partials does not overflow where the result is finite: `avg` switches to a
/// mean when the summed partials overflow, and `stdvar` does not square the mean difference on
/// its own.
#[test]
fn merges_of_large_finite_partials_stay_finite() {
let schema = schema(&["value"]);
let merged = |op, values: [f64; 2]| {
let mut merger = FloatMerger::try_new(&schema, op).unwrap();
for value in values {
let mut aggregator = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
aggregator
.update(&input(&schema, metric("m", &[]), 0, &[vec![Some(value)]]))
.unwrap();
merger.merge(aggregator.finish_partial()).unwrap();
}
values_of(&merger.finish().unwrap(), 0, 128).1[0].unwrap()
};
assert_eq!(merged(AggregateOp::Avg, [1e308, 1e308]), 1e308);
let stdvar = merged(AggregateOp::Stdvar, [0.0, 1.5e154]);
assert!(stdvar.is_finite(), "{stdvar}");
assert!(crate::grid_series::reference::close(
stdvar, 5.625e307, 1e-10
));
}
/// `min` and `max` keep the first of two equal values, so with `0` and `-0` the sign is that of
/// the partial merged first.
#[test]
fn equal_zero_extremes_follow_the_merge_order() {
let schema = schema(&["value"]);
for op in [AggregateOp::Min, AggregateOp::Max] {
for (first, second) in [(0.0, -0.0), (-0.0, 0.0)] {
let mut merger = FloatMerger::try_new(&schema, op).unwrap();
for value in [first, second] {
let mut aggregator =
FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
aggregator
.update(&input(&schema, metric("m", &[]), 0, &[vec![Some(value)]]))
.unwrap();
merger.merge(aggregator.finish_partial()).unwrap();
}
let value = values_of(&merger.finish().unwrap(), 0, 128).1[0].unwrap();
assert_eq!(
value.to_bits(),
f64::to_bits(first),
"{op:?} {first} {second}"
);
}
}
}
/// A partial of another aggregation, field count or grid fails the merge.
#[test]
fn a_merge_rejects_state_that_does_not_fit() {
let schema = schema(&["value"]);
let partial = |op| {
let mut aggregator = FloatAggregator::try_new(&schema, op, Grouping::By(&[])).unwrap();
aggregator
.update(&input(&schema, metric("m", &[]), 5, &[vec![Some(1.0)]]))
.unwrap();
aggregator.finish_partial()
};
let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
assert!(merger.merge(partial(AggregateOp::Avg)).is_err());
let mut wide = partial(AggregateOp::Sum);
wide.groups[0].points[0].1.push(None);
assert!(merger.merge(wide).is_err());
let mut late = partial(AggregateOp::Sum);
late.groups[0].points[0].0 = 128;
assert!(merger.merge(late).is_err());
assert!(merger.finish().unwrap().is_empty());
}