Skip to main content

promql/histogram_eval/
legacy_bridge.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The legacy native-histogram estimators, delegated to the native kernel.
16//!
17//! `prom_native_histogram_quantile` and `prom_native_histogram_fraction` used to estimate with the
18//! bucket walk inside `NativeHistogram` itself: exponential bucket bounds computed as `2^x`, and a
19//! forward walk from the lowest bucket only. The native kernel (`histogram_eval`) walks the same
20//! histogram the way Prometheus does -- the bound table in `bounds` and, for a quantile above the
21//! median of a histogram whose sum is not NaN, a walk from the highest bucket down -- so keeping
22//! both estimators leaves two answers for one histogram that differ in their last places.
23//!
24//! These functions read a [`NativeHistogram`] through the borrowed [`HistogramView`] that both
25//! representations share, hand it to the kernel as the [`FloatHistogram`] the kernel owns, and
26//! return the answer in the shape the legacy UDFs report it. The scalar arithmetic -- `add`, `sub`,
27//! `scale`, `divide_by` -- takes the same route below the estimators, so Prometheus's rules for
28//! reconciling a zero bucket, reducing a schema and intersecting custom bounds live in one place.
29
30use 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
39/// A [`NativeHistogram`] borrowed as a [`HistogramView`], the form the native kernel reads.
40///
41/// A view holds its spans as two parallel slices while a `NativeHistogram` holds them as
42/// [`Span`]s, so the offsets and lengths are copied here and the counts, bounds and metadata stay
43/// borrowed for as long as the view lives.
44pub(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    /// The view of the histogram these span columns were taken from.
66    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
94/// `histogram_quantile(q, histogram)`, with the NaN-observation note the legacy UDF records.
95pub(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        // The kernel refuses a layout it cannot walk, a custom histogram carrying a zero count
103        // among them. The legacy estimator reported a histogram it could not read as no estimate,
104        // which is the same NaN without a note about NaN observations.
105        Err(_) => (f64::NAN, None),
106    }
107}
108
109/// `histogram_fraction(lower, upper, histogram)`, with whether NaN observations were excluded.
110pub(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            // The same answer the legacy estimator gave: a fraction is degenerate, and reports
119            // nothing, unless it runs for a non-empty histogram over an increasing pair of bounds.
120            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
132/// The note for a NaN observation, which the kernel accounts for but does not report.
133///
134/// A NaN observation leaves the sum NaN and puts fewer observations in the buckets than the count
135/// holds them (Prometheus marks it the same way). The kernel then walks the buckets forward from
136/// the lowest, so the note distinguishes the two outcomes: the estimate is skewed higher when the
137/// requested rank falls inside the buckets' total, and NaN when it falls past it because the
138/// observations the buckets cannot carry were the highest ones.
139fn 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
157/// What the populated buckets hold, summed in the order the kernel walks them: the negative side
158/// from its highest index down, the zero bucket, then the positive side upwards.
159fn 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
171/// The native kernel's owned form of `histogram`.
172///
173/// A view borrows the offsets and lengths it needs from two temporary slices, so the copy happens
174/// here and the `FloatHistogram` owns the counts that result.
175fn 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
185/// Whether a span list steps backwards, which the legacy `bucket_indices` refused.
186///
187/// The kernel's `side_from_view` adds each offset to a running index and accepts a later span that
188/// steps backwards, so the expanded indices repeat or go negative. Legacy refused such a list
189/// outright, so the bridge refuses it too: `add`/`sub` answer `None` as they did, and
190/// `scale`/`divide_by` keep their field-by-field fallback.
191fn steps_backwards(spans: &[Span]) -> bool {
192    spans.iter().skip(1).any(|span| span.offset < 0)
193}
194
195/// The legacy representation of `histogram`, with the span layout it carries.
196fn 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
225/// `left + right`, or `None` for a pair the kernel refuses to combine.
226pub(crate) fn add(left: &NativeHistogram, right: &NativeHistogram) -> Option<NativeHistogram> {
227    combine(left, right, false)
228}
229
230/// `left - right`, a gauge histogram the way Prometheus's `-` leaves it.
231pub(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    // The outcome reports what the kernel already folded into the result, and the legacy callers
249    // report both from the operands before the call: `custom_bounds_reconciled` is the intersection
250    // the kernel keeps in `custom_values`, which `needs_custom_reconciliation` announces, and a
251    // `counter_reset_collision` is the contradiction the kernel answers with an unknown hint, which
252    // is what the legacy arithmetic derived from two hints that disagree. Holding the kernel to
253    // both keeps a change there from dropping either.
254    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    // The legacy arithmetic compacted a sum, so a bucket the two sides cancel out of leaves no
265    // span behind; the kernel keeps the bucket until a caller drops it.
266    combined.compact();
267    Some(legacy_histogram(&combined))
268}
269
270/// `histogram * factor`, a gauge histogram for a negative factor.
271pub(crate) fn scale(histogram: &NativeHistogram, factor: f64) -> NativeHistogram {
272    let Ok(mut scaled) = float_histogram(histogram) else {
273        // A layout the kernel cannot read -- spans that disagree with the counts, or a bucket index
274        // that leaves `i32` once expanded -- keeps the field-by-field scaling the legacy caller
275        // had, so such a histogram is still multiplied instead of dropped, and reports its layout
276        // when it is serialized. Scaling has no bounds to reconcile, so nothing is lost here.
277        return field_scaled(histogram, factor);
278    };
279    scaled.mul(factor);
280    legacy_histogram(&scaled)
281}
282
283/// `histogram / divisor`, with no buckets left for a zero divisor.
284pub(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(&divided)
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    /// Every kind of histogram the legacy representation can hold: exponential and custom, one
350    /// side and two, a zero bucket, gaps between the spans, a NaN sum standing for NaN
351    /// observations, and a histogram with no buckets at all.
352    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        // With more than one bucket, the kernel's NaN branch walks the remaining buckets and leaves
367        // the last one behind for the interpolation, so the chosen bucket is not the one the rank
368        // fell into. A single-bucket fixture cannot reach that path.
369        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        // Its zero bucket holds observations of its own, so the layout is not empty even though
380        // no span is populated.
381        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    /// The view of `histogram`, written out here rather than through [`super::LegacyView`] so that
427    /// a conversion mistake shows up as a failed comparison instead of cancelling out.
428    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    /// The legacy UDFs read their quantile out of the kernel now, so the two must agree to the
456    /// last bit for every kind of histogram the legacy representation can hold.
457    #[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    /// Prometheus's NaN branch walks the remaining buckets and leaves the last one for the
489    /// interpolation, so a multi-bucket `sum = NaN` histogram answers with the top bucket rather
490    /// than the bucket the rank fell into. Pinning the number here, rather than only comparing
491    /// against the kernel, keeps a future kernel change from silently re-deciding it.
492    #[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        // The nine observations the buckets hold are fewer than the count of ten and the sum is
499        // NaN, so the note reports the skew: the rank still falls inside what the buckets carry.
500        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    /// The other half of the same note: a rank past the total the buckets carry is no estimate at
515    /// all, because the observations the buckets cannot hold were the highest ones.
516    #[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        // The rank 0.95 * 10 = 9.5 lies past the 9 observations the buckets hold, so the forward
523        // walk never reaches it and the estimate is NaN rather than the last bucket's bound.
524        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        // The single-bucket fixture the earlier note test uses reaches the same branch: the rank
536        // 0.9 * 10 = 9 lies past the 8 observations the one bucket holds.
537        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    /// A tie between two buckets that do not touch resolves differently in the two walks, and that
548    /// difference is why the kernel replaced the estimator: the legacy walk goes up from the lowest
549    /// bucket and stops at the first one the rank fits in, while the kernel walks a finite-sum
550    /// histogram at or above the median down from the highest. Both numbers are pinned as literals,
551    /// the legacy one computed through the estimator still in `common/query`, so that a later
552    /// change to either walk shows up as an arithmetic difference instead of a quiet one.
553    #[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        // Index 0 and index 2 hold one observation each, and index 1 is empty, so the two buckets
557        // do not touch and nothing interpolates across the gap.
558        tie.positive_spans = vec![span(0, 1), span(1, 1)];
559        tie.positive_buckets = vec![1.0, 1.0];
560
561        // `NativeHistogram::quantile_with_info` is the estimator the legacy UDF used before the
562        // kernel replaced it and is still in the workspace: rank 0.5 * 2 = 1 fills the bucket at
563        // index 0 exactly, whose fraction is 1, so the answer is that bucket's upper bound.
564        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        // The kernel's backwards walk meets the bucket at index 2 first, and the rank inside it is
571        // 0, so the answer is the lower bound of (2, 4].
572        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    /// The same agreement for `histogram_fraction`, whose legacy wrapper also returns a note.
585    #[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    /// Pairs the legacy arithmetic has to reconcile: the same layout, a resolution difference, a
618    /// zero bucket one side has to grow into the other, mismatched custom bounds, and NaN
619    /// observations.
620    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        // Every operand carries a start timestamp of its own, because the arithmetic is expected to
663        // clear it: a sum differs from both samples it was derived from, so it names no start.
664        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    /// The buckets a side holds that carry observations, by index and bit pattern.
685    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    /// Bucket counts by their exact bit patterns, so a comparison also holds for a NaN or a signed
715    /// zero a scaling left behind.
716    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    /// A span list as the `(offset, length)` pairs [`FloatHistogram::spans`] reports.
725    fn segments(spans: &[Span]) -> Vec<(i32, i32)> {
726        spans
727            .iter()
728            .map(|span| (span.offset, span.length))
729            .collect()
730    }
731
732    /// Every field of the legacy payload against the kernel's, span segmentation included: a
733    /// comparison of the populated buckets alone cannot tell one span of two buckets from two
734    /// spans of one bucket each, and says nothing about the metadata beside the counts.
735    ///
736    /// `expected_start_timestamp` states the policy of the operation that produced the payload. One
737    /// that derives a histogram from its input -- `add`, `sub`, `scale`, `divide_by` -- clears the
738    /// start timestamp, because the field names the start of the sample the payload was read from
739    /// and a derived value is not that sample; the kernel clears it in the same step, so both sides
740    /// must carry the value passed here. `scale` and `divide_by` keep a field-by-field fallback for
741    /// a layout the kernel cannot read, which derives nothing and copies the field, and the test
742    /// that exercises it asserts `Some(..)` where it belongs. `quantile_with_info` and
743    /// `fraction_with_info` return no payload and leave their input untouched, so they have no
744    /// start timestamp to compare here.
745    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    /// The added histogram is the kernel's addition, bucket for bucket and bit for bit.
816    #[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            // The bridge compacts a sum, dropping the buckets the two sides left empty, so the
823            // kernel's own addition needs the same step before the two payloads can be compared
824            // bucket for bucket.
825            native.compact();
826            assert_same_payload(name, &combined, &native, None);
827        }
828    }
829
830    /// The same for subtraction, which the kernel reports as an addition of the negation.
831    #[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    /// Scaling and dividing move every count and leave the layout alone, as the kernel's own
845    /// multiplication and division do.
846    #[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, &divided, &native, None);
859            }
860        }
861    }
862
863    /// The note the legacy UDFs turn into an annotation follows the kernel's outcome instead of a
864    /// second reading of the histogram.
865    #[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    /// The two conversions are inverse: the payload survives `NativeHistogram` to
895    /// [`FloatHistogram`] and back field for field, including the parts a comparison of the counts
896    /// alone would not see.
897    #[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        // A zero-length span carries nothing but its offset, and the two gaps between the three
903        // populated segments are part of the layout the legacy representation reports: the counts
904        // live at indices 2 and 3 and then 5, with nothing at 4.
905        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            // Everything else the payload holds -- schema, zero threshold, count, sum and the zero
951            // count -- is compared in one place above.
952            assert_eq!(
953                round_tripped, original,
954                "{name}: the round trip changed the histogram"
955            );
956        }
957    }
958
959    /// A histogram an operation derived carries no start timestamp: the field names the start of
960    /// the sample the payload was read from, and a sum, a difference, a product or a quotient is
961    /// not that sample.
962    #[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        // Reading the operands is not deriving from them.
985        assert_eq!(left.start_timestamp, Some(1_000));
986        assert_eq!(right.start_timestamp, Some(2_000));
987    }
988
989    /// The estimators read the buckets rather than the sample's start timestamp, and neither of
990    /// them hands back a payload, so the field neither changes the answer nor changes itself.
991    #[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    /// The arithmetic reconciles what the two operands disagree about, and reports it in the
1024    /// payload: the reset hint combination and the custom bounds.
1025    #[test]
1026    fn add_and_sub_reconcile_the_reset_hint_and_the_custom_bounds() {
1027        // A reset and a confirmation contradict each other, so a sum of the two cannot claim
1028        // either: the kernel answers with the hint that must be inspected.
1029        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        // Custom bounds that disagree leave the result with the bounds both sides carry.
1064        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        // Each side's buckets land in the interval of the merged bounds they fall in: `(-inf, 2]`
1082        // takes 1 + 3 from the left and 4 from the right, and `(2, 4]` takes 2 from the left and
1083        // 1 + 1 from the right. The empty `(4, inf)` bucket is dropped before it reaches a span.
1084        assert_eq!(combined.positive_buckets, vec![8.0, 4.0]);
1085        assert_eq!(combined.positive_spans, vec![span(0, 2)]);
1086    }
1087
1088    /// A bucket the two sides cancel out of leaves no span behind, and `promql_eq` reads the
1089    /// buckets the spans expand to rather than the span list they are written with.
1090    #[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        // The same histogram as no histogram at all.
1111        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        // Two spans of one bucket each describe the same buckets as one span of two: the first
1117        // span's offset is the bucket index, and each later offset is the gap after the previous
1118        // span, so `(0, 1), (0, 1)` puts the second bucket at index 1 while `(0, 1), (1, 1)`
1119        // leaves index 1 empty and puts it at index 2.
1120        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    /// Payloads the legacy caller could still produce and the kernel refuses to read: a span whose
1147    /// length disagrees with the counts, a span list that steps backwards, an index that leaves
1148    /// `i32` once expanded, and a negative span length. All four carry the same numbers, so the
1149    /// field-by-field answers below are the same for each of them.
1150    fn unreadable_layouts() -> Vec<(&'static str, NativeHistogram, Option<i64>)> {
1151        // The span claims one bucket and the counts hold two.
1152        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    /// A layout the kernel cannot walk keeps the field-by-field scaling and division the legacy
1178    /// caller had, so such a histogram is still multiplied instead of dropped, and keeps the start
1179    /// timestamp it was stored with.
1180    #[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            // A negative factor turns the histogram into a gauge; the untouched hint otherwise.
1184            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            // A zero divisor empties the buckets on this path too.
1233            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            // The addition and the subtraction refuse the same layout outright, as the legacy
1242            // arithmetic did, rather than answering with a payload the kernel never built.
1243            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    /// The factors that are not a plain finite number, on a layout the kernel can walk: a zero
1255    /// divisor leaves no bucket, a NaN factor reaches every count, and a negative one turns the
1256    /// histogram into a gauge.
1257    #[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        // A negative zero is still zero, so the buckets go the same way, and the quotients it
1286        // leaves behind are the negative infinities.
1287        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}