1use common_query::native_histogram::{
31 CounterResetHint, NativeHistogram, NativeHistogramQuantileInfo, Span,
32};
33use datafusion::error::Result;
34use datatypes::series::histogram::{BucketSideView, HistogramView};
35
36use crate::histogram_eval::float_histogram::FloatHistogram;
37use crate::histogram_eval::native;
38
39pub(crate) struct LegacyView<'a> {
45 histogram: &'a NativeHistogram,
46 positive_offsets: Vec<i32>,
47 positive_lengths: Vec<i32>,
48 negative_offsets: Vec<i32>,
49 negative_lengths: Vec<i32>,
50}
51
52impl<'a> LegacyView<'a> {
53 pub(crate) fn new(histogram: &'a NativeHistogram) -> Self {
54 let (positive_offsets, positive_lengths) = span_columns(&histogram.positive_spans);
55 let (negative_offsets, negative_lengths) = span_columns(&histogram.negative_spans);
56 Self {
57 histogram,
58 positive_offsets,
59 positive_lengths,
60 negative_offsets,
61 negative_lengths,
62 }
63 }
64
65 pub(crate) fn view(&self) -> HistogramView<'_> {
67 HistogramView {
68 schema: self.histogram.schema,
69 zero_threshold: self.histogram.zero_threshold,
70 sum: self.histogram.sum,
71 count: self.histogram.count,
72 zero_count: self.histogram.zero_count,
73 reset_hint: self.histogram.reset_hint,
74 start_timestamp: self.histogram.start_timestamp,
75 custom_values: &self.histogram.custom_values,
76 positive: BucketSideView {
77 span_offsets: &self.positive_offsets,
78 span_lengths: &self.positive_lengths,
79 buckets: &self.histogram.positive_buckets,
80 },
81 negative: BucketSideView {
82 span_offsets: &self.negative_offsets,
83 span_lengths: &self.negative_lengths,
84 buckets: &self.histogram.negative_buckets,
85 },
86 }
87 }
88}
89
90fn span_columns(spans: &[Span]) -> (Vec<i32>, Vec<i32>) {
91 spans.iter().map(|span| (span.offset, span.length)).unzip()
92}
93
94pub(crate) fn quantile_with_info(
96 histogram: &NativeHistogram,
97 q: f64,
98) -> (f64, Option<NativeHistogramQuantileInfo>) {
99 let view = LegacyView::new(histogram);
100 match native::quantile(q, &view.view(), &mut Vec::new()) {
101 Ok(value) => (value, nan_observation_info(histogram, q)),
102 Err(_) => (f64::NAN, None),
106 }
107}
108
109pub(crate) fn fraction_with_info(
111 histogram: &NativeHistogram,
112 lower: f64,
113 upper: f64,
114) -> (f64, bool) {
115 let view = LegacyView::new(histogram);
116 match native::fraction(lower, upper, &view.view(), &mut Vec::new()) {
117 Ok(value) => {
118 let excluded_nans = histogram.count != 0.0
121 && !lower.is_nan()
122 && !upper.is_nan()
123 && lower < upper
124 && histogram.sum.is_nan()
125 && bucket_total(histogram) < histogram.count;
126 (value, excluded_nans)
127 }
128 Err(_) => (f64::NAN, false),
129 }
130}
131
132fn nan_observation_info(
140 histogram: &NativeHistogram,
141 q: f64,
142) -> Option<NativeHistogramQuantileInfo> {
143 if histogram.count == 0.0 || !(0.0..=1.0).contains(&q) {
144 return None;
145 }
146 let total = bucket_total(histogram);
147 if !(histogram.sum.is_nan() && total < histogram.count) {
148 return None;
149 }
150 Some(if total < q * histogram.count {
151 NativeHistogramQuantileInfo::NaNResult
152 } else {
153 NativeHistogramQuantileInfo::NaNSkew
154 })
155}
156
157fn bucket_total(histogram: &NativeHistogram) -> f64 {
160 let mut total = 0.0;
161 for count in histogram.negative_buckets.iter().rev() {
162 total += count;
163 }
164 total += histogram.zero_count;
165 for count in &histogram.positive_buckets {
166 total += count;
167 }
168 total
169}
170
171fn float_histogram(histogram: &NativeHistogram) -> Result<FloatHistogram> {
176 if steps_backwards(&histogram.positive_spans) || steps_backwards(&histogram.negative_spans) {
177 return Err(datafusion::error::DataFusionError::Execution(
178 "native histogram has an invalid layout".into(),
179 ));
180 }
181 let view = LegacyView::new(histogram);
182 FloatHistogram::try_from_view(&view.view())
183}
184
185fn steps_backwards(spans: &[Span]) -> bool {
192 spans.iter().skip(1).any(|span| span.offset < 0)
193}
194
195fn legacy_histogram(histogram: &FloatHistogram) -> NativeHistogram {
197 let [positive, negative] = histogram.spans();
198 NativeHistogram {
199 schema: histogram.schema,
200 zero_threshold: histogram.zero_threshold,
201 sum: histogram.sum,
202 reset_hint: histogram.reset_hint,
203 start_timestamp: histogram.start_timestamp,
204 custom_values: histogram.custom_values.clone(),
205 positive_spans: legacy_spans(positive),
206 negative_spans: legacy_spans(negative),
207 count: histogram.count,
208 zero_count: histogram.zero_count,
209 positive_buckets: bucket_counts(&histogram.positive),
210 negative_buckets: bucket_counts(&histogram.negative),
211 }
212}
213
214fn legacy_spans(spans: Vec<(i32, i32)>) -> Vec<Span> {
215 spans
216 .into_iter()
217 .map(|(offset, length)| Span { offset, length })
218 .collect()
219}
220
221fn bucket_counts(buckets: &[(i32, f64)]) -> Vec<f64> {
222 buckets.iter().map(|&(_, count)| count).collect()
223}
224
225pub(crate) fn add(left: &NativeHistogram, right: &NativeHistogram) -> Option<NativeHistogram> {
227 combine(left, right, false)
228}
229
230pub(crate) fn sub(left: &NativeHistogram, right: &NativeHistogram) -> Option<NativeHistogram> {
232 combine(left, right, true)
233}
234
235fn combine(
236 left: &NativeHistogram,
237 right: &NativeHistogram,
238 subtract: bool,
239) -> Option<NativeHistogram> {
240 let mut combined = float_histogram(left).ok()?;
241 let other = float_histogram(right).ok()?;
242 let outcome = if subtract {
243 combined.sub(&other)
244 } else {
245 combined.add(&other)
246 }
247 .ok()?;
248 debug_assert_eq!(
255 outcome.custom_bounds_reconciled,
256 left.needs_custom_reconciliation(right)
257 );
258 if outcome.counter_reset_collision {
259 debug_assert_eq!(combined.reset_hint, CounterResetHint::Unknown);
260 }
261 if subtract {
262 combined.reset_hint = CounterResetHint::Gauge;
263 }
264 combined.compact();
267 Some(legacy_histogram(&combined))
268}
269
270pub(crate) fn scale(histogram: &NativeHistogram, factor: f64) -> NativeHistogram {
272 let Ok(mut scaled) = float_histogram(histogram) else {
273 return field_scaled(histogram, factor);
278 };
279 scaled.mul(factor);
280 legacy_histogram(&scaled)
281}
282
283pub(crate) fn divide_by(histogram: &NativeHistogram, divisor: f64) -> NativeHistogram {
285 let Ok(mut divided) = float_histogram(histogram) else {
286 return field_divided(histogram, divisor);
287 };
288 divided.div(divisor);
289 legacy_histogram(÷d)
290}
291
292fn field_scaled(histogram: &NativeHistogram, factor: f64) -> NativeHistogram {
293 let mut scaled = histogram.clone();
294 scaled.count *= factor;
295 scaled.zero_count *= factor;
296 scaled.sum *= factor;
297 for count in scaled
298 .positive_buckets
299 .iter_mut()
300 .chain(&mut scaled.negative_buckets)
301 {
302 *count *= factor;
303 }
304 if factor < 0.0 {
305 scaled.reset_hint = CounterResetHint::Gauge;
306 }
307 scaled
308}
309
310fn field_divided(histogram: &NativeHistogram, divisor: f64) -> NativeHistogram {
311 let mut divided = histogram.clone();
312 divided.count /= divisor;
313 divided.zero_count /= divisor;
314 divided.sum /= divisor;
315 if divisor == 0.0 {
316 divided.positive_spans.clear();
317 divided.positive_buckets.clear();
318 divided.negative_spans.clear();
319 divided.negative_buckets.clear();
320 } else {
321 for count in divided
322 .positive_buckets
323 .iter_mut()
324 .chain(&mut divided.negative_buckets)
325 {
326 *count /= divisor;
327 }
328 }
329 if divisor < 0.0 {
330 divided.reset_hint = CounterResetHint::Gauge;
331 }
332 divided
333}
334
335#[cfg(test)]
336mod tests {
337 use common_query::native_histogram::{
338 CUSTOM_BUCKETS_SCHEMA, CounterResetHint, NativeHistogram, NativeHistogramQuantileInfo, Span,
339 };
340 use datatypes::series::histogram::{BucketSideView, HistogramView};
341
342 use super::{
343 add, divide_by, float_histogram, fraction_with_info, legacy_histogram, quantile_with_info,
344 scale, sub,
345 };
346 use crate::histogram_eval::float_histogram::FloatHistogram;
347 use crate::histogram_eval::native;
348
349 fn fixtures() -> Vec<(&'static str, NativeHistogram)> {
353 let mut custom = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 7.0, 21.0, 0.0);
354 custom.custom_values = vec![1.0, 2.0, 4.0];
355 custom.positive_spans = vec![span(0, 3)];
356 custom.positive_buckets = vec![2.0, 0.0, 5.0];
357
358 let mut spaced = empty(3, 0.0, 6.0, 6.0, 0.0);
359 spaced.positive_spans = vec![span(-3, 2), span(5, 2)];
360 spaced.positive_buckets = vec![2.0, 1.0, 2.5, 0.5];
361
362 let mut nan_sum = empty(0, 0.0, 10.0, f64::NAN, 0.0);
363 nan_sum.positive_spans = vec![span(0, 1)];
364 nan_sum.positive_buckets = vec![8.0];
365
366 let mut nan_sum_multi_bucket = empty(0, 0.0, 10.0, f64::NAN, 0.0);
370 nan_sum_multi_bucket.positive_spans = vec![span(0, 2)];
371 nan_sum_multi_bucket.positive_buckets = vec![8.0, 1.0];
372
373 let mut both_sides = empty(2, 0.5, 20.0, -3.0, 3.0);
374 both_sides.positive_spans = vec![span(0, 3)];
375 both_sides.positive_buckets = vec![4.0, 2.0, 5.0];
376 both_sides.negative_spans = vec![span(0, 2)];
377 both_sides.negative_buckets = vec![3.0, 3.0];
378
379 let zero_bucket_only = empty(1, 1.0, 4.0, 2.0, 4.0);
382 let empty_histogram = empty(0, 0.0, 0.0, 0.0, 0.0);
383
384 vec![
385 ("custom", custom),
386 ("spaced", spaced),
387 ("nan_sum", nan_sum),
388 ("nan_sum_multi_bucket", nan_sum_multi_bucket),
389 ("both_sides", both_sides),
390 ("zero_bucket_only", zero_bucket_only),
391 ("empty", empty_histogram),
392 ]
393 }
394
395 fn empty(
396 schema: i32,
397 zero_threshold: f64,
398 count: f64,
399 sum: f64,
400 zero_count: f64,
401 ) -> NativeHistogram {
402 NativeHistogram {
403 schema,
404 zero_threshold,
405 sum,
406 reset_hint: CounterResetHint::Unknown,
407 start_timestamp: None,
408 custom_values: Vec::new(),
409 positive_spans: Vec::new(),
410 negative_spans: Vec::new(),
411 count,
412 zero_count,
413 positive_buckets: Vec::new(),
414 negative_buckets: Vec::new(),
415 }
416 }
417
418 fn span(offset: i32, length: i32) -> Span {
419 Span { offset, length }
420 }
421
422 fn columns(spans: &[Span]) -> (Vec<i32>, Vec<i32>) {
423 spans.iter().map(|span| (span.offset, span.length)).unzip()
424 }
425
426 fn view<'a>(
429 histogram: &'a NativeHistogram,
430 positive: &'a (Vec<i32>, Vec<i32>),
431 negative: &'a (Vec<i32>, Vec<i32>),
432 ) -> HistogramView<'a> {
433 HistogramView {
434 schema: histogram.schema,
435 zero_threshold: histogram.zero_threshold,
436 sum: histogram.sum,
437 count: histogram.count,
438 zero_count: histogram.zero_count,
439 reset_hint: histogram.reset_hint,
440 start_timestamp: histogram.start_timestamp,
441 custom_values: &histogram.custom_values,
442 positive: BucketSideView {
443 span_offsets: &positive.0,
444 span_lengths: &positive.1,
445 buckets: &histogram.positive_buckets,
446 },
447 negative: BucketSideView {
448 span_offsets: &negative.0,
449 span_lengths: &negative.1,
450 buckets: &histogram.negative_buckets,
451 },
452 }
453 }
454
455 #[test]
458 fn quantile_with_info_is_the_native_quantile() {
459 for (name, histogram) in fixtures() {
460 let positive = columns(&histogram.positive_spans);
461 let negative = columns(&histogram.negative_spans);
462 for q in [
463 f64::NEG_INFINITY,
464 -0.1,
465 0.0,
466 0.001,
467 0.25,
468 0.5,
469 0.75,
470 1.0,
471 1.1,
472 f64::INFINITY,
473 f64::NAN,
474 ] {
475 let (value, _) = quantile_with_info(&histogram, q);
476 let expected =
477 native::quantile(q, &view(&histogram, &positive, &negative), &mut Vec::new())
478 .unwrap();
479 assert_eq!(
480 value.to_bits(),
481 expected.to_bits(),
482 "{name} q {q}: {value} vs {expected}"
483 );
484 }
485 }
486 }
487
488 #[test]
493 fn quantile_with_nan_sum_uses_the_last_bucket() {
494 let mut histogram = empty(0, 0.0, 10.0, f64::NAN, 0.0);
495 histogram.positive_spans = vec![span(0, 2)];
496 histogram.positive_buckets = vec![8.0, 1.0];
497
498 let (value, info) = quantile_with_info(&histogram, 0.5);
501 assert_eq!(
502 value.to_bits(),
503 32.0f64.to_bits(),
504 "rank 5 lands in (0.5, 1] (0.7711), but the NaN walk leaves (1, 2] behind and \
505 fraction 5 / 1 puts the answer at 2^5"
506 );
507 assert_eq!(
508 info,
509 Some(NativeHistogramQuantileInfo::NaNSkew),
510 "a rank inside the bucket total is still an estimate"
511 );
512 }
513
514 #[test]
517 fn quantile_with_nan_sum_below_the_rank_is_nan() {
518 let mut histogram = empty(0, 0.0, 10.0, f64::NAN, 0.0);
519 histogram.positive_spans = vec![span(0, 2)];
520 histogram.positive_buckets = vec![8.0, 1.0];
521
522 let (value, info) = quantile_with_info(&histogram, 0.95);
525 assert!(
526 value.is_nan(),
527 "a rank the buckets cannot reach has no estimate, got {value}"
528 );
529 assert_eq!(
530 info,
531 Some(NativeHistogramQuantileInfo::NaNResult),
532 "the note says the NaN observations were the highest ones"
533 );
534
535 let mut single = empty(0, 0.0, 10.0, f64::NAN, 0.0);
538 single.positive_spans = vec![span(0, 1)];
539 single.positive_buckets = vec![8.0];
540 assert!(quantile_with_info(&single, 0.9).0.is_nan());
541 assert_eq!(
542 quantile_with_info(&single, 0.9).1,
543 Some(NativeHistogramQuantileInfo::NaNResult)
544 );
545 }
546
547 #[test]
554 fn exact_tie_answers_one_from_the_legacy_walk_and_two_from_the_kernel() {
555 let mut tie = empty(0, 0.0, 2.0, 3.75, 0.0);
556 tie.positive_spans = vec![span(0, 1), span(1, 1)];
559 tie.positive_buckets = vec![1.0, 1.0];
560
561 assert_eq!(
565 tie.quantile_with_info(0.5),
566 (1.0, None),
567 "the legacy walk answers with the upper bound of (0.5, 1]"
568 );
569
570 let (value, info) = quantile_with_info(&tie, 0.5);
573 assert_eq!(
574 value.to_bits(),
575 2.0f64.to_bits(),
576 "the kernel's walk answers with the lower bound of (2, 4]"
577 );
578 assert_eq!(
579 info, None,
580 "a tie between two buckets is not a NaN observation"
581 );
582 }
583
584 #[test]
586 fn fraction_with_info_is_the_native_fraction() {
587 for (name, histogram) in fixtures() {
588 let positive = columns(&histogram.positive_spans);
589 let negative = columns(&histogram.negative_spans);
590 for (lower, upper) in [
591 (f64::NEG_INFINITY, f64::INFINITY),
592 (-2.0, 0.5),
593 (0.0, 1.0),
594 (1.0, 4.0),
595 (2.0, 2.0),
596 (3.0, 1.0),
597 (f64::NAN, 1.0),
598 (0.0, f64::NAN),
599 ] {
600 let (value, _) = fraction_with_info(&histogram, lower, upper);
601 let expected = native::fraction(
602 lower,
603 upper,
604 &view(&histogram, &positive, &negative),
605 &mut Vec::new(),
606 )
607 .unwrap();
608 assert_eq!(
609 value.to_bits(),
610 expected.to_bits(),
611 "{name} [{lower}, {upper}]: {value} vs {expected}"
612 );
613 }
614 }
615 }
616
617 fn pairs() -> Vec<(&'static str, NativeHistogram, NativeHistogram)> {
621 let mut same_left = empty(2, 0.0, 6.0, 6.0, 1.0);
622 same_left.positive_spans = vec![span(0, 2)];
623 same_left.positive_buckets = vec![2.0, 3.0];
624 same_left.negative_spans = vec![span(0, 1)];
625 same_left.negative_buckets = vec![1.0];
626 let mut same_right = empty(2, 0.0, 5.0, 8.0, 0.0);
627 same_right.positive_spans = vec![span(-1, 3)];
628 same_right.positive_buckets = vec![1.0, 2.0, 2.0];
629 same_right.negative_spans = vec![span(1, 1)];
630 same_right.negative_buckets = vec![2.0];
631
632 let mut fine = empty(3, 0.0, 2.0, 2.0, 0.0);
633 fine.positive_spans = vec![span(0, 2)];
634 fine.positive_buckets = vec![1.0, 1.0];
635 let mut coarse = empty(0, 0.0, 4.0, 5.0, 0.0);
636 coarse.positive_spans = vec![span(0, 1)];
637 coarse.positive_buckets = vec![4.0];
638
639 let mut narrow_zero = empty(0, 0.0, 3.0, 3.0, 0.0);
640 narrow_zero.positive_spans = vec![span(0, 1)];
641 narrow_zero.positive_buckets = vec![3.0];
642 let mut wide_zero = empty(0, 2.0, 4.0, 5.0, 1.0);
643 wide_zero.positive_spans = vec![span(1, 1)];
644 wide_zero.positive_buckets = vec![3.0];
645
646 let mut custom_left = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 6.0, 12.0, 0.0);
647 custom_left.custom_values = vec![1.0, 2.0, 4.0];
648 custom_left.positive_spans = vec![span(0, 3)];
649 custom_left.positive_buckets = vec![1.0, 3.0, 2.0];
650 let mut custom_right = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 6.0, 14.0, 0.0);
651 custom_right.custom_values = vec![2.0, 3.0, 4.0];
652 custom_right.positive_spans = vec![span(0, 3)];
653 custom_right.positive_buckets = vec![4.0, 1.0, 1.0];
654
655 let mut nan_left = empty(1, 0.0, 10.0, f64::NAN, 0.0);
656 nan_left.positive_spans = vec![span(0, 2)];
657 nan_left.positive_buckets = vec![3.0, 5.0];
658 let mut nan_right = empty(1, 0.0, 2.0, 2.0, 0.0);
659 nan_right.positive_spans = vec![span(0, 1)];
660 nan_right.positive_buckets = vec![2.0];
661
662 same_left.start_timestamp = Some(1_000);
665 same_right.start_timestamp = Some(2_000);
666 fine.start_timestamp = Some(3_001);
667 coarse.start_timestamp = Some(3_002);
668 narrow_zero.start_timestamp = Some(3_003);
669 wide_zero.start_timestamp = Some(3_004);
670 custom_left.start_timestamp = Some(3_005);
671 custom_right.start_timestamp = Some(3_006);
672 nan_left.start_timestamp = Some(3_007);
673 nan_right.start_timestamp = Some(3_008);
674
675 vec![
676 ("same_layout", same_left, same_right),
677 ("schema_reduction", fine, coarse),
678 ("zero_threshold", narrow_zero, wide_zero),
679 ("custom_bounds", custom_left, custom_right),
680 ("nan_sum", nan_left, nan_right),
681 ]
682 }
683
684 fn populated_buckets(spans: &[Span], buckets: &[f64]) -> Vec<(i32, u64)> {
686 let (offsets, lengths) = columns(spans);
687 let mut index = 0;
688 let mut out = Vec::new();
689 let mut counts = buckets.iter();
690 for (position, (offset, length)) in offsets.into_iter().zip(lengths).enumerate() {
691 index = if position == 0 {
692 offset
693 } else {
694 index + offset
695 };
696 for _ in 0..length {
697 let count = *counts.next().unwrap();
698 if count != 0.0 {
699 out.push((index, count.to_bits()));
700 }
701 index += 1;
702 }
703 }
704 out
705 }
706
707 fn populated(side: &[(i32, f64)]) -> Vec<(i32, u64)> {
708 side.iter()
709 .filter(|(_, count)| *count != 0.0)
710 .map(|(index, count)| (*index, count.to_bits()))
711 .collect()
712 }
713
714 fn count_bits(counts: &[f64]) -> Vec<u64> {
717 counts.iter().map(|count| count.to_bits()).collect()
718 }
719
720 fn side_count_bits(side: &[(i32, f64)]) -> Vec<u64> {
721 side.iter().map(|&(_, count)| count.to_bits()).collect()
722 }
723
724 fn segments(spans: &[Span]) -> Vec<(i32, i32)> {
726 spans
727 .iter()
728 .map(|span| (span.offset, span.length))
729 .collect()
730 }
731
732 fn assert_same_payload(
746 name: &str,
747 legacy: &NativeHistogram,
748 native: &FloatHistogram,
749 expected_start_timestamp: Option<i64>,
750 ) {
751 assert_eq!(legacy.schema, native.schema, "{name} schema");
752 assert_eq!(
753 legacy.zero_threshold.to_bits(),
754 native.zero_threshold.to_bits(),
755 "{name} zero_threshold"
756 );
757 assert_eq!(
758 legacy.count.to_bits(),
759 native.count.to_bits(),
760 "{name} count"
761 );
762 assert_eq!(legacy.sum.to_bits(), native.sum.to_bits(), "{name} sum");
763 assert_eq!(
764 legacy.zero_count.to_bits(),
765 native.zero_count.to_bits(),
766 "{name} zero_count"
767 );
768 assert_eq!(legacy.reset_hint, native.reset_hint, "{name} reset_hint");
769 assert_eq!(
770 legacy.custom_values, native.custom_values,
771 "{name} custom_values"
772 );
773 assert_eq!(
774 legacy.start_timestamp, expected_start_timestamp,
775 "{name} start_timestamp"
776 );
777 assert_eq!(
778 native.start_timestamp, expected_start_timestamp,
779 "{name} kernel start_timestamp"
780 );
781
782 let [positive, negative] = native.spans();
783 assert_eq!(
784 segments(&legacy.positive_spans),
785 positive,
786 "{name} positive spans"
787 );
788 assert_eq!(
789 segments(&legacy.negative_spans),
790 negative,
791 "{name} negative spans"
792 );
793 assert_eq!(
794 count_bits(&legacy.positive_buckets),
795 side_count_bits(&native.positive),
796 "{name} positive buckets"
797 );
798 assert_eq!(
799 count_bits(&legacy.negative_buckets),
800 side_count_bits(&native.negative),
801 "{name} negative buckets"
802 );
803 assert_eq!(
804 populated_buckets(&legacy.positive_spans, &legacy.positive_buckets),
805 populated(&native.positive),
806 "{name} positive bucket indices"
807 );
808 assert_eq!(
809 populated_buckets(&legacy.negative_spans, &legacy.negative_buckets),
810 populated(&native.negative),
811 "{name} negative bucket indices"
812 );
813 }
814
815 #[test]
817 fn add_is_the_native_add() {
818 for (name, left, right) in pairs() {
819 let combined = add(&left, &right).unwrap();
820 let mut native = float_histogram(&left).unwrap();
821 native.add(&float_histogram(&right).unwrap()).unwrap();
822 native.compact();
826 assert_same_payload(name, &combined, &native, None);
827 }
828 }
829
830 #[test]
832 fn sub_is_the_native_sub() {
833 for (name, left, right) in pairs() {
834 let combined = sub(&left, &right).unwrap();
835 assert_eq!(combined.reset_hint, CounterResetHint::Gauge, "{name}");
836 let mut native = float_histogram(&left).unwrap();
837 native.sub(&float_histogram(&right).unwrap()).unwrap();
838 native.reset_hint = CounterResetHint::Gauge;
839 native.compact();
840 assert_same_payload(name, &combined, &native, None);
841 }
842 }
843
844 #[test]
847 fn scale_and_divide_by_are_the_native_mul_and_div() {
848 for (name, histogram, _) in pairs() {
849 for factor in [2.0, 0.5, -1.0, 0.0, f64::INFINITY] {
850 let scaled = scale(&histogram, factor);
851 let mut native = float_histogram(&histogram).unwrap();
852 native.mul(factor);
853 assert_same_payload(name, &scaled, &native, None);
854
855 let divided = divide_by(&histogram, factor);
856 let mut native = float_histogram(&histogram).unwrap();
857 native.div(factor);
858 assert_same_payload(name, ÷d, &native, None);
859 }
860 }
861 }
862
863 #[test]
866 fn nan_notes_follow_the_kernel_outcome() {
867 use NativeHistogramQuantileInfo::{NaNResult, NaNSkew};
868
869 let nan_sum = fixtures()
870 .into_iter()
871 .find(|(name, _)| *name == "nan_sum")
872 .map(|(_, histogram)| histogram)
873 .unwrap();
874 assert_eq!(quantile_with_info(&nan_sum, 0.5).1, Some(NaNSkew));
875 assert_eq!(quantile_with_info(&nan_sum, 0.9).1, Some(NaNResult));
876 assert_eq!(quantile_with_info(&nan_sum, 0.0).1, Some(NaNSkew));
877 assert_eq!(quantile_with_info(&nan_sum, 1.0).1, Some(NaNResult));
878 assert_eq!(quantile_with_info(&nan_sum, -1.0).1, None);
879 assert_eq!(quantile_with_info(&nan_sum, 2.0).1, None);
880 assert_eq!(quantile_with_info(&nan_sum, f64::NAN).1, None);
881
882 let mut complete = empty(0, 0.0, 8.0, 8.0, 0.0);
883 complete.positive_spans = vec![span(0, 1)];
884 complete.positive_buckets = vec![8.0];
885 assert_eq!(quantile_with_info(&complete, 0.5).1, None);
886
887 assert!(fraction_with_info(&nan_sum, f64::NEG_INFINITY, f64::INFINITY).1);
888 assert!(!fraction_with_info(&complete, f64::NEG_INFINITY, f64::INFINITY).1);
889 assert!(!fraction_with_info(&nan_sum, f64::NAN, 1.0).1);
890 assert!(!fraction_with_info(&nan_sum, 1.0, 1.0).1);
891 assert!(!fraction_with_info(&nan_sum, 2.0, 1.0).1);
892 }
893
894 #[test]
898 fn round_trip_preserves_the_payload_and_its_span_layout() {
899 let mut exponential = empty(2, 0.5, 12.0, -7.5, 1.0);
900 exponential.reset_hint = CounterResetHint::NotCounterReset;
901 exponential.start_timestamp = Some(1_234_567);
902 exponential.positive_spans = vec![span(0, 0), span(2, 2), span(1, 1)];
906 exponential.positive_buckets = vec![1.0, 3.0, 2.0];
907 exponential.negative_spans = vec![span(-2, 2)];
908 exponential.negative_buckets = vec![2.5, 1.5];
909
910 let mut custom = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 6.0, 9.0, 0.0);
911 custom.reset_hint = CounterResetHint::Gauge;
912 custom.start_timestamp = Some(42);
913 custom.custom_values = vec![1.0, 2.0, 4.0, 8.0];
914 custom.positive_spans = vec![span(0, 1), span(1, 2)];
915 custom.positive_buckets = vec![1.0, 2.0, 3.0];
916
917 for (name, original) in [("exponential", exponential), ("custom", custom)] {
918 let round_tripped = legacy_histogram(&float_histogram(&original).unwrap());
919
920 assert_eq!(
921 round_tripped.reset_hint, original.reset_hint,
922 "{name} reset_hint"
923 );
924 assert_eq!(
925 round_tripped.start_timestamp, original.start_timestamp,
926 "{name} start_timestamp"
927 );
928 assert_eq!(
929 round_tripped.custom_values, original.custom_values,
930 "{name} custom_values"
931 );
932 assert_eq!(
933 round_tripped.positive_spans, original.positive_spans,
934 "{name} positive spans, zero-length and gapped segments included"
935 );
936 assert_eq!(
937 round_tripped.negative_spans, original.negative_spans,
938 "{name} negative spans"
939 );
940 assert_eq!(
941 count_bits(&round_tripped.positive_buckets),
942 count_bits(&original.positive_buckets),
943 "{name} positive buckets"
944 );
945 assert_eq!(
946 count_bits(&round_tripped.negative_buckets),
947 count_bits(&original.negative_buckets),
948 "{name} negative buckets"
949 );
950 assert_eq!(
953 round_tripped, original,
954 "{name}: the round trip changed the histogram"
955 );
956 }
957 }
958
959 #[test]
963 fn the_arithmetic_clears_the_start_timestamp() {
964 let mut left = empty(0, 0.0, 2.0, 3.0, 0.0);
965 left.start_timestamp = Some(1_000);
966 left.positive_spans = vec![span(0, 1)];
967 left.positive_buckets = vec![2.0];
968 let mut right = empty(0, 0.0, 1.0, 1.0, 0.0);
969 right.start_timestamp = Some(2_000);
970 right.positive_spans = vec![span(0, 1)];
971 right.positive_buckets = vec![1.0];
972
973 for (name, derived) in [
974 ("add", add(&left, &right).unwrap()),
975 ("sub", sub(&left, &right).unwrap()),
976 ("scale", scale(&left, 2.0)),
977 ("divide_by", divide_by(&left, 2.0)),
978 ] {
979 assert_eq!(
980 derived.start_timestamp, None,
981 "{name}: a derived histogram names no start"
982 );
983 }
984 assert_eq!(left.start_timestamp, Some(1_000));
986 assert_eq!(right.start_timestamp, Some(2_000));
987 }
988
989 #[test]
992 fn the_estimators_leave_the_start_timestamp_alone() {
993 let mut timed = empty(2, 0.5, 20.0, -3.0, 3.0);
994 timed.start_timestamp = Some(1_700_000_000_000);
995 timed.positive_spans = vec![span(0, 3)];
996 timed.positive_buckets = vec![4.0, 2.0, 5.0];
997 timed.negative_spans = vec![span(0, 2)];
998 timed.negative_buckets = vec![3.0, 3.0];
999 let mut untimed = timed.clone();
1000 untimed.start_timestamp = None;
1001
1002 for q in [0.0, 0.25, 0.5, 0.75, 1.0] {
1003 assert_eq!(
1004 quantile_with_info(&timed, q).0.to_bits(),
1005 quantile_with_info(&untimed, q).0.to_bits(),
1006 "q {q}: the start timestamp takes no part in the estimate"
1007 );
1008 }
1009 for (lower, upper) in [(-1.0, 2.0), (0.0, 1.0)] {
1010 assert_eq!(
1011 fraction_with_info(&timed, lower, upper).0.to_bits(),
1012 fraction_with_info(&untimed, lower, upper).0.to_bits(),
1013 "[{lower}, {upper}]: the start timestamp takes no part in the estimate"
1014 );
1015 }
1016 assert_eq!(
1017 timed.start_timestamp,
1018 Some(1_700_000_000_000),
1019 "estimating from a histogram must not rewrite it"
1020 );
1021 }
1022
1023 #[test]
1026 fn add_and_sub_reconcile_the_reset_hint_and_the_custom_bounds() {
1027 let mut reset = empty(0, 0.0, 2.0, 2.0, 0.0);
1030 reset.reset_hint = CounterResetHint::CounterReset;
1031 reset.positive_spans = vec![span(0, 1)];
1032 reset.positive_buckets = vec![2.0];
1033 let mut confirmed = empty(0, 0.0, 1.0, 1.0, 0.0);
1034 confirmed.reset_hint = CounterResetHint::NotCounterReset;
1035 confirmed.positive_spans = vec![span(0, 1)];
1036 confirmed.positive_buckets = vec![1.0];
1037
1038 let sum = add(&reset, &confirmed).unwrap();
1039 assert_eq!(
1040 sum.reset_hint,
1041 CounterResetHint::Unknown,
1042 "a contradiction the payload has to be inspected for"
1043 );
1044 assert_eq!(sum.count.to_bits(), 3.0f64.to_bits());
1045 assert_eq!(sum.sum.to_bits(), 3.0f64.to_bits());
1046 assert_eq!(sum.positive_buckets, vec![3.0]);
1047 assert_eq!(
1048 add(&confirmed, &reset).unwrap().reset_hint,
1049 CounterResetHint::Unknown,
1050 "the same contradiction in the other order"
1051 );
1052 assert_eq!(
1053 add(&confirmed, &confirmed).unwrap().reset_hint,
1054 CounterResetHint::NotCounterReset,
1055 "two counters that agree keep their agreement"
1056 );
1057 assert_eq!(
1058 sub(&reset, &confirmed).unwrap().reset_hint,
1059 CounterResetHint::Gauge,
1060 "subtraction is a gauge operation whatever the operands said"
1061 );
1062
1063 let mut left = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 6.0, 12.0, 0.0);
1065 left.custom_values = vec![1.0, 2.0, 4.0];
1066 left.positive_spans = vec![span(0, 3)];
1067 left.positive_buckets = vec![1.0, 3.0, 2.0];
1068 let mut right = empty(CUSTOM_BUCKETS_SCHEMA, 0.0, 6.0, 14.0, 0.0);
1069 right.custom_values = vec![2.0, 3.0, 4.0];
1070 right.positive_spans = vec![span(0, 3)];
1071 right.positive_buckets = vec![4.0, 1.0, 1.0];
1072
1073 let combined = add(&left, &right).unwrap();
1074 assert_eq!(
1075 combined.custom_values,
1076 vec![2.0, 4.0],
1077 "the intersection of (1, 2, 4) and (2, 3, 4)"
1078 );
1079 assert_eq!(combined.count.to_bits(), 12.0f64.to_bits());
1080 assert_eq!(combined.sum.to_bits(), 26.0f64.to_bits());
1081 assert_eq!(combined.positive_buckets, vec![8.0, 4.0]);
1085 assert_eq!(combined.positive_spans, vec![span(0, 2)]);
1086 }
1087
1088 #[test]
1091 fn sub_compacts_the_buckets_it_cancels_and_promql_eq_expands_the_spans() {
1092 let mut left = empty(2, 0.5, 4.0, 6.0, 0.0);
1093 left.positive_spans = vec![span(0, 2)];
1094 left.positive_buckets = vec![2.0, 1.5];
1095 left.negative_spans = vec![span(0, 1)];
1096 left.negative_buckets = vec![0.5];
1097
1098 let difference = sub(&left, &left).unwrap();
1099 assert_eq!(difference.count.to_bits(), 0.0f64.to_bits());
1100 assert_eq!(difference.sum.to_bits(), 0.0f64.to_bits());
1101 assert_eq!(difference.zero_count.to_bits(), 0.0f64.to_bits());
1102 assert!(
1103 difference.positive_spans.is_empty(),
1104 "a cancelled bucket leaves no span behind, got {:?}",
1105 difference.positive_spans
1106 );
1107 assert!(difference.positive_buckets.is_empty());
1108 assert!(difference.negative_spans.is_empty());
1109 assert!(difference.negative_buckets.is_empty());
1110 assert!(
1112 difference.promql_eq(&empty(2, 0.5, 0.0, 0.0, 0.0)),
1113 "the cancelling subtraction is the empty histogram"
1114 );
1115
1116 let mut one_span = empty(0, 0.0, 3.0, 3.0, 0.0);
1121 one_span.positive_spans = vec![span(0, 2)];
1122 one_span.positive_buckets = vec![1.0, 2.0];
1123 let mut two_spans = empty(0, 0.0, 3.0, 3.0, 0.0);
1124 two_spans.positive_spans = vec![span(0, 1), span(0, 1)];
1125 two_spans.positive_buckets = vec![1.0, 2.0];
1126 assert!(
1127 one_span.promql_eq(&two_spans),
1128 "the same indices and counts under a different segmentation"
1129 );
1130
1131 let mut gapped = empty(0, 0.0, 3.0, 3.0, 0.0);
1132 gapped.positive_spans = vec![span(0, 1), span(1, 1)];
1133 gapped.positive_buckets = vec![1.0, 2.0];
1134 assert!(
1135 !one_span.promql_eq(&gapped),
1136 "the same counts at indices 0 and 2 are not the same histogram"
1137 );
1138 let mut other_counts = two_spans.clone();
1139 other_counts.positive_buckets = vec![2.0, 1.0];
1140 assert!(
1141 !one_span.promql_eq(&other_counts),
1142 "the same indices with other counts are not the same histogram"
1143 );
1144 }
1145
1146 fn unreadable_layouts() -> Vec<(&'static str, NativeHistogram, Option<i64>)> {
1151 let mut short_counts = empty(0, 0.0, 3.0, 5.0, 1.0);
1153 short_counts.reset_hint = CounterResetHint::NotCounterReset;
1154 short_counts.positive_spans = vec![span(0, 1)];
1155 short_counts.positive_buckets = vec![1.0, 2.0];
1156 let mut backwards = short_counts.clone();
1157 backwards.positive_spans = vec![span(0, 1), span(-1, 1)];
1158 let mut overflow = short_counts.clone();
1159 overflow.positive_spans = vec![span(i32::MAX, 2)];
1160 let mut negative_length = short_counts.clone();
1161 negative_length.positive_spans = vec![span(0, -1)];
1162
1163 vec![
1164 ("short_counts", short_counts, Some(4_242)),
1165 ("backwards", backwards, Some(4_243)),
1166 ("overflow", overflow, Some(4_244)),
1167 ("negative_length", negative_length, Some(4_245)),
1168 ]
1169 .into_iter()
1170 .map(|(name, mut histogram, start_timestamp)| {
1171 histogram.start_timestamp = start_timestamp;
1172 (name, histogram, start_timestamp)
1173 })
1174 .collect()
1175 }
1176
1177 #[test]
1181 fn scale_and_divide_fall_back_to_the_fields_for_an_unreadable_layout() {
1182 for (name, histogram, start_timestamp) in unreadable_layouts() {
1183 let negated = scale(&histogram, -0.5);
1185 assert_eq!(negated.count, -1.5, "{name} count");
1186 assert_eq!(negated.sum, -2.5, "{name} sum");
1187 assert_eq!(negated.zero_count, -0.5, "{name} zero_count");
1188 assert_eq!(
1189 negated.positive_buckets,
1190 vec![-0.5, -1.0],
1191 "{name} positive"
1192 );
1193 assert_eq!(negated.reset_hint, CounterResetHint::Gauge, "{name} hint");
1194 assert_eq!(
1195 negated.start_timestamp, start_timestamp,
1196 "{name}: the field-by-field fallback copies the payload, so the start timestamp \
1197 survives where the kernel path clears it"
1198 );
1199 assert_eq!(
1200 negated.positive_spans, histogram.positive_spans,
1201 "{name}: the fallback keeps the layout it cannot expand"
1202 );
1203
1204 let doubled = scale(&histogram, 2.0);
1205 assert_eq!(doubled.count, 6.0, "{name} count");
1206 assert_eq!(doubled.sum, 10.0, "{name} sum");
1207 assert_eq!(doubled.zero_count, 2.0, "{name} zero_count");
1208 assert_eq!(doubled.positive_buckets, vec![2.0, 4.0], "{name} positive");
1209 assert_eq!(
1210 doubled.reset_hint,
1211 CounterResetHint::NotCounterReset,
1212 "{name}: a positive factor leaves a hint alone"
1213 );
1214 assert_eq!(doubled.start_timestamp, start_timestamp, "{name}");
1215
1216 let quartered = divide_by(&histogram, 4.0);
1217 assert_eq!(quartered.count, 0.75, "{name} count");
1218 assert_eq!(quartered.sum, 1.25, "{name} sum");
1219 assert_eq!(quartered.zero_count, 0.25, "{name} zero_count");
1220 assert_eq!(
1221 quartered.positive_buckets,
1222 vec![0.25, 0.5],
1223 "{name} positive"
1224 );
1225 assert_eq!(
1226 quartered.reset_hint,
1227 CounterResetHint::NotCounterReset,
1228 "{name}: a positive divisor leaves a hint alone"
1229 );
1230 assert_eq!(quartered.start_timestamp, start_timestamp, "{name}");
1231
1232 let over_zero = divide_by(&histogram, 0.0);
1234 assert_eq!(over_zero.count, f64::INFINITY, "{name} count");
1235 assert_eq!(over_zero.sum, f64::INFINITY, "{name} sum");
1236 assert_eq!(over_zero.zero_count, f64::INFINITY, "{name} zero_count");
1237 assert!(over_zero.positive_spans.is_empty(), "{name}");
1238 assert!(over_zero.positive_buckets.is_empty(), "{name}");
1239 assert_eq!(over_zero.start_timestamp, start_timestamp, "{name}");
1240
1241 assert!(
1244 add(&histogram, &histogram).is_none(),
1245 "{name}: a layout the kernel cannot read has no sum"
1246 );
1247 assert!(
1248 sub(&histogram, &histogram).is_none(),
1249 "{name}: a layout the kernel cannot read has no difference"
1250 );
1251 }
1252 }
1253
1254 #[test]
1258 fn scale_and_divide_by_the_edge_factors() {
1259 let mut histogram = empty(0, 0.0, 4.0, 6.0, 0.0);
1260 histogram.reset_hint = CounterResetHint::NotCounterReset;
1261 histogram.start_timestamp = Some(7);
1262 histogram.positive_spans = vec![span(0, 2)];
1263 histogram.positive_buckets = vec![3.0, 1.0];
1264 histogram.negative_spans = vec![span(0, 1)];
1265 histogram.negative_buckets = vec![1.0];
1266
1267 let over_zero = divide_by(&histogram, 0.0);
1268 assert_eq!(over_zero.count, f64::INFINITY, "a positive count over zero");
1269 assert_eq!(over_zero.sum, f64::INFINITY, "a positive sum over zero");
1270 assert!(
1271 over_zero.zero_count.is_nan(),
1272 "a zero count over zero is NaN"
1273 );
1274 assert!(over_zero.positive_spans.is_empty());
1275 assert!(over_zero.positive_buckets.is_empty());
1276 assert!(over_zero.negative_spans.is_empty());
1277 assert!(over_zero.negative_buckets.is_empty());
1278 assert_eq!(over_zero.start_timestamp, None);
1279 assert_eq!(
1280 over_zero.reset_hint,
1281 CounterResetHint::NotCounterReset,
1282 "a zero divisor is not a negative one"
1283 );
1284
1285 let over_negative_zero = divide_by(&histogram, -0.0);
1288 assert_eq!(
1289 over_negative_zero.count,
1290 f64::NEG_INFINITY,
1291 "a positive count over negative zero"
1292 );
1293 assert_eq!(
1294 over_negative_zero.sum,
1295 f64::NEG_INFINITY,
1296 "a positive sum over negative zero"
1297 );
1298 assert!(over_negative_zero.zero_count.is_nan());
1299 assert!(over_negative_zero.positive_spans.is_empty());
1300 assert!(over_negative_zero.positive_buckets.is_empty());
1301 assert_eq!(over_negative_zero.start_timestamp, None);
1302 assert_eq!(
1303 over_negative_zero.reset_hint,
1304 CounterResetHint::NotCounterReset,
1305 "negative zero is not a negative factor"
1306 );
1307
1308 let over_nan = scale(&histogram, f64::NAN);
1309 assert!(over_nan.count.is_nan() && over_nan.sum.is_nan());
1310 assert!(over_nan.positive_buckets.iter().all(|count| count.is_nan()));
1311 assert!(over_nan.negative_buckets.iter().all(|count| count.is_nan()));
1312 assert_eq!(
1313 over_nan.positive_spans,
1314 vec![span(0, 2)],
1315 "a NaN factor moves the counts, not the layout"
1316 );
1317 assert_eq!(over_nan.start_timestamp, None);
1318 assert_eq!(
1319 over_nan.reset_hint,
1320 CounterResetHint::NotCounterReset,
1321 "a NaN factor is not a negative one"
1322 );
1323
1324 let negated = scale(&histogram, -2.0);
1325 assert_eq!(negated.count, -8.0);
1326 assert_eq!(negated.sum, -12.0);
1327 assert_eq!(negated.positive_buckets, vec![-6.0, -2.0]);
1328 assert_eq!(negated.negative_buckets, vec![-2.0]);
1329 assert_eq!(negated.positive_spans, vec![span(0, 2)]);
1330 assert_eq!(negated.reset_hint, CounterResetHint::Gauge);
1331 assert_eq!(negated.start_timestamp, None);
1332
1333 let negated_division = divide_by(&histogram, -2.0);
1334 assert_eq!(negated_division.count, -2.0);
1335 assert_eq!(negated_division.sum, -3.0);
1336 assert_eq!(negated_division.positive_buckets, vec![-1.5, -0.5]);
1337 assert_eq!(negated_division.negative_buckets, vec![-0.5]);
1338 assert_eq!(negated_division.reset_hint, CounterResetHint::Gauge);
1339 assert_eq!(negated_division.start_timestamp, None);
1340 }
1341}