diff --git a/src/promql/src/aggregate.rs b/src/promql/src/aggregate.rs index 59ab98912aa..49c67f375fa 100644 --- a/src/promql/src/aggregate.rs +++ b/src/promql/src/aggregate.rs @@ -624,7 +624,7 @@ fn finish_histogram_group( /// mean with the compensation folded in; one that never switched divides the sum and the compensation /// by the sample count and then folds the compensation in, which is what `sum_or_avg` does at the end /// of both paths. -fn finished_histogram( +pub(crate) fn finished_histogram( op: AggregateOp, accumulator: &HistogramAccumulator, ) -> Result> { @@ -1171,7 +1171,11 @@ struct Group { /// `histogram_value`, `mean` is its `incremental_mean` mode, `count` is its `count`, and /// `compensation` is its `histogram_compensation`. A `sum` fold leaves `mean` at `None` and only /// counts for the average's sake. -struct HistogramAccumulator { +/// +/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulators fold through this one as well, so +/// their arithmetic is this arithmetic; only their state frame differs. +#[derive(Debug)] +pub(crate) struct HistogramAccumulator { /// The live value: the running sum, or -- once an average switched -- the sum the switch started /// from, which the mean is derived from. value: FloatHistogram, @@ -1185,7 +1189,9 @@ struct HistogramAccumulator { mean: Option, /// Samples folded into this position, which is the divisor an average's mean uses. count: f64, - evidence: HistogramEvidence, + /// The evidence bits this fold recorded. A legacy accumulator keeps its own copy of the bits its + /// state frame can carry and seeds them in before every operation. + pub(crate) evidence: HistogramEvidence, } /// The evidence bits a histogram fold records beside its payload. @@ -1413,16 +1419,10 @@ impl Group { .saturating_add(backing), )?; } - let accumulator = self.histograms.entry(key).or_insert_with(|| { - let compensation = sample.new_compensation(); - HistogramAccumulator { - value: sample.clone(), - compensation: Some(compensation), - mean: None, - count: 1.0, - evidence: HistogramEvidence::default(), - } - }); + let accumulator = self + .histograms + .entry(key) + .or_insert_with(|| HistogramAccumulator::from_sample(&sample)); // The evidence follows the sample's own reset hint, whether or not the point still folds. match sample.reset_hint { CounterResetHint::CounterReset => accumulator.evidence.counter_reset_seen = true, @@ -1446,12 +1446,10 @@ impl Group { .saturating_add(before) .saturating_add(sample.heap_bytes()), )?; - if accumulator.value.uses_custom_buckets() != sample.uses_custom_buckets() { + if accumulator.uses_custom_buckets() != sample.uses_custom_buckets() { // Exponential buckets cannot be added to custom ones: the point is removed rather than // answered, and the evidence says why. - accumulator.evidence.poisoned = true; - accumulator.evidence.incompatible_layout = true; - accumulator.compensation = None; + accumulator.poison(); return Ok(retained); } match fold.op { @@ -1466,8 +1464,36 @@ impl Group { } impl HistogramAccumulator { + /// A fold that has taken `sample` and nothing else: the sample is the live value, the + /// compensation is the layout-carrying zero built beside it, and one sample is counted. + pub(crate) fn from_sample(sample: &FloatHistogram) -> Self { + Self { + value: sample.clone(), + compensation: Some(sample.new_compensation()), + mean: None, + count: 1.0, + evidence: HistogramEvidence::default(), + } + } + + /// Whether the live value -- the mean once an average switched -- uses custom buckets. + pub(crate) fn uses_custom_buckets(&self) -> bool { + match &self.mean { + Some(mean) => mean.uses_custom_buckets(), + None => self.value.uses_custom_buckets(), + } + } + + /// Removes this position: its samples disagreed on their bucket layout, so it answers nothing + /// and the evidence says why. + pub(crate) fn poison(&mut self) { + self.evidence.poisoned = true; + self.evidence.incompatible_layout = true; + self.compensation = None; + } + /// Adds one sample into the running sum, one compensated add into the live value. - fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> { + pub(crate) fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> { let (compensation, outcome) = self.value.kahan_add(sample, self.compensation.take())?; self.compensation = Some(compensation); self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled; @@ -1483,7 +1509,7 @@ impl HistogramAccumulator { /// `sample / count` weighted by `(count - 1) / count`. Dividing before adding is what keeps a /// mean of finite inputs finite: two histograms of `1e308` at one observation each average to /// `1e308`, while `(1e308 + 1e308) / 2` would be `Inf`. - fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> { + pub(crate) fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> { self.count += 1.0; if self.mean.is_none() { // The trial runs on a copy, so an overflowing add leaves the sum it started from intact @@ -1532,7 +1558,7 @@ impl HistogramAccumulator { /// /// A poisoned position exports the empty placeholders the state layout reserves for it: it /// answers nothing, and the merge reads its evidence, not its buckets. - fn payload(&self, op: AggregateOp) -> Result { + pub(crate) fn payload(&self, op: AggregateOp) -> Result { if self.evidence.poisoned { let empty = self.value.empty_like(); return Ok(StatePayload::Histogram(Box::new(HistogramState { @@ -1579,7 +1605,7 @@ impl HistogramAccumulator { } /// The state a decoded payload carries, as the merge keeps it. - fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result { + pub(crate) fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result { let value = decoded_histogram(&payload.value)?; let compensation = decoded_histogram(&payload.compensation)?; let switched = op == AggregateOp::Avg && payload.incremental_mean; @@ -1610,7 +1636,7 @@ impl HistogramAccumulator { /// into the live value, and an average either adds its sums the same way -- when that stays /// finite -- or continues in mean mode from the means and the counts, dividing before it adds. /// Poison is sticky, and both sides' evidence is kept whatever the outcome of the arithmetic. - fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> { + pub(crate) fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> { self.evidence.poisoned |= other.poisoned; self.evidence.incompatible_layout |= other.incompatible_layout; self.evidence.custom_bounds_reconciled |= other.custom_bounds_reconciled; @@ -1626,10 +1652,7 @@ impl HistogramAccumulator { // buckets, the other custom ones. The fold removes such a point when both layouts meet // inside one partition, so the merge reports it the same way instead of letting the add // refuse the layouts and fail the whole statement. - let left_uses_custom = match &self.mean { - Some(mean) => mean.uses_custom_buckets(), - None => self.value.uses_custom_buckets(), - }; + let left_uses_custom = self.uses_custom_buckets(); if left_uses_custom != right.uses_custom_buckets() { self.evidence.poisoned = true; self.evidence.incompatible_layout = true; @@ -1745,7 +1768,7 @@ impl HistogramAccumulator { } /// One histogram as the frame payload's own one-row batch. -fn histogram_batch(histogram: &FloatHistogram) -> Result> { +pub(crate) fn histogram_batch(histogram: &FloatHistogram) -> Result> { let mut builder = HistogramBatchBuilder::new(); histogram.push_to(&mut builder)?; builder.finish().map_err(external) @@ -1789,7 +1812,7 @@ fn evidence_summary(groups: &[Group]) -> HistogramEvidence { } /// Bytes one histogram position holds: every histogram it keeps, with buckets, bounds and spans. -fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize { +pub(crate) fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize { size_of::() .saturating_add(accumulator.value.heap_bytes()) .saturating_add( diff --git a/src/promql/src/functions/native_histogram.rs b/src/promql/src/functions/native_histogram.rs index 15093f0314d..45445ce3644 100644 --- a/src/promql/src/functions/native_histogram.rs +++ b/src/promql/src/functions/native_histogram.rs @@ -33,12 +33,19 @@ use datafusion::physical_plan::ColumnarValue; use datafusion_common::ScalarValue; use datafusion_expr::function::AccumulatorArgs; use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, create_udaf, create_udf}; +use datatypes::series::aggregate_state::HistogramState; +use datatypes::series::histogram::{BucketSideView, HistogramView}; +use crate::aggregate::{ + AggregateOp, HistogramAccumulator, HistogramEvidence, accumulator_bytes, finished_histogram, + histogram_batch, +}; use crate::functions::{ AvgOverTime, Deriv, DoubleExponentialSmoothing, IDelta, Increase, LastOverTime, MaxOverTime, MinOverTime, PredictLinear, QuantileOverTime, Rate, StddevOverTime, StdvarOverTime, SumOverTime, extract_array, extract_range_dict, }; +use crate::histogram_eval::float_histogram::FloatHistogram; use crate::histogram_eval::legacy_bridge; use crate::range_array::{RangeArray, unpack}; @@ -294,13 +301,21 @@ fn record_custom_reconciliation( rhs: &NativeHistogram, ) { if lhs.needs_custom_reconciliation(rhs) { - record_info( - collector, - format!("{name}: reconciled native histograms with different custom buckets"), - ); + record_reconciled_custom_buckets(collector, name); } } +/// Records that two custom-bucket layouts met and the result uses the bounds they share. +fn record_reconciled_custom_buckets( + collector: &Option, + name: &'static str, +) { + record_info( + collector, + format!("{name}: reconciled native histograms with different custom buckets"), + ); +} + fn record_counter_reset_contradiction( collector: &Option, name: &'static str, @@ -922,14 +937,30 @@ impl NativeHistogramAggAvg { } } +/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulator. +/// +/// Its state frame is the one it has always been -- one native histogram, an average's `UInt64` +/// count, and three Booleans -- but the arithmetic behind it is the kernel's own +/// [`HistogramAccumulator`], the same fold a native aggregate uses. What this type adds is the frame: +/// the fold's answer, its count, and the evidence bits the frame can carry. #[derive(Debug)] struct NativeHistogramAggregateAccumulator { kind: NativeHistogramAggregateKind, - value: Option, + /// The fold, once a sample established it. + /// + /// `None` while no histogram reached this accumulator, and `None` again once the position is + /// poisoned: a dropped position answers nothing, so it keeps no histogram to answer with. + fold: Option, + /// The evidence this accumulator records, seeded into the fold before every operation and read + /// back out of it afterwards so the two never disagree about what the inputs reported. + /// + /// It is what the state frame exports: a position is poisoned, or saw a counter reset, or saw + /// its absence. The reconciliation bit has no component of its own and only drives a warning + /// here, because the frame a reader decodes has nowhere to put it. + evidence: HistogramEvidence, + /// Samples folded in, as the `UInt64` component an average's state declares. A sum declares no + /// count, so it leaves this at zero. count: u64, - dropped_incompatible: bool, - counter_reset_seen: bool, - not_counter_reset_seen: bool, collector: Option, } @@ -940,11 +971,9 @@ impl NativeHistogramAggregateAccumulator { ) -> Self { Self { kind, - value: None, + fold: None, + evidence: HistogramEvidence::default(), count: 0, - dropped_incompatible: false, - counter_reset_seen: false, - not_counter_reset_seen: false, collector, } } @@ -957,14 +986,45 @@ impl NativeHistogramAggregateAccumulator { Ok(Box::new(Self::new(kind, collector))) } + /// This kind as the kernel's own aggregate operation, which is what the fold is told it folds. + fn op(&self) -> AggregateOp { + match self.kind { + NativeHistogramAggregateKind::Sum => AggregateOp::Sum, + NativeHistogramAggregateKind::Avg => AggregateOp::Avg, + } + } + fn observe_reset_hints(&mut self, counter_reset_seen: bool, not_counter_reset_seen: bool) { - self.counter_reset_seen |= counter_reset_seen; - self.not_counter_reset_seen |= not_counter_reset_seen; - if self.counter_reset_seen && self.not_counter_reset_seen { + self.evidence.counter_reset_seen |= counter_reset_seen; + self.evidence.not_counter_reset_seen |= not_counter_reset_seen; + if self.evidence.counter_reset_seen && self.evidence.not_counter_reset_seen { record_counter_reset_contradiction_warning(&self.collector, self.kind.name()); } } + /// The count the state declares after folding `count` more samples. + /// + /// It is a `u64` because that is the state component's Arrow type, so a merge that would carry + /// it past `u64::MAX` is an overflow of the frame rather than of the arithmetic. A sum declares + /// no count at all and keeps this at zero. + fn combined_count(&self, count: u64) -> DfResult { + if !self.kind.needs_count() { + return Ok(self.count); + } + self.count.checked_add(count).ok_or_else(|| { + DataFusionError::Execution(format!( + "{}: native histogram sample count overflow", + self.kind.name() + )) + }) + } + + /// Folds one sample into the position's fold, one `fold_sum` or `fold_avg` per kind. + /// + /// The evidence follows the sample's own reset hint whether or not the position still folds, as + /// it always has. A sample whose bucket layout cannot be added to the fold's -- exponential + /// buckets meeting custom ones -- poisons the position instead of failing the statement: the + /// aggregate drops the point, as Prometheus does, and reports why. fn push_histogram(&mut self, histogram: NativeHistogram, count: u64) -> DfResult<()> { if self.kind.needs_count() && count == 0 { return Ok(()); @@ -974,49 +1034,57 @@ impl NativeHistogramAggregateAccumulator { histogram.reset_hint == COUNTER_RESET_HINT, histogram.reset_hint == NOT_COUNTER_RESET_HINT, ); - if self.dropped_incompatible { + if self.evidence.poisoned { return Ok(()); } - let combined_count = if self.kind.needs_count() { - self.count.checked_add(count).ok_or_else(|| { - DataFusionError::Execution(format!( - "{}: native histogram sample count overflow", - self.kind.name() - )) - })? - } else { - self.count - }; - let value = match self.value.take() { - Some(value) => { - record_custom_reconciliation(&self.collector, self.kind.name(), &value, &histogram); - let combined = match self.kind { - NativeHistogramAggregateKind::Sum => legacy_bridge::add(&value, &histogram), - NativeHistogramAggregateKind::Avg => { - weighted_histogram_mean(value, self.count, histogram, count, combined_count) - } - }; - match combined { - Some(value) => Some(value), - None => { - self.record_incompatible(); - None - } - } + let combined_count = self.combined_count(count)?; + // A layout this crate cannot read -- its spans and its buckets disagree about how many + // buckets there are -- drops the position instead of failing the query. The position is + // dropped as a whole, with the warning below: none of its samples count toward the answer, + // not even the ones that are readable. + let sample = match float_histogram(&histogram) { + Ok(sample) => sample, + Err(_) => { + self.record_incompatible(); + return Ok(()); } - None => Some(histogram), }; - if !self.dropped_incompatible { - self.value = value; - self.count = combined_count; + let recorded = self.evidence; + // The first sample of a position *is* the fold's value, so it is not added into it. + let vacant = self.fold.is_none(); + let fold = self + .fold + .get_or_insert_with(|| HistogramAccumulator::from_sample(&sample)); + // The bits this accumulator already recorded go in beside the sample, so the fold exports + // the merge-time evidence along with its own. + fold.evidence = recorded; + if fold.uses_custom_buckets() != sample.uses_custom_buckets() { + fold.poison(); + } else if !vacant { + match self.kind { + NativeHistogramAggregateKind::Sum => fold.fold_sum(&sample)?, + NativeHistogramAggregateKind::Avg => fold.fold_avg(&sample)?, + } + } + let evidence = fold.evidence; + self.evidence = evidence; + if evidence.poisoned { + self.record_incompatible(); + return Ok(()); + } + self.count = combined_count; + if evidence.custom_bounds_reconciled && !recorded.custom_bounds_reconciled { + record_reconciled_custom_buckets(&self.collector, self.kind.name()); } Ok(()) } + /// Drops this position: its inputs disagreed on their bucket layout, so it answers nothing. fn mark_incompatible(&mut self) { - self.value = None; + self.evidence.poisoned = true; + self.evidence.incompatible_layout = true; self.count = 0; - self.dropped_incompatible = true; + self.fold = None; } fn record_incompatible(&mut self) { @@ -1029,6 +1097,109 @@ impl NativeHistogramAggregateAccumulator { ), ); } + + /// The histogram component of this position's state, or `None` when it answers nothing. + /// + /// The legacy frame declares no compensation component and no mean mode, so what it carries is + /// the fold's answer: the running sum with its compensation folded in for a sum, and the running + /// mean of its samples for an average. Both are the value a reader of the frame adds or weights, + /// which is what makes a merged state mean what the state already means. + /// + /// Folding the compensation back into one `f64` rounds again, so this is not a lossless Kahan + /// state: a partition holding `[1e16, 1]` still exports `1e16`, and merging it with a partition + /// holding `[-1e16]` answers `0`. What the frame preserves is the residual of samples already + /// folded into one position, which a frame exporting the running sum would lose even there. + fn state_histogram(&self) -> DfResult> { + if self.evidence.poisoned || (self.kind.needs_count() && self.count == 0) { + return Ok(None); + } + let Some(fold) = &self.fold else { + return Ok(None); + }; + Ok(finished_histogram(self.op(), fold)? + .as_ref() + .map(native_histogram)) + } +} + +/// The fold's form of one legacy sample. +/// +/// A legacy sample is the same histogram in the frame's row representation, so this only re-borrows +/// the spans it stores as pairs and hands the payload slices on. +fn float_histogram(histogram: &NativeHistogram) -> DfResult { + let spans = |spans: &[Span]| -> (Vec, Vec) { + ( + spans.iter().map(|span| span.offset).collect(), + spans.iter().map(|span| span.length).collect(), + ) + }; + let (positive_offsets, positive_lengths) = spans(&histogram.positive_spans); + let (negative_offsets, negative_lengths) = spans(&histogram.negative_spans); + FloatHistogram::try_from_view(&HistogramView { + schema: histogram.schema, + zero_threshold: histogram.zero_threshold, + sum: histogram.sum, + count: histogram.count, + zero_count: histogram.zero_count, + reset_hint: histogram.reset_hint, + start_timestamp: histogram.start_timestamp, + custom_values: &histogram.custom_values, + positive: BucketSideView { + span_offsets: &positive_offsets, + span_lengths: &positive_lengths, + buckets: &histogram.positive_buckets, + }, + negative: BucketSideView { + span_offsets: &negative_offsets, + span_lengths: &negative_lengths, + buckets: &histogram.negative_buckets, + }, + }) +} + +/// The frame's row form of one owned histogram, as the state's histogram component. +fn native_histogram(histogram: &FloatHistogram) -> NativeHistogram { + let (positive_spans, positive_buckets) = spans_and_counts(&histogram.positive); + let (negative_spans, negative_buckets) = spans_and_counts(&histogram.negative); + NativeHistogram { + schema: histogram.schema, + zero_threshold: histogram.zero_threshold, + sum: histogram.sum, + reset_hint: histogram.reset_hint, + start_timestamp: histogram.start_timestamp, + custom_values: histogram.custom_values.clone(), + positive_spans, + negative_spans, + count: histogram.count, + zero_count: histogram.zero_count, + positive_buckets, + negative_buckets, + } +} + +/// The spans and absolute counts an owned bucket list encodes as: one span per run of consecutive +/// bucket indices, the first span starting at its own index and every later one stating its gap. +fn spans_and_counts(buckets: &[(i32, f64)]) -> (Vec, Vec) { + let mut spans: Vec = Vec::new(); + let mut counts = Vec::with_capacity(buckets.len()); + // The absolute index the last span continues at. + let mut next: Option = None; + for &(index, count) in buckets { + match next { + Some(expected) if expected == index => { + if let Some(span) = spans.last_mut() { + span.length += 1; + } + } + _ => spans.push(Span { + offset: next.map_or(index, |expected| index - expected), + length: 1, + }), + } + next = Some(index + 1); + counts.push(count); + } + (spans, counts) } fn weighted_histogram_mean( @@ -2300,38 +2471,28 @@ impl DfAccumulator for NativeHistogramAggregateAccumulator { } fn evaluate(&mut self) -> DfResult { - let histogram = match (self.kind, self.dropped_incompatible, self.value.clone()) { - (_, true, _) => None, - (_, false, None) => None, - (NativeHistogramAggregateKind::Sum, false, value) => value, - (NativeHistogramAggregateKind::Avg, false, Some(value)) if self.count > 0 => { - Some(value) - } - (NativeHistogramAggregateKind::Avg, _, _) => None, - }; - - Ok(native_histogram_scalar(histogram)) + Ok(native_histogram_scalar(self.state_histogram()?)) } fn size(&self) -> usize { + // The fold sits inline in this struct, so only the histograms it owns are counted on top of + // it. size_of::() - + self.value.as_ref().map_or(0, |histogram| { - histogram.custom_values.capacity() * size_of::() - + histogram.positive_spans.capacity() * size_of::() - + histogram.negative_spans.capacity() * size_of::() - + histogram.positive_buckets.capacity() * size_of::() - + histogram.negative_buckets.capacity() * size_of::() + + self.fold.as_ref().map_or(0, |fold| { + accumulator_bytes(fold).saturating_sub(size_of::()) }) } fn state(&mut self) -> DfResult> { - let mut state = vec![native_histogram_scalar(self.value.clone())]; + let mut state = vec![native_histogram_scalar(self.state_histogram()?)]; if self.kind.needs_count() { state.push(ScalarValue::UInt64(Some(self.count))); } - state.push(ScalarValue::Boolean(Some(self.dropped_incompatible))); - state.push(ScalarValue::Boolean(Some(self.counter_reset_seen))); - state.push(ScalarValue::Boolean(Some(self.not_counter_reset_seen))); + state.push(ScalarValue::Boolean(Some(self.evidence.poisoned))); + state.push(ScalarValue::Boolean(Some(self.evidence.counter_reset_seen))); + state.push(ScalarValue::Boolean(Some( + self.evidence.not_counter_reset_seen, + ))); Ok(state) } @@ -2393,22 +2554,78 @@ impl DfAccumulator for NativeHistogramAggregateAccumulator { )) })?; + let op = self.op(); for row in 0..histograms.len() { self.observe_reset_hints( counter_reset_seen.value(row), not_counter_reset_seen.value(row), ); if dropped.value(row) { + // A dropped partition answers nothing, so only its poison crosses the boundary. self.mark_incompatible(); } - if self.dropped_incompatible { + if self.evidence.poisoned { continue; } let Some(histogram) = read_histogram(histograms, row)? else { continue; }; let count = counts.map(|counts| counts.value(row)).unwrap_or(1); - self.push_histogram(histogram, count)?; + if self.kind.needs_count() && count == 0 { + continue; + } + let combined_count = self.combined_count(count)?; + // The same disagreement `push_histogram` drops a position for, met through a state + // frame: a layout this crate cannot read drops the partition's state instead of failing + // the statement, and with it the position the state was headed into. + let sample = match float_histogram(&histogram) { + Ok(sample) => sample, + Err(_) => { + self.record_incompatible(); + continue; + } + }; + // The incoming side carries what its frame could: its answer, its count and its + // evidence. It has no compensation component, so the compensation it brings is the + // layout-carrying zero -- the residual it exported is already inside its answer. + let payload = HistogramState { + value: histogram_batch(&sample)?, + compensation: histogram_batch(&sample.new_compensation())?, + count: count as f64, + // A legacy average exports the mean of its `count` samples, because its frame has + // no mean mode to export instead; a sum exports a sum. + incremental_mean: self.kind.needs_count(), + poisoned: false, + incompatible_layout: false, + custom_bounds_reconciled: false, + counter_reset_seen: false, + not_counter_reset_seen: false, + }; + let recorded = self.evidence; + if let Some(mut fold) = self.fold.take() { + fold.evidence = recorded; + let merged = fold.merge_state(op, &payload); + self.evidence = fold.evidence; + self.fold = Some(fold); + merged?; + } else { + // Nothing folded here yet, so the incoming state is this position's state. + let mut fold = HistogramAccumulator::from_payload(op, &payload)?; + fold.evidence = recorded; + self.fold = Some(fold); + } + let evidence = self.fold.as_ref().map_or(recorded, |fold| fold.evidence); + self.evidence = evidence; + if evidence.poisoned { + // Two partitions can each be valid on their own and still disagree on their bucket + // layout, which the merge reports the way a fold inside one partition reports it. + self.record_incompatible(); + continue; + } + self.count = combined_count; + if evidence.custom_bounds_reconciled && !recorded.custom_bounds_reconciled { + record_reconciled_custom_buckets(&self.collector, self.kind.name()); + } } Ok(()) @@ -2915,6 +3132,7 @@ mod tests { use datafusion::arrow::datatypes::Field; use datafusion_common::config::ConfigOptions; use datafusion_expr::ScalarFunctionArgs; + use datatypes::series::aggregate_state::StatePayload; use super::*; @@ -2979,10 +3197,145 @@ mod tests { fn evaluated_histogram( accumulator: &mut NativeHistogramAggregateAccumulator, ) -> NativeHistogram { + evaluated(accumulator).expect("native histogram accumulator answered nothing") + } + + fn evaluated(accumulator: &mut NativeHistogramAggregateAccumulator) -> Option { let ScalarValue::Struct(array) = accumulator.evaluate().unwrap() else { panic!("native histogram accumulator returned a non-struct value"); }; - read_histogram(&array, 0).unwrap().unwrap() + read_histogram(&array, 0).unwrap() + } + + /// The Arrow arrays one accumulator's state frame spans, one row each. + fn state_arrays(aggregate: &mut NativeHistogramAggregateAccumulator) -> Vec { + aggregate + .state() + .unwrap() + .into_iter() + .map(|value| value.to_array_of_size(1).unwrap()) + .collect() + } + + /// The components of one legacy accumulator's state frame. + struct LegacyState { + histogram: Option, + /// The `UInt64` component; only an average declares one. + count: Option, + /// The `dropped_incompatible` component. + dropped: bool, + counter_reset_seen: bool, + not_counter_reset_seen: bool, + } + + fn legacy_state(aggregate: &mut NativeHistogramAggregateAccumulator) -> LegacyState { + let state = aggregate.state().unwrap(); + let ScalarValue::Struct(array) = state[0].clone() else { + panic!("native histogram accumulator state is not a struct"); + }; + let mut offset = 1; + let count = if aggregate.kind.needs_count() { + let count = match state[offset].clone() { + ScalarValue::UInt64(count) => count, + _ => panic!("native histogram accumulator count state is not UInt64"), + }; + offset += 1; + count + } else { + None + }; + let boolean = |index: usize| match state[index] { + ScalarValue::Boolean(value) => value.unwrap_or_default(), + _ => panic!("native histogram accumulator state component is not Boolean"), + }; + LegacyState { + histogram: read_histogram(&array, 0).unwrap(), + count, + dropped: boolean(offset), + counter_reset_seen: boolean(offset + 1), + not_counter_reset_seen: boolean(offset + 2), + } + } + + /// Asserts one legacy frame histogram carries what one fold histogram carries, bit for bit. + fn assert_frame_carries(actual: &NativeHistogram, expected: &FloatHistogram, case: &str) { + assert_eq!( + actual.count.to_bits(), + expected.count.to_bits(), + "{case}: count" + ); + assert_eq!( + actual.zero_count.to_bits(), + expected.zero_count.to_bits(), + "{case}: zero count" + ); + assert_eq!(actual.sum.to_bits(), expected.sum.to_bits(), "{case}: sum"); + assert_eq!(actual.schema, expected.schema, "{case}: schema"); + assert_eq!( + actual.zero_threshold.to_bits(), + expected.zero_threshold.to_bits(), + "{case}: zero threshold" + ); + assert_eq!( + actual + .custom_values + .iter() + .map(|bound| bound.to_bits()) + .collect::>(), + expected + .custom_values + .iter() + .map(|bound| bound.to_bits()) + .collect::>(), + "{case}: custom bounds" + ); + for (side, spans, counts, buckets) in [ + ( + "positive", + &actual.positive_spans, + &actual.positive_buckets, + &expected.positive, + ), + ( + "negative", + &actual.negative_spans, + &actual.negative_buckets, + &expected.negative, + ), + ] { + assert_eq!( + expand_spans(spans), + buckets.iter().map(|&(index, _)| index).collect::>(), + "{case}: {side} bucket indices" + ); + assert_eq!( + counts + .iter() + .map(|count| count.to_bits()) + .collect::>(), + buckets + .iter() + .map(|&(_, count)| count.to_bits()) + .collect::>(), + "{case}: {side} bucket counts" + ); + } + } + + /// The absolute bucket indices a span list expands to, as the frame's reader expands them. + fn expand_spans(spans: &[Span]) -> Vec { + let mut indices = Vec::new(); + let mut cursor = 0; + for (position, span) in spans.iter().enumerate() { + cursor = if position == 0 { + span.offset + } else { + cursor + span.offset + }; + indices.extend(cursor..cursor + span.length); + cursor += span.length; + } + indices } fn histogram_range_input(values: Vec>) -> Vec { @@ -3364,7 +3717,47 @@ mod tests { } #[test] - fn sum_aggregate_keeps_the_start_timestamp_of_a_single_sample() { + fn an_illegally_shaped_histogram_drops_its_position_rather_than_failing_the_query() { + // The spans claim two buckets and the row carries one, which is a layout this crate cannot + // read: it drops the position instead of failing the query. A single sample is enough to + // drop it, because the position goes as a whole, with the warning below. + let collector = PromqlAnnotationCollector::default(); + for kind in [ + NativeHistogramAggregateKind::Sum, + NativeHistogramAggregateKind::Avg, + ] { + let mut aggregate = + NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone())); + let mut invalid = sample_histogram(2.0, 3.0, vec![2.0]); + invalid.positive_spans = vec![Span { + offset: 0, + length: 2, + }]; + + aggregate.push_histogram(invalid, 1).expect( + "a histogram this crate cannot read drops its position, it does not fail the query", + ); + + assert!(aggregate.evidence.poisoned, "{}: poisoned", kind.name()); + assert!( + aggregate.state_histogram().unwrap().is_none(), + "{}: the position answers nothing", + kind.name() + ); + let warnings = collected_warnings(&collector); + assert!( + warnings.contains(&format!( + "{}: dropped native histogram aggregate with incompatible schemas", + kind.name() + )), + "{}: {warnings:?}", + kind.name() + ); + } + } + + #[test] + fn sum_aggregate_exports_no_start_timestamp_of_its_own() { let mut histogram = sample_histogram(2.0, 3.0, vec![2.0]); histogram.start_timestamp = Some(1_234); @@ -3372,10 +3765,17 @@ mod tests { NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None); accumulator.push_histogram(histogram, 1).unwrap(); + // The answer is a derived histogram, not the sample that was pushed: it is read out of the + // fold the way the native kernel reads one, and that clears the timestamp along with the + // empty buckets it compacts away. The sample's own timestamp stays inside the fold. assert_eq!( - accumulator.value.unwrap().start_timestamp, - Some(1_234), - "the first sample is passed through untouched, so its start timestamp survives" + accumulator + .state_histogram() + .unwrap() + .unwrap() + .start_timestamp, + None, + "a derived sum carries no start timestamp, not even from a single sample" ); } @@ -3392,7 +3792,11 @@ mod tests { accumulator.push_histogram(second, 1).unwrap(); assert_eq!( - accumulator.value.unwrap().start_timestamp, + accumulator + .state_histogram() + .unwrap() + .unwrap() + .start_timestamp, None, "a derived sum carries no start timestamp of its own" ); @@ -3420,6 +3824,109 @@ mod tests { assert!(!values.value(0)); } + /// The one sample the two tests below fold: one bucket holding observations and one explicit + /// empty bucket beside it. + /// + /// The answer keeps the bucket with observations and drops the empty one, which is a difference + /// [`NativeHistogramEq`] can tell apart from the input. + fn one_explicit_zero_bucket() -> NativeHistogram { + sample_histogram(1.0, 1.0, vec![1.0, 0.0]) + } + + /// A `sum` or `avg` over one sample answers `[1]` where the sample carried `[1, 0]`. + /// + /// The comparison change is intended. The answer is the fold's, not the sample's: + /// [`finished_histogram`] compacts the empty bucket away, and the native `Aggregate` node reads + /// its answers through that same function, so both paths answer `[1]` -- a one-sample group + /// included. `promql_eq` tells an explicit zero bucket from an absent one (see + /// [`comparison_observes_explicit_sparse_zero_buckets`]), so `sum(h)` is no longer equal to the + /// single sample `h` it folded. + #[test] + fn sum_and_avg_compact_a_single_samples_explicit_zero_bucket() { + for kind in [ + NativeHistogramAggregateKind::Sum, + NativeHistogramAggregateKind::Avg, + ] { + let mut aggregate = NativeHistogramAggregateAccumulator::new(kind, None); + aggregate + .push_histogram(one_explicit_zero_bucket(), 1) + .unwrap(); + + // The answer the state hands over is where the bucket list is decided. + let answered = aggregate + .state_histogram() + .unwrap() + .expect("a single sample answers"); + assert_eq!( + answered.positive_buckets, + vec![1.0], + "{}: the empty bucket is compacted away", + kind.name() + ); + assert_eq!(answered.count, 1.0, "{}: the count", kind.name()); + assert_eq!(answered.sum, 1.0, "{}: the sum", kind.name()); + + let evaluated = evaluated_histogram(&mut aggregate); + assert_eq!( + evaluated.positive_buckets, + vec![1.0], + "{}: reading the answer back keeps the empty bucket out", + kind.name() + ); + } + } + + /// A partial state round trip answers what the direct evaluation answers: `[1]`. + /// + /// The exported state carries the fold's answer, which has already lost the explicit zero + /// bucket, so merging it into an empty accumulator cannot put the bucket back: a state boundary + /// does not restore what the fold compacted away. The comparison change is the direct + /// evaluation's -- `promql_eq` tells `[1]` from the input's `[1, 0]` -- and it survives the + /// state the same way. + #[test] + fn a_partial_state_round_trip_answers_the_compacted_explicit_zero_bucket() { + for kind in [ + NativeHistogramAggregateKind::Sum, + NativeHistogramAggregateKind::Avg, + ] { + let mut direct = NativeHistogramAggregateAccumulator::new(kind, None); + direct + .push_histogram(one_explicit_zero_bucket(), 1) + .unwrap(); + let evaluated = evaluated_histogram(&mut direct); + + let state = state_arrays(&mut direct); + let mut merged = NativeHistogramAggregateAccumulator::new(kind, None); + merged.merge_batch(&state).unwrap(); + let round_tripped = evaluated_histogram(&mut merged); + + assert_eq!( + round_tripped.positive_buckets, + vec![1.0], + "{}: the round trip keeps the empty bucket out", + kind.name() + ); + assert_eq!( + round_tripped.positive_buckets, + evaluated.positive_buckets, + "{}: the round trip answers the direct buckets", + kind.name() + ); + assert_eq!( + round_tripped.count, + evaluated.count, + "{}: the round trip answers the direct count", + kind.name() + ); + assert_eq!( + round_tripped.sum, + evaluated.sum, + "{}: the round trip answers the direct sum", + kind.name() + ); + } + } + #[test] fn unary_minus_returns_gauge_histogram() { let result = run_histogram_udf( @@ -3535,7 +4042,9 @@ mod tests { fn histogram_average_rejects_sample_count_overflow() { let mut aggregate = NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None); - aggregate.value = Some(sample_histogram(1.0, 1.0, vec![1.0])); + aggregate + .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1) + .unwrap(); aggregate.count = u64::MAX; let error = aggregate @@ -3544,6 +4053,219 @@ mod tests { assert!(error.to_string().contains("sample count overflow")); } + /// The legacy frame and the canonical fold answer the same thing, bit for bit. + /// + /// The same inputs are folded twice: once through the legacy accumulator, whose state frame is + /// the Arrow partial a distributed aggregate hands over, and once through the kernel's own + /// [`HistogramAccumulator`], whose `payload` is the canonical partial state. The frame declares + /// one native histogram, an average's count and three Booleans, so what it can carry is the + /// fold's *answer* -- `finished_histogram`, the running sum with its compensation folded in or + /// the average's mean -- and that is what it is compared on. The count and the evidence are + /// compared against the payload, which is where they come from, and a state boundary is then + /// expected to keep the answer: merging an exported state into an empty accumulator answers + /// what the accumulator that exported it answered. + #[test] + fn legacy_state_carries_the_canonical_histogram_fold() { + for (case, inputs) in aggregate_agreement_cases() { + let samples = inputs + .iter() + .map(|histogram| float_histogram(histogram).unwrap()) + .collect::>(); + for kind in [ + NativeHistogramAggregateKind::Sum, + NativeHistogramAggregateKind::Avg, + ] { + let op = match kind { + NativeHistogramAggregateKind::Sum => AggregateOp::Sum, + NativeHistogramAggregateKind::Avg => AggregateOp::Avg, + }; + let mut legacy = NativeHistogramAggregateAccumulator::new(kind, None); + for histogram in &inputs { + legacy.push_histogram(histogram.clone(), 1).unwrap(); + } + let frame = legacy_state(&mut legacy); + let fold = canonical_fold(op, &samples); + let StatePayload::Histogram(payload) = fold.payload(op).unwrap() else { + panic!("{case}: the canonical fold exported a non-histogram payload"); + }; + + // The three Booleans of the frame are the payload's own evidence. + assert_eq!(frame.dropped, payload.poisoned, "{case}: poisoned"); + assert_eq!( + frame.counter_reset_seen, payload.counter_reset_seen, + "{case}: counter reset seen" + ); + assert_eq!( + frame.not_counter_reset_seen, payload.not_counter_reset_seen, + "{case}: not-counter-reset seen" + ); + assert_eq!( + legacy.evidence.poisoned, payload.poisoned, + "{case}: poisoned evidence" + ); + assert_eq!( + legacy.evidence.incompatible_layout, payload.incompatible_layout, + "{case}: incompatible layout" + ); + + // The count the frame declares is the samples it folded, as a `UInt64` -- except + // on a dropped position, whose count goes with its answer. + if kind.needs_count() { + let folded = if frame.dropped { + 0 + } else { + inputs.len() as u64 + }; + assert_eq!(frame.count, Some(folded), "{case}: count"); + assert_eq!( + frame.count.map(|count| count as f64), + Some(payload.count), + "{case}: payload count" + ); + } else { + assert_eq!(frame.count, None, "{case}: a sum declares no count"); + } + + // The histogram component is the fold's answer, bit for bit. + let answer = finished_histogram(op, &fold).unwrap(); + match (&frame.histogram, &answer) { + (Some(actual), Some(expected)) => assert_frame_carries(actual, expected, case), + (None, None) => {} + _ => panic!( + "{case}: the frame and the fold disagree on whether the point answers" + ), + } + + // A state boundary keeps that answer. + let mut merged = NativeHistogramAggregateAccumulator::new(kind, None); + merged.merge_batch(&state_arrays(&mut legacy)).unwrap(); + let merged = evaluated(&mut merged); + let direct = evaluated(&mut legacy); + match (merged, direct) { + (Some(merged), Some(direct)) => assert_frame_carries( + &merged, + &float_histogram(&direct).unwrap(), + &format!("{case}, merged"), + ), + (None, None) => {} + _ => panic!("{case}: a merged state answers where its source did not"), + } + } + } + } + + /// The compensated sum's residual belongs to the state, not to one partition's fold. + /// + /// `1e16 + 1 - 1e16` answers `1` only because the Kahan compensation carries what the running sum + /// lost. The legacy frame has no compensation component, so it carries the answer instead: a + /// merge of the exported state answers `1` too, which a frame exporting the running sum could + /// not do. + /// + /// The guarantee stops at samples already folded into one position. Splitting those same samples + /// across two partitions loses the residual, because exporting folds the compensation back into + /// a single `f64`: `[1e16, 1]` exports `1e16`, and merging it with `[-1e16]` answers `0`. + #[test] + fn legacy_state_keeps_the_compensated_sum() { + let mut aggregate = + NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None); + for histogram in [ + sample_histogram(1.0, 1.0e16, vec![1.0e16]), + sample_histogram(1.0, 1.0, vec![1.0]), + sample_histogram(1.0, -1.0e16, vec![-1.0e16]), + ] { + aggregate.push_histogram(histogram, 1).unwrap(); + } + let direct = evaluated_histogram(&mut aggregate); + assert_eq!(direct.count, 3.0); + assert_eq!(direct.sum, 1.0); + assert_eq!(direct.positive_buckets, vec![1.0]); + + let state = state_arrays(&mut aggregate); + let mut merged = + NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None); + merged.merge_batch(&state).unwrap(); + let merged = evaluated_histogram(&mut merged); + assert_eq!(merged.count, 3.0); + assert_eq!(merged.sum, 1.0); + assert_eq!(merged.positive_buckets, vec![1.0]); + } + + /// The inputs the two accumulators are compared on: two exponential resolutions, two custom + /// layouts with different bounds, exponential meeting custom, and a compensated sum whose + /// residual lives in the compensation alone. + fn aggregate_agreement_cases() -> Vec<(&'static str, Vec)> { + let mut coarse = sample_histogram(2.0, 3.0, vec![1.0, 1.0]); + coarse.schema = 2; + coarse.reset_hint = NOT_COUNTER_RESET_HINT; + let mut fine = sample_histogram(1.0, 1.0, vec![1.0]); + fine.reset_hint = COUNTER_RESET_HINT; + + let mut custom = sample_histogram(2.0, 3.0, vec![1.0, 1.0, 0.0]); + custom.schema = CUSTOM_BUCKETS_SCHEMA; + custom.custom_values = vec![1.0, 2.0, 3.0]; + let mut narrower = sample_histogram(2.0, 5.0, vec![1.0, 1.0]); + narrower.schema = CUSTOM_BUCKETS_SCHEMA; + narrower.custom_values = vec![2.0, 3.0]; + + let mut custom_only = sample_histogram(1.0, 1.0, vec![1.0]); + custom_only.schema = CUSTOM_BUCKETS_SCHEMA; + custom_only.custom_values = vec![1.0]; + + vec![ + ( + "two exponential resolutions", + vec![fine, coarse.clone(), coarse], + ), + ( + "custom bounds reconciled", + vec![custom, narrower.clone(), narrower], + ), + ( + "exponential meeting custom", + vec![ + sample_histogram(1.0, 1.0, vec![1.0]), + custom_only, + sample_histogram(1.0, 1.0, vec![1.0, 1.0]), + ], + ), + ( + "compensated sum", + vec![ + sample_histogram(1.0, 1.0e16, vec![1.0e16]), + sample_histogram(1.0, 1.0, vec![1.0]), + sample_histogram(1.0, -1.0e16, vec![-1.0e16]), + ], + ), + ] + } + + /// One case's inputs folded through the kernel's own accumulator, as `fold_histogram` folds + /// them: reset evidence per sample, and a layout disagreement poisoning the position instead of + /// failing it. + fn canonical_fold(op: AggregateOp, samples: &[FloatHistogram]) -> HistogramAccumulator { + let mut fold = HistogramAccumulator::from_sample(&samples[0]); + for sample in samples { + fold.evidence.counter_reset_seen |= sample.reset_hint == CounterResetHint::CounterReset; + fold.evidence.not_counter_reset_seen |= + sample.reset_hint == CounterResetHint::NotCounterReset; + } + for sample in &samples[1..] { + if fold.evidence.poisoned { + break; + } + if fold.uses_custom_buckets() != sample.uses_custom_buckets() { + fold.poison(); + break; + } + match op { + AggregateOp::Sum => fold.fold_sum(sample).unwrap(), + AggregateOp::Avg => fold.fold_avg(sample).unwrap(), + op => unreachable!("{op:?} does not fold a histogram payload"), + } + } + fold + } + #[test] fn presence_only_range_functions_preserve_null_semantics() { let first = sample_histogram(1.0, 1.0, vec![1.0]); @@ -3788,7 +4510,7 @@ mod tests { aggregate.push_histogram(histogram, 1).unwrap(); } - assert!(aggregate.dropped_incompatible); + assert!(aggregate.evidence.poisoned); let warnings = collected_warnings(&collector); assert!(warnings.contains(&format!( "{}: dropped native histogram aggregate with incompatible schemas", @@ -3833,7 +4555,7 @@ mod tests { merged.merge_batch(first).unwrap(); merged.merge_batch(second).unwrap(); - assert!(merged.dropped_incompatible); + assert!(merged.evidence.poisoned); assert!(collected_warnings(&collector).contains(&format!( "{}: native histogram counter reset hints contradict", kind.name() @@ -3874,19 +4596,17 @@ mod tests { #[test] fn histogram_aggregate_accumulator_accounts_for_heap_allocations() { let histogram = sample_histogram(3.0, 3.0, vec![1.0, 2.0]); - let heap_size = histogram.custom_values.capacity() * size_of::() - + histogram.positive_spans.capacity() * size_of::() - + histogram.negative_spans.capacity() * size_of::() - + histogram.positive_buckets.capacity() * size_of::() - + histogram.negative_buckets.capacity() * size_of::(); + let sample = float_histogram(&histogram).unwrap(); let mut accumulator = NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None); let empty_size = accumulator.size(); accumulator.push_histogram(histogram, 1).unwrap(); - assert!(heap_size > 0); - assert_eq!(accumulator.size(), empty_size + heap_size); + // The fold keeps the sample's buckets and a compensation carrying the same layout, so at + // least the sample's own heap is counted beyond the accumulator struct that holds it. + assert!(sample.heap_bytes() > 0); + assert!(accumulator.size() >= empty_size + sample.heap_bytes()); } #[test]