diff --git a/docs/rfcs/2026-08-04-native-histograms.md b/docs/rfcs/2026-08-04-native-histograms.md index cc31a8df5e4..f35578214ca 100644 --- a/docs/rfcs/2026-08-04-native-histograms.md +++ b/docs/rfcs/2026-08-04-native-histograms.md @@ -309,16 +309,25 @@ reconciled according to their shared bounds. The only layout bypass is local to counter rate: when the first-to-second pair is a reset, the first sample's layout is irrelevant and the second sample starts the accumulated segment. -`avg` and `avg_over_time` use a mergeable weighted running mean. This prevents a -finite mean from becoming infinity solely because the intermediate sum -overflowed. Native-histogram aggregates are not currently split into datanode -partial aggregation and frontend state merging, so this state does not cross -nodes or versions. If distributed stepping is added later, its state must be -versioned before rolling upgrades can safely mix implementations. +`sum` and `sum_over_time` add histogram counts, sums and buckets with Kahan +compensation. `avg` and `avg_over_time` use the same compensated sum and switch +to a running mean if the trial sum has an infinite count, sum, bucket count, or +custom bound. For three one-observation histograms with a single custom bound of +`0` and sums of `1e16`, `1`, and `-1e16`, the sum field of `sum_over_time` is +`1` and the sum field of `avg_over_time` is `1/3`. With a custom bound of +`-Inf`, the running mean gives a sum field of approximately `-1/6`. -The rejected alternative is Prometheus's direct-sum/Kahan-compensation design -with an overflow-triggered mode change. It offers closer rounding parity but -requires additional state and substantially more merge logic. +The range functions follow Prometheus v3.15.0 at floating-point limits. For +110 identical histogram sums at the largest finite `f64`, the final correction +in `avg_over_time` yields `+Inf`. When `sum_over_time` widens an exponential +zero bucket in two passes, it carries the first pass's rounding correction into +the second. At counts above `2^53`, the zero-bucket count can exceed the total +even when all observations fall in the widened bucket. + +The native PromQL aggregate carries compensation in its partial state. The +legacy aggregate folds the correction into its result before exporting each +partial state. For example, a partition containing `1e16` and `1` exports +`1e16`. Merging that partial sum with `-1e16` yields `0`. ## Equality, changes, and resets @@ -378,7 +387,7 @@ boundary already recorded in Compatibility coverage includes protocol rejection, OTLP scale conversion and partial-success behavior, kind exclusivity, stale-marker selector semantics, synthetic-zero rates, incompatible empty -layouts, overflow-safe averages, layout-sensitive equality, infinite custom +layouts, average behavior at overflow, layout-sensitive equality, infinite custom midpoints, and exponential overflow indices for schemas `-4`, `0`, and `8`. Behavioral coverage also verifies frontend PromQL warning and info responses, sampled Remote Read before and after flush in standalone and distributed @@ -401,8 +410,7 @@ a new configuration option; existing native-histogram data remains readable. - Start-timestamp overlap annotations. - Datanode-to-frontend PromQL annotation propagation. - Versioned two-phase native-histogram aggregation state. -- Exact Prometheus summation compensation if measured precision differences - justify the extra aggregate state. +- Preserve summation compensation across legacy aggregate partial-state merges. ## Configuration migration diff --git a/src/promql/benches/bench_range_fn.rs b/src/promql/benches/bench_range_fn.rs index 51e0aefdc79..6b8ce19f5dc 100644 --- a/src/promql/benches/bench_range_fn.rs +++ b/src/promql/benches/bench_range_fn.rs @@ -16,6 +16,9 @@ use std::sync::Arc; +use common_query::native_histogram::{ + GAUGE_RESET_HINT, NativeHistogram, Span, build_histogram_array, native_histogram_arrow_type, +}; use criterion::{BenchmarkId, Criterion, criterion_group}; use datafusion::arrow::array::{Array, Float64Array, TimestampMillisecondArray}; use datafusion::arrow::datatypes::TimeUnit; @@ -27,8 +30,8 @@ use datatypes::arrow::datatypes::{DataType, Field}; use promql::extension_plan::RangeManipulateStream; use promql::functions::{ AbsentOverTime, Changes, CountOverTime, Delta, DoubleExponentialSmoothing, IDelta, Increase, - LastOverTime, MaxOverTime, MinOverTime, PredictLinear, PresentOverTime, QuantileOverTime, Rate, - Resets, SumOverTime, + LastOverTime, MaxOverTime, MinOverTime, NativeHistogramAvgOverTime, NativeHistogramSumOverTime, + PredictLinear, PresentOverTime, QuantileOverTime, Rate, Resets, SumOverTime, }; use promql::range_array::RangeArray; @@ -306,6 +309,10 @@ struct PreparedUdfCall { impl PreparedUdfCall { fn new(args: Vec) -> Self { + Self::with_return_type(args, DataType::Float64) + } + + fn with_return_type(args: Vec, return_type: DataType) -> Self { let arg_fields = args .iter() .enumerate() @@ -322,7 +329,7 @@ impl PreparedUdfCall { args, arg_fields, number_rows, - return_field: Arc::new(Field::new("out", DataType::Float64, true)), + return_field: Arc::new(Field::new("out", return_type, true)), config_options: Arc::new(ConfigOptions::default()), } } @@ -346,6 +353,164 @@ fn invoke_prepared(udf: &datafusion::logical_expr::ScalarUDF, prepared: &Prepare let _ = invoke_prepared_output(udf, prepared); } +fn bench_sparse_histogram_ranges(c: &mut Criterion) { + let sample = NativeHistogram { + schema: 8, + zero_threshold: 0.0, + sum: 1.0, + reset_hint: GAUGE_RESET_HINT, + start_timestamp: None, + custom_values: vec![], + positive_spans: vec![ + Span { + offset: 0, + length: 1, + }, + Span { + offset: 1, + length: 1, + }, + ], + negative_spans: vec![], + count: 1.0, + zero_count: 0.0, + positive_buckets: vec![1.0, 0.0], + negative_buckets: vec![], + }; + for (name, udf) in [ + ( + "sparse_histogram_avg_over_time", + NativeHistogramAvgOverTime::scalar_udf(), + ), + ( + "sparse_histogram_sum_over_time", + NativeHistogramSumOverTime::scalar_udf(), + ), + ] { + let mut group = c.benchmark_group(name); + let mut bench = |label: &str, values: Vec>| { + let length = u32::try_from(values.len()).unwrap(); + let range = [(0, length)]; + let ts = Arc::new(TimestampMillisecondArray::from_iter_values( + (1..=length).map(|i| i64::from(i) * 1000), + )); + let ts = Arc::new(RangeArray::from_ranges(ts, range).unwrap().into_dict()); + let values = RangeArray::from_ranges(build_histogram_array(&values), range).unwrap(); + let call = PreparedUdfCall::with_return_type( + vec![ + ColumnarValue::Array(ts), + ColumnarValue::Array(Arc::new(values.into_dict())), + ], + native_histogram_arrow_type(), + ); + group.bench_with_input(BenchmarkId::new(label, length), &call, |b, call| { + b.iter(|| invoke_prepared(&udf, call)); + }); + }; + // The same 128 observations at two resolutions, with each gap encoded as zero counts. + let packed = |schema, pattern: &[f64]| { + let buckets = pattern.repeat(128); + NativeHistogram { + schema, + positive_spans: vec![Span { + offset: 1, + length: buckets.len() as i32, + }], + positive_buckets: buckets, + count: 128.0, + sum: (1..=512) + .step_by(4) + .map(|idx| 2f64.powf(f64::from(idx) / 256.0)) + .sum(), + ..sample.clone() + } + }; + let fine = packed(8, &[1.0, 0.0, 0.0, 0.0]); + let coarse = packed(7, &[1.0, 0.0]); + for (label, coarse_at) in [ + ("packed_empty_buckets", None), + ("packed_empty_buckets_last_downscale", Some(511)), + ("packed_empty_buckets_finer_tail", Some(0)), + ] { + let mut values = vec![Some(fine.clone()); 512]; + if let Some(index) = coarse_at { + values[index] = Some(coarse.clone()); + } + bench(label, values); + } + for length in [4096, 8192] { + bench( + "fixed_empty_bucket", + vec![Some(sample.clone()); length as usize], + ); + let mut moving = |label, schema: &dyn Fn(u32) -> i32| { + let values = (0..length).map(|i| { + let mut h = sample.clone(); + h.schema = schema(i); + h.positive_spans[1].offset = i as i32 + 1; + Some(h) + }); + bench(label, values.collect()); + }; + for (label, fine_prefix) in [ + ("moving_empty_bucket", length), + ("moving_empty_bucket_after_downscale", 1), + ("moving_empty_bucket_middle_downscale", length / 2), + ("moving_empty_bucket_last_downscale", length - 1), + ] { + moving(label, &|i| if i < fine_prefix { 8 } else { 7 }); + } + moving("moving_empty_bucket_alternating_schema", &|i| { + 8 - (i % 2) as i32 + }); + + // Revisit an interior zero of a populated accumulator before a final downscale. + let width = 512; + let gap = width / 2; + let mut first = NativeHistogram { + positive_spans: vec![Span { + offset: 0, + length: width, + }], + positive_buckets: vec![1.0; width as usize], + count: f64::from(width - 1), + sum: (0..width) + .filter(|&idx| idx != gap) + .map(|idx| 2f64.powf(f64::from(idx) / 256.0)) + .sum(), + ..sample.clone() + }; + first.positive_buckets[gap as usize] = 0.0; + let mut sparse = sample.clone(); + sparse.positive_spans[1].offset = gap - 1; + let last = NativeHistogram { + schema: 7, + ..sparse.clone() + }; + let values = std::iter::once(Some(first)) + .chain(std::iter::repeat_n(Some(sparse), length as usize - 2)) + .chain([Some(last)]); + bench("populated_with_interior_empty_bucket", values.collect()); + + // idelta of one observation moving to the next exponential bucket at each step. + let deltas = (0..length).map(|i| { + Some(NativeHistogram { + sum: 2f64.powf(f64::from(i + 1) / 256.0) - 2f64.powf(f64::from(i) / 256.0), + count: 0.0, + positive_spans: vec![Span { + offset: i as i32, + length: 2, + }], + positive_buckets: vec![-1.0, 1.0], + ..sample.clone() + }) + }); + bench("moving_idelta", deltas.collect()); + } + group.finish(); + } +} + fn edge_count_oracle( values: &[f64], ranges: &[(u32, u32)], @@ -1251,6 +1416,7 @@ fn bench_cursor_scan_carriers(c: &mut Criterion) { criterion_group!( benches, bench_range_functions, + bench_sparse_histogram_ranges, bench_presence_range_functions, bench_delta_rate_comparison, bench_rate_window_steps, diff --git a/src/promql/src/functions/native_histogram.rs b/src/promql/src/functions/native_histogram.rs index e75302b7df9..1412cf3961c 100644 --- a/src/promql/src/functions/native_histogram.rs +++ b/src/promql/src/functions/native_histogram.rs @@ -46,7 +46,7 @@ use crate::functions::{ SumOverTime, extract_array, extract_range_dict, }; use crate::histogram_eval::float_histogram::FloatHistogram; -use crate::histogram_eval::legacy_bridge; +use crate::histogram_eval::{self, HistogramAggregate, legacy_bridge}; use crate::range_array::{RangeArray, unpack}; fn extract_histogram_array(value: &ColumnarValue, func_name: &str) -> DfResult { @@ -1202,26 +1202,40 @@ fn spans_and_counts(buckets: &[(i32, f64)]) -> (Vec, Vec) { (spans, counts) } -fn weighted_histogram_mean( - left: NativeHistogram, - left_count: u64, - right: NativeHistogram, - right_count: u64, - total_count: u64, -) -> Option { - let total_count = total_count as f64; - legacy_bridge::add( - &legacy_bridge::scale(&left, left_count as f64 / total_count), - &legacy_bridge::scale(&right, right_count as f64 / total_count), - ) +/// The last addition that reduces either operand's exponential resolution, or zero if none. +/// The fold stops at the first switch between exponential and custom buckets. Unsupported +/// schemas keep their explicit buckets for validation. +fn range_last_rebin(samples: &[NativeHistogram]) -> Option { + let mut schema = samples.first()?.schema; + if schema == CUSTOM_BUCKETS_SCHEMA { + return Some(0); + } + exponential_overflow_bucket_index(schema)?; + let mut last = 0; + for (index, sample) in samples.iter().enumerate().skip(1) { + if sample.schema == schema { + continue; + } + if sample.schema == CUSTOM_BUCKETS_SCHEMA { + break; + } + exponential_overflow_bucket_index(sample.schema)?; + schema = schema.min(sample.schema); + last = index; + } + Some(last) } fn range_fold_histograms( - samples: Vec, - kind: NativeHistogramAggregateKind, + mut samples: Vec, + kind: HistogramAggregate, name: &'static str, collector: &Option, ) -> Option { + // A single legacy sample retains its start timestamp and explicit zero buckets. + if samples.len() <= 1 { + return samples.pop(); + } if samples .iter() .any(|histogram| histogram.reset_hint == COUNTER_RESET_HINT) @@ -1232,37 +1246,30 @@ fn range_fold_histograms( record_counter_reset_contradiction_warning(collector, name); } - let mut value = None; - let mut count = 0u64; - for histogram in samples { - value = match value { - Some(value) => { - record_custom_reconciliation(collector, name, &value, &histogram); - let next_count = count.checked_add(1)?; - let combined = match kind { - NativeHistogramAggregateKind::Sum => legacy_bridge::add(&value, &histogram), - NativeHistogramAggregateKind::Avg => { - weighted_histogram_mean(value, count, histogram, 1, next_count) - } - }; - match combined { - Some(value) => Some(value), - None => { - record_warning( - collector, - format!( - "{name}: dropped native histogram range with incompatible schemas" - ), - ); - return None; - } - } - } - None => Some(histogram), - }; - count = count.checked_add(1)?; + let last_rebin = range_last_rebin(&samples); + let mut remaining = samples.iter(); + let histograms = remaining.by_ref().map(legacy_bridge::float_histogram); + let (histogram, reconciled) = histogram_eval::sum_or_avg(kind, histograms, last_rebin) + .unwrap_or_else(|_| { + // Legacy checked both operands' bounds before decoding even the first pair. + let attempted = (samples.len() - remaining.len()).max(2); + let reconciled = samples[..attempted] + .windows(2) + .any(|pair| pair[0].needs_custom_reconciliation(&pair[1])); + (None, reconciled) + }); + if reconciled { + record_reconciled_custom_buckets(collector, name); } - value + let Some(mut histogram) = histogram else { + record_warning( + collector, + format!("{name}: dropped native histogram range with incompatible schemas"), + ); + return None; + }; + histogram.compact(); + Some(legacy_bridge::legacy_histogram(&histogram)) } #[derive(Debug, Clone, Copy)] @@ -1354,18 +1361,12 @@ fn native_histogram_range_histogram( continue; }; let histogram = match kind { - NativeHistogramRangeHistogramKind::Sum => range_fold_histograms( - samples, - NativeHistogramAggregateKind::Sum, - func_name, - &collector, - ), - NativeHistogramRangeHistogramKind::Avg => range_fold_histograms( - samples, - NativeHistogramAggregateKind::Avg, - func_name, - &collector, - ), + NativeHistogramRangeHistogramKind::Sum => { + range_fold_histograms(samples, HistogramAggregate::Sum, func_name, &collector) + } + NativeHistogramRangeHistogramKind::Avg => { + range_fold_histograms(samples, HistogramAggregate::Avg, func_name, &collector) + } NativeHistogramRangeHistogramKind::Last => samples.last().cloned(), }; result.push(histogram); @@ -3977,6 +3978,320 @@ mod tests { assert_eq!(result.positive_buckets, vec![2.0]); } + #[test] + fn range_folds_preserve_singletons_and_compact_combined_buckets() { + let mut sample = one_explicit_zero_bucket(); + sample.reset_hint = GAUGE_RESET_HINT; + sample.start_timestamp = Some(100); + // Both buckets cancel. Only the first has a correction when compaction runs. + let window: Vec<_> = (1..) + .zip([(1e16, 1.0), (1.0, 0.0), (-1e16, -1.0), (0.0, 0.0)]) + .map(|(offset, (count, adjacent))| NativeHistogram { + count: count + adjacent, + sum: count, + positive_spans: vec![ + Span { + offset: 0, + length: 2, + }, + Span { offset, length: 1 }, + ], + positive_buckets: vec![count, adjacent, 0.0], + ..sample.clone() + }) + .collect(); + for (udf, expected_bucket) in [ + (NativeHistogramSumOverTime::scalar_udf(), 1.0), + (NativeHistogramAvgOverTime::scalar_udf(), 0.25), + ] { + let single = run_histogram_range_udf(udf.clone(), vec![sample.clone()]); + assert_eq!(single, sample); + + let combined = run_histogram_range_udf(udf, window.clone()); + assert_eq!(combined.positive_buckets, vec![expected_bucket]); + assert_eq!(combined.start_timestamp, None); + } + } + + #[test] + fn range_folds_keep_the_correction_at_every_downscale_position() { + for schemas in [ + [8, 7, 7, 7, 7], + [8, 8, 7, 7, 7], + [8, 8, 8, 8, 7], + [8, 7, 8, 7, 8], + ] { + let samples: Vec<_> = schemas + .into_iter() + .zip([1e16, 1.0, -1e16, 0.0, 0.0]) + .zip(1..) + .map(|((schema, count), gap)| NativeHistogram { + schema, + reset_hint: GAUGE_RESET_HINT, + positive_spans: vec![ + Span { + offset: 0, + length: 1, + }, + Span { + offset: gap, + length: 1, + }, + ], + ..sample_histogram(count, count, vec![count, 0.0]) + }) + .collect(); + + for (op, expected) in [ + (HistogramAggregate::Sum, 1.0), + (HistogramAggregate::Avg, 0.2), + ] { + let (value, _) = histogram_eval::sum_or_avg( + op, + samples.iter().map(legacy_bridge::float_histogram), + range_last_rebin(&samples), + ) + .unwrap(); + // Before the caller compacts the result, only the bucket with the correction survives. + assert_eq!( + value.unwrap().positive, + [(0, expected)], + "{op:?} {schemas:?}" + ); + } + } + } + + #[test] + fn sparse_range_average_copies_linearly_across_schema_changes() { + use crate::histogram_eval::float_histogram::copies::take_cloned_buckets; + + let check = |window: Vec, expected| { + let len = window.len(); + let input = histogram_range_input(window.into_iter().map(Some).collect()); + take_cloned_buckets(); + let avg = mixed_histogram_result(NativeHistogramAvgOverTime::scalar_udf(), input); + let copied = take_cloned_buckets(); + assert_eq!(avg.map(|h| h.positive_buckets), expected); + // A downscale can copy the whole prefix once. Repeating that copy would be quadratic. + assert!( + copied <= 8 * len, + "{copied} buckets copied for {len} samples" + ); + }; + let mut custom = NativeHistogram { + schema: CUSTOM_BUCKETS_SCHEMA, + custom_values: (1..32).map(f64::from).collect(), + ..sample_histogram(1.0, 1.0, vec![0.0; 32]) + }; + custom.positive_buckets[0] = 1.0; + let length = 256; + for first_coarse in [1, length / 2, length - 1, length] { + let mut samples: Vec<_> = (0..length) + .map(|i| NativeHistogram { + schema: if i < first_coarse { 8 } else { 7 }, + positive_spans: vec![ + Span { + offset: 0, + length: 1, + }, + Span { + offset: i + 1, + length: 1, + }, + ], + ..sample_histogram(1.0, 1.0, vec![1.0, 0.0]) + }) + .collect(); + check(samples.clone(), Some(vec![1.0])); + samples.push(custom.clone()); + check(samples, None); + } + check( + vec![ + custom.clone(), + custom, + sample_histogram(1.0, 1.0, vec![1.0]), + ], + None, + ); + } + + #[test] + fn range_sum_preserves_empty_buckets_when_reducing_the_accumulator() { + for (prefix, expected) in [ + (vec![0.0, 0.0, 0.0, 1e16], 10_000_000_000_000_002.0), + (vec![1e16], 10_000_000_000_000_004.0), + ] { + let mut first = sample_histogram(1e16, 1e16, prefix); + first.schema = 2; + first.positive_spans[0].offset = 1 - first.positive_spans[0].length; + let one = NativeHistogram { + schema: 2, + ..sample_histogram(1.0, 1.0, vec![1.0]) + }; + let count = 1.0_f64.next_down(); + let last = sample_histogram(count, count, vec![count]); + let mut window = vec![first, one.clone(), one, last]; + // Index 0 has a correction of 2. An earlier empty index in its new bucket changes + // when that correction is added. Mirror both sides to exercise both layouts. + for h in &mut window { + h.negative_spans.clone_from(&h.positive_spans); + h.negative_buckets.clone_from(&h.positive_buckets); + h.count *= 2.0; + h.sum = 0.0; + } + let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window); + assert_eq!(sum.positive_buckets, [expected]); + assert_eq!(sum.negative_buckets, [expected]); + } + } + + #[test] + fn widening_the_zero_bucket_discards_previous_empty_positions() { + let mut fine = sample_histogram(1e16 + 2.0, 5.5e16, vec![1e16, 1.0, 1.0]); + fine.schema = 2; + fine.positive_spans[0].offset = 9; + let count = 1.0_f64.next_down(); + let mut last = sample_histogram(count, 6.0 * count, vec![count]); + last.positive_spans[0].offset = 3; + // The second case widens indirectly: the incoming (1, 2] bucket straddles 1.5. + let mut crossing = sample_histogram(1.0, 1.75, vec![1.0]); + crossing.positive_spans[0].offset = 1; + let direct = NativeHistogram { + zero_threshold: 0.5, + ..sample_histogram(0.0, 0.0, vec![]) + }; + for (threshold, wider) in [(0.0, direct), (1.5, crossing)] { + let mut empty = sample_histogram(0.0, 0.0, vec![0.0]); + empty.zero_threshold = threshold; + empty.positive_spans[0].offset = 3; + let window = vec![empty.clone(), empty, wider, fine.clone(), last.clone()]; + let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window); + // All three fine indices map to index 3, which the widening removed from the layout. + assert_eq!(sum.positive_buckets, [10_000_000_000_000_004.0]); + } + } + + #[test] + fn range_sum_preserves_an_empty_bucket_in_a_mixed_schema_window() { + let total = 10_000_000_000_000_002.0; + let mut fine = sample_histogram(total, 5.5e15, vec![1e16, 1.0, 1.0]); + fine.schema = 2; + // These three buckets all map to the explicit zero at index 0 of the first sample. + fine.positive_spans[0].offset = -3; + let empty = sample_histogram(0.0, 0.0, vec![0.0]); + let count = 1.0_f64.next_down(); + let last = sample_histogram(count, 0.75 * count, vec![count]); + // Consecutive fine samples still need reduction when the accumulator is coarse. + let empty_fine = NativeHistogram { + schema: 2, + ..empty.clone() + }; + let last_fine = NativeHistogram { + schema: 2, + ..last.clone() + }; + for window in [ + vec![empty.clone(), fine.clone(), last], + vec![empty, empty_fine, fine, last_fine], + ] { + let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window); + assert_eq!(sum.count, total); + assert_eq!(sum.positive_buckets, vec![total]); + } + } + + #[test] + fn range_avg_preserves_a_cancelled_bucket_in_a_mixed_schema_window() { + let gain = sample_histogram(1.0, 0.75, vec![1.0]); + let loss = legacy_bridge::scale(&gain, -1.0); + let mut fine = sample_histogram( + 10_000_000_000_000_009_i64 as f64, + 5.5e15, + vec![1e16 + 4.0, 2.0, 1.0, 2.0], + ); + fine.schema = 2; + // All four fine buckets merge into the bucket that the two coarse samples cancelled. + fine.positive_spans[0].offset = -3; + let avg = run_histogram_range_udf( + NativeHistogramAvgOverTime::scalar_udf(), + vec![gain, loss, fine], + ); + assert_eq!(avg.positive_buckets, vec![3_333_333_333_333_336.5]); + } + + #[test] + fn range_fold_reports_layout_errors_and_custom_reconciliation() { + let mut first = sample_histogram(2.0, 3.0, vec![1.0, 1.0]); + first.schema = CUSTOM_BUCKETS_SCHEMA; + first.custom_values = vec![1.0, 2.0]; + let mut second = first.clone(); + second.custom_values = vec![2.0]; + let mut invalid = first.clone(); + invalid.positive_spans = vec![ + Span { + offset: 0, + length: 1, + }, + Span { + offset: -1, + length: 1, + }, + ]; + let mut unsupported = sample_histogram(0.0, 0.0, vec![]); + unsupported.schema = -5; + let exponential = sample_histogram(1.0, 1.0, vec![1.0]); + + let name = NativeHistogramSumOverTime::name(); + for (samples, expected_bounds, reconciled) in [ + (vec![first.clone(), second.clone()], Some(vec![2.0]), true), + ( + vec![first.clone(), second.clone(), exponential.clone()], + None, + true, + ), + ( + vec![exponential, first.clone(), second.clone()], + None, + false, + ), + ( + vec![first.clone(), second.clone(), invalid.clone()], + None, + true, + ), + (vec![invalid.clone(), second.clone()], None, true), + (vec![first, invalid, second], None, false), + ( + vec![unsupported, sample_histogram(0.0, 0.0, vec![0.0])], + None, + false, + ), + ] { + let collector = PromqlAnnotationCollector::default(); + let result = range_fold_histograms( + samples, + HistogramAggregate::Sum, + name, + &Some(collector.clone()), + ); + assert_eq!(result.map(|h| h.custom_values), expected_bounds); + assert_eq!( + collected_infos(&collector).contains(&format!( + "{name}: reconciled native histograms with different custom buckets" + )), + reconciled, + ); + assert_eq!( + collected_warnings(&collector).contains(&format!( + "{name}: dropped native histogram range with incompatible schemas" + )), + expected_bounds.is_none(), + ); + } + } + #[test] fn histogram_averages_avoid_sum_overflow() { let large = sample_histogram(1.0e308, 1.0e308, vec![1.0e308]); @@ -3999,6 +4314,100 @@ mod tests { assert_eq!(aggregate_average.positive_buckets, vec![1.0e308]); } + #[test] + fn range_average_preserves_deferred_empty_buckets_when_it_overflows_before_a_downscale() { + let sample = |schema, sum, offset, buckets: Vec| { + let mut h = sample_histogram(2.0 * buckets.iter().sum::(), sum, buckets); + h.schema = schema; + h.positive_spans[0].offset = offset; + h.negative_spans.clone_from(&h.positive_spans); + h.negative_buckets.clone_from(&h.positive_buckets); + h + }; + let tiny = f64::from_bits(1); + let mut first = sample(8, f64::MAX, -1, vec![0.0, 1e16, tiny]); + first.negative_buckets.swap(0, 2); + // At index -1 the positive zero is deferred on sample two. The negative bucket + // underflows to zero when sample three overflows the sum and scales the running mean. + let samples = vec![ + first, + sample(8, 0.0, 0, vec![3.0]), + sample(8, f64::MAX, 0, vec![3.0]), + sample(7, 0.0, 0, vec![f64::EPSILON / 2.0]), + ]; + let (reference, _) = histogram_eval::sum_or_avg( + HistogramAggregate::Avg, + samples.iter().map(legacy_bridge::float_histogram), + None, + ) + .unwrap(); + let mut reference = reference.unwrap(); + reference.compact(); + + let avg = run_histogram_range_udf(NativeHistogramAvgOverTime::scalar_udf(), samples); + assert_eq!(avg, legacy_bridge::legacy_histogram(&reference)); + // Downscaling indices -1 and 0 folds the leading zero before the live bucket's correction. + assert_eq!(avg.positive_buckets, [2_500_000_000_000_001.0]); + assert_eq!(avg.negative_buckets, avg.positive_buckets); + } + + #[test] + fn range_average_matches_prometheus_at_the_largest_finite_sum() { + let mut sample = sample_histogram(1.0, f64::MAX, vec![1.0]); + sample.schema = CUSTOM_BUCKETS_SCHEMA; + sample.custom_values = vec![0.0]; + sample.positive_spans[0].offset = 1; + // Prometheus v3.15.0 overflows when it adds the final correction at 110 samples. + for (length, expected) in [(109, f64::MAX), (110, f64::INFINITY)] { + let avg = run_histogram_range_udf( + NativeHistogramAvgOverTime::scalar_udf(), + vec![sample.clone(); length], + ); + assert_eq!(avg.sum, expected); + } + } + + #[test] + fn range_average_switches_to_a_running_mean_for_an_infinite_custom_bound() { + for (bound, expected) in [(0.0, 1.0 / 3.0), (f64::NEG_INFINITY, -0.16666666666666669)] { + let samples = [1e16, 1.0, -1e16].map(|sum| NativeHistogram { + schema: CUSTOM_BUCKETS_SCHEMA, + custom_values: vec![bound], + positive_spans: vec![Span { + offset: i32::from(sum > bound), + length: 1, + }], + ..sample_histogram(1.0, sum, vec![1.0]) + }); + let avg = + run_histogram_range_udf(NativeHistogramAvgOverTime::scalar_udf(), samples.into()); + assert_eq!(avg.sum, expected); + } + } + + #[test] + fn range_sum_matches_prometheus_when_the_zero_bucket_widens_twice() { + let mut sample = sample_histogram(10_000_000_000_000_005_i64 as f64, -6.0, vec![1.0]); + sample.zero_count = 1e16; + sample.negative_spans = vec![Span { + offset: 1, + length: 1, + }]; + sample.negative_buckets = vec![4.0]; + let mut empty = sample_histogram(0.0, 0.0, vec![]); + empty.zero_threshold = 1.5; + + let sum = run_histogram_range_udf( + NativeHistogramSumOverTime::scalar_udf(), + vec![sample, empty], + ); + assert_eq!(sum.zero_threshold, 2.0); + assert!(sum.positive_buckets.is_empty() && sum.negative_buckets.is_empty()); + // Prometheus v3.15.0 carries the first pass's correction into the second pass. + assert_eq!(sum.count, 10_000_000_000_000_004.0); + assert_eq!(sum.zero_count, 10_000_000_000_000_006.0); + } + #[test] fn histogram_average_partial_states_are_weighted() { let mut first = @@ -4438,7 +4847,7 @@ mod tests { assert!( range_fold_histograms( vec![reset.clone(), unknown.clone(), not_reset.clone()], - NativeHistogramAggregateKind::Sum, + HistogramAggregate::Sum, NativeHistogramSumOverTime::name(), &Some(range_collector.clone()), ) @@ -4564,14 +4973,8 @@ mod tests { } for (kind, name) in [ - ( - NativeHistogramAggregateKind::Sum, - NativeHistogramSumOverTime::name(), - ), - ( - NativeHistogramAggregateKind::Avg, - NativeHistogramAvgOverTime::name(), - ), + (HistogramAggregate::Sum, NativeHistogramSumOverTime::name()), + (HistogramAggregate::Avg, NativeHistogramAvgOverTime::name()), ] { let collector = PromqlAnnotationCollector::default(); assert!( diff --git a/src/promql/src/histogram_eval/aggregate.rs b/src/promql/src/histogram_eval/aggregate.rs index 3abbac8e05c..cb6a4fa43d7 100644 --- a/src/promql/src/histogram_eval/aggregate.rs +++ b/src/promql/src/histogram_eval/aggregate.rs @@ -19,7 +19,7 @@ use datafusion::error::Result; -use crate::histogram_eval::float_histogram::FloatHistogram; +use crate::histogram_eval::float_histogram::{BucketLayout, EmptyBuckets, FloatHistogram}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum HistogramAggregate { @@ -27,95 +27,117 @@ pub(crate) enum HistogramAggregate { Avg, } -/// The Kahan sum or the mean of `histograms` in order, without compaction; `None` when there is -/// none or they mix exponential and custom buckets. The first input error ends the fold. The -/// result has no start timestamp. The flag reports whether any add reconciled two different -/// custom-bucket sets, which Prometheus annotates with an info. +/// The Kahan sum or the mean of `histograms` in order. A compact fold remembers represented +/// zeros through `last_rebin` (zero for a uniform schema). `None` preserves the full layout. +/// Returns `None` for an empty window or a mix of exponential and custom buckets. The first +/// input error ends the fold. The result has no start timestamp. The flag reports whether any +/// add reconciled two different custom-bucket sets, which Prometheus annotates with an info. pub(crate) fn sum_or_avg( op: HistogramAggregate, histograms: impl IntoIterator>, + last_rebin: Option, ) -> Result<(Option, bool)> { - let mut value: Option = None; + let mut histograms = histograms.into_iter(); + let Some(first) = histograms.next() else { + return Ok((None, false)); + }; + let mut value = first?; + if last_rebin == Some(0) { + value.compact(); + } let mut compensation: Option = None; - let mut mean: Option = None; - let mut count = 0.0; + let mut empty = EmptyBuckets::default(); + let mut incremental_mean = false; + let mut count = 1.0; let mut custom_reconciled = false; - for h in histograms { - let h = h?; - count += 1.0; - let Some(current) = value.as_mut() else { - value = Some(h); - continue; - }; - // Go drops the result with a warning for this addition error only; others propagate. - if current.uses_custom_buckets() != h.uses_custom_buckets() { + for (index, h) in histograms.enumerate() { + let mut h = h?; + // A mixed window still reports any custom bounds reconciled before the mismatch. + if value.uses_custom_buckets() != h.uses_custom_buckets() { return Ok((None, custom_reconciled)); } + let index = index + 1; + let layout = if last_rebin.is_some_and(|last| index > last) { + h.compact(); + BucketLayout::Compact + } else { + BucketLayout::Preserve + }; + count += 1.0; + if incremental_mean { + h.div(count); + } + let track_empty = last_rebin.is_some() && layout == BucketLayout::Preserve; + let rebin_value = h.schema < value.schema; + if track_empty && let Some(c) = compensation.as_mut() { + empty.prepare_for_add(&mut value, c, &mut h)?; + } match op { HistogramAggregate::Sum => { - let (c, outcome) = current.kahan_add(&h, compensation.take())?; + let (c, outcome) = value.kahan_add_with_layout(&h, compensation.take(), layout)?; custom_reconciled |= outcome.custom_bounds_reconciled; compensation = Some(c); } HistogramAggregate::Avg => { - if mean.is_none() { - let mut sum = current.clone(); - let (c, outcome) = sum.kahan_add(&h, compensation.clone())?; + if !incremental_mean { + let mut sum = value.clone(); + let (c, outcome) = + sum.kahan_add_with_layout(&h, compensation.clone(), layout)?; custom_reconciled |= outcome.custom_bounds_reconciled; - if !sum.has_overflow() { - *current = sum; + if sum.has_overflow() { + value.div(count - 1.0); + if let Some(c) = compensation.as_mut() { + c.div(count - 1.0); + } + h.div(count); + incremental_mean = true; + } else { + value = sum; compensation = Some(c); - continue; } - let mut started = current.clone(); - started.div(count - 1.0); + } + if incremental_mean { + let q = (count - 1.0) / count; if let Some(c) = compensation.as_mut() { - c.div(count - 1.0); + c.mul(q); } - mean = Some(started); + value.mul(q); + let (mut c, outcome) = value.kahan_add(&h, compensation.take())?; + // Scaling the mean can also empty buckets outside the incoming sample. + if layout == BucketLayout::Compact { + value.compact_with_compensation(&mut c); + } + custom_reconciled |= outcome.custom_bounds_reconciled; + compensation = Some(c); } - // Go switches to an incremental mean once the plain sum overflows. - let q = (count - 1.0) / count; - if let Some(c) = compensation.as_mut() { - c.mul(q); - } - let mut to_add = h; - to_add.div(count); - let mean = mean.as_mut().expect("set above"); - mean.mul(q); - let (c, outcome) = mean.kahan_add(&to_add, compensation.take())?; - custom_reconciled |= outcome.custom_bounds_reconciled; - compensation = Some(c); + } + } + if track_empty && let Some(c) = compensation.as_mut() { + if last_rebin == Some(index) { + value.compact_with_compensation(c); + empty = EmptyBuckets::default(); + } else { + // Copying the first input, reducing the accumulator, and scaling a mean can + // leave zeros anywhere. An ordinary add changes only its input's buckets. + empty.take_from( + &mut value, + c, + &h, + index == 1 || rebin_value || incremental_mean, + ); } } } - let Some(mut value) = value else { - return Ok((None, custom_reconciled)); - }; - match op { - HistogramAggregate::Sum => { - if let Some(c) = compensation { - value.add(&c)?; - } + if op == HistogramAggregate::Avg && !incremental_mean { + value.div(count); + if let Some(c) = compensation.as_mut() { + c.div(count); } - HistogramAggregate::Avg => match mean { - Some(mut mean) => { - if let Some(c) = compensation { - mean.add(&c)?; - } - value = mean; - } - None => { - value.div(count); - if let Some(mut c) = compensation { - c.div(count); - value.add(&c)?; - } - } - }, } - // A single-input fold returns its input unchanged, so clear the start timestamp the adds - // would otherwise have cleared. + if let Some(c) = compensation { + value.add(&c)?; + } + // A single-input fold skips the adds that would clear the start timestamp. value.start_timestamp = None; Ok((Some(value), custom_reconciled)) } diff --git a/src/promql/src/histogram_eval/float_histogram.rs b/src/promql/src/histogram_eval/float_histogram.rs index ab6012931db..cac262c0b9d 100644 --- a/src/promql/src/histogram_eval/float_histogram.rs +++ b/src/promql/src/histogram_eval/float_histogram.rs @@ -17,9 +17,13 @@ //! `CopyToSchema`, `DetectReset` and `Equals`, including zero bucket reconciliation, resolution //! reduction and the intersection of mismatched custom bounds. //! -//! Each side is a list of `(bucket index, count)` sorted by index. Go splices span layouts in -//! place; the bucket indices and the order of additions to each bucket do not depend on the -//! layout, so the results are the same. +//! Each side is a list of `(bucket index, count)` sorted by index. Consecutive indices may share +//! a span. An explicitly represented zero can affect the order of compensated additions when +//! several indices map to one bucket. + +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; +use std::ops::Range; use datafusion::error::{DataFusionError, Result}; use datatypes::series::histogram::{ @@ -30,6 +34,187 @@ use crate::functions::kahan_inc; use crate::histogram_eval::native::{CUSTOM_BUCKETS_SCHEMA, bound}; type Buckets = Vec<(i32, f64)>; +// Only the signs are needed to restore the two zero operands bit for bit. +type EmptySide = BTreeMap; + +/// Whether a fold keeps explicitly represented empty buckets. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum BucketLayout { + Preserve, + Compact, +} + +/// Explicit zero pairs omitted from a range accumulator while a later sample can still rebin it. +#[derive(Default)] +pub(super) struct EmptyBuckets { + positive: EmptySide, + negative: EmptySide, +} + +impl EmptyBuckets { + pub(super) fn take_from( + &mut self, + value: &mut FloatHistogram, + c: &mut FloatHistogram, + sample: &FloatHistogram, + all: bool, + ) { + for (empty, side, correction, incoming) in [ + ( + &mut self.positive, + &mut value.positive, + &mut c.positive, + &sample.positive, + ), + ( + &mut self.negative, + &mut value.negative, + &mut c.negative, + &sample.negative, + ), + ] { + let range = if all { + 0..side.len() + } else if let (Some(first), Some(last)) = (incoming.first(), incoming.last()) { + let first = target_index(first.0, sample.schema, value.schema); + let last = target_index(last.0, sample.schema, value.schema); + side.partition_point(|b| b.0 < first)..side.partition_point(|b| b.0 <= last) + } else { + continue; + }; + compact_range(side, correction, range, |idx, count, residual| { + empty.insert(idx, (count.is_sign_negative(), residual.is_sign_negative())); + }); + } + } + + /// Restores the zeros needed for this addition and skips redundant zeros in the incoming sample. + /// Reducing the accumulator or widening its zero bucket visits the whole old layout. + pub(super) fn prepare_for_add( + &mut self, + value: &mut FloatHistogram, + c: &mut FloatHistogram, + sample: &mut FloatHistogram, + ) -> Result<()> { + if self.positive.is_empty() && self.negative.is_empty() { + return Ok(()); + } + let restore_all = sample.schema < value.schema + || sample.zero_threshold > value.zero_threshold + || (sample.zero_threshold < value.zero_threshold + && sample + .zero_count_for_larger_threshold(value.zero_threshold, None)? + .1 + > value.zero_threshold); + let widen_input_to = + (sample.zero_threshold < value.zero_threshold).then_some(value.zero_threshold); + for (empty, side, correction, incoming) in [ + ( + &mut self.positive, + &mut value.positive, + &mut c.positive, + &mut sample.positive, + ), + ( + &mut self.negative, + &mut value.negative, + &mut c.negative, + &mut sample.negative, + ), + ] { + if empty.is_empty() { + continue; + } + if restore_all { + merge_empty_buckets(side, correction, std::mem::take(empty).into_iter()); + continue; + } + let original_len = incoming.len(); + let restored = + take_touched_zeros(empty, incoming, sample.schema, value.schema, widen_input_to)?; + if incoming.len() != original_len { + sample.layout = None; + sample.start_timestamp = None; + } + merge_empty_buckets(side, correction, restored.into_iter()); + } + Ok(()) + } +} + +/// Takes the deferred destinations needed for the add. Outside zero-bucket reconciliation, an +/// all-zero source group can be omitted when it preserves the signs of the count and correction. +fn take_touched_zeros( + empty: &mut EmptySide, + incoming: &mut Buckets, + schema: i32, + target_schema: i32, + mut widen_input_to: Option, +) -> Result> { + let mut restored = Vec::new(); + let mut kept = 0; + let mut start = 0; + while start < incoming.len() { + let target = target_index(incoming[start].0, schema, target_schema); + let mut end = start + 1; + while end < incoming.len() && target_index(incoming[end].0, schema, target_schema) == target + { + end += 1; + } + if let Entry::Occupied(entry) = empty.entry(target) { + // From the first lower bound beyond the widened zero bucket, no later group is visited. + if let Some(threshold) = widen_input_to + && bound(incoming[start].0.saturating_sub(1), schema, &[])? >= threshold + { + widen_input_to = None; + } + let (negative_count, negative_correction) = *entry.get(); + // A lone -0 preserves a -0 count. Reducing multiple buckets also adds their corrections. + let keeps_count_sign = + !negative_count || (end == start + 1 && incoming[start].1.is_sign_negative()); + // A zero beside a nonzero can affect rounding when the source group is reduced. + if widen_input_to.is_none() + && !negative_correction + && keeps_count_sign + && incoming[start..end].iter().all(|&(_, count)| count == 0.0) + { + start = end; + continue; + } + restored.push(entry.remove_entry()); + } + if kept != start { + incoming.copy_within(start..end, kept); + } + kept += end - start; + start = end; + } + incoming.truncate(kept); + Ok(restored) +} + +fn merge_empty_buckets( + side: &mut Buckets, + correction: &mut Buckets, + restored: impl DoubleEndedIterator + ExactSizeIterator, +) { + let mut live = side.len(); + let mut dest = live + restored.len(); + side.resize(dest, (0, 0.0)); + correction.resize(dest, (0, 0.0)); + // The two runs are ordered and disjoint. Filling from the end moves each live pair at most once. + for (idx, (negative_count, negative_residual)) in restored.rev() { + while live > 0 && side[live - 1].0 > idx { + live -= 1; + dest -= 1; + side[dest] = side[live]; + correction[dest] = correction[live]; + } + dest -= 1; + side[dest] = (idx, if negative_count { -0.0 } else { 0.0 }); + correction[dest] = (idx, if negative_residual { -0.0 } else { 0.0 }); + } +} /// Counts owned histograms built from views on this thread, so a test can assert that a path /// borrows instead of copying; the values alone cannot tell the two apart. @@ -40,6 +225,7 @@ pub(crate) mod copies { thread_local! { /// Owned histograms [`super::FloatHistogram::try_from_view`] built on this thread. static MATERIALIZED: Cell = const { Cell::new(0) }; + static CLONED_BUCKETS: Cell = const { Cell::new(0) }; } pub(crate) fn record_materialized() { @@ -50,6 +236,14 @@ pub(crate) mod copies { pub(crate) fn take_materialized() -> usize { MATERIALIZED.with(|built| built.replace(0)) } + + pub(super) fn record_cloned_buckets(count: usize) { + CLONED_BUCKETS.with(|total| total.set(total.get() + count)); + } + + pub(crate) fn take_cloned_buckets() -> usize { + CLONED_BUCKETS.replace(0) + } } /// A native histogram with absolute bucket counts. @@ -90,6 +284,8 @@ pub(crate) struct AddOutcome { impl Clone for FloatHistogram { fn clone(&self) -> Self { + #[cfg(test)] + copies::record_cloned_buckets(self.positive.len() + self.negative.len()); Self { reset_hint: self.reset_hint, start_timestamp: self.start_timestamp, @@ -274,6 +470,14 @@ impl FloatHistogram { self.layout = None; } + /// Drops buckets whose value and correction are both zero, keeping the two lists aligned. + pub(super) fn compact_with_compensation(&mut self, c: &mut Self) { + compact_with(&mut self.positive, &mut c.positive); + if !self.uses_custom_buckets() { + compact_with(&mut self.negative, &mut c.negative); + } + } + /// Go `CopyToSchema`; `target` must not exceed the schema. pub(crate) fn copy_to_schema(&self, target: i32) -> Result { if target == self.schema { @@ -380,6 +584,17 @@ impl FloatHistogram { other: &Self, c: Option, ) -> Result<(Self, AddOutcome)> { + self.kahan_add_with_layout(other, c, BucketLayout::Preserve) + } + + /// A compact range fold may discard empty pairs when both operands share a schema. + pub(super) fn kahan_add_with_layout( + &mut self, + other: &Self, + c: Option, + layout: BucketLayout, + ) -> Result<(Self, AddOutcome)> { + debug_assert!(layout == BucketLayout::Preserve || self.schema == other.schema); check_schemas(self, other)?; self.layout = None; self.start_timestamp = None; @@ -401,7 +616,14 @@ impl FloatHistogram { if self.uses_custom_buckets() { if self.custom_values == other.custom_values { - add_buckets(self, &other.positive, 1.0, Some(&mut c), None, true)?; + add_buckets( + self, + &other.positive, + 1.0, + Some((&mut c, layout)), + None, + true, + )?; } else { outcome.custom_bounds_reconciled = true; let bounds = intersect_custom_bounds(&self.custom_values, &other.custom_values); @@ -455,12 +677,26 @@ impl FloatHistogram { Some((buckets, c)) => (buckets, Some(c)), None => (&other.positive, None), }; - add_buckets(self, positive, 1.0, Some(&mut c), positive_c, true)?; + add_buckets( + self, + positive, + 1.0, + Some((&mut c, layout)), + positive_c, + true, + )?; let (negative, negative_c) = match &other_negative { Some((buckets, c)) => (buckets, Some(c)), None => (&other.negative, None), }; - add_buckets(self, negative, 1.0, Some(&mut c), negative_c, false)?; + add_buckets( + self, + negative, + 1.0, + Some((&mut c, layout)), + negative_c, + false, + )?; c.schema = self.schema; c.zero_threshold = self.zero_threshold; Ok((c, outcome)) @@ -596,8 +832,7 @@ impl FloatHistogram { for bucket in &mut c.negative[..trimmed_negative] { bucket.1 = 0.0; } - compact_with(&mut self.positive, &mut c.positive); - compact_with(&mut self.negative, &mut c.negative); + self.compact_with_compensation(c); } None => self.compact(), } @@ -877,15 +1112,30 @@ fn zero_compensation(side: &Buckets) -> Buckets { /// Go `kahanCompact(0)`: drops the buckets whose count and compensation are both zero. fn compact_with(side: &mut Buckets, compensation: &mut Buckets) { - let keep: Vec = side - .iter() - .zip(compensation.iter()) - .map(|(&(_, count), &(_, c))| count != 0.0 || c != 0.0) - .collect(); - let mut flags = keep.iter(); - side.retain(|_| *flags.next().unwrap()); - let mut flags = keep.iter(); - compensation.retain(|_| *flags.next().unwrap()); + compact_range(side, compensation, 0..side.len(), |_, _, _| {}); +} + +fn compact_range( + side: &mut Buckets, + compensation: &mut Buckets, + range: Range, + mut on_empty: impl FnMut(i32, f64, f64), +) { + let mut kept = range.start; + let end = range.end; + for i in range { + if side[i].1 != 0.0 || compensation[i].1 != 0.0 { + side[kept] = side[i]; + compensation[kept] = compensation[i]; + kept += 1; + } else { + on_empty(side[i].0, side[i].1, compensation[i].1); + } + } + if kept < end { + side.drain(kept..end); + compensation.drain(kept..end); + } } /// Go `addBuckets` and `kahanAddBuckets`: adds `sign * other` to one side of `h`, inserting the @@ -894,7 +1144,7 @@ fn add_buckets( h: &mut FloatHistogram, other: &Buckets, sign: f64, - c: Option<&mut FloatHistogram>, + c: Option<(&mut FloatHistogram, BucketLayout)>, other_c: Option<&Buckets>, positive: bool, ) -> Result<()> { @@ -906,6 +1156,8 @@ fn add_buckets( } else { &mut h.negative }; + let (c, layout) = c.unzip(); + let compact = layout == Some(BucketLayout::Compact); let mut side_c = c.map(|c| { if positive { &mut c.positive @@ -915,6 +1167,7 @@ fn add_buckets( }); let mut below_threshold = true; let mut position = 0; + let mut cancelled = false; for (k, &(idx, count)) in other.iter().enumerate() { if below_threshold && exponential && bound(idx, schema, &[])? <= threshold { continue; @@ -922,6 +1175,9 @@ fn add_buckets( below_threshold = false; let value = count * sign; let value_c = other_c.map_or(0.0, |other_c| other_c[k].1) * sign; + if compact && value == 0.0 && value_c == 0.0 { + continue; + } while position < side.len() && side[position].0 < idx { position += 1; } @@ -933,6 +1189,7 @@ fn add_buckets( if value_c != 0.0 { (*sum, *comp) = kahan_inc(value_c, *sum, *comp); } + cancelled |= compact && *sum == 0.0 && *comp == 0.0; } None => side[position].1 += value, } @@ -943,6 +1200,10 @@ fn add_buckets( } } } + // Remove all cancellations together so a dense subtraction moves each surviving bucket once. + if cancelled && let Some(side_c) = side_c { + compact_with(side, side_c); + } Ok(()) } diff --git a/src/promql/src/histogram_eval/legacy_bridge.rs b/src/promql/src/histogram_eval/legacy_bridge.rs index e2d0c0690f1..21e1bac2565 100644 --- a/src/promql/src/histogram_eval/legacy_bridge.rs +++ b/src/promql/src/histogram_eval/legacy_bridge.rs @@ -148,7 +148,7 @@ fn bucket_total(histogram: &NativeHistogram) -> f64 { } /// The native kernel's owned form of `histogram`; errors on a span list that steps backwards. -fn float_histogram(histogram: &NativeHistogram) -> Result { +pub(crate) fn float_histogram(histogram: &NativeHistogram) -> Result { if steps_backwards(&histogram.positive_spans) || steps_backwards(&histogram.negative_spans) { return Err(datafusion::error::DataFusionError::Execution( "native histogram has an invalid layout".into(), @@ -166,7 +166,7 @@ fn steps_backwards(spans: &[Span]) -> bool { } /// The legacy representation of `histogram`, with the span layout it carries. -fn legacy_histogram(histogram: &FloatHistogram) -> NativeHistogram { +pub(crate) fn legacy_histogram(histogram: &FloatHistogram) -> NativeHistogram { let [positive, negative] = histogram.spans(); NativeHistogram { schema: histogram.schema, diff --git a/src/promql/src/histogram_eval/tests.rs b/src/promql/src/histogram_eval/tests.rs index 05c9bdfe1f5..1a3fa176a1c 100644 --- a/src/promql/src/histogram_eval/tests.rs +++ b/src/promql/src/histogram_eval/tests.rs @@ -22,7 +22,7 @@ use datatypes::series::histogram::{ use datatypes::series::samples::{FieldSpec, SampleRef, Series, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridSpec}; -use super::float_histogram::{AddOutcome, FloatHistogram}; +use super::float_histogram::{AddOutcome, BucketLayout, EmptyBuckets, FloatHistogram}; use super::{ HistogramFunction, HistogramParameters, NativeHistogramFunction, evaluate_histograms, evaluate_histograms_with_annotations, histogram_quantiles, histogram_string, @@ -353,6 +353,146 @@ fn histogram(text: &str) -> FloatHistogram { FloatHistogram::try_from_view(&OwnedHistogram::parse(text).view()).unwrap() } +#[test] +fn compact_kahan_add_keeps_only_live_buckets_between_samples() { + let mut sum = histogram("8/0/0/0/0/3/////"); + let mut c = None; + for index in 1..=64 { + // One positive and one negative observation each move up one bucket in absolute value. + let mut delta = sum.empty_like(); + delta.positive = vec![(index, -1.0), (index + 1, 1.0)]; + delta.negative.clone_from(&delta.positive); + let (correction, _) = sum + .kahan_add_with_layout(&delta, c, BucketLayout::Compact) + .unwrap(); + for side in [&sum.positive, &sum.negative] { + assert_eq!(side, &[(1, -1.0), (index + 1, 1.0)]); + } + for side in [&correction.positive, &correction.negative] { + assert_eq!(side, &[(1, 0.0), (index + 1, 0.0)]); + } + c = Some(correction); + } +} + +#[test] +fn restoring_empty_buckets_preserves_order_and_signed_compensation() { + let mut original = histogram("7/0/0/0/0/3/////"); + original.positive = vec![ + (-2, -0.0), + (-1, 3.0), + (0, 0.0), + (1, -0.0), + (2, 4.0), + (3, 0.0), + ]; + original.negative.clone_from(&original.positive); + let mut original_c = original.new_compensation(); + original_c.positive = vec![ + (-2, 0.0), + (-1, 0.25), + (0, -0.0), + (1, -0.0), + (2, 0.5), + (3, 0.0), + ]; + original_c.negative.clone_from(&original_c.positive); + let (mut value, mut c) = (original.clone(), original_c.clone()); + let mut empty = EmptyBuckets::default(); + empty.take_from(&mut value, &mut c, &original, true); + + let mut sample = original.empty_like(); + sample.schema += 1; + // The first two indices map to the same empty bucket in the accumulator. + sample.positive = vec![(-5, 1.0), (-4, 1.0), (0, 1.0), (6, 1.0)]; + sample.negative = vec![(2, 1.0)]; + empty + .prepare_for_add(&mut value, &mut c, &mut sample) + .unwrap(); + for (actual, initial) in [(&value, &original), (&c, &original_c)] { + let mut expected = initial.clone(); + expected.positive.retain(|(idx, _)| *idx != 1); + expected + .negative + .retain(|(idx, _)| [-1, 1, 2].contains(idx)); + assert_eq!(fingerprint(actual), fingerprint(&expected)); + } + + sample.schema = original.schema - 1; + empty + .prepare_for_add(&mut value, &mut c, &mut sample) + .unwrap(); + assert_eq!(fingerprint(&value), fingerprint(&original)); + assert_eq!(fingerprint(&c), fingerprint(&original_c)); +} + +#[test] +fn repeated_zero_adds_leave_empty_buckets_compact_until_a_downscale() { + let original = histogram("7/0/0/0/0/3/1_4/0,0,0,0/1_4/0,0,0,0/"); + let finer = histogram("8/0/0/0/0/3/1_8/0,0,0,0,0,0,0,0/1_8/0,0,0,0,0,0,0,0/"); + for (mut sample, retained_span) in [(original.clone(), (2, 3)), (finer, (3, 6))] { + sample.start_timestamp = Some(1000); + let mut value = original.clone(); + let mut c = value.new_compensation(); + for (incoming, side, correction) in [ + (&mut sample.positive, &mut value.positive, &mut c.positive), + (&mut sample.negative, &mut value.negative, &mut c.negative), + ] { + incoming[0].1 = -0.0; + correction[1].1 = -0.0; + side[2].1 = -0.0; + incoming.last_mut().unwrap().1 = 1.0; + } + if sample.schema == value.schema { + value.negative[0].1 = -0.0; + } + let mut expected = value.clone(); + let (expected_c, _) = expected.kahan_add(&sample, Some(c.clone())).unwrap(); + + let mut empty = EmptyBuckets::default(); + empty.take_from(&mut value, &mut c, &sample, true); + empty + .prepare_for_add(&mut value, &mut c, &mut sample) + .unwrap(); + assert_eq!(sample.spans(), [vec![retained_span], vec![retained_span]]); + assert_eq!(sample.start_timestamp, None); + let (mut c, _) = value.kahan_add(&sample, Some(c)).unwrap(); + for side in [&value.positive, &value.negative, &c.positive, &c.negative] { + assert!(side.iter().all(|&(idx, _)| idx != 1)); + } + + let mut coarse = value.empty_like(); + coarse.schema -= 1; + empty + .prepare_for_add(&mut value, &mut c, &mut coarse) + .unwrap(); + assert!(value.equals(&expected)); + assert!(c.equals(&expected_c)); + } +} + +#[test] +fn widening_the_input_zero_bucket_preserves_only_the_zeros_it_can_visit() { + let mut sample = histogram("0/0/0/0/0/3/-1_4/0,0,0,0/-1_4/0,0,0,0/"); + let mut value = sample.clone(); + value.zero_threshold = 0.75; + let mut c = value.new_compensation(); + let mut empty = EmptyBuckets::default(); + empty.take_from(&mut value, &mut c, &sample, true); + empty + .prepare_for_add(&mut value, &mut c, &mut sample) + .unwrap(); + // Index -1 ends at 0.5 and index 0 straddles the threshold. Both later buckets start above it. + for side in [ + &sample.positive, + &sample.negative, + &value.positive, + &value.negative, + ] { + assert_eq!(side.as_slice(), &[(-1, 0.0), (0, 0.0)]); + } +} + #[test] fn histogram_arithmetic_matches_prometheus() { let mut checked = 0; diff --git a/src/promql/src/range_eval/histogram.rs b/src/promql/src/range_eval/histogram.rs index f634ff70cf1..dc969032751 100644 --- a/src/promql/src/range_eval/histogram.rs +++ b/src/promql/src/range_eval/histogram.rs @@ -166,7 +166,7 @@ pub(super) fn evaluate( } // `None` is the mixed-bucket drop; the flag reports a custom-bucket reconciliation. let (result, custom_reconciled) = - sum_or_avg(op, histograms.iter().map(|(_, h)| Ok(h.clone())))?; + sum_or_avg(op, histograms.iter().map(|(_, h)| Ok(h.clone())), None)?; if result.is_none() { record_warning( collector, diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 88af43fab18..c8a5030ca01 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -5837,65 +5837,61 @@ pub async fn test_remote_write_v2_histogram_native_range_function(store_type: St .with_greptime_config_options(instance.opts.datanode_options().to_toml().unwrap()) .build(); let client = TestClient::new(server.build(server.make_app()).unwrap()).await; - // `__unit__` leaves with the metric name `sum_over_time` drops, and a scan that carries it can - // hold two series that agree on everything else: that is the collision the boundary below is - // carried by. A nullable key column is not one - see the note on - // `test_remote_write_v2_histogram_native_nullable_tag_boundary`. - write_native_histogram( - &client, - &[ - (prom_store::METRIC_NAME_LABEL, "native_histogram_range"), - ("job", "api"), - ("__unit__", "s"), - ], - 1000, - 5, - 10.0, - ) - .await; - write_native_histogram( - &client, - &[ - (prom_store::METRIC_NAME_LABEL, "native_histogram_range"), - ("job", "api"), - ("__unit__", "s"), - ], - 3000, - 8, - 20.0, - ) - .await; - observer.clear(); - let response = client.get("/v1/prometheus/api/v1/query?query=sum_over_time(native_histogram_range%5B1m%5D)&time=3") - .header("x-greptime-hints", "query.experimental_native_promql=true").send().await; - assert_eq!(response.status(), StatusCode::OK); - let body: Value = response.json().await; - assert_eq!(body["data"]["resultType"], "vector"); - assert_eq!(body["data"]["result"][0]["histogram"][0], 3.0); - assert_eq!( - body["data"]["result"][0]["histogram"][1]["count"], "13", - "`sum_over_time` adds the counts as {PROMETHEUS_REFERENCE} does" - ); - assert_eq!( - body["data"]["result"][0]["histogram"][1]["sum"], "30", - "`sum_over_time` adds the sums as {PROMETHEUS_REFERENCE} does" - ); - // `sum_over_time` over a native histogram drops the metadata labels, and this binding carries - // `__unit__`, so the canonical pass collects that drop: the answer stands on a canonical merge - // carrying histogram frames. Lowering such a boundary is two nodes, not one - a producer that - // runs the statement's own tree per partition and exports a frame, and the consumer above the - // router that converts the merged frames into the statement's rows. Both are the fused route; - // the answer asserted above is what proves the histograms survived the crossing. - let fused = observer.take_all("histogram sum_over_time"); - assert_eq!( - 2, - fused.len(), - "the canonical boundary is a producer and a consumer: {fused:?}" - ); - assert!( - fused.iter().all(|node| node.name() == "FusedSeriesExec"), - "the boundary executed a node that is not the fused producer: {fused:?}" - ); + let metric = "native_histogram_range"; + let labels = &[ + (prom_store::METRIC_NAME_LABEL, metric), + ("job", "api"), + ("__unit__", "s"), + ]; + for (timestamp, count, sum) in [(1000, 5, 1e16), (2000, 2, 1.0), (3000, 8, -1e16)] { + write_native_histogram_sample( + &client, + labels, + common_query::native_histogram::CUSTOM_BUCKETS_SCHEMA, + vec![0.0], + timestamp, + count, + sum, + ) + .await; + } + + // Dropping `__unit__` with the metric name requires a fused producer and consumer. + for (native, expected_fused_nodes) in [(true, 2), (false, 0)] { + for (function, expected) in [ + ("sum_over_time", (15.0, 1.0)), + ("avg_over_time", (5.0, 1.0 / 3.0)), + ] { + observer.clear(); + let query = format!("{function}({metric}[1m])"); + let response = client + .get(&format!( + "/v1/prometheus/api/v1/query?query={}&time=3", + encode(&query) + )) + .header( + "x-greptime-hints", + format!("query.experimental_native_promql={native}"), + ) + .send() + .await; + assert_eq!(response.status(), StatusCode::OK); + let body: Value = response.json().await; + assert_eq!(body["data"]["resultType"], "vector"); + let result = &body["data"]["result"][0]; + assert_eq!(result["histogram"][0], 3.0); + assert_eq!( + histogram_fields(result), + expected, + "{query}, native={native}" + ); + assert_eq!( + observer.0.lock().unwrap().len(), + expected_fused_nodes, + "{query}, native={native}" + ); + } + } } /// A native histogram answer crosses a canonical merge on a real metric table.