Skip to main content

promql/aggregate/
state.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Partial aggregation: the state one execution partition folds its series into, and the merge
16//! of such states into the final result.
17//!
18//! A merge regroups the operations of a serial fold, so floating-point results differ from
19//! [`aggregate_float`](crate::aggregate::aggregate_float) by rounding. The same reassociation can
20//! also move an overflow of finite values: a serial `sum` of `[1e308, 1e308, -1e308]` is `+Inf`,
21//! while the merge of `[1e308]` and `[1e308, -1e308]` is finite. `stddev` and `stdvar` differ
22//! more where the samples differ by little more than the rounding of their mean: Prometheus'
23//! uncompensated Welford update rounds the mean on every sample, and no pairwise merge reproduces
24//! those roundings. For `[1e16]` and `[1e16 + 2]` Prometheus gives a variance of 2 and the merge
25//! gives the exact 1. Explicit NaN and infinite inputs follow the same rules as the serial fold. Where the serial fold keeps the first of two equal
26//! values, as `min` and `max` do for `0` and `-0`, a merge keeps the one merged first.
27
28use std::collections::btree_map::Entry as BTreeEntry;
29use std::collections::hash_map::Entry;
30use std::collections::{BTreeMap, HashMap};
31use std::mem::size_of;
32use std::sync::Arc;
33
34use datafusion::arrow::array::Array;
35use datafusion::error::{DataFusionError, Result};
36use datatypes::series::SeriesLabels;
37use datatypes::series::aggregate_state::{
38    AggregateStateKind, HistogramState, StateComponent, StateFieldsBatch, StatePayload, StateSeries,
39};
40use datatypes::series::samples::{SampleRef, Series, SeriesSchema};
41use datatypes::series::time::{GridSpan, TimeAxis};
42
43use crate::aggregate::{
44    AggregateOp, BLOCK_POINTS, Counts, FloatAggregator, FloatState, Group, HistogramAccumulator,
45    HistogramEvidence, LabelKey, accumulator_bytes, block_bytes, btree_backing_bytes, count_series,
46    evidence_summary, finish_groups, finish_groups_budgeted, hash_map_backing_bytes,
47    histogram_backing_bytes, kahan_inc, label_key, metric_bytes, next_hash_capacity, state_seen,
48};
49use crate::map::validate_float_series;
50
51/// A component of [`AccumulatorState`].
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum StateField {
54    /// The running sum (`sum`, and `avg` until it switches to a mean), the extreme (`min`,
55    /// `max`), or the sum of squared deviations (`stddev`, `stdvar`).
56    Value,
57    /// The running mean (`avg` once switched, `stddev`, `stdvar`).
58    Mean,
59    /// The Kahan compensation of `Value`, or of `Mean` once `avg` has switched.
60    Compensation,
61    /// The number of samples folded in.
62    Count,
63    /// Whether `avg` has switched from a sum to a mean, which it does when the sum overflows.
64    IncrementalMean,
65}
66
67impl AggregateOp {
68    /// The components the state of this aggregation carries; the others are unused and need not
69    /// be stored. `group` has none: a state that exists has a value of 1.
70    pub fn state_fields(self) -> &'static [StateField] {
71        use StateField::*;
72        match self {
73            Self::Sum => &[Value, Compensation],
74            Self::Count => &[Count],
75            Self::Avg => &[Value, Mean, Compensation, Count, IncrementalMean],
76            Self::Min | Self::Max => &[Value],
77            Self::Group => &[],
78            Self::Stddev | Self::Stdvar => &[Value, Mean, Count],
79        }
80    }
81}
82
83/// The state of one field of one group at one grid point.
84///
85/// The fold and the frame carry the same five components, so they share one type: the frame's own
86/// [`AggregateStateValues`] is the definition, and this is the name the aggregate side reads it by.
87pub use datatypes::series::aggregate_state::AggregateStateValues as AccumulatorState;
88
89/// The state of one execution partition, with its groups in the order they first appeared.
90///
91/// A group is the frame's own [`StateSeries`]: field-major states addressed on that group's sparse
92/// absolute grid positions. Exporting therefore hands the same representation over instead of
93/// transposing a second one into it.
94#[derive(Clone, Debug)]
95pub struct PartialAggregate {
96    pub op: AggregateOp,
97    pub groups: Vec<StateSeries>,
98}
99
100/// One Arrow-backed aggregate state row, independent of executor plumbing.
101#[derive(Clone, Debug)]
102pub struct StateRow {
103    pub metric: SeriesLabels,
104    pub time: TimeAxis,
105    pub fields: StateFieldsBatch,
106    pub kind: AggregateStateKind,
107}
108
109impl FloatAggregator {
110    /// The state folded so far, for a merge with the state of other partitions.
111    pub fn finish_partial(self) -> Result<PartialAggregate> {
112        self.finish_partial_inner()
113    }
114
115    /// [`Self::finish_partial`] that admits what it builds first: the fold state and the groups it
116    /// is exported as, at the exact capacity [`Self::finish_partial_inner`] gives them. A refusal
117    /// consumes the aggregator, so the caller drops the execution.
118    pub(crate) fn finish_partial_budgeted(
119        self,
120        mut budget: impl FnMut(usize) -> Result<()>,
121    ) -> Result<PartialAggregate> {
122        let width = self.schema.fields.len();
123        let mut partial_bytes = self.groups.len().saturating_mul(size_of::<StateSeries>());
124        for group in &self.groups {
125            // A group that folded histograms keeps them in its own map instead of the blocks, so
126            // the points it exports and what each of their payloads builds come from there: the
127            // export builds two one-row Arrow batches per point, which the chunk they are handed
128            // to is charged for only once that chunk exists.
129            let (points, payloads) = if group.histograms.is_empty() {
130                (seen_points(group, width, self.op), 0)
131            } else {
132                let payloads = group
133                    .histograms
134                    .values()
135                    .fold(0usize, |bytes, accumulator| {
136                        bytes.saturating_add(exported_payload_bytes(accumulator))
137                    });
138                (group.histograms.len(), payloads)
139            };
140            partial_bytes = partial_bytes
141                .saturating_add(size_of::<TimeAxis>())
142                .saturating_add(
143                    points.saturating_mul(size_of::<GridSpan>().saturating_add(size_of::<usize>())),
144                )
145                .saturating_add(width.saturating_mul(size_of::<Vec<Option<StatePayload>>>()))
146                .saturating_add(
147                    points
148                        .saturating_mul(width)
149                        .saturating_mul(size_of::<Option<StatePayload>>()),
150                )
151                .saturating_add(payloads);
152        }
153        budget(self.state_bytes().saturating_add(partial_bytes))?;
154        self.finish_partial_inner()
155    }
156
157    /// Turns the fold into the frame's own groups: field-major states on sparse absolute positions.
158    ///
159    /// The blocks are walked once, in ascending position order, so a position's states are appended
160    /// to every field at the same time and adjacent positions coalesce into one span as they come.
161    /// What comes out is the representation the frame writes; no per-point vector is built.
162    fn finish_partial_inner(self) -> Result<PartialAggregate> {
163        let width = self.schema.fields.len();
164        let grid = self.schema.eval_grid.as_ref().ok_or_else(|| {
165            DataFusionError::Execution("aggregate state is indexed on an evaluated grid".into())
166        })?;
167        let grid_len = grid.spec().len as usize;
168        let op = self.op;
169        let words = op.state_words();
170        let point_words = width.saturating_mul(words);
171        let mut groups: Vec<StateSeries> = Vec::with_capacity(self.groups.len());
172        for group in self.groups {
173            let points = if group.histograms.is_empty() {
174                seen_points(&group, width, op)
175            } else {
176                // A field's state is one family, so a group that kept histogram payloads exports
177                // those: a float state beside them would be one column carrying two kinds.
178                if group.blocks.values().any(|states| {
179                    states
180                        .chunks_exact(op.state_words())
181                        .any(|state| state_seen(state, op))
182                }) {
183                    return Err(DataFusionError::Execution(
184                        "an aggregate field cannot carry both float and histogram state".into(),
185                    ));
186                }
187                group.histograms.len()
188            };
189            let mut spans: Vec<GridSpan> = Vec::with_capacity(points.min(1));
190            let mut states: Vec<Vec<Option<StatePayload>>> =
191                (0..width).map(|_| Vec::with_capacity(points)).collect();
192            if !group.histograms.is_empty() {
193                // The histogram fold is keyed by absolute position, and its keys are ordered, so one
194                // pass visits each carried position once with its fields' payloads.
195                let mut position = None;
196                for (&(point, field), accumulator) in &group.histograms {
197                    if position != Some(point) {
198                        if point >= grid_len {
199                            return Err(DataFusionError::Execution(format!(
200                                "aggregate state point {point} exceeds a grid of {grid_len}"
201                            )));
202                        }
203                        extend_spans(&mut spans, point);
204                        for field_states in &mut states {
205                            field_states.push(None);
206                        }
207                        position = Some(point);
208                    }
209                    // The row just opened is the one this position's payloads belong to. It is the
210                    // row the field's states just grew, not the one the span *count* names: adjacent
211                    // points share one span while each of them still opens its own row, so a run
212                    // index would write every point of the run into the run's first row, leave the
213                    // rest empty, and the frame would drop them.
214                    let row = states[field].len() - 1;
215                    states[field][row] = Some(accumulator.payload(self.op)?);
216                }
217                let time = TimeAxis::from_grid_spans(Arc::clone(grid), spans)
218                    .map_err(|error| DataFusionError::Execution(error.to_string()))?;
219                groups.push(StateSeries {
220                    metric: group.metric,
221                    time,
222                    states,
223                });
224                continue;
225            }
226            for (&block, block_states) in &group.blocks {
227                for (offset, point) in block_states.chunks_exact(point_words).enumerate() {
228                    if !point.chunks_exact(words).any(|state| state_seen(state, op)) {
229                        continue;
230                    }
231                    let position = block * BLOCK_POINTS + offset;
232                    if position >= grid_len {
233                        return Err(DataFusionError::Execution(format!(
234                            "aggregate state point {position} exceeds a grid of {grid_len}"
235                        )));
236                    }
237                    extend_spans(&mut spans, position);
238                    for (field, state) in point.chunks_exact(words).enumerate() {
239                        states[field].push(state_partial(state, op).map(StatePayload::Float));
240                    }
241                }
242            }
243            let time = TimeAxis::from_grid_spans(Arc::clone(grid), spans)
244                .map_err(|error| DataFusionError::Execution(error.to_string()))?;
245            groups.push(StateSeries {
246                metric: group.metric,
247                time,
248                states,
249            });
250        }
251        Ok(PartialAggregate {
252            op: self.op,
253            groups,
254        })
255    }
256}
257
258/// Appends `position` to `spans`, extending the last run when it continues.
259fn extend_spans(spans: &mut Vec<GridSpan>, position: usize) {
260    match spans.last_mut() {
261        Some(span) if span.start() + span.len() == position => {
262            *span = GridSpan::new(span.start(), span.len() + 1);
263        }
264        _ => spans.push(GridSpan::new(position, 1)),
265    }
266}
267
268/// Bytes one one-row batch of the frame's histogram layout costs before its bucket data.
269///
270/// Every column of the layout owns an Arrow array node with its own buffers, and that cost does not
271/// shrink for a histogram with one bucket: one row measures 2.6 KB whatever the bucket count, which
272/// is what a payload reports once the batch exists to be measured. It is rounded up here, so a batch
273/// whose bucket lists land at the top of their buffer capacity is covered too.
274pub(super) const HISTOGRAM_LAYOUT_ROW_BYTES: usize = 3 * 1024;
275
276/// Bytes one exported point's payload builds: the boxed state and the two one-row batches
277/// [`HistogramAccumulator::payload`] makes from the accumulator's live histogram and its
278/// compensation.
279///
280/// It is counted from the histograms the payload is built from rather than from the batches, which
281/// is the point: this is what the export admits before those batches exist. The bucket data a batch
282/// writes is charged at the width of the padded Rust pair, which bounds the `f64` each bucket costs,
283/// and the layout is charged per batch.
284pub(super) fn exported_payload_bytes(accumulator: &HistogramAccumulator) -> usize {
285    // The batch the payload builds from the live value is the mean once an average switched, and
286    // the other one is the compensation paired with it: the widest of the three bounds both.
287    let widest = [
288        Some(&accumulator.value),
289        accumulator.mean.as_ref(),
290        accumulator.compensation.as_ref(),
291    ]
292    .into_iter()
293    .flatten()
294    .map(|histogram| histogram.heap_bytes())
295    .max()
296    .unwrap_or(0);
297    size_of::<HistogramState>().saturating_add(
298        HISTOGRAM_LAYOUT_ROW_BYTES
299            .saturating_add(widest)
300            .saturating_mul(2),
301    )
302}
303
304/// The points of `group` that carry a state: the ones a partial of it holds.
305fn seen_points(group: &Group, width: usize, op: AggregateOp) -> usize {
306    let words = op.state_words();
307    let point_words = width.saturating_mul(words);
308    group.blocks.values().fold(0usize, |count, states| {
309        count.saturating_add(
310            states
311                .chunks_exact(point_words)
312                .filter(|point| point.chunks_exact(words).any(|state| state_seen(state, op)))
313                .count(),
314        )
315    })
316}
317
318/// Bytes a group's label key holds: a pair per capacity slot, and the `__name__` entry, whose
319/// label and value `label_key` copies, each with its own `Arc` header. The other label strings are
320/// the metric's, already counted with it.
321fn key_bytes(key: &LabelKey) -> usize {
322    let name = key
323        .iter()
324        .find(|(label, _)| &**label == "__name__")
325        .map_or(0, |(label, value)| {
326            label
327                .len()
328                .saturating_add(value.len())
329                .saturating_add(4 * size_of::<usize>())
330        });
331    key.capacity()
332        .saturating_mul(size_of::<(Arc<str>, Arc<str>)>())
333        .saturating_add(name)
334}
335
336/// Coarse bytes the key of `metric` holds while it is built: a pair per slot, the `__name__` label
337/// and a copy of the metric name, each with its `Arc` header.
338fn key_workspace_bytes(metric: &SeriesLabels) -> usize {
339    metric
340        .tags()
341        .len()
342        .saturating_add(1)
343        .saturating_mul(size_of::<(Arc<str>, Arc<str>)>())
344        .saturating_add("__name__".len())
345        .saturating_add(metric.name().map_or(0, str::len))
346        .saturating_add(4 * size_of::<usize>())
347        .saturating_add(size_of::<LabelKey>())
348}
349
350/// Merges the partial states of one aggregation into its result. Groups are identified by their
351/// full label set, already grouped by the partitions, and keep the order they first arrive in.
352pub struct FloatMerger {
353    schema: Arc<SeriesSchema>,
354    op: AggregateOp,
355    group_index: HashMap<LabelKey, usize>,
356    groups: Vec<Group>,
357    retained: usize,
358}
359
360impl FloatMerger {
361    pub fn try_new(schema: &Arc<SeriesSchema>, op: AggregateOp) -> Result<Self> {
362        if schema.eval_grid.is_none() {
363            return Err(DataFusionError::Execution(
364                "Aggregate requires an evaluated grid".into(),
365            ));
366        }
367        Ok(Self {
368            schema: schema.clone(),
369            op,
370            group_index: HashMap::new(),
371            groups: Vec::new(),
372            retained: 0,
373        })
374    }
375
376    /// Bytes this merge keeps: groups, labels, blocks, B-tree nodes, index table and its keys. Added
377    /// to by the allocations that change it, never recounted.
378    pub(crate) fn state_bytes(&self) -> usize {
379        self.retained
380    }
381
382    /// What the merged inputs recorded about their points.
383    pub(crate) fn evidence_summary(&self) -> HistogramEvidence {
384        evidence_summary(&self.groups)
385    }
386
387    /// Merges one Arrow-backed state row directly, without materializing a partial aggregate.
388    pub(crate) fn merge_row(
389        &mut self,
390        row: &StateRow,
391        mut budget: impl FnMut(usize) -> Result<()>,
392    ) -> Result<()> {
393        if row.fields.kind().is_histogram() {
394            return self.merge_histogram_row(row, budget);
395        }
396        let op = crate::native::state::op_of_state(row.kind);
397        if op != self.op {
398            return Err(DataFusionError::Execution(format!(
399                "cannot merge {:?} state into {:?}",
400                op, self.op
401            )));
402        }
403        let width = self.schema.fields.len();
404        if row.fields.len() != width {
405            return Err(DataFusionError::Execution(
406                "aggregate state does not match the grid or fields of the merge".into(),
407            ));
408        }
409        let grid_len = self
410            .schema
411            .eval_grid
412            .as_ref()
413            .expect("checked at construction")
414            .spec()
415            .len as usize;
416        let mut opened = None;
417        let key_workspace = key_workspace_bytes(&row.metric);
418        let mut live = None;
419        for (point, position) in row.time.positions() {
420            if point >= grid_len {
421                return Err(DataFusionError::Execution(
422                    "aggregate state does not match the grid or fields of the merge".into(),
423                ));
424            }
425            let mut present = false;
426            for field in 0..width {
427                present |= row
428                    .fields
429                    .is_present(field, position)
430                    .map_err(crate::grid_series::external)?;
431            }
432            if !present {
433                return Err(DataFusionError::Execution(
434                    "aggregate state names a position with no contribution".into(),
435                ));
436            }
437            let index = match opened {
438                Some(index) => index,
439                None => {
440                    budget(self.retained.saturating_add(key_workspace))?;
441                    let key = label_key(&row.metric);
442                    let live_bytes = key_bytes(&key);
443                    let index = match self.group_index.get(&key).copied() {
444                        Some(index) => index,
445                        None => {
446                            self.open_group(row.metric.clone(), key, live_bytes, &mut budget)?
447                        }
448                    };
449                    live = Some(live_bytes);
450                    opened = Some(index);
451                    index
452                }
453            };
454            let mut field = 0;
455            let mut state_error = None;
456            let states = std::iter::from_fn(|| {
457                if field == width || state_error.is_some() {
458                    return None;
459                }
460                let current = field;
461                field += 1;
462                match state_at(&row.fields, current, position) {
463                    Ok(state) => Some(state),
464                    Err(error) => {
465                        state_error = Some(error);
466                        None
467                    }
468                }
469            });
470            self.write_point(index, point, states, live.unwrap_or(0), &mut budget)?;
471            if let Some(error) = state_error {
472                return Err(error);
473            }
474        }
475        Ok(())
476    }
477
478    /// Merges one Arrow-backed histogram state row: every present field's payload is merged into
479    /// that position's own state.
480    ///
481    /// A histogram state is sparse in both directions - a position is carried when any field has a
482    /// contribution there, and a field may be absent at a carried position - so the row is walked
483    /// position by position and each present component is merged where it belongs.
484    fn merge_histogram_row(
485        &mut self,
486        row: &StateRow,
487        mut budget: impl FnMut(usize) -> Result<()>,
488    ) -> Result<()> {
489        if crate::native::state::op_of_state(row.kind) != self.op {
490            return Err(DataFusionError::Execution(format!(
491                "cannot merge {:?} state into {:?}",
492                row.kind, self.op
493            )));
494        }
495        let width = self.schema.fields.len();
496        if row.fields.len() != width {
497            return Err(DataFusionError::Execution(
498                "aggregate state does not match the grid or fields of the merge".into(),
499            ));
500        }
501        let grid_len = self
502            .schema
503            .eval_grid
504            .as_ref()
505            .expect("checked at construction")
506            .spec()
507            .len as usize;
508        let mut opened = None;
509        for (point, position) in row.time.positions() {
510            if point >= grid_len {
511                return Err(DataFusionError::Execution(
512                    "aggregate state does not match the grid or fields of the merge".into(),
513                ));
514            }
515            let index = match opened {
516                Some(index) => index,
517                None => {
518                    let index = self.open_row_group(&row.metric, &mut budget)?;
519                    opened = Some(index);
520                    index
521                }
522            };
523            let mut present = false;
524            for field in 0..width {
525                let Some(payload) = histogram_state_at(&row.fields, field, position)? else {
526                    continue;
527                };
528                present = true;
529                self.merge_payload(index, point, field, &payload, &mut budget)?;
530            }
531            if !present {
532                return Err(DataFusionError::Execution(
533                    "aggregate state names a position with no contribution".into(),
534                ));
535            }
536        }
537        Ok(())
538    }
539
540    /// The group this row's labels name, opening it (and its key) on first sight.
541    fn open_row_group(
542        &mut self,
543        metric: &SeriesLabels,
544        budget: &mut impl FnMut(usize) -> Result<()>,
545    ) -> Result<usize> {
546        budget(self.retained.saturating_add(key_workspace_bytes(metric)))?;
547        let key = label_key(metric);
548        let live = key_bytes(&key);
549        match self.group_index.get(&key).copied() {
550            Some(index) => Ok(index),
551            None => self.open_group(metric.clone(), key, live, budget),
552        }
553    }
554
555    /// Merges one field's payload into the state of `(point, field)`, admitting what it allocates.
556    fn merge_payload(
557        &mut self,
558        index: usize,
559        point: usize,
560        field: usize,
561        payload: &StatePayload,
562        budget: &mut impl FnMut(usize) -> Result<()>,
563    ) -> Result<()> {
564        let StatePayload::Histogram(payload) = payload else {
565            return Err(DataFusionError::Execution(
566                "a histogram state carries a numeric payload".into(),
567            ));
568        };
569        let key = (point, field);
570        let histograms = &mut self.groups[index].histograms;
571        let vacant = !histograms.contains_key(&key);
572        let backing = if vacant {
573            histogram_backing_bytes(histograms.len() + 1)
574                .saturating_sub(histogram_backing_bytes(histograms.len()))
575        } else {
576            0
577        };
578        if vacant {
579            // Admit the state this position is about to hold before allocating it: both histograms
580            // the payload carries and the map node that holds them.
581            let incoming = payload.value.as_arrow().get_array_memory_size()
582                + payload.compensation.as_arrow().get_array_memory_size();
583            budget(
584                self.retained
585                    .saturating_add(size_of::<HistogramAccumulator>())
586                    .saturating_add(incoming)
587                    .saturating_add(backing),
588            )?;
589            let accumulator = HistogramAccumulator::from_payload(self.op, payload)?;
590            let bytes = accumulator_bytes(&accumulator).saturating_add(backing);
591            histograms.insert(key, accumulator);
592            self.retained = self.retained.saturating_add(bytes);
593            return Ok(());
594        }
595        let accumulator = histograms.get_mut(&key).expect("checked as occupied above");
596        let before = accumulator_bytes(accumulator);
597        let incoming = payload.value.as_arrow().get_array_memory_size()
598            + payload.compensation.as_arrow().get_array_memory_size();
599        budget(
600            self.retained
601                .saturating_add(before)
602                .saturating_add(incoming),
603        )?;
604        accumulator.merge_state(self.op, payload)?;
605        self.retained = self
606            .retained
607            .saturating_sub(before)
608            .saturating_add(accumulator_bytes(accumulator));
609        Ok(())
610    }
611
612    /// Adds a group and its key, admitting the group vector and index growth first.
613    fn open_group(
614        &mut self,
615        metric: SeriesLabels,
616        key: LabelKey,
617        live: usize,
618        budget: &mut impl FnMut(usize) -> Result<()>,
619    ) -> Result<usize> {
620        let capacity = self.groups.capacity();
621        let next_capacity = if self.groups.len() == capacity {
622            capacity.saturating_mul(2).max(4)
623        } else {
624            capacity
625        };
626        let map_capacity = self.group_index.capacity();
627        let next_map_capacity = if self.group_index.len().saturating_add(1) > map_capacity {
628            next_hash_capacity(map_capacity)
629        } else {
630            map_capacity
631        };
632        let key_live = key_bytes(&key);
633        let metric_live = metric_bytes(&metric);
634        // A realloc that cannot grow in place keeps both buffers alive while it copies, so a
635        // growing step admits the new buffer beside the old one, which `retained` already holds.
636        budget(
637            self.retained
638                .saturating_add(live)
639                .saturating_add(key_live)
640                .saturating_add(metric_live)
641                .saturating_add(if next_capacity > capacity {
642                    next_capacity.saturating_mul(size_of::<Group>())
643                } else {
644                    0
645                })
646                .saturating_add(if next_map_capacity > map_capacity {
647                    hash_map_backing_bytes(next_map_capacity)
648                } else {
649                    0
650                }),
651        )?;
652        self.groups.try_reserve(1).map_err(|error| {
653            DataFusionError::Execution(format!("cannot reserve aggregate groups: {error}"))
654        })?;
655        self.groups.push(Group {
656            metric,
657            blocks: BTreeMap::new(),
658            histograms: BTreeMap::new(),
659        });
660        let index = self.groups.len() - 1;
661        self.group_index.insert(key, index);
662        self.retained = self
663            .retained
664            .saturating_add(
665                self.groups
666                    .capacity()
667                    .saturating_sub(capacity)
668                    .saturating_mul(size_of::<Group>()),
669            )
670            .saturating_add(
671                hash_map_backing_bytes(self.group_index.capacity())
672                    .saturating_sub(hash_map_backing_bytes(map_capacity)),
673            )
674            .saturating_add(metric_live)
675            .saturating_add(key_live);
676        Ok(index)
677    }
678
679    /// Writes one point's states, admitting a missing block before allocating it.
680    fn write_point(
681        &mut self,
682        index: usize,
683        point: usize,
684        states: impl Iterator<Item = Option<AccumulatorState>>,
685        live: usize,
686        budget: &mut impl FnMut(usize) -> Result<()>,
687    ) -> Result<()> {
688        let width = self.schema.fields.len();
689        let op = self.op;
690        let words = op.state_words();
691        let point_words = width.saturating_mul(words);
692        let states_bytes = block_bytes(width, op);
693        let blocks = &mut self.groups[index].blocks;
694        let block_index = point / BLOCK_POINTS;
695        let entries = blocks.len();
696        let block = match blocks.entry(block_index) {
697            BTreeEntry::Occupied(entry) => entry.into_mut(),
698            BTreeEntry::Vacant(entry) => {
699                budget(
700                    self.retained
701                        .saturating_add(live)
702                        .saturating_add(states_bytes)
703                        .saturating_add(btree_backing_bytes(entries.saturating_add(1))),
704                )?;
705                self.retained = self
706                    .retained
707                    .saturating_add(states_bytes)
708                    .saturating_add(btree_backing_bytes(entries.saturating_add(1)))
709                    .saturating_sub(btree_backing_bytes(entries));
710                entry.insert(vec![0.0; BLOCK_POINTS * point_words].into_boxed_slice())
711            }
712        };
713        let offset = (point % BLOCK_POINTS) * point_words;
714        for (slot, state) in block[offset..offset + point_words]
715            .chunks_exact_mut(words)
716            .zip(states)
717        {
718            if let Some(state) = state {
719                FloatState::new(slot, op).merge_partial(&state);
720            }
721        }
722        Ok(())
723    }
724
725    /// The result of every group, in the order the groups first arrived.
726    pub fn finish(self) -> Result<Vec<Series>> {
727        finish_groups(self.schema, self.op, self.groups)
728    }
729
730    /// [`Self::finish`] that admits the result it builds, on top of what the merge still holds. The
731    /// merge is consumed either way, so a caller that budgets drops it on a refusal.
732    pub(crate) fn finish_budgeted(
733        self,
734        budget: impl FnMut(usize) -> Result<()>,
735    ) -> Result<Vec<Series>> {
736        finish_groups_budgeted(self.schema, self.op, self.groups, self.retained, budget)
737    }
738}
739
740/// One present field's histogram state at one position, read from the row's component arrays.
741///
742/// The two payload components are decoded into the kernel's own histograms, and the components a
743/// kind may omit - an average's count and mode flag - default to what the merge would fold from.
744fn histogram_state_at(
745    fields: &StateFieldsBatch,
746    field: usize,
747    position: usize,
748) -> Result<Option<StatePayload>> {
749    if !fields
750        .is_present(field, position)
751        .map_err(crate::grid_series::external)?
752    {
753        return Ok(None);
754    }
755    let mut state = datatypes::series::aggregate_state::HistogramState {
756        value: Arc::new(payload_histogram(
757            fields,
758            field,
759            StateComponent::HistogramValue,
760            position,
761        )?),
762        compensation: Arc::new(payload_histogram(
763            fields,
764            field,
765            StateComponent::HistogramCompensation,
766            position,
767        )?),
768        count: 0.0,
769        incremental_mean: false,
770        poisoned: false,
771        incompatible_layout: false,
772        custom_bounds_reconciled: false,
773        counter_reset_seen: false,
774        not_counter_reset_seen: false,
775    };
776    for &component in fields.components() {
777        match component {
778            StateComponent::HistogramValue | StateComponent::HistogramCompensation => {}
779            StateComponent::Count => {
780                state.count = payload_float(fields, field, component, position)?
781            }
782            StateComponent::IncrementalMean
783            | StateComponent::Poisoned
784            | StateComponent::IncompatibleLayout
785            | StateComponent::CustomBoundsReconciled
786            | StateComponent::CounterResetSeen
787            | StateComponent::NotCounterResetSeen => {
788                let flag = payload_bool(fields, field, component, position)?;
789                match component {
790                    StateComponent::IncrementalMean => state.incremental_mean = flag,
791                    StateComponent::Poisoned => state.poisoned = flag,
792                    StateComponent::IncompatibleLayout => state.incompatible_layout = flag,
793                    StateComponent::CustomBoundsReconciled => state.custom_bounds_reconciled = flag,
794                    StateComponent::CounterResetSeen => state.counter_reset_seen = flag,
795                    _ => state.not_counter_reset_seen = flag,
796                }
797            }
798            StateComponent::Value | StateComponent::Mean | StateComponent::Compensation => {
799                return Err(DataFusionError::Execution(
800                    "a histogram state declares a numeric component".into(),
801                ));
802            }
803        }
804    }
805    Ok(Some(StatePayload::Histogram(Box::new(state))))
806}
807
808fn payload_histogram(
809    fields: &StateFieldsBatch,
810    field: usize,
811    component: StateComponent,
812    position: usize,
813) -> Result<datatypes::series::histogram::HistogramBatch> {
814    fields
815        .field_histogram(field, component, position)
816        .map_err(crate::grid_series::external)?
817        .ok_or_else(missing_payload_component)
818}
819
820fn payload_float(
821    fields: &StateFieldsBatch,
822    field: usize,
823    component: StateComponent,
824    position: usize,
825) -> Result<f64> {
826    fields
827        .field_values(field, component)
828        .map_err(crate::grid_series::external)?
829        .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
830        .ok_or_else(missing_payload_component)
831}
832
833fn payload_bool(
834    fields: &StateFieldsBatch,
835    field: usize,
836    component: StateComponent,
837    position: usize,
838) -> Result<bool> {
839    fields
840        .field_bool_values(field, component)
841        .map_err(crate::grid_series::external)?
842        .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
843        .ok_or_else(missing_payload_component)
844}
845
846fn missing_payload_component() -> DataFusionError {
847    DataFusionError::Execution("present aggregate state has a missing component".into())
848}
849
850/// One present field's state at one position, read from the row's component arrays.
851///
852/// The components come from the row's own declaration; the native aggregate caller checks
853/// compatibility before this runs, so a component list that disagrees is caught before this runs.
854fn state_at(
855    fields: &StateFieldsBatch,
856    field: usize,
857    position: usize,
858) -> Result<Option<AccumulatorState>> {
859    if !fields
860        .is_present(field, position)
861        .map_err(crate::grid_series::external)?
862    {
863        return Ok(None);
864    }
865    let mut state = AccumulatorState::default();
866    for &component in fields.components() {
867        match component {
868            StateComponent::IncrementalMean => {
869                state.incremental_mean = fields
870                    .field_bool_values(field, component)
871                    .map_err(crate::grid_series::external)?
872                    .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
873                    .ok_or_else(|| {
874                        DataFusionError::Execution(
875                            "present aggregate state has a missing component".into(),
876                        )
877                    })?;
878            }
879            // A histogram state's payload is not numeric components, so this merge cannot read one:
880            // [`FloatMerger::merge_row`] sends a histogram row to `merge_histogram_row`, so a
881            // histogram component reaching here is a row whose kind says numeric and whose payload
882            // says otherwise. Refusing is what keeps a histogram from being folded as the numeric
883            // state it is not.
884            StateComponent::HistogramValue
885            | StateComponent::HistogramCompensation
886            | StateComponent::Poisoned
887            | StateComponent::IncompatibleLayout
888            | StateComponent::CustomBoundsReconciled
889            | StateComponent::CounterResetSeen
890            | StateComponent::NotCounterResetSeen => {
891                return Err(DataFusionError::Execution(
892                    "histogram aggregate state reached the numeric merge".into(),
893                ));
894            }
895            _ => {
896                let value = fields
897                    .field_values(field, component)
898                    .map_err(crate::grid_series::external)?
899                    .and_then(|array| (!array.is_null(position)).then(|| array.value(position)))
900                    .ok_or_else(|| {
901                        DataFusionError::Execution(
902                            "present aggregate state has a missing component".into(),
903                        )
904                    })?;
905                match component {
906                    StateComponent::Value => state.value = value,
907                    StateComponent::Mean => state.mean = value,
908                    StateComponent::Compensation => state.compensation = value,
909                    StateComponent::Count => state.count = value,
910                    _ => unreachable!("every other component is handled above"),
911                }
912            }
913        }
914    }
915    Ok(Some(state))
916}
917
918/// The exported form of the state in `words`, or `None` if it has seen no sample.
919///
920/// Only the components the op keeps are filled in; the rest stay at their defaults, exactly as the
921/// frame that carries them leaves them out.
922fn state_partial(words: &[f64], op: AggregateOp) -> Option<AccumulatorState> {
923    if !state_seen(words, op) {
924        return None;
925    }
926    Some(match op {
927        // `value`, its compensation, then the presence flag.
928        AggregateOp::Sum => AccumulatorState {
929            value: words[0],
930            compensation: words[1],
931            ..Default::default()
932        },
933        // `value`, `compensation`, `mean`, the incremental flag, then the count.
934        AggregateOp::Avg => AccumulatorState {
935            value: words[0],
936            compensation: words[1],
937            mean: words[2],
938            incremental_mean: words[3] != 0.0,
939            count: words[4],
940        },
941        AggregateOp::Count => AccumulatorState {
942            count: words[0],
943            ..Default::default()
944        },
945        AggregateOp::Min | AggregateOp::Max => AccumulatorState {
946            value: words[0],
947            ..Default::default()
948        },
949        AggregateOp::Group => AccumulatorState::default(),
950        // `value`, `mean`, then the count.
951        AggregateOp::Stddev | AggregateOp::Stdvar => AccumulatorState {
952            value: words[0],
953            mean: words[1],
954            count: words[2],
955            ..Default::default()
956        },
957    })
958}
959
960impl<'a> FloatState<'a> {
961    /// Writes `other` into this state, for a state that has seen nothing yet.
962    fn store_partial(self, other: &AccumulatorState) {
963        let (op, words) = (self.op, self.words);
964        match op {
965            AggregateOp::Count => words[0] = other.count,
966            // Presence alone, whatever the other side keeps: `group` answers 1 either way.
967            AggregateOp::Group => words[0] = 1.0,
968            AggregateOp::Min | AggregateOp::Max => {
969                words[0] = other.value;
970                words[1] = 1.0;
971            }
972            AggregateOp::Sum => {
973                words[0] = other.value;
974                words[1] = other.compensation;
975                words[2] = 1.0;
976            }
977            AggregateOp::Stddev | AggregateOp::Stdvar => {
978                words[0] = other.value;
979                words[1] = other.mean;
980                words[2] = other.count;
981            }
982            AggregateOp::Avg => {
983                words[0] = other.value;
984                words[1] = other.compensation;
985                words[2] = other.mean;
986                words[3] = if other.incremental_mean { 1.0 } else { 0.0 };
987                words[4] = other.count;
988            }
989        }
990    }
991
992    /// Folds the state of another partition into this one.
993    fn merge_partial(self, other: &AccumulatorState) {
994        if !state_seen(self.words, self.op) {
995            self.store_partial(other);
996            return;
997        }
998        let (op, words) = (self.op, self.words);
999        match op {
1000            AggregateOp::Sum => {
1001                (words[0], words[1]) =
1002                    add_compensated((words[0], words[1]), (other.value, other.compensation));
1003            }
1004            AggregateOp::Count => words[0] += other.count,
1005            AggregateOp::Group => {}
1006            AggregateOp::Max => {
1007                if words[0] < other.value || words[0].is_nan() {
1008                    words[0] = other.value;
1009                }
1010            }
1011            AggregateOp::Min => {
1012                if words[0] > other.value || words[0].is_nan() {
1013                    words[0] = other.value;
1014                }
1015            }
1016            AggregateOp::Avg => merge_avg(words, other),
1017            AggregateOp::Stddev | AggregateOp::Stdvar => {
1018                // Chan et al.'s pairwise update. `delta * (delta * weight)` keeps the product
1019                // finite where it is: `delta²` alone overflows for `[0]` and `[1.5e154]`, whose
1020                // merged sum of squares is finite.
1021                let count = words[2] + other.count;
1022                let delta = other.mean - words[1];
1023                let weight = words[2] * other.count / count;
1024                words[1] += delta * (other.count / count);
1025                words[0] = words[0] + other.value + delta * (delta * weight);
1026                words[2] = count;
1027            }
1028        }
1029    }
1030}
1031
1032/// Adds the sums while they stay finite, and otherwise continues with the count-weighted mean, as
1033/// the serial update switches to an incremental mean once its sum overflows.
1034///
1035/// The state words are `value`, `compensation`, `mean`, the incremental flag and the count.
1036fn merge_avg(words: &mut [f64], other: &AccumulatorState) {
1037    let count = words[4] + other.count;
1038    if words[3] == 0.0 && !other.incremental_mean {
1039        let (value, compensation) =
1040            add_compensated((words[0], words[1]), (other.value, other.compensation));
1041        if !value.is_infinite() {
1042            words[0] = value;
1043            words[1] = compensation;
1044            words[4] = count;
1045            return;
1046        }
1047    }
1048    let (mean, compensation) = mean_form(words[0], words[1], words[2], words[3] != 0.0, words[4]);
1049    let (other_mean, other_compensation) = mean_form(
1050        other.value,
1051        other.compensation,
1052        other.mean,
1053        other.incremental_mean,
1054        other.count,
1055    );
1056    let (weight, other_weight) = (words[4] / count, other.count / count);
1057    (words[2], words[1]) = kahan_inc(
1058        other_mean * other_weight,
1059        mean * weight,
1060        compensation * weight + other_compensation * other_weight,
1061    );
1062    words[3] = 1.0;
1063    words[4] = count;
1064}
1065
1066/// The mean and its compensation, converting a sum as the serial update does on switching.
1067fn mean_form(
1068    value: f64,
1069    compensation: f64,
1070    mean: f64,
1071    incremental: bool,
1072    count: f64,
1073) -> (f64, f64) {
1074    if incremental {
1075        (mean, compensation)
1076    } else {
1077        (value / count, compensation / count)
1078    }
1079}
1080
1081/// The compensated sum of two partial sums. Both the other sum and its compensation are added as
1082/// Kahan addends: adding the compensation plainly would drop what the compensation already
1083/// holds once later partials cancel the sums, as merging `[1e100, 1]`, `[-1e100, 1e84]` and
1084/// `[-1e84]` would lose the `1`.
1085fn add_compensated(this: (f64, f64), other: (f64, f64)) -> (f64, f64) {
1086    let (value, compensation) = kahan_inc(other.0, this.0, this.1);
1087    kahan_inc(other.1, value, compensation)
1088}
1089
1090/// Merges `count_values` results of several partitions. Each partial already carries its full
1091/// output label set, value label included, so series with one label set add their counts point
1092/// by point and field by field.
1093pub fn merge_count_values(
1094    schema: &Arc<SeriesSchema>,
1095    partials: impl IntoIterator<Item = Series>,
1096) -> Result<Vec<Series>> {
1097    let width = schema.fields.len();
1098    let mut group_index: HashMap<LabelKey, usize> = HashMap::new();
1099    let mut groups: Counts = Vec::new();
1100    for series in partials {
1101        validate_float_series(schema, &series)?;
1102        let index = match group_index.entry(label_key(&series.metric)) {
1103            Entry::Occupied(entry) => *entry.get(),
1104            Entry::Vacant(entry) => {
1105                groups.push((series.metric.clone(), BTreeMap::new()));
1106                *entry.insert(groups.len() - 1)
1107            }
1108        };
1109        for (field_index, field) in series.fields.iter().enumerate() {
1110            for ((point, _), sample) in series.time.positions().zip(field.iter()) {
1111                if let SampleRef::Float(count) = sample {
1112                    groups[index]
1113                        .1
1114                        .entry(point)
1115                        .or_insert_with(|| vec![0.0; width])[field_index] += count;
1116                }
1117            }
1118        }
1119    }
1120    count_series(schema, groups)
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use super::*;
1126    use datafusion::arrow::array::{Float64Array, ListArray, StructArray};
1127    use datafusion::arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
1128    use datafusion::arrow::datatypes::{DataType, Field};
1129    use datatypes::series::aggregate_state::{AggregateStateSchema, StateComponent};
1130    use datatypes::series::samples::FieldSpec;
1131    use datatypes::series::time::{EvalGrid, GridRange, GridSpec, TimeAxis};
1132
1133    fn fields_batch() -> StateFieldsBatch {
1134        let item_fields: datafusion::arrow::datatypes::Fields = vec![
1135            Field::new("value", DataType::Float64, true),
1136            Field::new("compensation", DataType::Float64, true),
1137        ]
1138        .into();
1139        let make_field =
1140            |values: Vec<Option<f64>>, compensation: Vec<Option<f64>>, validity: Vec<bool>| {
1141                let item = StructArray::new(
1142                    item_fields.clone(),
1143                    vec![
1144                        Arc::new(Float64Array::from(values)),
1145                        Arc::new(Float64Array::from(compensation)),
1146                    ],
1147                    Some(NullBuffer::from(validity)),
1148                );
1149                Arc::new(ListArray::new(
1150                    Arc::new(Field::new(
1151                        "item",
1152                        DataType::Struct(item_fields.clone()),
1153                        true,
1154                    )),
1155                    OffsetBuffer::new(ScalarBuffer::from(vec![0i32, 3])),
1156                    Arc::new(item),
1157                    None,
1158                ))
1159            };
1160        let field_a = make_field(
1161            vec![Some(2.), Some(3.), Some(4.)],
1162            vec![Some(0.), Some(0.), Some(0.)],
1163            vec![true, true, true],
1164        );
1165        let field_b = make_field(
1166            vec![Some(5.), None, Some(7.)],
1167            vec![Some(0.), None, Some(0.)],
1168            vec![true, false, true],
1169        );
1170        let outer_fields = vec![
1171            Field::new("a", field_a.data_type().clone(), false),
1172            Field::new("b", field_b.data_type().clone(), false),
1173        ]
1174        .into();
1175        let outer = StructArray::new(outer_fields, vec![field_a, field_b], None);
1176        let schema = AggregateStateSchema::try_new(
1177            AggregateStateKind::Sum,
1178            vec![StateComponent::Value, StateComponent::Compensation],
1179        )
1180        .unwrap();
1181        StateFieldsBatch::try_from_arrow(outer, &schema).unwrap()
1182    }
1183
1184    fn schema() -> Arc<SeriesSchema> {
1185        Arc::new(SeriesSchema {
1186            fields: vec![
1187                FieldSpec { name: "a".into() },
1188                FieldSpec { name: "b".into() },
1189            ]
1190            .into(),
1191            eval_grid: Some(Arc::new(
1192                EvalGrid::try_new(GridSpec::try_new(0, 1, 3).unwrap()).unwrap(),
1193            )),
1194        })
1195    }
1196
1197    /// The row's two fields carry different present states, so a hole in one of them is a hole in
1198    /// that field only: it stays absent rather than becoming a zero the sum would count.
1199    #[test]
1200    fn merge_row_keeps_a_field_hole_absent() {
1201        let schema = schema();
1202        let row = StateRow {
1203            metric: SeriesLabels::try_new(Some("m".into()), Vec::new()).unwrap(),
1204            time: TimeAxis::Grid(
1205                GridRange::try_new(schema.eval_grid.clone().unwrap(), 0, 3).unwrap(),
1206            ),
1207            fields: fields_batch(),
1208            kind: AggregateStateKind::Sum,
1209        };
1210        let mut merger = FloatMerger::try_new(&schema, AggregateOp::Sum).unwrap();
1211        merger.merge_row(&row, |_| Ok(())).unwrap();
1212        let merged = merger.finish().unwrap();
1213        assert_eq!(merged.len(), 1, "one group, one series");
1214        let values = |field: usize| {
1215            merged[0]
1216                .fields
1217                .get(field)
1218                .expect("the fixture has two fields")
1219                .iter()
1220                .map(|sample| match sample {
1221                    SampleRef::Float(value) => Some(value),
1222                    _ => None,
1223                })
1224                .collect::<Vec<_>>()
1225        };
1226        assert_eq!(values(0), [Some(2.0), Some(3.0), Some(4.0)]);
1227        assert_eq!(values(1), [Some(5.0), None, Some(7.0)]);
1228    }
1229}