Skip to main content

promql/
aggregate.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//! Local float aggregation over evaluated series, following Prometheus' `aggregation`. State
16//! is keyed by absolute grid index, never by local row number; sparse state and trimmed output
17//! do not expand the full grid.
18
19pub(crate) mod state;
20#[cfg(test)]
21mod tests;
22
23pub use state::{AccumulatorState, FloatMerger, PartialAggregate, StateField, merge_count_values};
24
25use std::cmp::Reverse;
26use std::collections::hash_map::Entry;
27use std::collections::{BTreeMap, BinaryHeap, HashMap};
28use std::mem::size_of;
29use std::sync::Arc;
30
31use datafusion::error::{DataFusionError, Result};
32use datatypes::arrow::array::{Float64Array, UInt32Array};
33use datatypes::series::SeriesLabels;
34use datatypes::series::aggregate_state::{HistogramState, StatePayload};
35use datatypes::series::histogram::{
36    CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView,
37};
38use datatypes::series::samples::{SampleRef, Samples, Series, SeriesFields, SeriesSchema};
39use datatypes::series::time::{GridSpan, TimeAxis};
40
41use crate::go_format::format_float_f;
42use crate::grid_series::{GridSeriesBuilder, external};
43use crate::histogram_eval::float_histogram::FloatHistogram;
44use crate::histogram_eval::histogram_string;
45use crate::map::{drop_empty_labels, validate_grid_series, validate_scalar};
46use crate::range_eval::quantile;
47
48/// Float aggregations without a parameter.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum AggregateOp {
51    Sum,
52    Count,
53    Avg,
54    Min,
55    Max,
56    Group,
57    Stddev,
58    Stdvar,
59}
60
61/// Grouping by series labels. No modifier is `By(&[])`, as in Prometheus.
62#[derive(Clone, Copy, Debug)]
63pub enum Grouping<'a> {
64    By(&'a [&'a str]),
65    Without(&'a [&'a str]),
66}
67
68/// Aggregates each field at each absolute evaluation instant.
69///
70/// Each field is aggregated independently; an output row exists where any field has a value,
71/// and a field without input values at that row is null. Ordinary NaNs count as values.
72///
73/// Inputs are folded in slice order. Prometheus folds them in storage postings order, and the
74/// compensated `sum`/`avg` depend on that order in the last bits, so callers must keep it.
75/// Groups are returned in the order their first input appears, as in Prometheus: a nested
76/// aggregation folds them in that order.
77///
78/// Evaluated inputs on the shared schema/grid are admitted. An operation that reads a value takes
79/// float samples only; `count` and `group` ask whether a sample is present, so they also accept a
80/// histogram. `by` on a value field needs per-point labels and an output schema adapter, and is
81/// rejected. There is no fallback.
82pub fn aggregate_float(
83    schema: &Arc<SeriesSchema>,
84    input: &[Series],
85    op: AggregateOp,
86    grouping: Grouping<'_>,
87) -> Result<Vec<Series>> {
88    let mut aggregator = FloatAggregator::try_new(schema, op, grouping)?;
89    for series in input {
90        aggregator.update(series)?;
91    }
92    aggregator.finish()
93}
94
95/// [`aggregate_float`] fed one series at a time, for a caller that does not hold all its input
96/// at once. Series are folded in the order they arrive, with the same semantics.
97///
98/// The grouping labels are copied in, so the aggregator borrows nothing and can live in the
99/// state of a stream.
100pub struct FloatAggregator {
101    schema: Arc<SeriesSchema>,
102    op: AggregateOp,
103    /// `by` (true) or `without`, and its labels.
104    by: bool,
105    labels: Vec<Arc<str>>,
106    group_index: HashMap<LabelKey, usize>,
107    groups: Vec<Group>,
108    retained: usize,
109}
110
111/// What an aggregate does with a native histogram sample.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub(crate) enum HistogramSamples {
114    /// Counts it as one present sample: `count` counts every present sample, and `group` answers
115    /// `1` for a non-empty group, whatever the sample's type is.
116    Presence,
117    /// Ignores it and reports that it did: `min`, `max`, `stddev`, `stdvar` and `quantile` read a
118    /// float value, and Prometheus skips the histogram samples instead of refusing the statement.
119    Ignored,
120    /// Folds the payload and answers a histogram: `sum` adds native histograms bucket by bucket
121    /// and `avg` adds them and divides, as Prometheus does, so one group's result is a native
122    /// histogram.
123    Folded,
124}
125
126impl AggregateOp {
127    /// The words of `f64` one field's state of this aggregation keeps for one grid point.
128    ///
129    /// The last word is the presence word: the op's own count where its state carries one, so a
130    /// zero count reads as unseen, and a `0`/`1` flag where it does not. The words before it are
131    /// the components the op folds, in [`Self::state_fields`] order. A state therefore costs what
132    /// its own operation needs instead of what the widest operation needs: a block holds
133    /// `BLOCK_POINTS * fields * state_words * size_of::<f64>()` bytes however wide the op is.
134    pub(crate) const fn state_words(self) -> usize {
135        match self {
136            Self::Count | Self::Group => 1,
137            Self::Min | Self::Max => 2,
138            Self::Sum | Self::Stddev | Self::Stdvar => 3,
139            Self::Avg => 5,
140        }
141    }
142}
143
144/// What `op` does with a native histogram sample.
145pub(crate) fn histogram_samples(op: AggregateOp) -> HistogramSamples {
146    match op {
147        AggregateOp::Count | AggregateOp::Group => HistogramSamples::Presence,
148        AggregateOp::Min | AggregateOp::Max | AggregateOp::Stddev | AggregateOp::Stdvar => {
149            HistogramSamples::Ignored
150        }
151        AggregateOp::Sum | AggregateOp::Avg => HistogramSamples::Folded,
152    }
153}
154
155/// Checks a series for the aggregate `op` folds, and returns its evaluated axis.
156///
157/// Every operation this route folds takes a histogram series: it counts the sample, skips it, or
158/// folds the payload. What a series must satisfy is therefore its axis, not its sample type -- the
159/// fold itself is where a payload an operation cannot use is refused or dropped.
160pub(crate) fn validate_aggregate_series<'a>(
161    schema: &SeriesSchema,
162    series: &'a Series,
163    op: AggregateOp,
164) -> Result<&'a TimeAxis> {
165    match histogram_samples(op) {
166        HistogramSamples::Presence | HistogramSamples::Ignored | HistogramSamples::Folded => {
167            validate_grid_series(schema, series)
168        }
169    }
170}
171
172impl FloatAggregator {
173    pub fn try_new(
174        schema: &Arc<SeriesSchema>,
175        op: AggregateOp,
176        grouping: Grouping<'_>,
177    ) -> Result<Self> {
178        Self::try_new_budgeted(schema, op, grouping, |_| Ok(()))
179    }
180
181    pub(crate) fn try_new_budgeted(
182        schema: &Arc<SeriesSchema>,
183        op: AggregateOp,
184        grouping: Grouping<'_>,
185        mut budget: impl FnMut(usize) -> Result<()>,
186    ) -> Result<Self> {
187        validate_input(schema, &[], grouping)?;
188        let (by, labels) = match grouping {
189            Grouping::By(labels) => (true, labels),
190            Grouping::Without(labels) => (false, labels),
191        };
192        let label_storage =
193            grouping_bytes(grouping).saturating_add(labels_capacity_bytes(grouping));
194        budget(label_storage)?;
195        let mut owned_labels: Vec<Arc<str>> = Vec::new();
196        owned_labels
197            .try_reserve_exact(labels.len())
198            .map_err(|error| {
199                DataFusionError::Execution(format!(
200                    "cannot reserve aggregate grouping labels: {error}"
201                ))
202            })?;
203        owned_labels.extend(labels.iter().map(|label| Arc::from(*label)));
204        let retained = owned_labels
205            .capacity()
206            .saturating_mul(size_of::<Arc<str>>())
207            .saturating_add(owned_labels.iter().fold(0usize, |bytes, label| {
208                bytes.saturating_add(label.len() + 2 * size_of::<usize>())
209            }));
210        Ok(Self {
211            schema: schema.clone(),
212            op,
213            by,
214            labels: owned_labels,
215            group_index: HashMap::new(),
216            groups: Vec::new(),
217            retained,
218        })
219    }
220
221    /// Folds `series` into its group. A series that fails validation leaves the state unchanged.
222    ///
223    /// A budget refusal is not a validation failure: the fold may have opened a group or filled
224    /// blocks before the allocation it could not admit, so a failed [`Self::update_budgeted`]
225    /// leaves the state half folded and its retained figure stale. The runtime stops the execution
226    /// and drops the aggregator on that error, which is why no rollback is kept; a caller holding
227    /// one must drop it rather than fold into it again.
228    pub fn update(&mut self, series: &Series) -> Result<()> {
229        self.update_budgeted(series, |_| Ok(()))
230    }
231
232    pub(crate) fn update_budgeted(
233        &mut self,
234        series: &Series,
235        mut budget: impl FnMut(usize) -> Result<()>,
236    ) -> Result<()> {
237        validate_aggregate_series(&self.schema, series, self.op)?;
238        let existing_bytes = self.state_bytes();
239        let group_capacity = self.groups.capacity();
240        let map_capacity = self.group_index.capacity();
241        // One admission for everything the fold can allocate before it writes a sample: the copy of
242        // this series' metric the grouping makes, the group's own copy of those labels and its
243        // key, the labels vector, and the group vector and index that may grow. What only a new
244        // group pays for is admitted whether or not this series opens one, so a chunk costs one
245        // pool call here instead of one per step, and a refusal still arrives before any of it is
246        // allocated.
247        //
248        // The grouping copy, the second workspace the copy is grouped into, and the group's
249        // retained labels and key are each a copy or a subset of this series' labels, so three
250        // copies of the one workspace bound all of them.
251        let label_workspace = grouping_workspace_bytes(&series.metric);
252        budget(
253            existing_bytes
254                .saturating_add(label_workspace.saturating_mul(3))
255                .saturating_add(pending_bytes(self.schema.fields.len()))
256                .saturating_add(
257                    self.labels
258                        .len()
259                        .saturating_mul(std::mem::size_of::<&str>()),
260                )
261                // A realloc that cannot grow in place keeps both buffers alive while it copies,
262                // so a growing step admits the new buffer beside the old one, which the retained
263                // state already holds. The map is admitted the same way.
264                .saturating_add(if self.groups.len() == group_capacity {
265                    group_capacity
266                        .saturating_mul(2)
267                        .max(4)
268                        .saturating_mul(size_of::<Group>())
269                } else {
270                    0
271                })
272                .saturating_add(if self.group_index.len() == map_capacity {
273                    hash_map_backing_bytes(next_hash_capacity(map_capacity))
274                } else {
275                    0
276                }),
277        )?;
278        let labels: Vec<&str> = self.labels.iter().map(|label| &**label).collect();
279        let grouping = if self.by {
280            Grouping::By(&labels)
281        } else {
282            Grouping::Without(&labels)
283        };
284        let metric = grouping.apply(&series.metric)?;
285        let key = label_key(&metric);
286        let key_retained = key
287            .capacity()
288            .saturating_mul(size_of::<(Arc<str>, Arc<str>)>());
289        let new_group = !self.group_index.contains_key(&key);
290        let old_map_backing = hash_map_backing_bytes(map_capacity);
291        let group_capacity_growth = if new_group && self.groups.len() == group_capacity {
292            group_capacity.saturating_mul(2).max(4)
293        } else {
294            group_capacity
295        };
296        if new_group && group_capacity_growth > group_capacity {
297            self.groups.reserve(1);
298        }
299        if new_group && self.group_index.len() == self.group_index.capacity() {
300            self.group_index.reserve(1);
301        }
302        let index = match self.group_index.entry(key) {
303            Entry::Occupied(entry) => *entry.get(),
304            Entry::Vacant(entry) => {
305                self.groups.push(Group {
306                    metric: metric.clone(),
307                    blocks: BTreeMap::new(),
308                    histograms: BTreeMap::new(),
309                });
310                let index = self.groups.len() - 1;
311                entry.insert(index);
312                index
313            }
314        };
315        if new_group {
316            self.retained = self
317                .retained
318                .saturating_add(metric_bytes(&metric))
319                .saturating_add(key_retained)
320                .saturating_add(
321                    self.groups
322                        .capacity()
323                        .saturating_sub(group_capacity)
324                        .saturating_mul(size_of::<Group>()),
325                )
326                .saturating_add(
327                    hash_map_backing_bytes(self.group_index.capacity())
328                        .saturating_sub(old_map_backing),
329                );
330        }
331        drop(labels);
332        drop(metric);
333        self.retained = self.groups[index].accumulate(
334            series,
335            self.op,
336            &mut budget,
337            self.retained,
338            self.schema.fields.len(),
339        )?;
340        Ok(())
341    }
342
343    /// Number of groups currently retained by this fold.
344    pub(crate) fn groups(&self) -> usize {
345        self.groups.len()
346    }
347
348    /// The evidence the fold recorded, for the node that finishes the answer to report.
349    pub(crate) fn evidence_summary(&self) -> HistogramEvidence {
350        evidence_summary(&self.groups)
351    }
352
353    /// Bytes reserved for this fold, using bounded allowances for its maps and group payloads.
354    pub(crate) fn state_bytes(&self) -> usize {
355        self.retained
356    }
357
358    /// The evidence the histogram fold recorded for one position, for a fold test.
359    ///
360    /// It is the state the fold keeps beside its payload, so a test reads the bits where the state
361    /// export would read them rather than from a value the answer happens to imply.
362    #[cfg(test)]
363    pub(crate) fn histogram_evidence(
364        &self,
365        group: usize,
366        position: usize,
367        field: usize,
368    ) -> Option<HistogramEvidence> {
369        self.groups
370            .get(group)
371            .and_then(|group| group.histograms.get(&(position, field)))
372            .map(|accumulator| accumulator.evidence)
373    }
374
375    #[cfg(test)]
376    pub(crate) fn recounted_state_bytes(&self) -> usize {
377        let groups = self.groups.iter().fold(0usize, |total, group| {
378            total
379                .saturating_add(metric_bytes(&group.metric))
380                .saturating_add(
381                    group
382                        .blocks
383                        .len()
384                        .saturating_mul(BLOCK_POINTS)
385                        .saturating_mul(self.schema.fields.len())
386                        .saturating_mul(self.op.state_words())
387                        .saturating_mul(std::mem::size_of::<f64>()),
388                )
389                .saturating_add(btree_backing_bytes(group.blocks.len()))
390                .saturating_add(histogram_backing_bytes(group.histograms.len()))
391                .saturating_add(
392                    group
393                        .histograms
394                        .values()
395                        .fold(0usize, |bytes, accumulator| {
396                            bytes.saturating_add(accumulator_bytes(accumulator))
397                        }),
398                )
399        });
400        groups
401            .saturating_add(
402                self.labels
403                    .capacity()
404                    .saturating_mul(std::mem::size_of::<Arc<str>>()),
405            )
406            .saturating_add(hash_map_backing_bytes(self.group_index.capacity()))
407            .saturating_add(self.group_index.keys().fold(0usize, |bytes, key| {
408                bytes.saturating_add(
409                    key.capacity()
410                        .saturating_mul(size_of::<(Arc<str>, Arc<str>)>()),
411                )
412            }))
413            .saturating_add(
414                self.labels
415                    .iter()
416                    .map(|label| label.len() + 2 * std::mem::size_of::<usize>())
417                    .sum::<usize>(),
418            )
419            .saturating_add(
420                self.groups
421                    .capacity()
422                    .saturating_mul(std::mem::size_of::<Group>()),
423            )
424    }
425
426    /// The result of every group, in the order the groups first appeared.
427    pub fn finish(self) -> Result<Vec<Series>> {
428        self.finish_budgeted(|_| Ok(()))
429    }
430
431    pub(crate) fn finish_budgeted(
432        self,
433        budget: impl FnMut(usize) -> Result<()>,
434    ) -> Result<Vec<Series>> {
435        let state = self.state_bytes();
436        finish_groups_budgeted(self.schema, self.op, self.groups, state, budget)
437    }
438}
439
440/// Turns the state of `groups` into result series, in group order, admitting as it builds.
441fn finish_groups_budgeted(
442    schema: Arc<SeriesSchema>,
443    op: AggregateOp,
444    groups: Vec<Group>,
445    state: usize,
446    mut budget: impl FnMut(usize) -> Result<()>,
447) -> Result<Vec<Series>> {
448    let width = schema.fields.len();
449    let group_count = groups.len();
450    if group_count == 0 {
451        return Ok(Vec::new());
452    }
453    let groups = groups.into_iter();
454    let schema_arc = Arc::clone(&schema);
455    let mut builder = GridSeriesBuilder::try_new(schema)?;
456    let output_capacity_bytes = group_count.saturating_mul(std::mem::size_of::<Series>());
457    let row_capacity_bytes = width.saturating_mul(std::mem::size_of::<Option<f64>>());
458    let base = state
459        .saturating_add(output_capacity_bytes)
460        .saturating_add(row_capacity_bytes);
461    budget(base)?;
462    let mut output = Vec::new();
463    output.try_reserve_exact(group_count).map_err(|error| {
464        DataFusionError::Execution(format!("cannot reserve aggregate outputs: {error}"))
465    })?;
466    let mut row = Vec::new();
467    row.try_reserve_exact(width).map_err(|error| {
468        DataFusionError::Execution(format!("cannot reserve aggregate row: {error}"))
469    })?;
470    let mut completed_output_bytes = 0usize;
471    let words = op.state_words();
472    let point_words = width.saturating_mul(words);
473    for group in groups {
474        // A group that folded histogram samples answers histogram columns; one that folded floats
475        // keeps the float path below, so a group without a single histogram payload is built
476        // exactly as before.
477        if !group.histograms.is_empty() {
478            let finish_bytes = histogram_finish_bytes(&group, width);
479            budget(
480                state
481                    .saturating_add(output_capacity_bytes)
482                    .saturating_add(row_capacity_bytes)
483                    .saturating_add(completed_output_bytes)
484                    .saturating_add(finish_bytes),
485            )?;
486            if let Some(finished) = finish_histogram_group(op, &schema_arc, group, width)? {
487                completed_output_bytes = completed_output_bytes
488                    .saturating_add(crate::grid_series::series_bytes(&finished));
489                output.push(finished);
490            }
491            budget(
492                state
493                    .saturating_add(output_capacity_bytes)
494                    .saturating_add(row_capacity_bytes)
495                    .saturating_add(completed_output_bytes),
496            )?;
497            continue;
498        }
499        // One builder serves every group, so each result series starts explicitly.
500        builder.begin_series();
501        let (rows, runs) = group_rows_runs(&group, width, op);
502        let finish_bytes = finish_working_bytes(rows, runs, width);
503        budget(
504            state
505                .saturating_add(output_capacity_bytes)
506                .saturating_add(row_capacity_bytes)
507                .saturating_add(completed_output_bytes)
508                .saturating_add(finish_bytes),
509        )?;
510        builder.reserve_rows(rows)?;
511        for (&block, states) in &group.blocks {
512            // The last block can extend past the grid; only points with a sample are pushed.
513            for (offset, point) in states.chunks_exact(point_words).enumerate() {
514                if !point.chunks_exact(words).any(|state| state_seen(state, op)) {
515                    continue;
516                }
517                row.clear();
518                row.extend(
519                    point
520                        .chunks_exact(words)
521                        .map(|state| state_finish(state, op)),
522                );
523                builder.push(block * BLOCK_POINTS + offset, &row)?;
524            }
525        }
526        let finished = builder.finish(group.metric)?;
527        completed_output_bytes = completed_output_bytes.saturating_add(
528            finished
529                .iter()
530                .map(crate::grid_series::series_bytes)
531                .sum::<usize>(),
532        );
533        output.extend(finished);
534        budget(
535            state
536                .saturating_add(output_capacity_bytes)
537                .saturating_add(row_capacity_bytes)
538                .saturating_add(completed_output_bytes),
539        )?;
540    }
541    Ok(output)
542}
543
544/// Builds one group's histogram result, or `None` when it has nothing left to answer.
545///
546/// A position's answer is its live sum plus the compensation paired with it -- what the kernel's own
547/// `sum` does at the end of its fold -- with the start timestamp cleared and the empty buckets
548/// dropped. A poisoned position was removed, so it contributes no value; a position that is
549/// poisoned in one field and answered in another still carries the row.
550fn finish_histogram_group(
551    op: AggregateOp,
552    schema: &Arc<SeriesSchema>,
553    group: Group,
554    width: usize,
555) -> Result<Option<Series>> {
556    // A field's column is one type. The fold already refuses a histogram where it had folded a
557    // float at that position; a float folded after a histogram is caught here, where the column
558    // type is chosen for the whole group.
559    if group.blocks.values().any(|states| {
560        states
561            .chunks_exact(op.state_words())
562            .any(|state| state_seen(state, op))
563    }) {
564        return Err(DataFusionError::Execution(
565            "a native aggregate cannot mix float and histogram samples in one field".into(),
566        ));
567    }
568    let grid = schema.eval_grid.clone().ok_or_else(|| {
569        DataFusionError::Execution("histogram aggregation requires an evaluation grid".into())
570    })?;
571    let mut positions: Vec<usize> = group
572        .histograms
573        .keys()
574        .map(|&(position, _)| position)
575        .collect();
576    positions.dedup();
577    let mut builders: Vec<HistogramBatchBuilder> =
578        (0..width).map(|_| HistogramBatchBuilder::new()).collect();
579    let mut indices: Vec<Vec<Option<u32>>> = vec![Vec::new(); width];
580    let mut spans: Vec<GridSpan> = Vec::new();
581    let mut row: Vec<Option<FloatHistogram>> = vec![None; width];
582    for position in positions {
583        // A poisoned position has no answer, so the row it would have made is dropped whole: every
584        // column is written once per *answered* position, or the columns and the axis would drift.
585        let mut answered = false;
586        for (field, value) in row.iter_mut().enumerate() {
587            *value = match group.histograms.get(&(position, field)) {
588                Some(accumulator) => {
589                    let value = finished_histogram(op, accumulator)?;
590                    answered |= value.is_some();
591                    value
592                }
593                None => None,
594            };
595        }
596        if !answered {
597            continue;
598        }
599        // A gap between two answered positions ends a run, and a row belongs to the run it opens.
600        match spans.last_mut() {
601            Some(span) if span.start() + span.len() == position => {
602                *span = GridSpan::new(span.start(), span.len() + 1);
603            }
604            _ => spans.push(GridSpan::new(position, 1)),
605        }
606        for ((builder, indices), value) in builders.iter_mut().zip(&mut indices).zip(&row) {
607            indices.push(match value {
608                Some(value) => Some(value.push_to(builder)?),
609                None => None,
610            });
611        }
612    }
613    if spans.is_empty() {
614        return Ok(None);
615    }
616    let mut samples = Vec::with_capacity(width);
617    for (builder, indices) in builders.into_iter().zip(indices) {
618        let batch = builder.finish().map_err(external)?;
619        samples.push(
620            Samples::try_from_histogram(UInt32Array::from(indices), batch).map_err(external)?,
621        );
622    }
623    // The result is addressed by the runs that carry a histogram, not by the span between the first
624    // and the last one: the nulls padding them stay inside a run, never between two.
625    let time = TimeAxis::from_grid_spans(grid, spans).map_err(external)?;
626    Series::try_new(
627        schema,
628        group.metric,
629        time,
630        SeriesFields::try_from_vec(samples).map_err(external)?,
631    )
632    .map(Some)
633    .map_err(external)
634}
635
636/// One position's answer, compacted, or `None` when the point was poisoned.
637///
638/// A sum answers its live value with the compensation folded in. An average in mean mode answers its
639/// mean with the compensation folded in; one that never switched divides the sum and the compensation
640/// by the sample count and then folds the compensation in, which is what `sum_or_avg` does at the end
641/// of both paths.
642pub(crate) fn finished_histogram(
643    op: AggregateOp,
644    accumulator: &HistogramAccumulator,
645) -> Result<Option<FloatHistogram>> {
646    if accumulator.evidence.poisoned {
647        return Ok(None);
648    }
649    let mut value = match (op, accumulator.mean.as_ref()) {
650        (AggregateOp::Avg, Some(mean)) => {
651            let mut mean = mean.clone();
652            if let Some(compensation) = accumulator.compensation.as_ref() {
653                mean.add(compensation)?;
654            }
655            mean
656        }
657        (AggregateOp::Avg, None) => {
658            let mut value = accumulator.value.clone();
659            value.div(accumulator.count);
660            if let Some(mut compensation) = accumulator.compensation.clone() {
661                compensation.div(accumulator.count);
662                value.add(&compensation)?;
663            }
664            value
665        }
666        _ => {
667            let mut value = accumulator.value.clone();
668            if let Some(compensation) = accumulator.compensation.as_ref() {
669                value.add(compensation)?;
670            }
671            value
672        }
673    };
674    // The answer's empty buckets are dropped the way the kernel's own aggregate drops them. It also
675    // carries no start timestamp of its own, which every derivation above clears along with
676    // `compact`.
677    value.compact();
678    Ok(Some(value))
679}
680
681/// Bytes [`finish_histogram_group`] works in while it builds one group's result.
682fn histogram_finish_bytes(group: &Group, width: usize) -> usize {
683    let payload = group
684        .histograms
685        .values()
686        .fold(0usize, |bytes, accumulator| {
687            bytes.saturating_add(accumulator_bytes(accumulator))
688        });
689    let rows = group.histograms.len();
690    let fields = width.saturating_mul(
691        size_of::<HistogramBatchBuilder>()
692            .saturating_add(size_of::<Vec<Option<u32>>>())
693            .saturating_add(size_of::<Samples>()),
694    );
695    // Twice the fold's payload: the answer is one derived histogram per position, and an average
696    // divides a copy of its live value before it adds the compensation in.
697    payload
698        .saturating_mul(2)
699        .saturating_add(rows.saturating_mul(size_of::<Option<u32>>()))
700        .saturating_add(rows.saturating_mul(size_of::<GridSpan>()))
701        .saturating_add(fields)
702        .saturating_add(size_of::<Series>().saturating_add(size_of::<TimeAxis>()))
703}
704
705/// The result of every group, without a budget: the entry the partial-state merger takes, which
706/// does not hold a query pool to admit against.
707fn finish_groups(
708    schema: Arc<SeriesSchema>,
709    op: AggregateOp,
710    groups: Vec<Group>,
711) -> Result<Vec<Series>> {
712    finish_groups_budgeted(schema, op, groups, 0, |_| Ok(()))
713}
714
715fn group_rows_runs(group: &Group, width: usize, op: AggregateOp) -> (usize, usize) {
716    if width == 0 {
717        return (0, 0);
718    }
719    let words = op.state_words();
720    let point_words = width * words;
721    let mut rows = 0usize;
722    let mut runs = 0usize;
723    let mut previous: Option<usize> = None;
724    for (&block, states) in &group.blocks {
725        for (offset, point) in states.chunks_exact(point_words).enumerate() {
726            if point.chunks_exact(words).any(|state| state_seen(state, op)) {
727                let index = block.saturating_mul(BLOCK_POINTS).saturating_add(offset);
728                rows = rows.saturating_add(1);
729                if previous.is_none_or(|previous| previous.checked_add(1) != Some(index)) {
730                    runs = runs.saturating_add(1);
731                }
732                previous = Some(index);
733            }
734        }
735    }
736    (rows, runs)
737}
738
739fn finish_working_bytes(rows: usize, runs: usize, width: usize) -> usize {
740    let values = rows
741        .saturating_mul(width)
742        .saturating_mul(std::mem::size_of::<f64>());
743    let validity_bytes = rows
744        .saturating_add(7)
745        .checked_div(8)
746        .unwrap_or(0)
747        .div_ceil(64)
748        .saturating_mul(64);
749    let fields = crate::grid_series::field_builder_bytes(width).saturating_add(
750        width.saturating_mul(
751            std::mem::size_of::<Float64Array>()
752                .saturating_add(std::mem::size_of::<Samples>())
753                .saturating_add(std::mem::size_of::<usize>()),
754        ),
755    );
756    let indices = rows.saturating_mul(std::mem::size_of::<usize>());
757    let spans = runs.saturating_mul(std::mem::size_of::<GridSpan>());
758    let axis_conversion = runs
759        .saturating_mul(
760            2 * std::mem::size_of::<GridSpan>() + std::mem::size_of::<Arc<[GridSpan]>>(),
761        )
762        .saturating_add(rows.saturating_mul(std::mem::size_of::<usize>()));
763    values
764        .saturating_add(width.saturating_mul(validity_bytes))
765        .saturating_add(fields)
766        .saturating_add(indices)
767        .saturating_add(spans)
768        .saturating_add(axis_conversion)
769        .saturating_add(std::mem::size_of::<Series>() + std::mem::size_of::<TimeAxis>())
770}
771
772/// `quantile(q, v)`, with `q` read at each grid point from an unlabelled single-field scalar on
773/// the same grid, as Prometheus evaluates the parameter at every step. A point where `q` has no
774/// value has no result; `q` outside `[0, 1]` or NaN gives what Prometheus' `quantile` gives.
775pub fn aggregate_quantile(
776    schema: &Arc<SeriesSchema>,
777    input: &[Series],
778    q: &Series,
779    grouping: Grouping<'_>,
780) -> Result<Vec<Series>> {
781    validate_input(schema, input, grouping)?;
782    let q_axis = validate_scalar(schema, q)?;
783    let q: Vec<(usize, f64)> = q_axis
784        .positions()
785        .zip(q.fields.as_slice()[0].iter())
786        .filter_map(|((point, _), sample)| match sample {
787            SampleRef::Float(value) => Some((point, value)),
788            _ => None,
789        })
790        .collect();
791    // Members keep input order, the order Prometheus appends to its per-step heap.
792    let mut group_index = HashMap::new();
793    let mut groups: Vec<(SeriesLabels, Vec<&Series>)> = Vec::new();
794    for series in input {
795        let metric = grouping.apply(&series.metric)?;
796        let index = *group_index.entry(label_key(&metric)).or_insert_with(|| {
797            groups.push((metric, Vec::new()));
798            groups.len() - 1
799        });
800        groups[index].1.push(series);
801    }
802    let width = schema.fields.len();
803    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
804    let mut output = Vec::with_capacity(groups.len());
805    let (mut values, mut sorted, mut row) = (Vec::new(), Vec::new(), Vec::with_capacity(width));
806    for (metric, members) in groups {
807        builder.begin_series();
808        // Each member's next position waits in a min-heap, so a point costs the members present
809        // there and not the whole group: a group of short-lived series stays linear in its
810        // samples. Ties pop in member order, the input order Prometheus appends values in.
811        let mut positions: Vec<_> = members
812            .iter()
813            .map(|series| series.time.positions())
814            .collect();
815        // Indexed by field, then member.
816        let mut cursors: Vec<Vec<_>> = (0..width)
817            .map(|field| {
818                members
819                    .iter()
820                    .map(|series| series.fields.as_slice()[field].cursor())
821                    .collect()
822            })
823            .collect();
824        let mut next: BinaryHeap<Reverse<(usize, usize, usize)>> = positions
825            .iter_mut()
826            .enumerate()
827            .filter_map(|(member, positions)| {
828                positions
829                    .next()
830                    .map(|(point, row)| Reverse((point, member, row)))
831            })
832            .collect();
833        let mut present = Vec::new();
834        while let Some(&Reverse((point, _, _))) = next.peek() {
835            present.clear();
836            while let Some(&Reverse((at, member, row))) = next.peek()
837                && at == point
838            {
839                next.pop();
840                present.push((member, row));
841                if let Some((point, row)) = positions[member].next() {
842                    next.push(Reverse((point, member, row)));
843                }
844            }
845            let q = q
846                .binary_search_by_key(&point, |&(point, _)| point)
847                .ok()
848                .map(|index| q[index].1);
849            row.clear();
850            for field in &mut cursors {
851                values.clear();
852                for &(member, member_row) in &present {
853                    if let Some(SampleRef::Float(value)) = field[member].at(member_row) {
854                        values.push(value);
855                    }
856                }
857                row.push(match q {
858                    Some(q) if !values.is_empty() => Some(quantile(q, &values, &mut sorted)),
859                    _ => None,
860                });
861            }
862            builder.push(point, &row)?;
863        }
864        output.extend(builder.finish(metric)?);
865    }
866    Ok(output)
867}
868
869/// Validates the schema-only requirements shared by the kernel and native runtime construction.
870pub(crate) fn validate_count_values(
871    schema: &SeriesSchema,
872    label: &str,
873    grouping: Grouping<'_>,
874) -> Result<()> {
875    // `by` may list the value label, which this operator writes itself, even when an input field
876    // has that name; grouping by any other field name stays unsupported.
877    let other_labels: Vec<&str>;
878    let checked = match grouping {
879        Grouping::By(labels) => {
880            other_labels = labels
881                .iter()
882                .copied()
883                .filter(|name| *name != label)
884                .collect();
885            Grouping::By(&other_labels)
886        }
887        without => without,
888    };
889    validate_grouping(schema, checked)?;
890    if label.is_empty() {
891        return Err(DataFusionError::Execution(format!(
892            "invalid label name {label:?}"
893        )));
894    }
895    Ok(())
896}
897
898/// `count_values(label, v)`: at each grid point, the number of samples in each group of series
899/// that share a value, with the value written to `label` in Prometheus' `FormatFloat(v, 'f', -1)`
900/// form, or for a native histogram as its `FloatHistogram.String`. With `by`, `label` is part of
901/// the grouping; with `without`, it is dropped if listed.
902pub fn count_values(
903    schema: &Arc<SeriesSchema>,
904    input: &[Series],
905    label: &str,
906    grouping: Grouping<'_>,
907) -> Result<Vec<Series>> {
908    validate_count_values(schema, label, grouping)?;
909    // Unlike the other aggregations, this one reads histogram samples too.
910    for series in input {
911        validate_grid_series(schema, series)?;
912    }
913    let by_labels: Vec<&str>;
914    let grouping = match grouping {
915        Grouping::By(labels) => {
916            by_labels = labels.iter().copied().chain([label]).collect();
917            Grouping::By(&by_labels)
918        }
919        without => without,
920    };
921    let width = schema.fields.len();
922    let mut group_index = HashMap::new();
923    // Counts are kept per point that has one, not in blocks: a gauge with distinct values makes
924    // about one group per sample.
925    let mut groups: Counts = Vec::new();
926    for series in input {
927        // Equal bits format to the same label value, so each distinct value of a series
928        // resolves its group once. A histogram is keyed by the text it is written as.
929        let mut group_of_value: HashMap<Value, usize> = HashMap::new();
930        for (field_index, field) in series.fields.iter().enumerate() {
931            for ((point, _), sample) in series.time.positions().zip(field.iter()) {
932                let key = match sample {
933                    SampleRef::Missing => continue,
934                    SampleRef::Float(value) => Value::Float(value.to_bits()),
935                    SampleRef::Histogram(h) => Value::Histogram(histogram_string(&h)?),
936                };
937                let group = match group_of_value.entry(key) {
938                    Entry::Occupied(entry) => *entry.get(),
939                    Entry::Vacant(entry) => {
940                        // Prometheus writes a float in Go's `'f'` form and a histogram as
941                        // `FloatHistogram.String` does.
942                        let text = match entry.key() {
943                            Value::Float(bits) => format_float_f(f64::from_bits(*bits)),
944                            Value::Histogram(text) => text.clone(),
945                        };
946                        let mut metric = series.metric.clone();
947                        metric.set(label, Arc::from(text)).map_err(external)?;
948                        let metric = grouping.apply(&metric)?;
949                        let index = *group_index.entry(label_key(&metric)).or_insert_with(|| {
950                            groups.push((metric, BTreeMap::new()));
951                            groups.len() - 1
952                        });
953                        *entry.insert(index)
954                    }
955                };
956                groups[group]
957                    .1
958                    .entry(point)
959                    .or_insert_with(|| vec![0.0; width])[field_index] += 1.0;
960            }
961        }
962    }
963    count_series(schema, groups)
964}
965
966/// Counts per point and field: one series per label set, a count of 0 being no sample.
967type Counts = Vec<(SeriesLabels, BTreeMap<usize, Vec<f64>>)>;
968
969fn count_series(schema: &Arc<SeriesSchema>, groups: Counts) -> Result<Vec<Series>> {
970    let mut builder = GridSeriesBuilder::try_new(schema.clone())?;
971    let mut output = Vec::with_capacity(groups.len());
972    let mut row = Vec::with_capacity(schema.fields.len());
973    for (metric, counts) in groups {
974        builder.begin_series();
975        for (point, counts) in counts {
976            row.clear();
977            row.extend(counts.iter().map(|&count| (count > 0.0).then_some(count)));
978            builder.push(point, &row)?;
979        }
980        output.extend(builder.finish(metric)?);
981    }
982    Ok(output)
983}
984
985/// The value of a `count_values` sample, as it is grouped.
986#[derive(PartialEq, Eq, Hash)]
987enum Value {
988    Float(u64),
989    Histogram(String),
990}
991
992/// Schema validation is repeated because Series exposes its fields publicly.
993fn validate_input(schema: &SeriesSchema, input: &[Series], grouping: Grouping<'_>) -> Result<()> {
994    validate_grouping(schema, grouping)?;
995    for series in input {
996        // `quantile` reads float values and skips a histogram sample the way Prometheus does, so
997        // the only thing it needs from a series is that it fits this schema and grid.
998        validate_grid_series(schema, series)?;
999    }
1000    Ok(())
1001}
1002
1003/// Validates the grouping a whole-vector operation addresses its series by.
1004///
1005/// The native route keys `topk`, `bottomk` and `limitk` groups by series labels only, while the
1006/// existing planner also accepts a value field there, where it varies between samples. Refusing
1007/// the field here keeps such a statement on the existing plan before native execution is chosen.
1008pub(crate) fn validate_vector_grouping(
1009    schema: &SeriesSchema,
1010    grouping: Grouping<'_>,
1011) -> Result<()> {
1012    validate_grouping(schema, grouping)
1013}
1014
1015fn validate_grouping(schema: &SeriesSchema, grouping: Grouping<'_>) -> Result<()> {
1016    if schema.eval_grid.is_none() {
1017        return Err(DataFusionError::Execution(
1018            "Aggregate requires an evaluated grid".into(),
1019        ));
1020    }
1021    grouping.validate(schema)
1022}
1023
1024impl Grouping<'_> {
1025    fn validate(self, schema: &SeriesSchema) -> Result<()> {
1026        if let Self::By(labels) = self
1027            && schema
1028                .fields
1029                .iter()
1030                .any(|field| labels.contains(&field.name.as_ref()))
1031        {
1032            return Err(DataFusionError::NotImplemented(
1033                "aggregate by value field requires a per-point label/schema adapter".into(),
1034            ));
1035        }
1036        Ok(())
1037    }
1038
1039    /// Prometheus `generateGroupingLabels`; empty values are dropped as absent labels.
1040    fn apply(self, input: &SeriesLabels) -> Result<SeriesLabels> {
1041        let mut metric = input.clone();
1042        match self {
1043            Self::By(labels) => metric.keep_only(labels),
1044            Self::Without(labels) => {
1045                metric.remove_all(labels);
1046                metric.remove("__name__");
1047            }
1048        }
1049        drop_empty_labels(&metric)
1050    }
1051}
1052
1053type LabelKey = Vec<(Arc<str>, Arc<str>)>;
1054
1055fn metric_bytes(metric: &SeriesLabels) -> usize {
1056    metric
1057        .name()
1058        .map_or(0, str::len)
1059        .saturating_add(
1060            metric
1061                .tags()
1062                .iter()
1063                .map(|tag| tag.name.len() + tag.value.len())
1064                .sum::<usize>(),
1065        )
1066        .saturating_add(
1067            metric
1068                .tags()
1069                .len()
1070                .saturating_mul(std::mem::size_of::<(Arc<str>, Arc<str>)>()),
1071        )
1072        .saturating_add(std::mem::size_of::<SeriesLabels>())
1073}
1074
1075fn grouping_workspace_bytes(metric: &SeriesLabels) -> usize {
1076    metric_bytes(metric)
1077        .saturating_add(
1078            metric
1079                .tags()
1080                .len()
1081                .saturating_add(1)
1082                .saturating_mul(std::mem::size_of::<(Arc<str>, Arc<str>)>()),
1083        )
1084        .saturating_add(std::mem::size_of::<LabelKey>())
1085}
1086
1087/// Conservative backing estimate for Rust 1.98.1's insert-only `HashMap` (hashbrown 0.17.1).
1088/// Bucket count follows its 7/8 load factor; entries, one control byte per bucket and the
1089/// 16-byte control-group tail are counted. This models requested table storage, not allocator slack.
1090/// An upper bound on the bytes the group index holds for `capacity` entries.
1091///
1092/// The table keeps its entries in a power-of-two number of buckets below `16/7` of the usable
1093/// capacity, with one control byte beside each bucket. Three buckets per entry therefore covers the
1094/// table whatever exact growth the map uses, which is what keeps this a bound rather than a model of
1095/// one implementation: a toolchain that changes how the map grows cannot make it under-count.
1096fn hash_map_backing_bytes(capacity: usize) -> usize {
1097    capacity
1098        .saturating_mul(3)
1099        .saturating_mul(size_of::<(LabelKey, usize)>() + 1)
1100}
1101
1102/// An upper bound on the capacity a map holding `capacity` entries grows to.
1103fn next_hash_capacity(capacity: usize) -> usize {
1104    capacity.saturating_mul(2).max(7)
1105}
1106
1107/// An upper bound on the bytes one B-tree node holds.
1108///
1109/// A node keeps at most eleven key/value pairs and twelve child pointers, plus a header of a few
1110/// words; the leaf form is smaller than that. The header allowance is generous on purpose, so the
1111/// bound does not depend on how a toolchain lays the node out.
1112fn btree_node_bytes() -> usize {
1113    11 * size_of::<(usize, Box<[f64]>)>() + 16 * size_of::<usize>()
1114}
1115
1116/// An upper bound on the bytes a B-tree of `entries` holds.
1117///
1118/// Every node but the root keeps at least five entries, so `entries / 5` nodes is enough to hold
1119/// them; a tree of one entry is one node.
1120fn btree_backing_bytes(entries: usize) -> usize {
1121    if entries == 0 {
1122        return 0;
1123    }
1124    entries.div_ceil(5).saturating_mul(btree_node_bytes())
1125}
1126
1127/// Transient bytes the fold needs for one field's row while it folds a series. The samples are
1128/// written straight into their blocks, so a block's staging buffer is no longer part of this.
1129fn pending_bytes(fields: usize) -> usize {
1130    fields.saturating_mul(std::mem::size_of::<Option<f64>>() + 1)
1131}
1132
1133fn labels_capacity_bytes(grouping: Grouping<'_>) -> usize {
1134    let labels = match grouping {
1135        Grouping::By(labels) | Grouping::Without(labels) => labels,
1136    };
1137    labels.len().saturating_mul(std::mem::size_of::<Arc<str>>())
1138}
1139
1140fn grouping_bytes(grouping: Grouping<'_>) -> usize {
1141    let labels = match grouping {
1142        Grouping::By(labels) | Grouping::Without(labels) => labels,
1143    };
1144    labels
1145        .iter()
1146        .map(|label| label.len() + std::mem::size_of::<Arc<str>>())
1147        .sum::<usize>()
1148}
1149
1150fn label_key(metric: &SeriesLabels) -> LabelKey {
1151    let mut labels = Vec::with_capacity(metric.tags().len() + 1);
1152    if let Some(name) = metric.name() {
1153        labels.push((Arc::from("__name__"), Arc::from(name)));
1154    }
1155    labels.extend(
1156        metric
1157            .tags()
1158            .iter()
1159            .map(|label| (label.name.clone(), label.value.clone())),
1160    );
1161    labels
1162}
1163
1164/// Grid points per state block. A block is allocated only once a sample falls in it, so sparse
1165/// input never expands to the full grid and dense input costs one allocation per block.
1166const BLOCK_POINTS: usize = 64;
1167
1168/// Bytes one allocated block keeps: a state per point per field, [`AggregateOp::state_words`]
1169/// words of `f64` each. The fold, the merge and the recount all size a block through this, so what
1170/// is admitted and what is allocated cannot drift apart.
1171fn block_bytes(width: usize, op: AggregateOp) -> usize {
1172    BLOCK_POINTS
1173        .saturating_mul(width)
1174        .saturating_mul(op.state_words())
1175        .saturating_mul(size_of::<f64>())
1176}
1177
1178struct Group {
1179    metric: SeriesLabels,
1180    /// Keyed by absolute grid index / `BLOCK_POINTS`; each block holds one state per field for
1181    /// each of its points, point by point, each state as many `f64` words as the op folds.
1182    blocks: BTreeMap<usize, Box<[f64]>>,
1183    /// The histogram states of this group, keyed by absolute grid position and field.
1184    ///
1185    /// Only an aggregate that folds a payload allocates one, and only where it saw a histogram
1186    /// sample, so a float fold never touches this map and its state stays the blocks alone.
1187    histograms: BTreeMap<(usize, usize), HistogramAccumulator>,
1188}
1189
1190/// One position's histogram fold: the live payload, the compensation paired with it, the running
1191/// mean an average switched to, and the evidence the fold recorded beside them.
1192///
1193/// The payload here is the kernel's own owned histogram rather than the state frame's row
1194/// representation: a fold adds bucket by bucket, and rebuilding a frame row per sample would
1195/// re-encode the layout it just added into. The state export builds that row from this.
1196///
1197/// The fields are the `HistogramAvg` state layout of the design: `value` is the state's
1198/// `histogram_value`, `mean` is its `incremental_mean` mode, `count` is its `count`, and
1199/// `compensation` is its `histogram_compensation`. A `sum` fold leaves `mean` at `None` and only
1200/// counts for the average's sake.
1201///
1202/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulators fold through this one as well, so
1203/// their arithmetic is this arithmetic; only their state frame differs.
1204#[derive(Debug)]
1205pub(crate) struct HistogramAccumulator {
1206    /// The live value: the running sum, or -- once an average switched -- the sum the switch started
1207    /// from, which the mean is derived from.
1208    value: FloatHistogram,
1209    /// The compensation paired with `value`, carrying `value`'s bucket layout.
1210    ///
1211    /// It is `None` only while a [`FloatHistogram::kahan_add`] call owns it, and stays `None` once
1212    /// the position is poisoned: a poisoned point folds nothing more, so there is nothing left to
1213    /// compensate.
1214    compensation: Option<FloatHistogram>,
1215    /// The running mean an average switched to once its sum overflowed; `None` while it still sums.
1216    mean: Option<FloatHistogram>,
1217    /// Samples folded into this position, which is the divisor an average's mean uses.
1218    count: f64,
1219    /// The evidence bits this fold recorded. A legacy accumulator keeps its own copy of the bits its
1220    /// state frame can carry and seeds them in before every operation.
1221    pub(crate) evidence: HistogramEvidence,
1222}
1223
1224/// The evidence bits a histogram fold records beside its payload.
1225///
1226/// These are the Boolean components of the histogram state layout: the fold records them per point
1227/// so a merge of two partitions can report what the inputs disagreed about. Only `poisoned` steers
1228/// the fold's own output today -- a poisoned point is removed -- and the rest are carried for that
1229/// merge, except `counter_reset_collision`, which is decided from them when the answer is finished.
1230#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1231pub(crate) struct HistogramEvidence {
1232    /// The point cannot be answered because its samples disagreed on their bucket layout.
1233    pub(crate) poisoned: bool,
1234    /// The disagreement was exponential buckets meeting custom buckets.
1235    pub(crate) incompatible_layout: bool,
1236    /// Two custom-bucket samples were reconciled into the intersection of their bounds.
1237    pub(crate) custom_bounds_reconciled: bool,
1238    /// Some sample reported a counter reset.
1239    pub(crate) counter_reset_seen: bool,
1240    /// Some sample reported that no counter reset happened.
1241    pub(crate) not_counter_reset_seen: bool,
1242    /// One point saw both a reset hint and its negation, which cannot both hold of its samples.
1243    ///
1244    /// The two bits above are recorded per point and travel through the state, so a summary of them
1245    /// is a claim about the fold rather than about one point. This bit is the per-point decision:
1246    /// [`evidence_summary`] sets it for a point that holds both bits and is not poisoned, so two
1247    /// groups that each saw one of the hints do not contradict each other.
1248    pub(crate) counter_reset_collision: bool,
1249}
1250
1251/// Which field of which layout a fold is writing, and how it folds it.
1252///
1253/// One value carried through the per-block work instead of three separate arguments: the three
1254/// never vary independently within one series, and the block loop is the only place that reads
1255/// them.
1256#[derive(Clone, Copy)]
1257struct FieldFold {
1258    width: usize,
1259    field_index: usize,
1260    op: AggregateOp,
1261}
1262
1263impl FieldFold {
1264    /// Words one point of this fold's block keeps: every field's state, side by side.
1265    fn point_words(self) -> usize {
1266        self.width.saturating_mul(self.op.state_words())
1267    }
1268
1269    /// Where this field's state of the point at `offset` starts inside a block.
1270    fn state_start(self, offset: usize) -> usize {
1271        offset
1272            .saturating_mul(self.point_words())
1273            .saturating_add(self.field_index.saturating_mul(self.op.state_words()))
1274    }
1275}
1276
1277impl Group {
1278    /// Folds one series' float samples into this group's blocks, one field at a time.
1279    ///
1280    /// Within a field the samples arrive in position order, so the first sample of a block admits
1281    /// that block and allocates its states, and every following sample of the same block is written
1282    /// into the states just placed. Each block needs one acquisition per field run, and a field
1283    /// with no value in a block leaves that block unallocated.
1284    fn accumulate(
1285        &mut self,
1286        series: &Series,
1287        op: AggregateOp,
1288        budget: &mut impl FnMut(usize) -> Result<()>,
1289        mut retained: usize,
1290        width: usize,
1291    ) -> Result<usize> {
1292        // The grouping workspace the caller admitted for this series is gone once the fold starts,
1293        // so only the retained state stays charged while the samples are written.
1294        budget(retained)?;
1295        for (field_index, field) in series.fields.iter().enumerate() {
1296            let fold = FieldFold {
1297                width,
1298                field_index,
1299                op,
1300            };
1301            // A payload-folding aggregate keeps its own per-position histogram state, addressed by
1302            // the absolute grid position: histogram samples never enter the block buffer the float
1303            // samples share, and a field that carries them cannot also carry floats. A float field
1304            // of the same aggregate still folds through that buffer, so the branch is per field.
1305            let folds_histograms = histogram_samples(op) == HistogramSamples::Folded
1306                && field
1307                    .iter()
1308                    .any(|sample| matches!(sample, SampleRef::Histogram(_)));
1309            if folds_histograms {
1310                for ((index, _), sample) in series.time.positions().zip(field.iter()) {
1311                    match sample {
1312                        SampleRef::Missing => {}
1313                        SampleRef::Histogram(view) => {
1314                            retained = self.fold_histogram(fold, index, &view, budget, retained)?;
1315                        }
1316                        // The finish step refuses the other order (a float folded after a
1317                        // histogram); refusing this one here keeps the column single-typed.
1318                        SampleRef::Float(_) => {
1319                            return Err(DataFusionError::Execution(
1320                                "a native aggregate cannot mix float and histogram samples in one field"
1321                                    .into(),
1322                            ));
1323                        }
1324                    }
1325                }
1326                continue;
1327            }
1328            // The axis says which absolute positions the field holds and the field iterator
1329            // supplies them in order, so a sparse axis never turns into its envelope here. Samples
1330            // that hold nothing never reach a state, and `validate_aggregate_series` has already
1331            // decided how this aggregate treats histogram samples.
1332            let mut samples = series
1333                .time
1334                .positions()
1335                .zip(field.iter())
1336                .filter_map(|((index, _), sample)| match sample {
1337                    SampleRef::Float(sample) => Some((index, sample)),
1338                    SampleRef::Histogram(_) => match histogram_samples(op) {
1339                        // `count` and `group` ask whether a sample is present, not which payload
1340                        // it carries, so a histogram is one contribution. The value is a
1341                        // placeholder: `FloatState` counts the contributions for `count` and only
1342                        // records that it saw one for `group`.
1343                        HistogramSamples::Presence => Some((index, 1.0)),
1344                        // Prometheus skips a histogram sample where the aggregate reads a float
1345                        // value; the runtime reports that it did.
1346                        HistogramSamples::Ignored => None,
1347                        // A payload-folding aggregate never reaches this loop: its samples were
1348                        // folded in the histogram branch above, and a field carrying both kinds is
1349                        // refused there.
1350                        HistogramSamples::Folded => {
1351                            unreachable!("a payload-folding aggregate folds histograms above")
1352                        }
1353                    },
1354                    _ => None,
1355                })
1356                .peekable();
1357            while let Some((index, sample)) = samples.next() {
1358                let block = index / BLOCK_POINTS;
1359                let (states, admitted) = self.block_states(block, fold, budget, retained)?;
1360                retained = admitted;
1361                let words = fold.op.state_words();
1362                let start = fold.state_start(index % BLOCK_POINTS);
1363                FloatState::new(&mut states[start..start + words], fold.op).update(sample);
1364                while let Some(&(at, sample)) = samples.peek()
1365                    && at / BLOCK_POINTS == block
1366                {
1367                    samples.next();
1368                    let start = fold.state_start(at % BLOCK_POINTS);
1369                    FloatState::new(&mut states[start..start + words], fold.op).update(sample);
1370                }
1371            }
1372        }
1373        Ok(retained)
1374    }
1375
1376    /// The states of `block` for this field, admitting and allocating the block if this field has
1377    /// not written there yet, along with the retained bytes after that admission.
1378    ///
1379    /// A new block is admitted before the tree holds it, so a refused allocation leaves no block
1380    /// behind and the retained figure never counts an allocation that was not made.
1381    fn block_states<'a>(
1382        &'a mut self,
1383        block: usize,
1384        fold: FieldFold,
1385        budget: &mut impl FnMut(usize) -> Result<()>,
1386        retained: usize,
1387    ) -> Result<(&'a mut [f64], usize)> {
1388        let new_block = !self.blocks.contains_key(&block);
1389        let (states_bytes, backing_delta) = if new_block {
1390            (
1391                block_bytes(fold.width, fold.op),
1392                btree_backing_bytes(self.blocks.len() + 1)
1393                    .saturating_sub(btree_backing_bytes(self.blocks.len())),
1394            )
1395        } else {
1396            (0, 0)
1397        };
1398        let retained = retained
1399            .saturating_add(backing_delta)
1400            .saturating_add(states_bytes);
1401        if new_block {
1402            budget(retained)?;
1403        }
1404        let states = self
1405            .blocks
1406            .entry(block)
1407            .or_insert_with(|| vec![0.0; BLOCK_POINTS * fold.point_words()].into_boxed_slice());
1408        Ok((&mut states[..], retained))
1409    }
1410}
1411
1412impl Group {
1413    /// Folds one histogram sample into its position's state, admitting what the fold allocates.
1414    ///
1415    /// The first sample of a position establishes the state: it is the live value, and its
1416    /// compensation is the layout-carrying zero `new_compensation` builds -- never an `empty_like`
1417    /// histogram, which has no bucket indices for the compensated add to index. Every later sample
1418    /// is one [`FloatHistogram::kahan_add`] into the live value (an average's mean once it switched),
1419    /// carrying the compensation this position already holds.
1420    ///
1421    /// Two samples whose bucket layouts cannot be added (exponential meeting custom buckets) poison
1422    /// the position instead of failing the statement, and a poisoned position folds nothing more:
1423    /// Prometheus drops the point, so the evidence is what survives. Numeric overflow is not a reason
1424    /// to poison a point -- a saturated sum answers `Inf`, as the kernel's own sum does, and an
1425    /// average switches to its mean instead.
1426    fn fold_histogram(
1427        &mut self,
1428        fold: FieldFold,
1429        position: usize,
1430        view: &HistogramView<'_>,
1431        budget: &mut impl FnMut(usize) -> Result<()>,
1432        retained: usize,
1433    ) -> Result<usize> {
1434        // A field's column is either float or histogram, so a position that already folded a float
1435        // cannot also fold a histogram. The other order is caught when the fold is finished, which
1436        // is where the column type is chosen.
1437        if let Some(states) = self.blocks.get(&(position / BLOCK_POINTS)) {
1438            let words = fold.op.state_words();
1439            let start = fold.state_start(position % BLOCK_POINTS);
1440            if state_seen(&states[start..start + words], fold.op) {
1441                return Err(DataFusionError::Execution(
1442                    "a native aggregate cannot mix float and histogram samples in one field".into(),
1443                ));
1444            }
1445        }
1446        let sample = FloatHistogram::try_from_view(view)?;
1447        let key = (position, fold.field_index);
1448        let vacant = !self.histograms.contains_key(&key);
1449        let backing = if vacant {
1450            histogram_backing_bytes(self.histograms.len() + 1)
1451                .saturating_sub(histogram_backing_bytes(self.histograms.len()))
1452        } else {
1453            0
1454        };
1455        if vacant {
1456            // Admit the new position before allocating it: a live value, the compensation that
1457            // starts beside it, and the map node holding both.
1458            budget(
1459                retained
1460                    .saturating_add(size_of::<HistogramAccumulator>())
1461                    .saturating_add(sample.heap_bytes().saturating_mul(2))
1462                    .saturating_add(backing),
1463            )?;
1464        }
1465        let accumulator = self
1466            .histograms
1467            .entry(key)
1468            .or_insert_with(|| HistogramAccumulator::from_sample(&sample));
1469        // The evidence follows the sample's own reset hint, whether or not the point still folds.
1470        match sample.reset_hint {
1471            CounterResetHint::CounterReset => accumulator.evidence.counter_reset_seen = true,
1472            CounterResetHint::NotCounterReset => accumulator.evidence.not_counter_reset_seen = true,
1473            _ => {}
1474        }
1475        if accumulator.evidence.poisoned {
1476            return Ok(retained);
1477        }
1478        if vacant {
1479            // The admitted estimate is an upper bound; what the fold keeps is the real figure.
1480            return Ok(retained
1481                .saturating_add(accumulator_bytes(accumulator))
1482                .saturating_add(backing));
1483        }
1484        // An add can grow both bucket lists, so the incoming sample's payload on top of what the
1485        // position already holds is what is admitted; the figure kept afterwards is the real one.
1486        let before = accumulator_bytes(accumulator);
1487        budget(
1488            retained
1489                .saturating_add(before)
1490                .saturating_add(sample.heap_bytes()),
1491        )?;
1492        if accumulator.uses_custom_buckets() != sample.uses_custom_buckets() {
1493            // Exponential buckets cannot be added to custom ones: the point is removed rather than
1494            // answered, and the evidence says why.
1495            accumulator.poison();
1496            return Ok(retained);
1497        }
1498        match fold.op {
1499            AggregateOp::Sum => accumulator.fold_sum(&sample)?,
1500            AggregateOp::Avg => accumulator.fold_avg(&sample)?,
1501            op => unreachable!("{op:?} does not fold a histogram payload"),
1502        }
1503        Ok(retained
1504            .saturating_sub(before)
1505            .saturating_add(accumulator_bytes(accumulator)))
1506    }
1507}
1508
1509impl HistogramAccumulator {
1510    /// A fold that has taken `sample` and nothing else: the sample is the live value, the
1511    /// compensation is the layout-carrying zero built beside it, and one sample is counted.
1512    pub(crate) fn from_sample(sample: &FloatHistogram) -> Self {
1513        Self {
1514            value: sample.clone(),
1515            compensation: Some(sample.new_compensation()),
1516            mean: None,
1517            count: 1.0,
1518            evidence: HistogramEvidence::default(),
1519        }
1520    }
1521
1522    /// Whether the live value -- the mean once an average switched -- uses custom buckets.
1523    pub(crate) fn uses_custom_buckets(&self) -> bool {
1524        match &self.mean {
1525            Some(mean) => mean.uses_custom_buckets(),
1526            None => self.value.uses_custom_buckets(),
1527        }
1528    }
1529
1530    /// Removes this position: its samples disagreed on their bucket layout, so it answers nothing
1531    /// and the evidence says why.
1532    pub(crate) fn poison(&mut self) {
1533        self.evidence.poisoned = true;
1534        self.evidence.incompatible_layout = true;
1535        self.compensation = None;
1536    }
1537
1538    /// Adds one sample into the running sum, one compensated add into the live value.
1539    pub(crate) fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> {
1540        let (compensation, outcome) = self.value.kahan_add(sample, self.compensation.take())?;
1541        self.compensation = Some(compensation);
1542        self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled;
1543        Ok(())
1544    }
1545
1546    /// Averages one sample in, switching from the running sum to a running mean when the sum would
1547    /// overflow.
1548    ///
1549    /// Each step is Prometheus v3.15's `aggregation`/`sum_or_avg` average in the same order: the
1550    /// trial add is what decides the mode, and once it overflows the trial is discarded, the sum so
1551    /// far becomes the mean of the samples before this one, and every later sample enters as
1552    /// `sample / count` weighted by `(count - 1) / count`. Dividing before adding is what keeps a
1553    /// mean of finite inputs finite: two histograms of `1e308` at one observation each average to
1554    /// `1e308`, while `(1e308 + 1e308) / 2` would be `Inf`.
1555    pub(crate) fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> {
1556        self.count += 1.0;
1557        if self.mean.is_none() {
1558            // The trial runs on a copy, so an overflowing add leaves the sum it started from intact
1559            // -- that sum is what the mean begins at.
1560            let mut trial = self.value.clone();
1561            let (compensation, outcome) = trial.kahan_add(sample, self.compensation.clone())?;
1562            // A reconciliation counts whether or not the trial is kept: the two sides' bounds meet
1563            // in it either way.
1564            self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled;
1565            if !trial.has_overflow() {
1566                self.value = trial;
1567                self.compensation = Some(compensation);
1568                return Ok(());
1569            }
1570            let mut started = self.value.clone();
1571            started.div(self.count - 1.0);
1572            if let Some(compensation) = self.compensation.as_mut() {
1573                compensation.div(self.count - 1.0);
1574            }
1575            self.mean = Some(started);
1576        }
1577        // The mean's unit follows the value's: the compensation is scaled by the same weight the
1578        // value is, and the incoming sample is divided before it is added.
1579        let q = (self.count - 1.0) / self.count;
1580        if let Some(compensation) = self.compensation.as_mut() {
1581            compensation.mul(q);
1582        }
1583        let mut sample = sample.clone();
1584        sample.div(self.count);
1585        let mean = self.mean.as_mut().expect("set above");
1586        mean.mul(q);
1587        let (compensation, outcome) = mean.kahan_add(&sample, self.compensation.take())?;
1588        self.compensation = Some(compensation);
1589        self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled;
1590        Ok(())
1591    }
1592}
1593
1594impl HistogramAccumulator {
1595    /// This position's state as the frame payload a `Partial` hands over.
1596    ///
1597    /// The payload is the fold's own state, not its answer: a sum exports the running sum and the
1598    /// compensation beside it, and folding the compensation in belongs to the merge that finishes the
1599    /// answer. An average exports whichever value it is keeping -- the sum it still adds to, or the
1600    /// mean it switched to -- with the count and the mode flag that say how to read them.
1601    ///
1602    /// A poisoned position exports the empty placeholders the state layout reserves for it: it
1603    /// answers nothing, and the merge reads its evidence, not its buckets.
1604    pub(crate) fn payload(&self, op: AggregateOp) -> Result<StatePayload> {
1605        if self.evidence.poisoned {
1606            let empty = self.value.empty_like();
1607            return Ok(StatePayload::Histogram(Box::new(HistogramState {
1608                value: histogram_batch(&empty)?,
1609                compensation: histogram_batch(&empty)?,
1610                count: 0.0,
1611                incremental_mean: false,
1612                poisoned: true,
1613                incompatible_layout: self.evidence.incompatible_layout,
1614                custom_bounds_reconciled: self.evidence.custom_bounds_reconciled,
1615                counter_reset_seen: self.evidence.counter_reset_seen,
1616                not_counter_reset_seen: self.evidence.not_counter_reset_seen,
1617            })));
1618        }
1619        let switched = self.mean.is_some();
1620        let value = match op {
1621            // A sum's state is its running sum: adding the compensation in is the merge's job.
1622            AggregateOp::Sum => &self.value,
1623            AggregateOp::Avg if switched => self.mean.as_ref().expect("checked above"),
1624            AggregateOp::Avg => &self.value,
1625            op => unreachable!("{op:?} does not fold a histogram payload"),
1626        };
1627        let compensation = self
1628            .compensation
1629            .clone()
1630            .unwrap_or_else(|| value.new_compensation());
1631        Ok(StatePayload::Histogram(Box::new(HistogramState {
1632            value: histogram_batch(value)?,
1633            compensation: histogram_batch(&compensation)?,
1634            // A sum's state declares no count and no mean mode, so both stay at their defaults: the
1635            // payload cannot claim a component its kind does not carry.
1636            count: if op == AggregateOp::Avg {
1637                self.count
1638            } else {
1639                0.0
1640            },
1641            incremental_mean: switched && op == AggregateOp::Avg,
1642            poisoned: false,
1643            incompatible_layout: self.evidence.incompatible_layout,
1644            custom_bounds_reconciled: self.evidence.custom_bounds_reconciled,
1645            counter_reset_seen: self.evidence.counter_reset_seen,
1646            not_counter_reset_seen: self.evidence.not_counter_reset_seen,
1647        })))
1648    }
1649
1650    /// The state a decoded payload carries, as the merge keeps it.
1651    pub(crate) fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result<Self> {
1652        let value = decoded_histogram(&payload.value)?;
1653        let compensation = decoded_histogram(&payload.compensation)?;
1654        let switched = op == AggregateOp::Avg && payload.incremental_mean;
1655        Ok(Self {
1656            // An average that switched keeps its mean in the mean slot; the sum it switched from is
1657            // not part of the state it exported, so the value slot holds the mean too.
1658            value: value.clone(),
1659            compensation: Some(compensation),
1660            mean: switched.then_some(value),
1661            count: payload.count,
1662            // A decoded state is one point's payload, so whether its two hint bits contradict is
1663            // decided where the whole answer is, in `evidence_summary`: the state layout carries the
1664            // bits, not the decision.
1665            evidence: HistogramEvidence {
1666                poisoned: payload.poisoned,
1667                incompatible_layout: payload.incompatible_layout,
1668                custom_bounds_reconciled: payload.custom_bounds_reconciled,
1669                counter_reset_seen: payload.counter_reset_seen,
1670                not_counter_reset_seen: payload.not_counter_reset_seen,
1671                counter_reset_collision: false,
1672            },
1673        })
1674    }
1675
1676    /// Merges another partition's state into this position's.
1677    ///
1678    /// The rules are the design's: a sum adds both sides' values and then both sides' compensations
1679    /// into the live value, and an average either adds its sums the same way -- when that stays
1680    /// finite -- or continues in mean mode from the means and the counts, dividing before it adds.
1681    /// Poison is sticky, and both sides' evidence is kept whatever the outcome of the arithmetic.
1682    pub(crate) fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> {
1683        self.evidence.poisoned |= other.poisoned;
1684        self.evidence.incompatible_layout |= other.incompatible_layout;
1685        self.evidence.custom_bounds_reconciled |= other.custom_bounds_reconciled;
1686        self.evidence.counter_reset_seen |= other.counter_reset_seen;
1687        self.evidence.not_counter_reset_seen |= other.not_counter_reset_seen;
1688        if self.evidence.poisoned {
1689            // A poisoned point answers nothing, so there is no value to merge into it.
1690            return Ok(());
1691        }
1692        let right = decoded_histogram(&other.value)?;
1693        let right_compensation = decoded_histogram(&other.compensation)?;
1694        // Two partitions can each be valid on their own and still disagree: one folded exponential
1695        // buckets, the other custom ones. The fold removes such a point when both layouts meet
1696        // inside one partition, so the merge reports it the same way instead of letting the add
1697        // refuse the layouts and fail the whole statement.
1698        let left_uses_custom = self.uses_custom_buckets();
1699        if left_uses_custom != right.uses_custom_buckets() {
1700            self.evidence.poisoned = true;
1701            self.evidence.incompatible_layout = true;
1702            return Ok(());
1703        }
1704        match op {
1705            AggregateOp::Sum => self.merge_sum(right, right_compensation),
1706            AggregateOp::Avg => self.merge_avg(
1707                right,
1708                right_compensation,
1709                other.count,
1710                other.incremental_mean,
1711            ),
1712            op => unreachable!("{op:?} does not merge a histogram payload"),
1713        }
1714    }
1715
1716    /// Merges two sums: both values and then both compensations go into the live value.
1717    ///
1718    /// The receiver stays the live value for both adds -- the compensation's unit follows the value's
1719    /// -- so the second add folds the other side's compensation into the sum this state carries, not
1720    /// into the compensation the first add returned.
1721    fn merge_sum(
1722        &mut self,
1723        right: FloatHistogram,
1724        right_compensation: FloatHistogram,
1725    ) -> Result<()> {
1726        let left_compensation = self
1727            .compensation
1728            .take()
1729            .expect("a folding position keeps its compensation");
1730        let (compensation, first) = self.value.kahan_add(&right, Some(left_compensation))?;
1731        let (compensation, second) = self
1732            .value
1733            .kahan_add(&right_compensation, Some(compensation))?;
1734        self.compensation = Some(compensation);
1735        self.evidence.custom_bounds_reconciled |=
1736            first.custom_bounds_reconciled || second.custom_bounds_reconciled;
1737        Ok(())
1738    }
1739
1740    /// Merges an average: the sums add while they stay finite, and otherwise the means and their
1741    /// counts do.
1742    fn merge_avg(
1743        &mut self,
1744        right: FloatHistogram,
1745        right_compensation: FloatHistogram,
1746        right_count: f64,
1747        right_is_mean: bool,
1748    ) -> Result<()> {
1749        let left_is_mean = self.mean.is_some();
1750        let left_count = self.count;
1751        let total = left_count + right_count;
1752        let left_value = if left_is_mean {
1753            self.mean.clone().expect("checked above")
1754        } else {
1755            self.value.clone()
1756        };
1757        let left_compensation = self
1758            .compensation
1759            .clone()
1760            .unwrap_or_else(|| left_value.new_compensation());
1761        if !left_is_mean && !right_is_mean {
1762            // Sum and sum: steps 1-2 on a copy of the left sum. The trial is what decides the mode,
1763            // and a reconciliation it reports counts whether or not it is kept.
1764            let mut trial = left_value.clone();
1765            let (compensation, first) = trial.kahan_add(&right, Some(left_compensation.clone()))?;
1766            let (compensation, second) =
1767                trial.kahan_add(&right_compensation, Some(compensation))?;
1768            self.evidence.custom_bounds_reconciled |=
1769                first.custom_bounds_reconciled || second.custom_bounds_reconciled;
1770            if !trial.has_overflow() {
1771                self.value = trial;
1772                self.compensation = Some(compensation);
1773                self.count = total;
1774                return Ok(());
1775            }
1776        }
1777        // The mean path, written so that no intermediate product or sum can overflow: each side
1778        // becomes a mean, its count becomes a weight, and the weighted means are scaled before they
1779        // are added -- with their compensations scaled the same way, because the compensation's unit
1780        // is the value's.
1781        let weight_left = left_count / total;
1782        let weight_right = right_count / total;
1783        let mut left_mean = left_value;
1784        let mut left_mean_compensation = left_compensation;
1785        if !left_is_mean {
1786            left_mean.div(left_count);
1787            left_mean_compensation.div(left_count);
1788        }
1789        let mut right_mean = right;
1790        let mut right_mean_compensation = right_compensation;
1791        if !right_is_mean {
1792            right_mean.div(right_count);
1793            right_mean_compensation.div(right_count);
1794        }
1795        left_mean.mul(weight_left);
1796        left_mean_compensation.mul(weight_left);
1797        right_mean.mul(weight_right);
1798        right_mean_compensation.mul(weight_right);
1799        let (compensation, first) =
1800            left_mean.kahan_add(&right_mean, Some(left_mean_compensation))?;
1801        let (compensation, second) =
1802            left_mean.kahan_add(&right_mean_compensation, Some(compensation))?;
1803        self.value = left_mean.clone();
1804        self.mean = Some(left_mean);
1805        self.compensation = Some(compensation);
1806        self.count = total;
1807        self.evidence.custom_bounds_reconciled |=
1808            first.custom_bounds_reconciled || second.custom_bounds_reconciled;
1809        Ok(())
1810    }
1811}
1812
1813/// One histogram as the frame payload's own one-row batch.
1814pub(crate) fn histogram_batch(histogram: &FloatHistogram) -> Result<Arc<HistogramBatch>> {
1815    let mut builder = HistogramBatchBuilder::new();
1816    histogram.push_to(&mut builder)?;
1817    builder.finish().map_err(external)
1818}
1819
1820/// The histogram a payload component carries.
1821fn decoded_histogram(batch: &HistogramBatch) -> Result<FloatHistogram> {
1822    let view = batch.view(0).ok_or_else(|| {
1823        DataFusionError::Execution("a histogram state component carries no histogram".into())
1824    })?;
1825    FloatHistogram::try_from_view(&view)
1826}
1827
1828/// The evidence a fold or a merge has to report, once, wherever it finishes.
1829///
1830/// A poisoned point suppresses its own reconciliation bit: the point answers nothing, so reporting
1831/// that its bounds were reconciled would report a reconciliation of an answer that is not there.
1832///
1833/// The reset hints are per point too: a point whose samples report a reset and no reset contradicts
1834/// itself -- Prometheus skips such a point -- while two points that each report one of the two do
1835/// not contradict each other, and neither does one series whose hint changes from one point to the
1836/// next. The summary therefore ORs the per-point collision rather than the two bits themselves: a
1837/// `sum by (job)` whose `job` a only ever resets and whose `job` b never does is two ordinary
1838/// points, and a point cannot be both poisoned and in contradiction.
1839///
1840/// Everything else is reported if any point recorded it, which is what makes the message set the same
1841/// whichever order the partitions were merged in.
1842fn evidence_summary(groups: &[Group]) -> HistogramEvidence {
1843    let mut summary = HistogramEvidence::default();
1844    for accumulator in groups.iter().flat_map(|group| group.histograms.values()) {
1845        let evidence = accumulator.evidence;
1846        summary.poisoned |= evidence.poisoned;
1847        summary.incompatible_layout |= evidence.incompatible_layout;
1848        summary.counter_reset_seen |= evidence.counter_reset_seen;
1849        summary.not_counter_reset_seen |= evidence.not_counter_reset_seen;
1850        summary.counter_reset_collision |=
1851            evidence.counter_reset_seen && evidence.not_counter_reset_seen && !evidence.poisoned;
1852        summary.custom_bounds_reconciled |= evidence.custom_bounds_reconciled && !evidence.poisoned;
1853    }
1854    summary
1855}
1856
1857/// Bytes one histogram position holds: every histogram it keeps, with buckets, bounds and spans.
1858pub(crate) fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize {
1859    size_of::<HistogramAccumulator>()
1860        .saturating_add(accumulator.value.heap_bytes())
1861        .saturating_add(
1862            accumulator
1863                .mean
1864                .as_ref()
1865                .map_or(0, FloatHistogram::heap_bytes),
1866        )
1867        .saturating_add(
1868            accumulator
1869                .compensation
1870                .as_ref()
1871                .map_or(0, FloatHistogram::heap_bytes),
1872        )
1873}
1874
1875/// An upper bound on the bytes one node of a group's histogram map holds.
1876fn histogram_node_bytes() -> usize {
1877    11 * size_of::<((usize, usize), HistogramAccumulator)>() + 16 * size_of::<usize>()
1878}
1879
1880/// An upper bound on the bytes a histogram map of `entries` holds, like [`btree_backing_bytes`].
1881fn histogram_backing_bytes(entries: usize) -> usize {
1882    if entries == 0 {
1883        return 0;
1884    }
1885    entries.div_ceil(5).saturating_mul(histogram_node_bytes())
1886}
1887
1888/// The float part of Prometheus' `groupedAggregation`, as a view of one state's words.
1889///
1890/// A state is [`AggregateOp::state_words`] words of the block it sits in: the components the op
1891/// folds, then the presence word. The view reads and writes that layout in place, so folding
1892/// allocates nothing per state and an op that keeps less memory keeps less.
1893struct FloatState<'a> {
1894    words: &'a mut [f64],
1895    op: AggregateOp,
1896}
1897
1898/// Whether the state in `words` has seen a sample: its presence word is set.
1899///
1900/// The presence word is the last one, which is the op's count where its state carries one - a
1901/// state that has folded nothing has no count - and a `0`/`1` flag where it does not.
1902fn state_seen(words: &[f64], op: AggregateOp) -> bool {
1903    words[op.state_words() - 1] != 0.0
1904}
1905
1906/// The value the state in `words` finishes to, or `None` if it has seen no sample.
1907fn state_finish(words: &[f64], op: AggregateOp) -> Option<f64> {
1908    if !state_seen(words, op) {
1909        return None;
1910    }
1911    Some(match op {
1912        // `value`, its compensation, then the presence flag.
1913        AggregateOp::Sum => words[0] + words[1],
1914        // `value`, `compensation`, `mean`, the incremental flag, then the count.
1915        AggregateOp::Avg if words[3] != 0.0 => words[2] + words[1],
1916        AggregateOp::Avg => words[0] / words[4] + words[1] / words[4],
1917        AggregateOp::Count => words[0],
1918        AggregateOp::Min | AggregateOp::Max => words[0],
1919        AggregateOp::Group => 1.0,
1920        // `value`, `mean`, then the count.
1921        AggregateOp::Stdvar => words[0] / words[2],
1922        AggregateOp::Stddev => (words[0] / words[2]).sqrt(),
1923    })
1924}
1925
1926impl<'a> FloatState<'a> {
1927    /// The state at `words`, which is `op`'s layout: [`AggregateOp::state_words`] words.
1928    fn new(words: &'a mut [f64], op: AggregateOp) -> Self {
1929        debug_assert_eq!(words.len(), op.state_words());
1930        Self { words, op }
1931    }
1932
1933    /// Folds one sample in, initializing the state if it had seen none.
1934    fn update(self, sample: f64) {
1935        let (op, words) = (self.op, self.words);
1936        if !state_seen(words, op) {
1937            match op {
1938                // The count is the presence word.
1939                AggregateOp::Count => words[0] = 1.0,
1940                // Presence alone: `group` answers 1 for any kind of sample, NaN included, so the
1941                // sample itself is not kept - a zero sample would read as unseen.
1942                AggregateOp::Group => words[0] = 1.0,
1943                // `value`, then the presence flag.
1944                AggregateOp::Min | AggregateOp::Max => {
1945                    words[0] = sample;
1946                    words[1] = 1.0;
1947                }
1948                // `value`, its compensation, then the presence flag.
1949                AggregateOp::Sum => {
1950                    words[0] = sample;
1951                    words[1] = 0.0;
1952                    words[2] = 1.0;
1953                }
1954                // The running sum of squared deviations, which Prometheus starts at NaN for a
1955                // non-finite first sample; then `mean` and the count that says it is seen.
1956                AggregateOp::Stddev | AggregateOp::Stdvar => {
1957                    words[0] = if sample.is_finite() { 0.0 } else { f64::NAN };
1958                    words[1] = sample;
1959                    words[2] = 1.0;
1960                }
1961                // `value`, `compensation`, `mean`, the incremental flag, then the count.
1962                AggregateOp::Avg => {
1963                    words[0] = sample;
1964                    words[1] = 0.0;
1965                    words[2] = sample;
1966                    words[3] = 0.0;
1967                    words[4] = 1.0;
1968                }
1969            }
1970            return;
1971        }
1972        match op {
1973            AggregateOp::Sum => {
1974                (words[0], words[1]) = kahan_inc(sample, words[0], words[1]);
1975            }
1976            AggregateOp::Avg => update_avg(words, sample),
1977            AggregateOp::Count => words[0] += 1.0,
1978            AggregateOp::Max => {
1979                if words[0] < sample || words[0].is_nan() {
1980                    words[0] = sample;
1981                }
1982            }
1983            AggregateOp::Min => {
1984                if words[0] > sample || words[0].is_nan() {
1985                    words[0] = sample;
1986                }
1987            }
1988            AggregateOp::Group => {}
1989            // Welford's update, uncompensated as in Prometheus.
1990            AggregateOp::Stddev | AggregateOp::Stdvar => {
1991                let count = words[2] + 1.0;
1992                let delta = sample - words[1];
1993                words[1] += delta / count;
1994                words[0] += delta * (sample - words[1]);
1995                words[2] = count;
1996            }
1997        }
1998    }
1999}
2000
2001/// `avg`'s update: sums directly until the running sum would overflow, then switches to an
2002/// incremental mean, whose flag is the fourth word.
2003fn update_avg(words: &mut [f64], sample: f64) {
2004    let count = words[4] + 1.0;
2005    words[4] = count;
2006    if words[3] == 0.0 {
2007        let (value, compensation) = kahan_inc(sample, words[0], words[1]);
2008        if !value.is_infinite() {
2009            words[0] = value;
2010            words[1] = compensation;
2011            return;
2012        }
2013        words[3] = 1.0;
2014        words[2] = words[0] / (count - 1.0);
2015        words[1] /= count - 1.0;
2016    }
2017    let q = (count - 1.0) / count;
2018    (words[2], words[1]) = kahan_inc(sample / count, q * words[2], q * words[1]);
2019}
2020
2021/// Prometheus `kahansum.Inc`, with the Neumaier swap.
2022fn kahan_inc(inc: f64, sum: f64, compensation: f64) -> (f64, f64) {
2023    let t = sum + inc;
2024    let compensation = if t.is_infinite() {
2025        0.0
2026    } else if sum.abs() >= inc.abs() {
2027        compensation + ((sum - t) + inc)
2028    } else {
2029        compensation + ((inc - t) + sum)
2030    };
2031    (t, compensation)
2032}