1pub(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#[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#[derive(Clone, Copy, Debug)]
63pub enum Grouping<'a> {
64 By(&'a [&'a str]),
65 Without(&'a [&'a str]),
66}
67
68pub 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
95pub struct FloatAggregator {
101 schema: Arc<SeriesSchema>,
102 op: AggregateOp,
103 by: bool,
105 labels: Vec<Arc<str>>,
106 group_index: HashMap<LabelKey, usize>,
107 groups: Vec<Group>,
108 retained: usize,
109}
110
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub(crate) enum HistogramSamples {
114 Presence,
117 Ignored,
120 Folded,
124}
125
126impl AggregateOp {
127 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
144pub(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
155pub(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 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 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 .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 pub(crate) fn groups(&self) -> usize {
345 self.groups.len()
346 }
347
348 pub(crate) fn evidence_summary(&self) -> HistogramEvidence {
350 evidence_summary(&self.groups)
351 }
352
353 pub(crate) fn state_bytes(&self) -> usize {
355 self.retained
356 }
357
358 #[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 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
440fn 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 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 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 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
544fn finish_histogram_group(
551 op: AggregateOp,
552 schema: &Arc<SeriesSchema>,
553 group: Group,
554 width: usize,
555) -> Result<Option<Series>> {
556 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 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 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 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
636pub(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 value.compact();
678 Ok(Some(value))
679}
680
681fn 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 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
705fn 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
772pub 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 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 let mut positions: Vec<_> = members
812 .iter()
813 .map(|series| series.time.positions())
814 .collect();
815 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
869pub(crate) fn validate_count_values(
871 schema: &SeriesSchema,
872 label: &str,
873 grouping: Grouping<'_>,
874) -> Result<()> {
875 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
898pub 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 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 let mut groups: Counts = Vec::new();
926 for series in input {
927 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 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
966type 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#[derive(PartialEq, Eq, Hash)]
987enum Value {
988 Float(u64),
989 Histogram(String),
990}
991
992fn validate_input(schema: &SeriesSchema, input: &[Series], grouping: Grouping<'_>) -> Result<()> {
994 validate_grouping(schema, grouping)?;
995 for series in input {
996 validate_grid_series(schema, series)?;
999 }
1000 Ok(())
1001}
1002
1003pub(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 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
1087fn hash_map_backing_bytes(capacity: usize) -> usize {
1097 capacity
1098 .saturating_mul(3)
1099 .saturating_mul(size_of::<(LabelKey, usize)>() + 1)
1100}
1101
1102fn next_hash_capacity(capacity: usize) -> usize {
1104 capacity.saturating_mul(2).max(7)
1105}
1106
1107fn btree_node_bytes() -> usize {
1113 11 * size_of::<(usize, Box<[f64]>)>() + 16 * size_of::<usize>()
1114}
1115
1116fn 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
1127fn 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
1164const BLOCK_POINTS: usize = 64;
1167
1168fn 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 blocks: BTreeMap<usize, Box<[f64]>>,
1183 histograms: BTreeMap<(usize, usize), HistogramAccumulator>,
1188}
1189
1190#[derive(Debug)]
1205pub(crate) struct HistogramAccumulator {
1206 value: FloatHistogram,
1209 compensation: Option<FloatHistogram>,
1215 mean: Option<FloatHistogram>,
1217 count: f64,
1219 pub(crate) evidence: HistogramEvidence,
1222}
1223
1224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1231pub(crate) struct HistogramEvidence {
1232 pub(crate) poisoned: bool,
1234 pub(crate) incompatible_layout: bool,
1236 pub(crate) custom_bounds_reconciled: bool,
1238 pub(crate) counter_reset_seen: bool,
1240 pub(crate) not_counter_reset_seen: bool,
1242 pub(crate) counter_reset_collision: bool,
1249}
1250
1251#[derive(Clone, Copy)]
1257struct FieldFold {
1258 width: usize,
1259 field_index: usize,
1260 op: AggregateOp,
1261}
1262
1263impl FieldFold {
1264 fn point_words(self) -> usize {
1266 self.width.saturating_mul(self.op.state_words())
1267 }
1268
1269 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 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 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 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 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 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 HistogramSamples::Presence => Some((index, 1.0)),
1344 HistogramSamples::Ignored => None,
1347 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 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 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 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 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 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 return Ok(retained
1481 .saturating_add(accumulator_bytes(accumulator))
1482 .saturating_add(backing));
1483 }
1484 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 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 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 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 pub(crate) fn poison(&mut self) {
1533 self.evidence.poisoned = true;
1534 self.evidence.incompatible_layout = true;
1535 self.compensation = None;
1536 }
1537
1538 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 pub(crate) fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> {
1556 self.count += 1.0;
1557 if self.mean.is_none() {
1558 let mut trial = self.value.clone();
1561 let (compensation, outcome) = trial.kahan_add(sample, self.compensation.clone())?;
1562 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 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 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 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 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 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 value: value.clone(),
1659 compensation: Some(compensation),
1660 mean: switched.then_some(value),
1661 count: payload.count,
1662 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 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 return Ok(());
1691 }
1692 let right = decoded_histogram(&other.value)?;
1693 let right_compensation = decoded_histogram(&other.compensation)?;
1694 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 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 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 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 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
1813pub(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
1820fn 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
1828fn 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
1857pub(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
1875fn histogram_node_bytes() -> usize {
1877 11 * size_of::<((usize, usize), HistogramAccumulator)>() + 16 * size_of::<usize>()
1878}
1879
1880fn 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
1888struct FloatState<'a> {
1894 words: &'a mut [f64],
1895 op: AggregateOp,
1896}
1897
1898fn state_seen(words: &[f64], op: AggregateOp) -> bool {
1903 words[op.state_words() - 1] != 0.0
1904}
1905
1906fn state_finish(words: &[f64], op: AggregateOp) -> Option<f64> {
1908 if !state_seen(words, op) {
1909 return None;
1910 }
1911 Some(match op {
1912 AggregateOp::Sum => words[0] + words[1],
1914 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 AggregateOp::Stdvar => words[0] / words[2],
1922 AggregateOp::Stddev => (words[0] / words[2]).sqrt(),
1923 })
1924}
1925
1926impl<'a> FloatState<'a> {
1927 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 fn update(self, sample: f64) {
1935 let (op, words) = (self.op, self.words);
1936 if !state_seen(words, op) {
1937 match op {
1938 AggregateOp::Count => words[0] = 1.0,
1940 AggregateOp::Group => words[0] = 1.0,
1943 AggregateOp::Min | AggregateOp::Max => {
1945 words[0] = sample;
1946 words[1] = 1.0;
1947 }
1948 AggregateOp::Sum => {
1950 words[0] = sample;
1951 words[1] = 0.0;
1952 words[2] = 1.0;
1953 }
1954 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 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 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
2001fn 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
2021fn 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}