Skip to main content

promql/functions/
native_histogram.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//! Native histogram PromQL helpers.
16
17use std::hash::{Hash, Hasher};
18use std::mem::size_of;
19use std::sync::Arc;
20
21use common_query::native_histogram::*;
22use common_query::prometheus::format_prometheus_float;
23use common_query::promql_annotations::PromqlAnnotationCollector;
24use datafusion::arrow::array::{
25    Array, ArrayRef, BooleanArray, Float64Array, Float64Builder, Int64Array, StringBuilder,
26    StructArray, TimestampMillisecondArray, UInt64Array,
27};
28use datafusion::arrow::compute::filter;
29use datafusion::arrow::datatypes::{DataType, Field, TimeUnit};
30use datafusion::common::{DataFusionError, Result as DfResult};
31use datafusion::logical_expr::{Accumulator as DfAccumulator, AggregateUDF, ScalarUDF, Volatility};
32use datafusion::physical_plan::ColumnarValue;
33use datafusion_common::ScalarValue;
34use datafusion_expr::function::AccumulatorArgs;
35use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, create_udaf, create_udf};
36use datatypes::series::aggregate_state::HistogramState;
37use datatypes::series::histogram::{BucketSideView, HistogramView};
38
39use crate::aggregate::{
40    AggregateOp, HistogramAccumulator, HistogramEvidence, accumulator_bytes, finished_histogram,
41    histogram_batch,
42};
43use crate::functions::{
44    AvgOverTime, Deriv, DoubleExponentialSmoothing, IDelta, Increase, LastOverTime, MaxOverTime,
45    MinOverTime, PredictLinear, QuantileOverTime, Rate, StddevOverTime, StdvarOverTime,
46    SumOverTime, extract_array, extract_range_dict,
47};
48use crate::histogram_eval::float_histogram::FloatHistogram;
49use crate::histogram_eval::{self, HistogramAggregate, legacy_bridge};
50use crate::range_array::{RangeArray, unpack};
51
52fn extract_histogram_array(value: &ColumnarValue, func_name: &str) -> DfResult<ArrayRef> {
53    let array = extract_array(value)?;
54    if array.data_type() != &native_histogram_arrow_type() {
55        return Err(DataFusionError::Execution(format!(
56            "{func_name}: expected native histogram struct, found {}",
57            array.data_type()
58        )));
59    }
60    Ok(array)
61}
62
63fn read_scalar_f64_arg(
64    value: &ColumnarValue,
65    row: usize,
66    len: usize,
67    func_name: &str,
68) -> DfResult<f64> {
69    match value {
70        ColumnarValue::Scalar(ScalarValue::Float64(value)) => Ok(value.unwrap_or(f64::NAN)),
71        ColumnarValue::Array(array) => {
72            let array = array
73                .as_any()
74                .downcast_ref::<Float64Array>()
75                .ok_or_else(|| {
76                    DataFusionError::Execution(format!(
77                        "{func_name}: expected Float64 argument, found {}",
78                        array.data_type()
79                    ))
80                })?;
81            if array.len() != len {
82                return Err(DataFusionError::Execution(format!(
83                    "{func_name}: Float64 argument length mismatch: {} vs {len}",
84                    array.len()
85                )));
86            }
87            Ok(if array.is_null(row) {
88                f64::NAN
89            } else {
90                array.value(row)
91            })
92        }
93        other => Err(DataFusionError::Execution(format!(
94            "{func_name}: expected Float64 argument, found {}",
95            other.data_type()
96        ))),
97    }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101enum AnnotationReturn {
102    FloatNull,
103    BooleanTrue,
104    BooleanFalse,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108enum AnnotationLevel {
109    Info,
110    Warning,
111}
112
113impl AnnotationReturn {
114    fn data_type(self) -> DataType {
115        match self {
116            Self::FloatNull => DataType::Float64,
117            Self::BooleanTrue | Self::BooleanFalse => DataType::Boolean,
118        }
119    }
120
121    fn scalar_value(self) -> ScalarValue {
122        match self {
123            Self::FloatNull => ScalarValue::Float64(None),
124            Self::BooleanTrue => ScalarValue::Boolean(Some(true)),
125            Self::BooleanFalse => ScalarValue::Boolean(Some(false)),
126        }
127    }
128}
129
130#[derive(Debug, Clone)]
131struct NativeHistogramAnnotationUdf {
132    name: &'static str,
133    signature: Signature,
134    return_kind: AnnotationReturn,
135    level: AnnotationLevel,
136    message: String,
137    collector: Option<PromqlAnnotationCollector>,
138}
139
140impl NativeHistogramAnnotationUdf {
141    fn new(
142        name: &'static str,
143        return_kind: AnnotationReturn,
144        level: AnnotationLevel,
145        message: String,
146        collector: Option<PromqlAnnotationCollector>,
147    ) -> Self {
148        Self {
149            name,
150            signature: Signature::variadic_any(Volatility::Volatile),
151            return_kind,
152            level,
153            message,
154            collector,
155        }
156    }
157}
158
159impl PartialEq for NativeHistogramAnnotationUdf {
160    fn eq(&self, other: &Self) -> bool {
161        self.name == other.name
162            && self.return_kind == other.return_kind
163            && self.level == other.level
164            && self.message == other.message
165    }
166}
167
168impl Eq for NativeHistogramAnnotationUdf {}
169
170impl Hash for NativeHistogramAnnotationUdf {
171    fn hash<H: Hasher>(&self, state: &mut H) {
172        self.name.hash(state);
173        self.return_kind.hash(state);
174        self.level.hash(state);
175        self.message.hash(state);
176    }
177}
178
179impl ScalarUDFImpl for NativeHistogramAnnotationUdf {
180    fn name(&self) -> &str {
181        self.name
182    }
183
184    fn signature(&self) -> &Signature {
185        &self.signature
186    }
187
188    fn return_type(&self, _arg_types: &[DataType]) -> DfResult<DataType> {
189        Ok(self.return_kind.data_type())
190    }
191
192    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DfResult<ColumnarValue> {
193        let has_dropped_sample = !args.args.is_empty()
194            && (0..args.number_rows).any(|row| {
195                args.args.iter().all(|arg| match arg {
196                    ColumnarValue::Array(array) => array.is_valid(row),
197                    ColumnarValue::Scalar(value) => !value.is_null(),
198                })
199            });
200        if has_dropped_sample
201            && let Some(collector) = args
202                .config_options
203                .extensions
204                .get::<PromqlAnnotationCollector>()
205                .cloned()
206                .or_else(|| self.collector.clone())
207        {
208            match self.level {
209                AnnotationLevel::Info => collector.record_info(self.message.clone()),
210                AnnotationLevel::Warning => collector.record_warning(self.message.clone()),
211            }
212        }
213        Ok(ColumnarValue::Scalar(self.return_kind.scalar_value()))
214    }
215}
216
217pub struct NativeHistogramDrop;
218
219impl NativeHistogramDrop {
220    const fn float_null_name() -> &'static str {
221        "prom_native_histogram_drop_float"
222    }
223
224    const fn bool_false_name() -> &'static str {
225        "prom_native_histogram_drop_bool"
226    }
227
228    const fn bool_true_name() -> &'static str {
229        "prom_native_histogram_keep_bool"
230    }
231
232    pub fn float_null_udf(
233        message: String,
234        collector: Option<PromqlAnnotationCollector>,
235    ) -> ScalarUDF {
236        ScalarUDF::new_from_impl(NativeHistogramAnnotationUdf::new(
237            Self::float_null_name(),
238            AnnotationReturn::FloatNull,
239            AnnotationLevel::Info,
240            message,
241            collector,
242        ))
243    }
244
245    pub fn bool_false_udf(
246        message: String,
247        collector: Option<PromqlAnnotationCollector>,
248    ) -> ScalarUDF {
249        ScalarUDF::new_from_impl(NativeHistogramAnnotationUdf::new(
250            Self::bool_false_name(),
251            AnnotationReturn::BooleanFalse,
252            AnnotationLevel::Info,
253            message,
254            collector,
255        ))
256    }
257
258    pub fn bool_true_udf(
259        message: String,
260        collector: Option<PromqlAnnotationCollector>,
261    ) -> ScalarUDF {
262        ScalarUDF::new_from_impl(NativeHistogramAnnotationUdf::new(
263            Self::bool_true_name(),
264            AnnotationReturn::BooleanTrue,
265            AnnotationLevel::Info,
266            message,
267            collector,
268        ))
269    }
270
271    pub fn warning_bool_false_udf(
272        message: String,
273        collector: Option<PromqlAnnotationCollector>,
274    ) -> ScalarUDF {
275        ScalarUDF::new_from_impl(NativeHistogramAnnotationUdf::new(
276            Self::bool_false_name(),
277            AnnotationReturn::BooleanFalse,
278            AnnotationLevel::Warning,
279            message,
280            collector,
281        ))
282    }
283}
284
285fn record_info(collector: &Option<PromqlAnnotationCollector>, message: impl Into<String>) {
286    if let Some(collector) = collector {
287        collector.record_info(message);
288    }
289}
290
291fn record_warning(collector: &Option<PromqlAnnotationCollector>, message: impl Into<String>) {
292    if let Some(collector) = collector {
293        collector.record_warning(message);
294    }
295}
296
297fn record_custom_reconciliation(
298    collector: &Option<PromqlAnnotationCollector>,
299    name: &'static str,
300    lhs: &NativeHistogram,
301    rhs: &NativeHistogram,
302) {
303    if lhs.needs_custom_reconciliation(rhs) {
304        record_reconciled_custom_buckets(collector, name);
305    }
306}
307
308/// Records that two custom-bucket layouts met and the result uses the bounds they share.
309fn record_reconciled_custom_buckets(
310    collector: &Option<PromqlAnnotationCollector>,
311    name: &'static str,
312) {
313    record_info(
314        collector,
315        format!("{name}: reconciled native histograms with different custom buckets"),
316    );
317}
318
319fn record_counter_reset_contradiction(
320    collector: &Option<PromqlAnnotationCollector>,
321    name: &'static str,
322    lhs: &NativeHistogram,
323    rhs: &NativeHistogram,
324) {
325    if lhs.counter_reset_hints_contradict(rhs) {
326        record_counter_reset_contradiction_warning(collector, name);
327    }
328}
329
330fn record_counter_reset_contradiction_warning(
331    collector: &Option<PromqlAnnotationCollector>,
332    name: &'static str,
333) {
334    record_warning(
335        collector,
336        format!("{name}: native histogram counter reset hints contradict"),
337    );
338}
339
340fn scalar_histogram_udf<F>(
341    name: &'static str,
342    extra_input_types: Vec<DataType>,
343    calc: F,
344) -> ScalarUDF
345where
346    F: Fn(&NativeHistogram, &[ColumnarValue], usize, usize, &'static str) -> DfResult<f64>
347        + Send
348        + Sync
349        + 'static,
350{
351    let mut input_types = vec![native_histogram_arrow_type()];
352    input_types.extend(extra_input_types);
353    create_udf(
354        name,
355        input_types,
356        DataType::Float64,
357        Volatility::Volatile,
358        Arc::new(move |input: &[ColumnarValue]| {
359            if input.is_empty() {
360                return Err(DataFusionError::Plan(format!(
361                    "{name} requires a native histogram argument"
362                )));
363            }
364            let histograms = extract_histogram_array(&input[0], name)?;
365            let histograms = histograms
366                .as_any()
367                .downcast_ref::<StructArray>()
368                .expect("validated native histogram struct");
369            let mut result = Float64Builder::with_capacity(histograms.len());
370            for row in 0..histograms.len() {
371                match read_histogram(histograms, row)? {
372                    Some(histogram) => {
373                        result.append_value(calc(&histogram, input, row, histograms.len(), name)?)
374                    }
375                    None => result.append_null(),
376                }
377            }
378            Ok(ColumnarValue::Array(Arc::new(result.finish())))
379        }) as _,
380    )
381}
382
383fn histogram_pair_udf(
384    name: &'static str,
385    op: fn(&NativeHistogram, &NativeHistogram) -> Option<NativeHistogram>,
386) -> ScalarUDF {
387    histogram_pair_udf_with_collector(name, op, None)
388}
389
390fn histogram_pair_udf_with_collector(
391    name: &'static str,
392    op: fn(&NativeHistogram, &NativeHistogram) -> Option<NativeHistogram>,
393    collector: Option<PromqlAnnotationCollector>,
394) -> ScalarUDF {
395    create_udf(
396        name,
397        vec![native_histogram_arrow_type(), native_histogram_arrow_type()],
398        native_histogram_arrow_type(),
399        Volatility::Volatile,
400        Arc::new(move |input: &[ColumnarValue]| {
401            let lhs = extract_histogram_array(&input[0], name)?;
402            let rhs = extract_histogram_array(&input[1], name)?;
403            if lhs.len() != rhs.len() {
404                return Err(DataFusionError::Execution(format!(
405                    "{name}: native histogram argument length mismatch: {} vs {}",
406                    lhs.len(),
407                    rhs.len()
408                )));
409            }
410
411            let lhs = lhs
412                .as_any()
413                .downcast_ref::<StructArray>()
414                .expect("validated native histogram struct");
415            let rhs = rhs
416                .as_any()
417                .downcast_ref::<StructArray>()
418                .expect("validated native histogram struct");
419            let mut result = Vec::with_capacity(lhs.len());
420            for row in 0..lhs.len() {
421                result.push(
422                    match (read_histogram(lhs, row)?, read_histogram(rhs, row)?) {
423                        (Some(lhs), Some(rhs)) => {
424                            // The layouts decide whether there is a pair at all: Prometheus reports
425                            // a pair whose bucket layouts cannot be combined as that one error,
426                            // before it looks at the reset hints, so a pair that fails both carries
427                            // only the schema warning. This is the order the native matcher in
428                            // `vector_match` reports it in too.
429                            match op(&lhs, &rhs) {
430                                Some(result) => {
431                                    record_custom_reconciliation(&collector, name, &lhs, &rhs);
432                                    record_counter_reset_contradiction(&collector, name, &lhs, &rhs);
433                                    Some(result)
434                                }
435                                None => {
436                                    record_warning(
437                                        &collector,
438                                        format!(
439                                        "{name}: dropped native histogram sample with incompatible schemas"
440                                        ),
441                                    );
442                                    None
443                                }
444                            }
445                        }
446                        _ => None,
447                    },
448                );
449            }
450            Ok(ColumnarValue::Array(build_histogram_array(&result)))
451        }) as _,
452    )
453}
454
455fn histogram_transform_udf(
456    name: &'static str,
457    op: fn(NativeHistogram) -> NativeHistogram,
458) -> ScalarUDF {
459    create_udf(
460        name,
461        vec![native_histogram_arrow_type()],
462        native_histogram_arrow_type(),
463        Volatility::Volatile,
464        Arc::new(move |input: &[ColumnarValue]| {
465            let histograms = extract_histogram_array(&input[0], name)?;
466            let histograms = histograms
467                .as_any()
468                .downcast_ref::<StructArray>()
469                .expect("validated native histogram struct");
470            let mut result = Vec::with_capacity(histograms.len());
471            for row in 0..histograms.len() {
472                result.push(read_histogram(histograms, row)?.map(op));
473            }
474            Ok(ColumnarValue::Array(build_histogram_array(&result)))
475        }) as _,
476    )
477}
478
479fn histogram_string_udf(name: &'static str) -> ScalarUDF {
480    create_udf(
481        name,
482        vec![native_histogram_arrow_type()],
483        DataType::Utf8,
484        Volatility::Volatile,
485        Arc::new(move |input: &[ColumnarValue]| {
486            let histograms = extract_histogram_array(&input[0], name)?;
487            let histograms = histograms
488                .as_any()
489                .downcast_ref::<StructArray>()
490                .expect("validated native histogram struct");
491            let mut result = StringBuilder::with_capacity(histograms.len(), histograms.len() * 32);
492            for row in 0..histograms.len() {
493                match read_histogram(histograms, row)? {
494                    Some(histogram) => result.append_value(histogram.promql_string()),
495                    None => result.append_null(),
496                }
497            }
498            Ok(ColumnarValue::Array(Arc::new(result.finish())))
499        }) as _,
500    )
501}
502
503fn histogram_scalar_udf(
504    name: &'static str,
505    input_types: Vec<DataType>,
506    histogram_index: usize,
507    scalar_index: usize,
508    op: fn(NativeHistogram, f64) -> Option<NativeHistogram>,
509) -> ScalarUDF {
510    create_udf(
511        name,
512        input_types,
513        native_histogram_arrow_type(),
514        Volatility::Volatile,
515        Arc::new(move |input: &[ColumnarValue]| {
516            let histograms = extract_histogram_array(&input[histogram_index], name)?;
517            let histograms = histograms
518                .as_any()
519                .downcast_ref::<StructArray>()
520                .expect("validated native histogram struct");
521            let mut result = Vec::with_capacity(histograms.len());
522            for row in 0..histograms.len() {
523                result.push(match read_histogram(histograms, row)? {
524                    Some(histogram) => {
525                        let scalar =
526                            read_scalar_f64_arg(&input[scalar_index], row, histograms.len(), name)?;
527                        op(histogram, scalar)
528                    }
529                    None => None,
530                });
531            }
532            Ok(ColumnarValue::Array(build_histogram_array(&result)))
533        }) as _,
534    )
535}
536
537fn histogram_compare_udf(
538    name: &'static str,
539    op: fn(&NativeHistogram, &NativeHistogram) -> bool,
540) -> ScalarUDF {
541    create_udf(
542        name,
543        vec![native_histogram_arrow_type(), native_histogram_arrow_type()],
544        DataType::Boolean,
545        Volatility::Volatile,
546        Arc::new(move |input: &[ColumnarValue]| {
547            let lhs = extract_histogram_array(&input[0], name)?;
548            let rhs = extract_histogram_array(&input[1], name)?;
549            if lhs.len() != rhs.len() {
550                return Err(DataFusionError::Execution(format!(
551                    "{name}: native histogram argument length mismatch: {} vs {}",
552                    lhs.len(),
553                    rhs.len()
554                )));
555            }
556
557            let lhs = lhs
558                .as_any()
559                .downcast_ref::<StructArray>()
560                .expect("validated native histogram struct");
561            let rhs = rhs
562                .as_any()
563                .downcast_ref::<StructArray>()
564                .expect("validated native histogram struct");
565            let mut result = Vec::with_capacity(lhs.len());
566            for row in 0..lhs.len() {
567                result.push(
568                    match (read_histogram(lhs, row)?, read_histogram(rhs, row)?) {
569                        (Some(lhs), Some(rhs)) => Some(op(&lhs, &rhs)),
570                        _ => None,
571                    },
572                );
573            }
574            Ok(ColumnarValue::Array(Arc::new(BooleanArray::from(result))))
575        }) as _,
576    )
577}
578
579pub struct NativeHistogramAdd;
580
581impl NativeHistogramAdd {
582    pub const fn name() -> &'static str {
583        "prom_native_histogram_add"
584    }
585
586    pub fn scalar_udf() -> ScalarUDF {
587        histogram_pair_udf(Self::name(), legacy_bridge::add)
588    }
589
590    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
591        histogram_pair_udf_with_collector(Self::name(), legacy_bridge::add, collector)
592    }
593}
594
595pub struct NativeHistogramSub;
596
597impl NativeHistogramSub {
598    pub const fn name() -> &'static str {
599        "prom_native_histogram_sub"
600    }
601
602    pub fn scalar_udf() -> ScalarUDF {
603        histogram_pair_udf(Self::name(), legacy_bridge::sub)
604    }
605
606    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
607        histogram_pair_udf_with_collector(Self::name(), legacy_bridge::sub, collector)
608    }
609}
610
611pub struct NativeHistogramMulScalar;
612
613impl NativeHistogramMulScalar {
614    pub const fn name() -> &'static str {
615        "prom_native_histogram_mul_scalar"
616    }
617
618    pub fn scalar_udf() -> ScalarUDF {
619        histogram_scalar_udf(
620            Self::name(),
621            vec![native_histogram_arrow_type(), DataType::Float64],
622            0,
623            1,
624            |histogram, scalar| Some(legacy_bridge::scale(&histogram, scalar)),
625        )
626    }
627}
628
629pub struct NativeHistogramScalarMul;
630
631impl NativeHistogramScalarMul {
632    pub const fn name() -> &'static str {
633        "prom_native_histogram_scalar_mul"
634    }
635
636    pub fn scalar_udf() -> ScalarUDF {
637        histogram_scalar_udf(
638            Self::name(),
639            vec![DataType::Float64, native_histogram_arrow_type()],
640            1,
641            0,
642            |histogram, scalar| Some(legacy_bridge::scale(&histogram, scalar)),
643        )
644    }
645}
646
647pub struct NativeHistogramDivScalar;
648
649impl NativeHistogramDivScalar {
650    pub const fn name() -> &'static str {
651        "prom_native_histogram_div_scalar"
652    }
653
654    pub fn scalar_udf() -> ScalarUDF {
655        histogram_scalar_udf(
656            Self::name(),
657            vec![native_histogram_arrow_type(), DataType::Float64],
658            0,
659            1,
660            |histogram, scalar| Some(legacy_bridge::divide_by(&histogram, scalar)),
661        )
662    }
663}
664
665pub struct NativeHistogramNeg;
666
667impl NativeHistogramNeg {
668    pub const fn name() -> &'static str {
669        "prom_native_histogram_neg"
670    }
671
672    pub fn scalar_udf() -> ScalarUDF {
673        histogram_transform_udf(Self::name(), |histogram| {
674            legacy_bridge::scale(&histogram, -1.0)
675        })
676    }
677}
678
679pub struct NativeHistogramEq;
680
681impl NativeHistogramEq {
682    pub const fn name() -> &'static str {
683        "prom_native_histogram_eq"
684    }
685
686    pub fn scalar_udf() -> ScalarUDF {
687        histogram_compare_udf(Self::name(), NativeHistogram::promql_eq)
688    }
689}
690
691pub struct NativeHistogramNotEq;
692
693impl NativeHistogramNotEq {
694    pub const fn name() -> &'static str {
695        "prom_native_histogram_not_eq"
696    }
697
698    pub fn scalar_udf() -> ScalarUDF {
699        histogram_compare_udf(Self::name(), |lhs, rhs| !lhs.promql_eq(rhs))
700    }
701}
702
703pub struct NativeHistogramCount;
704
705impl NativeHistogramCount {
706    pub const fn name() -> &'static str {
707        "prom_native_histogram_count"
708    }
709
710    pub fn scalar_udf() -> ScalarUDF {
711        scalar_histogram_udf(Self::name(), vec![], |histogram, _, _, _, _| {
712            Ok(histogram.count)
713        })
714    }
715}
716
717pub struct NativeHistogramSum;
718
719impl NativeHistogramSum {
720    pub const fn name() -> &'static str {
721        "prom_native_histogram_sum"
722    }
723
724    pub fn scalar_udf() -> ScalarUDF {
725        scalar_histogram_udf(Self::name(), vec![], |histogram, _, _, _, _| {
726            Ok(histogram.sum)
727        })
728    }
729}
730
731pub struct NativeHistogramAvg;
732
733impl NativeHistogramAvg {
734    pub const fn name() -> &'static str {
735        "prom_native_histogram_avg"
736    }
737
738    pub fn scalar_udf() -> ScalarUDF {
739        scalar_histogram_udf(Self::name(), vec![], |histogram, _, _, _, _| {
740            Ok(histogram.sum / histogram.count)
741        })
742    }
743}
744
745pub struct NativeHistogramStddev;
746
747impl NativeHistogramStddev {
748    pub const fn name() -> &'static str {
749        "prom_native_histogram_stddev"
750    }
751
752    pub fn scalar_udf() -> ScalarUDF {
753        scalar_histogram_udf(Self::name(), vec![], |histogram, _, _, _, _| {
754            Ok(histogram.estimated_stddev())
755        })
756    }
757}
758
759pub struct NativeHistogramStdvar;
760
761impl NativeHistogramStdvar {
762    pub const fn name() -> &'static str {
763        "prom_native_histogram_stdvar"
764    }
765
766    pub fn scalar_udf() -> ScalarUDF {
767        scalar_histogram_udf(Self::name(), vec![], |histogram, _, _, _, _| {
768            Ok(histogram.estimated_stdvar())
769        })
770    }
771}
772
773/// Formats float samples as PromQL label values.
774pub struct PromqlFloatToString;
775
776impl PromqlFloatToString {
777    pub const fn name() -> &'static str {
778        "prom_float_to_string"
779    }
780
781    pub fn scalar_udf() -> ScalarUDF {
782        create_udf(
783            Self::name(),
784            vec![DataType::Float64],
785            DataType::Utf8,
786            Volatility::Volatile,
787            Arc::new(|input: &[ColumnarValue]| {
788                let values = extract_array(&input[0])?;
789                let values = values
790                    .as_any()
791                    .downcast_ref::<Float64Array>()
792                    .expect("validated Float64 input");
793                let mut result = StringBuilder::new();
794                for value in values.iter() {
795                    match value {
796                        Some(value) => result.append_value(format_prometheus_float(value)),
797                        None => result.append_null(),
798                    }
799                }
800                Ok(ColumnarValue::Array(Arc::new(result.finish())))
801            }),
802        )
803    }
804}
805
806pub struct NativeHistogramToString;
807
808impl NativeHistogramToString {
809    pub const fn name() -> &'static str {
810        "prom_native_histogram_to_string"
811    }
812
813    pub fn scalar_udf() -> ScalarUDF {
814        histogram_string_udf(Self::name())
815    }
816}
817
818pub struct NativeHistogramQuantile;
819
820impl NativeHistogramQuantile {
821    pub const fn name() -> &'static str {
822        "prom_native_histogram_quantile"
823    }
824
825    pub fn scalar_udf() -> ScalarUDF {
826        Self::scalar_udf_with_collector(None)
827    }
828
829    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
830        scalar_histogram_udf(
831            Self::name(),
832            vec![DataType::Float64],
833            move |histogram, input, row, len, name| {
834                let q = read_scalar_f64_arg(&input[1], row, len, name)?;
835                let (value, info) = legacy_bridge::quantile_with_info(histogram, q);
836                if let Some(info) = info {
837                    let message = match info {
838                        NativeHistogramQuantileInfo::NaNSkew => {
839                            "input to histogram_quantile has NaN observations, result is skewed higher"
840                        }
841                        NativeHistogramQuantileInfo::NaNResult => {
842                            "input to histogram_quantile has NaN observations, result is NaN"
843                        }
844                    };
845                    record_info(&collector, message);
846                }
847                Ok(value)
848            },
849        )
850    }
851}
852
853pub struct NativeHistogramFraction;
854
855impl NativeHistogramFraction {
856    pub const fn name() -> &'static str {
857        "prom_native_histogram_fraction"
858    }
859
860    pub fn scalar_udf() -> ScalarUDF {
861        Self::scalar_udf_with_collector(None)
862    }
863
864    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
865        scalar_histogram_udf(
866            Self::name(),
867            vec![DataType::Float64, DataType::Float64],
868            move |histogram, input, row, len, name| {
869                let lower = read_scalar_f64_arg(&input[1], row, len, name)?;
870                let upper = read_scalar_f64_arg(&input[2], row, len, name)?;
871                let (value, excluded_nans) =
872                    legacy_bridge::fraction_with_info(histogram, lower, upper);
873                if excluded_nans {
874                    record_info(
875                        &collector,
876                        "input to histogram_fraction has NaN observations, which are excluded from all fractions",
877                    );
878                }
879                Ok(value)
880            },
881        )
882    }
883}
884
885#[derive(Debug, Clone, Copy)]
886enum NativeHistogramAggregateKind {
887    Sum,
888    Avg,
889}
890
891impl NativeHistogramAggregateKind {
892    const fn name(self) -> &'static str {
893        match self {
894            Self::Sum => NativeHistogramAggSum::name(),
895            Self::Avg => NativeHistogramAggAvg::name(),
896        }
897    }
898
899    const fn needs_count(self) -> bool {
900        matches!(self, Self::Avg)
901    }
902}
903
904pub struct NativeHistogramAggSum;
905
906impl NativeHistogramAggSum {
907    pub const fn name() -> &'static str {
908        "prom_native_histogram_agg_sum"
909    }
910
911    pub fn aggregate_udf() -> AggregateUDF {
912        native_histogram_aggregate_udf(NativeHistogramAggregateKind::Sum, None)
913    }
914
915    pub fn aggregate_udf_with_collector(
916        collector: Option<PromqlAnnotationCollector>,
917    ) -> AggregateUDF {
918        native_histogram_aggregate_udf(NativeHistogramAggregateKind::Sum, collector)
919    }
920}
921
922pub struct NativeHistogramAggAvg;
923
924impl NativeHistogramAggAvg {
925    pub const fn name() -> &'static str {
926        "prom_native_histogram_agg_avg"
927    }
928
929    pub fn aggregate_udf() -> AggregateUDF {
930        native_histogram_aggregate_udf(NativeHistogramAggregateKind::Avg, None)
931    }
932
933    pub fn aggregate_udf_with_collector(
934        collector: Option<PromqlAnnotationCollector>,
935    ) -> AggregateUDF {
936        native_histogram_aggregate_udf(NativeHistogramAggregateKind::Avg, collector)
937    }
938}
939
940/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulator.
941///
942/// Its state frame is the one it has always been -- one native histogram, an average's `UInt64`
943/// count, and three Booleans -- but the arithmetic behind it is the kernel's own
944/// [`HistogramAccumulator`], the same fold a native aggregate uses. What this type adds is the frame:
945/// the fold's answer, its count, and the evidence bits the frame can carry.
946#[derive(Debug)]
947struct NativeHistogramAggregateAccumulator {
948    kind: NativeHistogramAggregateKind,
949    /// The fold, once a sample established it.
950    ///
951    /// `None` while no histogram reached this accumulator, and `None` again once the position is
952    /// poisoned: a dropped position answers nothing, so it keeps no histogram to answer with.
953    fold: Option<HistogramAccumulator>,
954    /// The evidence this accumulator records, seeded into the fold before every operation and read
955    /// back out of it afterwards so the two never disagree about what the inputs reported.
956    ///
957    /// It is what the state frame exports: a position is poisoned, or saw a counter reset, or saw
958    /// its absence. The reconciliation bit has no component of its own and only drives a warning
959    /// here, because the frame a reader decodes has nowhere to put it.
960    evidence: HistogramEvidence,
961    /// Samples folded in, as the `UInt64` component an average's state declares. A sum declares no
962    /// count, so it leaves this at zero.
963    count: u64,
964    collector: Option<PromqlAnnotationCollector>,
965}
966
967impl NativeHistogramAggregateAccumulator {
968    fn new(
969        kind: NativeHistogramAggregateKind,
970        collector: Option<PromqlAnnotationCollector>,
971    ) -> Self {
972        Self {
973            kind,
974            fold: None,
975            evidence: HistogramEvidence::default(),
976            count: 0,
977            collector,
978        }
979    }
980
981    fn from_args(
982        kind: NativeHistogramAggregateKind,
983        collector: Option<PromqlAnnotationCollector>,
984        _args: AccumulatorArgs,
985    ) -> DfResult<Box<dyn DfAccumulator>> {
986        Ok(Box::new(Self::new(kind, collector)))
987    }
988
989    /// This kind as the kernel's own aggregate operation, which is what the fold is told it folds.
990    fn op(&self) -> AggregateOp {
991        match self.kind {
992            NativeHistogramAggregateKind::Sum => AggregateOp::Sum,
993            NativeHistogramAggregateKind::Avg => AggregateOp::Avg,
994        }
995    }
996
997    fn observe_reset_hints(&mut self, counter_reset_seen: bool, not_counter_reset_seen: bool) {
998        self.evidence.counter_reset_seen |= counter_reset_seen;
999        self.evidence.not_counter_reset_seen |= not_counter_reset_seen;
1000        if self.evidence.counter_reset_seen && self.evidence.not_counter_reset_seen {
1001            record_counter_reset_contradiction_warning(&self.collector, self.kind.name());
1002        }
1003    }
1004
1005    /// The count the state declares after folding `count` more samples.
1006    ///
1007    /// It is a `u64` because that is the state component's Arrow type, so a merge that would carry
1008    /// it past `u64::MAX` is an overflow of the frame rather than of the arithmetic. A sum declares
1009    /// no count at all and keeps this at zero.
1010    fn combined_count(&self, count: u64) -> DfResult<u64> {
1011        if !self.kind.needs_count() {
1012            return Ok(self.count);
1013        }
1014        self.count.checked_add(count).ok_or_else(|| {
1015            DataFusionError::Execution(format!(
1016                "{}: native histogram sample count overflow",
1017                self.kind.name()
1018            ))
1019        })
1020    }
1021
1022    /// Folds one sample into the position's fold, one `fold_sum` or `fold_avg` per kind.
1023    ///
1024    /// The evidence follows the sample's own reset hint whether or not the position still folds, as
1025    /// it always has. A sample whose bucket layout cannot be added to the fold's -- exponential
1026    /// buckets meeting custom ones -- poisons the position instead of failing the statement: the
1027    /// aggregate drops the point, as Prometheus does, and reports why.
1028    fn push_histogram(&mut self, histogram: NativeHistogram, count: u64) -> DfResult<()> {
1029        if self.kind.needs_count() && count == 0 {
1030            return Ok(());
1031        }
1032
1033        self.observe_reset_hints(
1034            histogram.reset_hint == COUNTER_RESET_HINT,
1035            histogram.reset_hint == NOT_COUNTER_RESET_HINT,
1036        );
1037        if self.evidence.poisoned {
1038            return Ok(());
1039        }
1040        let combined_count = self.combined_count(count)?;
1041        // A layout this crate cannot read -- its spans and its buckets disagree about how many
1042        // buckets there are -- drops the position instead of failing the query. The position is
1043        // dropped as a whole, with the warning below: none of its samples count toward the answer,
1044        // not even the ones that are readable.
1045        let sample = match float_histogram(&histogram) {
1046            Ok(sample) => sample,
1047            Err(_) => {
1048                self.record_incompatible();
1049                return Ok(());
1050            }
1051        };
1052        let recorded = self.evidence;
1053        // The first sample of a position *is* the fold's value, so it is not added into it.
1054        let vacant = self.fold.is_none();
1055        let fold = self
1056            .fold
1057            .get_or_insert_with(|| HistogramAccumulator::from_sample(&sample));
1058        // The bits this accumulator already recorded go in beside the sample, so the fold exports
1059        // the merge-time evidence along with its own.
1060        fold.evidence = recorded;
1061        if fold.uses_custom_buckets() != sample.uses_custom_buckets() {
1062            fold.poison();
1063        } else if !vacant {
1064            match self.kind {
1065                NativeHistogramAggregateKind::Sum => fold.fold_sum(&sample)?,
1066                NativeHistogramAggregateKind::Avg => fold.fold_avg(&sample)?,
1067            }
1068        }
1069        let evidence = fold.evidence;
1070        self.evidence = evidence;
1071        if evidence.poisoned {
1072            self.record_incompatible();
1073            return Ok(());
1074        }
1075        self.count = combined_count;
1076        if evidence.custom_bounds_reconciled && !recorded.custom_bounds_reconciled {
1077            record_reconciled_custom_buckets(&self.collector, self.kind.name());
1078        }
1079        Ok(())
1080    }
1081
1082    /// Drops this position: its inputs disagreed on their bucket layout, so it answers nothing.
1083    fn mark_incompatible(&mut self) {
1084        self.evidence.poisoned = true;
1085        self.evidence.incompatible_layout = true;
1086        self.count = 0;
1087        self.fold = None;
1088    }
1089
1090    fn record_incompatible(&mut self) {
1091        self.mark_incompatible();
1092        record_warning(
1093            &self.collector,
1094            format!(
1095                "{}: dropped native histogram aggregate with incompatible schemas",
1096                self.kind.name()
1097            ),
1098        );
1099    }
1100
1101    /// The histogram component of this position's state, or `None` when it answers nothing.
1102    ///
1103    /// The legacy frame declares no compensation component and no mean mode, so what it carries is
1104    /// the fold's answer: the running sum with its compensation folded in for a sum, and the running
1105    /// mean of its samples for an average. Both are the value a reader of the frame adds or weights,
1106    /// which is what makes a merged state mean what the state already means.
1107    ///
1108    /// Folding the compensation back into one `f64` rounds again, so this is not a lossless Kahan
1109    /// state: a partition holding `[1e16, 1]` still exports `1e16`, and merging it with a partition
1110    /// holding `[-1e16]` answers `0`. What the frame preserves is the residual of samples already
1111    /// folded into one position, which a frame exporting the running sum would lose even there.
1112    fn state_histogram(&self) -> DfResult<Option<NativeHistogram>> {
1113        if self.evidence.poisoned || (self.kind.needs_count() && self.count == 0) {
1114            return Ok(None);
1115        }
1116        let Some(fold) = &self.fold else {
1117            return Ok(None);
1118        };
1119        Ok(finished_histogram(self.op(), fold)?
1120            .as_ref()
1121            .map(native_histogram))
1122    }
1123}
1124
1125/// The fold's form of one legacy sample.
1126///
1127/// A legacy sample is the same histogram in the frame's row representation, so this only re-borrows
1128/// the spans it stores as pairs and hands the payload slices on.
1129fn float_histogram(histogram: &NativeHistogram) -> DfResult<FloatHistogram> {
1130    let spans = |spans: &[Span]| -> (Vec<i32>, Vec<i32>) {
1131        (
1132            spans.iter().map(|span| span.offset).collect(),
1133            spans.iter().map(|span| span.length).collect(),
1134        )
1135    };
1136    let (positive_offsets, positive_lengths) = spans(&histogram.positive_spans);
1137    let (negative_offsets, negative_lengths) = spans(&histogram.negative_spans);
1138    FloatHistogram::try_from_view(&HistogramView {
1139        schema: histogram.schema,
1140        zero_threshold: histogram.zero_threshold,
1141        sum: histogram.sum,
1142        count: histogram.count,
1143        zero_count: histogram.zero_count,
1144        reset_hint: histogram.reset_hint,
1145        start_timestamp: histogram.start_timestamp,
1146        custom_values: &histogram.custom_values,
1147        positive: BucketSideView {
1148            span_offsets: &positive_offsets,
1149            span_lengths: &positive_lengths,
1150            buckets: &histogram.positive_buckets,
1151        },
1152        negative: BucketSideView {
1153            span_offsets: &negative_offsets,
1154            span_lengths: &negative_lengths,
1155            buckets: &histogram.negative_buckets,
1156        },
1157    })
1158}
1159
1160/// The frame's row form of one owned histogram, as the state's histogram component.
1161fn native_histogram(histogram: &FloatHistogram) -> NativeHistogram {
1162    let (positive_spans, positive_buckets) = spans_and_counts(&histogram.positive);
1163    let (negative_spans, negative_buckets) = spans_and_counts(&histogram.negative);
1164    NativeHistogram {
1165        schema: histogram.schema,
1166        zero_threshold: histogram.zero_threshold,
1167        sum: histogram.sum,
1168        reset_hint: histogram.reset_hint,
1169        start_timestamp: histogram.start_timestamp,
1170        custom_values: histogram.custom_values.clone(),
1171        positive_spans,
1172        negative_spans,
1173        count: histogram.count,
1174        zero_count: histogram.zero_count,
1175        positive_buckets,
1176        negative_buckets,
1177    }
1178}
1179
1180/// The spans and absolute counts an owned bucket list encodes as: one span per run of consecutive
1181/// bucket indices, the first span starting at its own index and every later one stating its gap.
1182fn spans_and_counts(buckets: &[(i32, f64)]) -> (Vec<Span>, Vec<f64>) {
1183    let mut spans: Vec<Span> = Vec::new();
1184    let mut counts = Vec::with_capacity(buckets.len());
1185    // The absolute index the last span continues at.
1186    let mut next: Option<i32> = None;
1187    for &(index, count) in buckets {
1188        match next {
1189            Some(expected) if expected == index => {
1190                if let Some(span) = spans.last_mut() {
1191                    span.length += 1;
1192                }
1193            }
1194            _ => spans.push(Span {
1195                offset: next.map_or(index, |expected| index - expected),
1196                length: 1,
1197            }),
1198        }
1199        next = Some(index + 1);
1200        counts.push(count);
1201    }
1202    (spans, counts)
1203}
1204
1205/// The last addition that reduces either operand's exponential resolution, or zero if none.
1206/// The fold stops at the first switch between exponential and custom buckets. Unsupported
1207/// schemas keep their explicit buckets for validation.
1208fn range_last_rebin(samples: &[NativeHistogram]) -> Option<usize> {
1209    let mut schema = samples.first()?.schema;
1210    if schema == CUSTOM_BUCKETS_SCHEMA {
1211        return Some(0);
1212    }
1213    exponential_overflow_bucket_index(schema)?;
1214    let mut last = 0;
1215    for (index, sample) in samples.iter().enumerate().skip(1) {
1216        if sample.schema == schema {
1217            continue;
1218        }
1219        if sample.schema == CUSTOM_BUCKETS_SCHEMA {
1220            break;
1221        }
1222        exponential_overflow_bucket_index(sample.schema)?;
1223        schema = schema.min(sample.schema);
1224        last = index;
1225    }
1226    Some(last)
1227}
1228
1229fn range_fold_histograms(
1230    mut samples: Vec<NativeHistogram>,
1231    kind: HistogramAggregate,
1232    name: &'static str,
1233    collector: &Option<PromqlAnnotationCollector>,
1234) -> Option<NativeHistogram> {
1235    // A single legacy sample retains its start timestamp and explicit zero buckets.
1236    if samples.len() <= 1 {
1237        return samples.pop();
1238    }
1239    if samples
1240        .iter()
1241        .any(|histogram| histogram.reset_hint == COUNTER_RESET_HINT)
1242        && samples
1243            .iter()
1244            .any(|histogram| histogram.reset_hint == NOT_COUNTER_RESET_HINT)
1245    {
1246        record_counter_reset_contradiction_warning(collector, name);
1247    }
1248
1249    let last_rebin = range_last_rebin(&samples);
1250    let mut remaining = samples.iter();
1251    let histograms = remaining.by_ref().map(legacy_bridge::float_histogram);
1252    let (histogram, reconciled) = histogram_eval::sum_or_avg(kind, histograms, last_rebin)
1253        .unwrap_or_else(|_| {
1254            // Legacy checked both operands' bounds before decoding even the first pair.
1255            let attempted = (samples.len() - remaining.len()).max(2);
1256            let reconciled = samples[..attempted]
1257                .windows(2)
1258                .any(|pair| pair[0].needs_custom_reconciliation(&pair[1]));
1259            (None, reconciled)
1260        });
1261    if reconciled {
1262        record_reconciled_custom_buckets(collector, name);
1263    }
1264    let Some(mut histogram) = histogram else {
1265        record_warning(
1266            collector,
1267            format!("{name}: dropped native histogram range with incompatible schemas"),
1268        );
1269        return None;
1270    };
1271    histogram.compact();
1272    Some(legacy_bridge::legacy_histogram(&histogram))
1273}
1274
1275#[derive(Debug, Clone, Copy)]
1276enum NativeHistogramRangeHistogramKind {
1277    Sum,
1278    Avg,
1279    Last,
1280}
1281
1282#[derive(Debug, Clone, Copy)]
1283enum NativeHistogramRangeFloatKind {
1284    Absent,
1285    Count,
1286    Present,
1287    Changes,
1288    Resets,
1289}
1290
1291fn collect_window_histograms(
1292    histograms: &StructArray,
1293    offset: usize,
1294    length: usize,
1295) -> DfResult<Option<Vec<NativeHistogram>>> {
1296    let mut samples = Vec::with_capacity(length);
1297    for row in offset..offset + length {
1298        let Some(histogram) = read_histogram(histograms, row)? else {
1299            return Ok(None);
1300        };
1301        samples.push(histogram);
1302    }
1303    Ok(Some(samples))
1304}
1305
1306fn native_histogram_range_histogram(
1307    input: &[ColumnarValue],
1308    kind: NativeHistogramRangeHistogramKind,
1309    func_name: &'static str,
1310    collector: Option<PromqlAnnotationCollector>,
1311) -> DfResult<ColumnarValue> {
1312    if input.len() != 2 {
1313        return Err(DataFusionError::Plan(format!(
1314            "{func_name} function should have 2 inputs"
1315        )));
1316    }
1317
1318    let ts_range = extract_range_dict(
1319        &input[0],
1320        func_name,
1321        "timestamp range vector",
1322        &DataType::Timestamp(TimeUnit::Millisecond, None),
1323    )?;
1324    let value_range = extract_range_dict(
1325        &input[1],
1326        func_name,
1327        "value range vector",
1328        &native_histogram_arrow_type(),
1329    )?;
1330    if ts_range.keys().values() != value_range.keys().values() {
1331        return Err(DataFusionError::Execution(format!(
1332            "{func_name}: timestamp and value ranges should have the same window layout"
1333        )));
1334    }
1335
1336    let histograms = value_range
1337        .values()
1338        .as_any()
1339        .downcast_ref::<StructArray>()
1340        .expect("validated native histogram range");
1341    let mut result = Vec::with_capacity(value_range.keys().len());
1342    for key in value_range.keys().values() {
1343        let (offset, length) = unpack(*key);
1344        let offset = offset as usize;
1345        let length = length as usize;
1346        if length == 0 {
1347            result.push(None);
1348            continue;
1349        }
1350        if matches!(kind, NativeHistogramRangeHistogramKind::Last) {
1351            let histogram = if (offset..offset + length).any(|row| histograms.is_null(row)) {
1352                None
1353            } else {
1354                read_histogram(histograms, offset + length - 1)?
1355            };
1356            result.push(histogram);
1357            continue;
1358        }
1359        let Some(samples) = collect_window_histograms(histograms, offset, length)? else {
1360            result.push(None);
1361            continue;
1362        };
1363        let histogram = match kind {
1364            NativeHistogramRangeHistogramKind::Sum => {
1365                range_fold_histograms(samples, HistogramAggregate::Sum, func_name, &collector)
1366            }
1367            NativeHistogramRangeHistogramKind::Avg => {
1368                range_fold_histograms(samples, HistogramAggregate::Avg, func_name, &collector)
1369            }
1370            NativeHistogramRangeHistogramKind::Last => samples.last().cloned(),
1371        };
1372        result.push(histogram);
1373    }
1374
1375    Ok(ColumnarValue::Array(build_histogram_array(&result)))
1376}
1377
1378fn native_histogram_range_float(
1379    input: &[ColumnarValue],
1380    kind: NativeHistogramRangeFloatKind,
1381    func_name: &'static str,
1382) -> DfResult<ColumnarValue> {
1383    if input.len() != 2 {
1384        return Err(DataFusionError::Plan(format!(
1385            "{func_name} function should have 2 inputs"
1386        )));
1387    }
1388
1389    let ts_range = extract_range_dict(
1390        &input[0],
1391        func_name,
1392        "timestamp range vector",
1393        &DataType::Timestamp(TimeUnit::Millisecond, None),
1394    )?;
1395    let value_range = extract_range_dict(
1396        &input[1],
1397        func_name,
1398        "value range vector",
1399        &native_histogram_arrow_type(),
1400    )?;
1401    if ts_range.keys().values() != value_range.keys().values() {
1402        return Err(DataFusionError::Execution(format!(
1403            "{func_name}: timestamp and value ranges should have the same window layout"
1404        )));
1405    }
1406
1407    let timestamps = ts_range
1408        .values()
1409        .as_any()
1410        .downcast_ref::<TimestampMillisecondArray>()
1411        .expect("validated timestamp range")
1412        .values();
1413    let histograms = value_range
1414        .values()
1415        .as_any()
1416        .downcast_ref::<StructArray>()
1417        .expect("validated native histogram range");
1418    let mut result = Float64Builder::with_capacity(value_range.keys().len());
1419    for key in value_range.keys().values() {
1420        let (offset, length) = unpack(*key);
1421        let offset = offset as usize;
1422        let length = length as usize;
1423        if length == 0 {
1424            match kind {
1425                NativeHistogramRangeFloatKind::Absent => result.append_value(1.0),
1426                _ => result.append_null(),
1427            }
1428            continue;
1429        }
1430        if matches!(kind, NativeHistogramRangeFloatKind::Absent) {
1431            result.append_null();
1432            continue;
1433        }
1434        if matches!(
1435            kind,
1436            NativeHistogramRangeFloatKind::Count | NativeHistogramRangeFloatKind::Present
1437        ) {
1438            if (offset..offset + length).any(|row| histograms.is_null(row)) {
1439                result.append_null();
1440            } else if matches!(kind, NativeHistogramRangeFloatKind::Count) {
1441                result.append_value(length as f64);
1442            } else {
1443                result.append_value(1.0);
1444            }
1445            continue;
1446        }
1447        let Some(samples) = collect_window_histograms(histograms, offset, length)? else {
1448            result.append_null();
1449            continue;
1450        };
1451        let value = match kind {
1452            NativeHistogramRangeFloatKind::Absent => {
1453                result.append_null();
1454                continue;
1455            }
1456            NativeHistogramRangeFloatKind::Count => length as f64,
1457            NativeHistogramRangeFloatKind::Present => 1.0,
1458            NativeHistogramRangeFloatKind::Changes => samples
1459                .windows(2)
1460                .filter(|pair| !pair[0].promql_eq(&pair[1]))
1461                .count() as f64,
1462            NativeHistogramRangeFloatKind::Resets => samples
1463                .windows(2)
1464                .zip(timestamps[offset..offset + length].windows(2))
1465                .filter(|(pair, ts_pair)| {
1466                    (pair[0].reset_hint == GAUGE_RESET_HINT)
1467                        != (pair[1].reset_hint == GAUGE_RESET_HINT)
1468                        || pair[1].detect_counter_reset(&pair[0], ts_pair[0], ts_pair[1])
1469                })
1470                .count() as f64,
1471        };
1472        result.append_value(value);
1473    }
1474
1475    Ok(ColumnarValue::Array(Arc::new(result.finish())))
1476}
1477
1478fn create_native_range_histogram_udf(
1479    name: &'static str,
1480    kind: NativeHistogramRangeHistogramKind,
1481    collector: Option<PromqlAnnotationCollector>,
1482) -> ScalarUDF {
1483    create_udf(
1484        name,
1485        vec![
1486            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
1487            RangeArray::convert_data_type(native_histogram_arrow_type()),
1488        ],
1489        native_histogram_arrow_type(),
1490        Volatility::Volatile,
1491        Arc::new(move |input: &[ColumnarValue]| {
1492            native_histogram_range_histogram(input, kind, name, collector.clone())
1493        }) as _,
1494    )
1495}
1496
1497fn create_native_range_float_udf(
1498    name: &'static str,
1499    kind: NativeHistogramRangeFloatKind,
1500) -> ScalarUDF {
1501    create_udf(
1502        name,
1503        vec![
1504            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
1505            RangeArray::convert_data_type(native_histogram_arrow_type()),
1506        ],
1507        DataType::Float64,
1508        Volatility::Volatile,
1509        Arc::new(move |input: &[ColumnarValue]| native_histogram_range_float(input, kind, name))
1510            as _,
1511    )
1512}
1513
1514pub struct NativeHistogramSumOverTime;
1515pub struct NativeHistogramAvgOverTime;
1516pub struct NativeHistogramAbsentOverTime;
1517pub struct NativeHistogramCountOverTime;
1518pub struct NativeHistogramLastOverTime;
1519pub struct NativeHistogramPresentOverTime;
1520pub struct NativeHistogramChanges;
1521pub struct NativeHistogramResets;
1522
1523impl NativeHistogramSumOverTime {
1524    pub const fn name() -> &'static str {
1525        "prom_native_histogram_sum_over_time"
1526    }
1527
1528    pub fn scalar_udf() -> ScalarUDF {
1529        Self::scalar_udf_with_collector(None)
1530    }
1531
1532    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1533        create_native_range_histogram_udf(
1534            Self::name(),
1535            NativeHistogramRangeHistogramKind::Sum,
1536            collector,
1537        )
1538    }
1539}
1540
1541impl NativeHistogramAvgOverTime {
1542    pub const fn name() -> &'static str {
1543        "prom_native_histogram_avg_over_time"
1544    }
1545
1546    pub fn scalar_udf() -> ScalarUDF {
1547        Self::scalar_udf_with_collector(None)
1548    }
1549
1550    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1551        create_native_range_histogram_udf(
1552            Self::name(),
1553            NativeHistogramRangeHistogramKind::Avg,
1554            collector,
1555        )
1556    }
1557}
1558
1559impl NativeHistogramAbsentOverTime {
1560    pub const fn name() -> &'static str {
1561        "prom_native_histogram_absent_over_time"
1562    }
1563
1564    pub fn scalar_udf() -> ScalarUDF {
1565        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Absent)
1566    }
1567}
1568
1569impl NativeHistogramCountOverTime {
1570    pub const fn name() -> &'static str {
1571        "prom_native_histogram_count_over_time"
1572    }
1573
1574    pub fn scalar_udf() -> ScalarUDF {
1575        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Count)
1576    }
1577}
1578
1579impl NativeHistogramLastOverTime {
1580    pub const fn name() -> &'static str {
1581        "prom_native_histogram_last_over_time"
1582    }
1583
1584    pub fn scalar_udf() -> ScalarUDF {
1585        create_native_range_histogram_udf(
1586            Self::name(),
1587            NativeHistogramRangeHistogramKind::Last,
1588            None,
1589        )
1590    }
1591}
1592
1593impl NativeHistogramPresentOverTime {
1594    pub const fn name() -> &'static str {
1595        "prom_native_histogram_present_over_time"
1596    }
1597
1598    pub fn scalar_udf() -> ScalarUDF {
1599        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Present)
1600    }
1601}
1602
1603impl NativeHistogramChanges {
1604    pub const fn name() -> &'static str {
1605        "prom_native_histogram_changes"
1606    }
1607
1608    pub fn scalar_udf() -> ScalarUDF {
1609        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Changes)
1610    }
1611}
1612
1613impl NativeHistogramResets {
1614    pub const fn name() -> &'static str {
1615        "prom_native_histogram_resets"
1616    }
1617
1618    pub fn scalar_udf() -> ScalarUDF {
1619        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Resets)
1620    }
1621}
1622
1623/// Coordinated float/native-histogram range evaluation.
1624///
1625/// The function name is passed as the first scalar argument so these two UDF names are enough for
1626/// distributed plan decoding. The remaining leading arguments are timestamp, float, and histogram
1627/// ranges, followed by the ordinary function arguments.
1628pub struct MixedRange;
1629
1630impl MixedRange {
1631    const fn float_name() -> &'static str {
1632        "prom_mixed_range_float"
1633    }
1634
1635    const fn histogram_name() -> &'static str {
1636        "prom_mixed_range_histogram"
1637    }
1638
1639    pub fn float_udf(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1640        ScalarUDF::new_from_impl(MixedRangeUdf::new(MixedRangeOutput::Float, collector))
1641    }
1642
1643    pub fn histogram_udf(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1644        ScalarUDF::new_from_impl(MixedRangeUdf::new(MixedRangeOutput::Histogram, collector))
1645    }
1646}
1647
1648#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1649enum MixedRangeOutput {
1650    Float,
1651    Histogram,
1652}
1653
1654impl MixedRangeOutput {
1655    fn name(self) -> &'static str {
1656        match self {
1657            Self::Float => MixedRange::float_name(),
1658            Self::Histogram => MixedRange::histogram_name(),
1659        }
1660    }
1661
1662    fn data_type(self) -> DataType {
1663        match self {
1664            Self::Float => DataType::Float64,
1665            Self::Histogram => native_histogram_arrow_type(),
1666        }
1667    }
1668}
1669
1670#[derive(Debug, Clone)]
1671struct MixedRangeUdf {
1672    output: MixedRangeOutput,
1673    signature: Signature,
1674    collector: Option<PromqlAnnotationCollector>,
1675}
1676
1677impl MixedRangeUdf {
1678    fn new(output: MixedRangeOutput, collector: Option<PromqlAnnotationCollector>) -> Self {
1679        Self {
1680            output,
1681            signature: Signature::variadic_any(Volatility::Volatile),
1682            collector,
1683        }
1684    }
1685}
1686
1687impl PartialEq for MixedRangeUdf {
1688    fn eq(&self, other: &Self) -> bool {
1689        self.output == other.output
1690    }
1691}
1692
1693impl Eq for MixedRangeUdf {}
1694
1695impl Hash for MixedRangeUdf {
1696    fn hash<H: Hasher>(&self, state: &mut H) {
1697        self.output.hash(state);
1698    }
1699}
1700
1701impl ScalarUDFImpl for MixedRangeUdf {
1702    fn name(&self) -> &str {
1703        self.output.name()
1704    }
1705
1706    fn signature(&self) -> &Signature {
1707        &self.signature
1708    }
1709
1710    fn return_type(&self, _arg_types: &[DataType]) -> DfResult<DataType> {
1711        Ok(self.output.data_type())
1712    }
1713
1714    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DfResult<ColumnarValue> {
1715        let collector = args
1716            .config_options
1717            .extensions
1718            .get::<PromqlAnnotationCollector>()
1719            .cloned()
1720            .or_else(|| self.collector.clone());
1721        mixed_range(&args, self.output, collector)
1722    }
1723}
1724
1725#[derive(Debug, Clone, Copy)]
1726enum MixedRangeFunction {
1727    Rate,
1728    Increase,
1729    // Raw-delta modes sum floats while preserving mixed-range drop/warning semantics.
1730    RawDeltaRate,
1731    RawDeltaIncrease,
1732    Delta,
1733    IDelta,
1734    IRate,
1735    Changes,
1736    Resets,
1737    AvgOverTime,
1738    MinOverTime,
1739    MaxOverTime,
1740    SumOverTime,
1741    CountOverTime,
1742    LastOverTime,
1743    AbsentOverTime,
1744    PresentOverTime,
1745    StddevOverTime,
1746    StdvarOverTime,
1747    QuantileOverTime,
1748    Deriv,
1749    PredictLinear,
1750    DoubleExponentialSmoothing,
1751    HoltWinters,
1752}
1753
1754impl MixedRangeFunction {
1755    fn parse(value: &ColumnarValue) -> DfResult<Self> {
1756        let name = match value {
1757            ColumnarValue::Scalar(ScalarValue::Utf8(Some(name)))
1758            | ColumnarValue::Scalar(ScalarValue::LargeUtf8(Some(name)))
1759            | ColumnarValue::Scalar(ScalarValue::Utf8View(Some(name))) => name.as_str(),
1760            other => {
1761                return Err(DataFusionError::Execution(format!(
1762                    "mixed range function name must be a non-null string scalar, found {}",
1763                    other.data_type()
1764                )));
1765            }
1766        };
1767
1768        match name {
1769            "rate" => Ok(Self::Rate),
1770            "increase" => Ok(Self::Increase),
1771            "raw_delta_rate" => Ok(Self::RawDeltaRate),
1772            "raw_delta_increase" => Ok(Self::RawDeltaIncrease),
1773            "delta" => Ok(Self::Delta),
1774            "idelta" => Ok(Self::IDelta),
1775            "irate" => Ok(Self::IRate),
1776            "changes" => Ok(Self::Changes),
1777            "resets" => Ok(Self::Resets),
1778            "avg_over_time" => Ok(Self::AvgOverTime),
1779            "min_over_time" => Ok(Self::MinOverTime),
1780            "max_over_time" => Ok(Self::MaxOverTime),
1781            "sum_over_time" => Ok(Self::SumOverTime),
1782            "count_over_time" => Ok(Self::CountOverTime),
1783            "last_over_time" => Ok(Self::LastOverTime),
1784            "absent_over_time" => Ok(Self::AbsentOverTime),
1785            "present_over_time" => Ok(Self::PresentOverTime),
1786            "stddev_over_time" => Ok(Self::StddevOverTime),
1787            "stdvar_over_time" => Ok(Self::StdvarOverTime),
1788            "quantile_over_time" => Ok(Self::QuantileOverTime),
1789            "deriv" => Ok(Self::Deriv),
1790            "predict_linear" => Ok(Self::PredictLinear),
1791            "double_exponential_smoothing" => Ok(Self::DoubleExponentialSmoothing),
1792            "holt_winters" => Ok(Self::HoltWinters),
1793            _ => Err(DataFusionError::Execution(format!(
1794                "unsupported mixed range function: {name}"
1795            ))),
1796        }
1797    }
1798
1799    fn name(self) -> &'static str {
1800        match self {
1801            Self::Rate => "rate",
1802            Self::Increase => "increase",
1803            Self::RawDeltaRate => "rate",
1804            Self::RawDeltaIncrease => "increase",
1805            Self::Delta => "delta",
1806            Self::IDelta => "idelta",
1807            Self::IRate => "irate",
1808            Self::Changes => "changes",
1809            Self::Resets => "resets",
1810            Self::AvgOverTime => "avg_over_time",
1811            Self::MinOverTime => "min_over_time",
1812            Self::MaxOverTime => "max_over_time",
1813            Self::SumOverTime => "sum_over_time",
1814            Self::CountOverTime => "count_over_time",
1815            Self::LastOverTime => "last_over_time",
1816            Self::AbsentOverTime => "absent_over_time",
1817            Self::PresentOverTime => "present_over_time",
1818            Self::StddevOverTime => "stddev_over_time",
1819            Self::StdvarOverTime => "stdvar_over_time",
1820            Self::QuantileOverTime => "quantile_over_time",
1821            Self::Deriv => "deriv",
1822            Self::PredictLinear => "predict_linear",
1823            Self::DoubleExponentialSmoothing => "double_exponential_smoothing",
1824            Self::HoltWinters => "holt_winters",
1825        }
1826    }
1827
1828    fn policy(self) -> MixedRangePolicy {
1829        match self {
1830            Self::Rate
1831            | Self::Increase
1832            | Self::RawDeltaRate
1833            | Self::RawDeltaIncrease
1834            | Self::Delta
1835            | Self::AvgOverTime
1836            | Self::SumOverTime => MixedRangePolicy::DropMixed,
1837            Self::IDelta | Self::IRate => MixedRangePolicy::LastTwo,
1838            Self::LastOverTime => MixedRangePolicy::Last,
1839            Self::Changes
1840            | Self::Resets
1841            | Self::CountOverTime
1842            | Self::AbsentOverTime
1843            | Self::PresentOverTime => MixedRangePolicy::Combined,
1844            Self::MinOverTime
1845            | Self::MaxOverTime
1846            | Self::StddevOverTime
1847            | Self::StdvarOverTime
1848            | Self::QuantileOverTime
1849            | Self::Deriv
1850            | Self::PredictLinear
1851            | Self::DoubleExponentialSmoothing
1852            | Self::HoltWinters => MixedRangePolicy::FloatOnly,
1853        }
1854    }
1855
1856    fn float_udf(self) -> Option<ScalarUDF> {
1857        match self {
1858            Self::Rate => Some(Rate::scalar_udf()),
1859            Self::Increase => Some(Increase::scalar_udf()),
1860            Self::RawDeltaRate | Self::RawDeltaIncrease => Some(SumOverTime::scalar_udf()),
1861            Self::Delta => Some(crate::functions::Delta::scalar_udf()),
1862            Self::IDelta => Some(IDelta::<false>::scalar_udf()),
1863            Self::IRate => Some(IDelta::<true>::scalar_udf()),
1864            Self::AvgOverTime => Some(AvgOverTime::scalar_udf()),
1865            Self::MinOverTime => Some(MinOverTime::scalar_udf()),
1866            Self::MaxOverTime => Some(MaxOverTime::scalar_udf()),
1867            Self::SumOverTime => Some(SumOverTime::scalar_udf()),
1868            Self::LastOverTime => Some(LastOverTime::scalar_udf()),
1869            Self::StddevOverTime => Some(StddevOverTime::scalar_udf()),
1870            Self::StdvarOverTime => Some(StdvarOverTime::scalar_udf()),
1871            Self::QuantileOverTime => Some(QuantileOverTime::scalar_udf()),
1872            Self::Deriv => Some(Deriv::scalar_udf()),
1873            Self::PredictLinear => Some(PredictLinear::scalar_udf()),
1874            Self::DoubleExponentialSmoothing | Self::HoltWinters => {
1875                Some(DoubleExponentialSmoothing::scalar_udf())
1876            }
1877            Self::Changes
1878            | Self::Resets
1879            | Self::CountOverTime
1880            | Self::AbsentOverTime
1881            | Self::PresentOverTime => None,
1882        }
1883    }
1884
1885    fn histogram_udf(self, collector: Option<PromqlAnnotationCollector>) -> Option<ScalarUDF> {
1886        match self {
1887            Self::Rate => Some(NativeHistogramRate::scalar_udf_with_collector(collector)),
1888            Self::Increase => Some(NativeHistogramIncrease::scalar_udf_with_collector(
1889                collector,
1890            )),
1891            Self::Delta => Some(NativeHistogramDelta::scalar_udf_with_collector(collector)),
1892            Self::IDelta => Some(NativeHistogramIDelta::scalar_udf_with_collector(collector)),
1893            Self::IRate => Some(NativeHistogramIRate::scalar_udf_with_collector(collector)),
1894            Self::AvgOverTime => Some(NativeHistogramAvgOverTime::scalar_udf_with_collector(
1895                collector,
1896            )),
1897            Self::SumOverTime => Some(NativeHistogramSumOverTime::scalar_udf_with_collector(
1898                collector,
1899            )),
1900            Self::LastOverTime => Some(NativeHistogramLastOverTime::scalar_udf()),
1901            Self::RawDeltaRate | Self::RawDeltaIncrease => None,
1902            _ => None,
1903        }
1904    }
1905}
1906
1907#[derive(Debug, Clone, Copy)]
1908enum MixedRangePolicy {
1909    DropMixed,
1910    LastTwo,
1911    Last,
1912    Combined,
1913    FloatOnly,
1914}
1915
1916#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1917enum SampleLane {
1918    Float,
1919    Histogram,
1920}
1921
1922fn mixed_range(
1923    args: &ScalarFunctionArgs,
1924    output: MixedRangeOutput,
1925    collector: Option<PromqlAnnotationCollector>,
1926) -> DfResult<ColumnarValue> {
1927    if args.args.len() < 4 {
1928        return Err(DataFusionError::Plan(format!(
1929            "{} function should have at least 4 inputs",
1930            output.name()
1931        )));
1932    }
1933    let function = MixedRangeFunction::parse(&args.args[0])?;
1934    let name = function.name();
1935    let ts_range = extract_range_dict(
1936        &args.args[1],
1937        name,
1938        "timestamp range vector",
1939        &DataType::Timestamp(TimeUnit::Millisecond, None),
1940    )?;
1941    let float_range = extract_range_dict(
1942        &args.args[2],
1943        name,
1944        "float range vector",
1945        &DataType::Float64,
1946    )?;
1947    let histogram_range = extract_range_dict(
1948        &args.args[3],
1949        name,
1950        "native histogram range vector",
1951        &native_histogram_arrow_type(),
1952    )?;
1953    let keys = ts_range.keys().values();
1954    if float_range.keys().values() != keys || histogram_range.keys().values() != keys {
1955        return Err(DataFusionError::Execution(format!(
1956            "{name}: timestamp, float, and native histogram ranges should have the same layout"
1957        )));
1958    }
1959    if args.number_rows != keys.len() {
1960        return Err(DataFusionError::Execution(format!(
1961            "{name}: range inputs have {} windows but the batch has {} rows",
1962            keys.len(),
1963            args.number_rows
1964        )));
1965    }
1966
1967    let timestamps = ts_range
1968        .values()
1969        .as_any()
1970        .downcast_ref::<TimestampMillisecondArray>()
1971        .expect("validated timestamp range");
1972    let floats = float_range
1973        .values()
1974        .as_any()
1975        .downcast_ref::<Float64Array>()
1976        .expect("validated float range");
1977    let histograms = histogram_range
1978        .values()
1979        .as_any()
1980        .downcast_ref::<StructArray>()
1981        .expect("validated native histogram range");
1982    if floats.len() != timestamps.len() || histograms.len() != timestamps.len() {
1983        return Err(DataFusionError::Execution(format!(
1984            "{name}: timestamp, float, and native histogram values should be row-aligned"
1985        )));
1986    }
1987
1988    let bounds = checked_window_bounds(keys, timestamps.len(), name)?;
1989    let float_valid = (0..floats.len())
1990        .map(|row| floats.is_valid(row))
1991        .collect::<Vec<_>>();
1992    let histogram_valid = (0..histograms.len())
1993        .map(|row| histograms.is_valid(row))
1994        .collect::<Vec<_>>();
1995    let float_prefix = validity_prefix(&float_valid, name)?;
1996    let histogram_prefix = validity_prefix(&histogram_valid, name)?;
1997
1998    if matches!(function.policy(), MixedRangePolicy::Combined) {
1999        if output != MixedRangeOutput::Float {
2000            return Err(DataFusionError::Execution(format!(
2001                "{name} does not return native histograms"
2002            )));
2003        }
2004        return combined_range_float(
2005            function,
2006            &bounds,
2007            timestamps,
2008            floats,
2009            histograms,
2010            &float_valid,
2011            &histogram_valid,
2012            &float_prefix,
2013            &histogram_prefix,
2014        );
2015    }
2016
2017    let selections = select_mixed_range_lanes(
2018        function,
2019        &bounds,
2020        timestamps,
2021        &float_valid,
2022        &histogram_valid,
2023        &float_prefix,
2024        &histogram_prefix,
2025        &collector,
2026    );
2027    let (lane, values, valid, prefix) = match output {
2028        MixedRangeOutput::Float => (
2029            SampleLane::Float,
2030            floats as &dyn Array,
2031            float_valid.as_slice(),
2032            float_prefix.as_slice(),
2033        ),
2034        MixedRangeOutput::Histogram => (
2035            SampleLane::Histogram,
2036            histograms as &dyn Array,
2037            histogram_valid.as_slice(),
2038            histogram_prefix.as_slice(),
2039        ),
2040    };
2041    let input = compact_lane_input(
2042        timestamps,
2043        values,
2044        valid,
2045        prefix,
2046        &bounds,
2047        &selections,
2048        lane,
2049        name,
2050    )?;
2051
2052    let udf = match output {
2053        MixedRangeOutput::Float => function.float_udf(),
2054        MixedRangeOutput::Histogram => function.histogram_udf(collector),
2055    }
2056    .ok_or_else(|| {
2057        DataFusionError::Execution(format!(
2058            "{name} does not return {} values",
2059            match output {
2060                MixedRangeOutput::Float => "float",
2061                MixedRangeOutput::Histogram => "native histogram",
2062            }
2063        ))
2064    })?;
2065    let mut input = input;
2066    input.extend_from_slice(&args.args[4..]);
2067    invoke_range_udf(udf, input, args, bounds.len())
2068}
2069
2070/// Decodes packed range keys into validated half-open `(offset, end)` bounds.
2071fn checked_window_bounds(
2072    keys: &[i64],
2073    value_len: usize,
2074    name: &str,
2075) -> DfResult<Vec<(usize, usize)>> {
2076    keys.iter()
2077        .map(|key| {
2078            let (offset, length) = unpack(*key);
2079            let offset = offset as usize;
2080            let end = offset
2081                .checked_add(length as usize)
2082                .filter(|end| *end <= value_len)
2083                .ok_or_else(|| {
2084                    DataFusionError::Execution(format!(
2085                        "{name}: invalid range ({offset}, {length}) for {value_len} values"
2086                    ))
2087                })?;
2088            Ok((offset, end))
2089        })
2090        .collect()
2091}
2092
2093/// Builds prefix counts where `prefix[i]` is the number of valid samples in `valid[..i]`.
2094fn validity_prefix(valid: &[bool], name: &str) -> DfResult<Vec<usize>> {
2095    let capacity = valid.len().checked_add(1).ok_or_else(|| {
2096        DataFusionError::Execution(format!("{name}: sample validity length overflow"))
2097    })?;
2098    let mut prefix = Vec::with_capacity(capacity);
2099    prefix.push(0usize);
2100    for is_valid in valid {
2101        prefix.push(
2102            prefix
2103                .last()
2104                .copied()
2105                .unwrap()
2106                .checked_add(usize::from(*is_valid))
2107                .ok_or_else(|| {
2108                    DataFusionError::Execution(format!("{name}: sample count overflow"))
2109                })?,
2110        );
2111    }
2112    Ok(prefix)
2113}
2114
2115/// Returns the number of valid samples in the half-open window `[offset, end)`.
2116fn valid_count(prefix: &[usize], offset: usize, end: usize) -> usize {
2117    prefix[end]
2118        .checked_sub(prefix[offset])
2119        .expect("validity prefix is monotonic")
2120}
2121
2122/// Selects the sample lane for each window and records policy-required annotations.
2123#[allow(clippy::too_many_arguments)]
2124fn select_mixed_range_lanes(
2125    function: MixedRangeFunction,
2126    bounds: &[(usize, usize)],
2127    timestamps: &TimestampMillisecondArray,
2128    float_valid: &[bool],
2129    histogram_valid: &[bool],
2130    float_prefix: &[usize],
2131    histogram_prefix: &[usize],
2132    collector: &Option<PromqlAnnotationCollector>,
2133) -> Vec<Option<SampleLane>> {
2134    bounds
2135        .iter()
2136        .map(|(offset, end)| {
2137            let float_count = valid_count(float_prefix, *offset, *end);
2138            let histogram_count = valid_count(histogram_prefix, *offset, *end);
2139            match function.policy() {
2140                MixedRangePolicy::DropMixed => match (float_count > 0, histogram_count > 0) {
2141                    (true, true) => {
2142                        record_warning(
2143                            collector,
2144                            format!(
2145                                "{}: encountered a mix of float and native histogram samples",
2146                                function.name()
2147                            ),
2148                        );
2149                        None
2150                    }
2151                    (true, false) => Some(SampleLane::Float),
2152                    (false, true) => Some(SampleLane::Histogram),
2153                    (false, false) => None,
2154                },
2155                MixedRangePolicy::FloatOnly => {
2156                    if float_count > 0 && histogram_count > 0 {
2157                        record_info(
2158                            collector,
2159                            format!(
2160                                "{}: ignored native histogram samples",
2161                                function.name()
2162                            ),
2163                        );
2164                    }
2165                    (float_count > 0).then_some(SampleLane::Float)
2166                }
2167                MixedRangePolicy::Last => (*offset..*end).rev().find_map(|row| {
2168                    if histogram_valid[row] {
2169                        Some(SampleLane::Histogram)
2170                    } else if float_valid[row] {
2171                        Some(SampleLane::Float)
2172                    } else {
2173                        None
2174                    }
2175                }),
2176                MixedRangePolicy::LastTwo => {
2177                    let mut last_two = Vec::with_capacity(2);
2178                    for row in (*offset..*end).rev() {
2179                        // Prometheus keeps a float as the newest sample if both lanes have the
2180                        // same timestamp, while the histogram becomes the preceding sample.
2181                        if float_valid[row] {
2182                            last_two.push((SampleLane::Float, timestamps.value(row)));
2183                        }
2184                        if last_two.len() < 2 && histogram_valid[row] {
2185                            last_two.push((SampleLane::Histogram, timestamps.value(row)));
2186                        }
2187                        if last_two.len() == 2 {
2188                            break;
2189                        }
2190                    }
2191                    if last_two.len() < 2 || last_two[0].1 == last_two[1].1 {
2192                        None
2193                    } else if last_two[0].0 == last_two[1].0 {
2194                        Some(last_two[0].0)
2195                    } else {
2196                        record_warning(
2197                            collector,
2198                            format!(
2199                                "{}: encountered a mix of float and native histogram samples in the last two points",
2200                                function.name()
2201                            ),
2202                        );
2203                        None
2204                    }
2205                }
2206                MixedRangePolicy::Combined => unreachable!(),
2207            }
2208        })
2209        .collect()
2210}
2211
2212/// Filters null placeholders from one sample lane and remaps its selected windows.
2213/// Windows assigned to the other lane become empty.
2214#[allow(clippy::too_many_arguments)]
2215fn compact_lane_input(
2216    timestamps: &TimestampMillisecondArray,
2217    values: &dyn Array,
2218    valid: &[bool],
2219    prefix: &[usize],
2220    bounds: &[(usize, usize)],
2221    selections: &[Option<SampleLane>],
2222    lane: SampleLane,
2223    name: &str,
2224) -> DfResult<Vec<ColumnarValue>> {
2225    let mask = BooleanArray::from(valid.to_vec());
2226    let filtered_timestamps = filter(timestamps, &mask)?;
2227    let filtered_values = filter(values, &mask)?;
2228    let ranges = bounds
2229        .iter()
2230        .zip(selections)
2231        .map(|((offset, end), selected)| {
2232            let compact_offset = prefix[*offset];
2233            let compact_length = if *selected == Some(lane) {
2234                valid_count(prefix, *offset, *end)
2235            } else {
2236                0
2237            };
2238            Ok((
2239                u32::try_from(compact_offset).map_err(|_| {
2240                    DataFusionError::Execution(format!(
2241                        "{name}: compacted range offset exceeds u32"
2242                    ))
2243                })?,
2244                u32::try_from(compact_length).map_err(|_| {
2245                    DataFusionError::Execution(format!(
2246                        "{name}: compacted range length exceeds u32"
2247                    ))
2248                })?,
2249            ))
2250        })
2251        .collect::<DfResult<Vec<_>>>()?;
2252    let timestamp_range = RangeArray::from_ranges(filtered_timestamps, ranges.clone())
2253        .map_err(DataFusionError::from)?;
2254    let value_range =
2255        RangeArray::from_ranges(filtered_values, ranges).map_err(DataFusionError::from)?;
2256    Ok(vec![
2257        ColumnarValue::Array(Arc::new(timestamp_range.into_dict())),
2258        ColumnarValue::Array(Arc::new(value_range.into_dict())),
2259    ])
2260}
2261
2262fn invoke_range_udf(
2263    udf: ScalarUDF,
2264    input: Vec<ColumnarValue>,
2265    outer_args: &ScalarFunctionArgs,
2266    number_rows: usize,
2267) -> DfResult<ColumnarValue> {
2268    let arg_fields = input
2269        .iter()
2270        .enumerate()
2271        .map(|(index, value)| Arc::new(Field::new(format!("arg_{index}"), value.data_type(), true)))
2272        .collect();
2273    udf.invoke_with_args(ScalarFunctionArgs {
2274        args: input,
2275        arg_fields,
2276        number_rows,
2277        return_field: outer_args.return_field.clone(),
2278        config_options: outer_args.config_options.clone(),
2279    })
2280}
2281
2282enum MixedSample {
2283    Float(f64),
2284    Histogram(NativeHistogram),
2285}
2286
2287#[allow(clippy::too_many_arguments)]
2288fn combined_range_float(
2289    function: MixedRangeFunction,
2290    bounds: &[(usize, usize)],
2291    timestamps: &TimestampMillisecondArray,
2292    floats: &Float64Array,
2293    histograms: &StructArray,
2294    float_valid: &[bool],
2295    histogram_valid: &[bool],
2296    float_prefix: &[usize],
2297    histogram_prefix: &[usize],
2298) -> DfResult<ColumnarValue> {
2299    let mut result = Float64Builder::with_capacity(bounds.len());
2300    for (offset, end) in bounds {
2301        let sample_count = valid_count(float_prefix, *offset, *end)
2302            .checked_add(valid_count(histogram_prefix, *offset, *end))
2303            .ok_or_else(|| {
2304                DataFusionError::Execution(format!("{}: sample count overflow", function.name()))
2305            })?;
2306        match function {
2307            MixedRangeFunction::CountOverTime => {
2308                if sample_count == 0 {
2309                    result.append_null();
2310                } else {
2311                    result.append_value(sample_count as f64);
2312                }
2313            }
2314            MixedRangeFunction::AbsentOverTime => {
2315                if sample_count == 0 {
2316                    result.append_value(1.0);
2317                } else {
2318                    result.append_null();
2319                }
2320            }
2321            MixedRangeFunction::PresentOverTime => {
2322                if sample_count == 0 {
2323                    result.append_null();
2324                } else {
2325                    result.append_value(1.0);
2326                }
2327            }
2328            MixedRangeFunction::Changes | MixedRangeFunction::Resets => {
2329                if sample_count == 0 {
2330                    result.append_null();
2331                    continue;
2332                }
2333                let mut count = 0usize;
2334                let mut previous = None;
2335                for row in *offset..*end {
2336                    if float_valid[row] {
2337                        count += mixed_transition(
2338                            function,
2339                            &mut previous,
2340                            timestamps.value(row),
2341                            MixedSample::Float(floats.value(row)),
2342                        );
2343                    }
2344                    if histogram_valid[row] {
2345                        let histogram = read_histogram(histograms, row)?
2346                            .expect("validated native histogram sample");
2347                        count += mixed_transition(
2348                            function,
2349                            &mut previous,
2350                            timestamps.value(row),
2351                            MixedSample::Histogram(histogram),
2352                        );
2353                    }
2354                }
2355                result.append_value(count as f64);
2356            }
2357            _ => {
2358                return Err(DataFusionError::Internal(format!(
2359                    "{} does not support combined range evaluation",
2360                    function.name()
2361                )));
2362            }
2363        }
2364    }
2365    Ok(ColumnarValue::Array(Arc::new(result.finish())))
2366}
2367
2368fn mixed_transition(
2369    function: MixedRangeFunction,
2370    previous: &mut Option<(i64, MixedSample)>,
2371    timestamp: i64,
2372    current: MixedSample,
2373) -> usize {
2374    let changed = previous.as_ref().is_some_and(|(previous_ts, previous)| {
2375        match (function, previous, &current) {
2376            (
2377                MixedRangeFunction::Changes,
2378                MixedSample::Float(previous),
2379                MixedSample::Float(current),
2380            ) => current != previous && !(current.is_nan() && previous.is_nan()),
2381            (
2382                MixedRangeFunction::Changes,
2383                MixedSample::Histogram(previous),
2384                MixedSample::Histogram(current),
2385            ) => !current.promql_eq(previous),
2386            (MixedRangeFunction::Changes, _, _) => true,
2387            (
2388                MixedRangeFunction::Resets,
2389                MixedSample::Float(previous),
2390                MixedSample::Float(current),
2391            ) => current < previous,
2392            (
2393                MixedRangeFunction::Resets,
2394                MixedSample::Histogram(previous),
2395                MixedSample::Histogram(current),
2396            ) => {
2397                (previous.reset_hint == GAUGE_RESET_HINT)
2398                    != (current.reset_hint == GAUGE_RESET_HINT)
2399                    || current.detect_counter_reset(previous, *previous_ts, timestamp)
2400            }
2401            (MixedRangeFunction::Resets, _, _) => true,
2402            _ => unreachable!(),
2403        }
2404    });
2405    *previous = Some((timestamp, current));
2406    usize::from(changed)
2407}
2408
2409fn native_histogram_scalar(histogram: Option<NativeHistogram>) -> ScalarValue {
2410    let array = build_histogram_array(&[histogram]);
2411    let histogram = array
2412        .as_any()
2413        .downcast_ref::<StructArray>()
2414        .expect("native histogram array is a StructArray")
2415        .clone();
2416    ScalarValue::Struct(Arc::new(histogram))
2417}
2418
2419fn native_histogram_aggregate_udf(
2420    kind: NativeHistogramAggregateKind,
2421    collector: Option<PromqlAnnotationCollector>,
2422) -> AggregateUDF {
2423    let state_types = if kind.needs_count() {
2424        vec![
2425            native_histogram_arrow_type(),
2426            DataType::UInt64,
2427            DataType::Boolean,
2428            DataType::Boolean,
2429            DataType::Boolean,
2430        ]
2431    } else {
2432        vec![
2433            native_histogram_arrow_type(),
2434            DataType::Boolean,
2435            DataType::Boolean,
2436            DataType::Boolean,
2437        ]
2438    };
2439
2440    create_udaf(
2441        kind.name(),
2442        vec![native_histogram_arrow_type()],
2443        Arc::new(native_histogram_arrow_type()),
2444        Volatility::Volatile,
2445        Arc::new(move |args| {
2446            NativeHistogramAggregateAccumulator::from_args(kind, collector.clone(), args)
2447        }),
2448        Arc::new(state_types),
2449    )
2450}
2451
2452impl DfAccumulator for NativeHistogramAggregateAccumulator {
2453    fn update_batch(&mut self, values: &[ArrayRef]) -> DfResult<()> {
2454        let histograms = values
2455            .first()
2456            .and_then(|array| array.as_any().downcast_ref::<StructArray>())
2457            .ok_or_else(|| {
2458                DataFusionError::Execution(format!(
2459                    "{}: expected native histogram struct input",
2460                    self.kind.name()
2461                ))
2462            })?;
2463
2464        for row in 0..histograms.len() {
2465            let Some(histogram) = read_histogram(histograms, row)? else {
2466                continue;
2467            };
2468            self.push_histogram(histogram, 1)?;
2469        }
2470
2471        Ok(())
2472    }
2473
2474    fn evaluate(&mut self) -> DfResult<ScalarValue> {
2475        Ok(native_histogram_scalar(self.state_histogram()?))
2476    }
2477
2478    fn size(&self) -> usize {
2479        // The fold sits inline in this struct, so only the histograms it owns are counted on top of
2480        // it.
2481        size_of::<Self>()
2482            + self.fold.as_ref().map_or(0, |fold| {
2483                accumulator_bytes(fold).saturating_sub(size_of::<HistogramAccumulator>())
2484            })
2485    }
2486
2487    fn state(&mut self) -> DfResult<Vec<ScalarValue>> {
2488        let mut state = vec![native_histogram_scalar(self.state_histogram()?)];
2489        if self.kind.needs_count() {
2490            state.push(ScalarValue::UInt64(Some(self.count)));
2491        }
2492        state.push(ScalarValue::Boolean(Some(self.evidence.poisoned)));
2493        state.push(ScalarValue::Boolean(Some(self.evidence.counter_reset_seen)));
2494        state.push(ScalarValue::Boolean(Some(
2495            self.evidence.not_counter_reset_seen,
2496        )));
2497        Ok(state)
2498    }
2499
2500    fn merge_batch(&mut self, states: &[ArrayRef]) -> DfResult<()> {
2501        if states.is_empty() {
2502            return Ok(());
2503        }
2504
2505        let histograms = states[0]
2506            .as_any()
2507            .downcast_ref::<StructArray>()
2508            .ok_or_else(|| {
2509                DataFusionError::Execution(format!(
2510                    "{}: expected native histogram struct state",
2511                    self.kind.name()
2512                ))
2513            })?;
2514        let counts = if self.kind.needs_count() {
2515            Some(
2516                states
2517                    .get(1)
2518                    .and_then(|array| array.as_any().downcast_ref::<UInt64Array>())
2519                    .ok_or_else(|| {
2520                        DataFusionError::Execution(format!(
2521                            "{}: expected UInt64 count state",
2522                            self.kind.name()
2523                        ))
2524                    })?,
2525            )
2526        } else {
2527            None
2528        };
2529        let dropped_index = if self.kind.needs_count() { 2 } else { 1 };
2530        let dropped = states
2531            .get(dropped_index)
2532            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2533            .ok_or_else(|| {
2534                DataFusionError::Execution(format!(
2535                    "{}: expected Boolean dropped state",
2536                    self.kind.name()
2537                ))
2538            })?;
2539        let counter_reset_seen = states
2540            .get(dropped_index + 1)
2541            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2542            .ok_or_else(|| {
2543                DataFusionError::Execution(format!(
2544                    "{}: expected Boolean counter reset state",
2545                    self.kind.name()
2546                ))
2547            })?;
2548        let not_counter_reset_seen = states
2549            .get(dropped_index + 2)
2550            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2551            .ok_or_else(|| {
2552                DataFusionError::Execution(format!(
2553                    "{}: expected Boolean not-counter-reset state",
2554                    self.kind.name()
2555                ))
2556            })?;
2557
2558        let op = self.op();
2559        for row in 0..histograms.len() {
2560            self.observe_reset_hints(
2561                counter_reset_seen.value(row),
2562                not_counter_reset_seen.value(row),
2563            );
2564            if dropped.value(row) {
2565                // A dropped partition answers nothing, so only its poison crosses the boundary.
2566                self.mark_incompatible();
2567            }
2568            if self.evidence.poisoned {
2569                continue;
2570            }
2571            let Some(histogram) = read_histogram(histograms, row)? else {
2572                continue;
2573            };
2574            let count = counts.map(|counts| counts.value(row)).unwrap_or(1);
2575            if self.kind.needs_count() && count == 0 {
2576                continue;
2577            }
2578            let combined_count = self.combined_count(count)?;
2579            // The same disagreement `push_histogram` drops a position for, met through a state
2580            // frame: a layout this crate cannot read drops the partition's state instead of failing
2581            // the statement, and with it the position the state was headed into.
2582            let sample = match float_histogram(&histogram) {
2583                Ok(sample) => sample,
2584                Err(_) => {
2585                    self.record_incompatible();
2586                    continue;
2587                }
2588            };
2589            // The incoming side carries what its frame could: its answer, its count and its
2590            // evidence. It has no compensation component, so the compensation it brings is the
2591            // layout-carrying zero -- the residual it exported is already inside its answer.
2592            let payload = HistogramState {
2593                value: histogram_batch(&sample)?,
2594                compensation: histogram_batch(&sample.new_compensation())?,
2595                count: count as f64,
2596                // A legacy average exports the mean of its `count` samples, because its frame has
2597                // no mean mode to export instead; a sum exports a sum.
2598                incremental_mean: self.kind.needs_count(),
2599                poisoned: false,
2600                incompatible_layout: false,
2601                custom_bounds_reconciled: false,
2602                counter_reset_seen: false,
2603                not_counter_reset_seen: false,
2604            };
2605            let recorded = self.evidence;
2606            if let Some(mut fold) = self.fold.take() {
2607                fold.evidence = recorded;
2608                let merged = fold.merge_state(op, &payload);
2609                self.evidence = fold.evidence;
2610                self.fold = Some(fold);
2611                merged?;
2612            } else {
2613                // Nothing folded here yet, so the incoming state is this position's state.
2614                let mut fold = HistogramAccumulator::from_payload(op, &payload)?;
2615                fold.evidence = recorded;
2616                self.fold = Some(fold);
2617            }
2618            let evidence = self.fold.as_ref().map_or(recorded, |fold| fold.evidence);
2619            self.evidence = evidence;
2620            if evidence.poisoned {
2621                // Two partitions can each be valid on their own and still disagree on their bucket
2622                // layout, which the merge reports the way a fold inside one partition reports it.
2623                self.record_incompatible();
2624                continue;
2625            }
2626            self.count = combined_count;
2627            if evidence.custom_bounds_reconciled && !recorded.custom_bounds_reconciled {
2628                record_reconciled_custom_buckets(&self.collector, self.kind.name());
2629            }
2630        }
2631
2632        Ok(())
2633    }
2634}
2635
2636fn histogram_delta(
2637    samples: &[NativeHistogram],
2638    timestamps: &[i64],
2639    is_counter: bool,
2640) -> Option<NativeHistogram> {
2641    if samples.len() < 2 || samples.len() != timestamps.len() {
2642        return None;
2643    }
2644
2645    if !is_counter {
2646        return legacy_bridge::sub(samples.last()?, samples.first()?)
2647            .map(NativeHistogram::into_gauge);
2648    }
2649
2650    let first_reset = samples[1].detect_counter_reset(&samples[0], timestamps[0], timestamps[1]);
2651    let (initial, reset_scan_start) = if first_reset {
2652        // The first sample is irrelevant after an immediate reset. Adopt the
2653        // second sample's layout so an incompatible pre-reset layout is ignored.
2654        (samples[1].zero_like(), 2)
2655    } else {
2656        (samples[0].clone(), 1)
2657    };
2658    let mut result = legacy_bridge::sub(samples.last()?, &initial)?;
2659    for index in reset_scan_start..samples.len() {
2660        if samples[index].detect_counter_reset(
2661            &samples[index - 1],
2662            timestamps[index - 1],
2663            timestamps[index],
2664        ) {
2665            result = legacy_bridge::add(&result, &samples[index - 1])?;
2666        }
2667    }
2668    Some(result.into_gauge())
2669}
2670
2671fn idelta_value(
2672    samples: &[NativeHistogram],
2673    is_rate: bool,
2674    previous_ts: i64,
2675    current_ts: i64,
2676    sampled_interval_secs: f64,
2677) -> Option<NativeHistogram> {
2678    if samples.len() < 2 {
2679        return None;
2680    }
2681    let previous = &samples[samples.len() - 2];
2682    let current = samples.last()?;
2683    let result = if is_rate && current.detect_counter_reset(previous, previous_ts, current_ts) {
2684        current.clone()
2685    } else {
2686        legacy_bridge::sub(current, previous)?
2687    };
2688    Some(
2689        if is_rate {
2690            legacy_bridge::scale(&result, 1.0 / sampled_interval_secs)
2691        } else {
2692            result
2693        }
2694        .into_gauge(),
2695    )
2696}
2697
2698fn native_extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
2699    input: &[ColumnarValue],
2700    range_length: i64,
2701    func_name: &'static str,
2702    collector: Option<PromqlAnnotationCollector>,
2703) -> DfResult<ColumnarValue> {
2704    if input.len() != 4 {
2705        return Err(DataFusionError::Plan(format!(
2706            "{func_name} function should have 4 inputs"
2707        )));
2708    }
2709
2710    let ts_dict = extract_range_dict(
2711        &input[0],
2712        func_name,
2713        "timestamp range vector",
2714        &DataType::Timestamp(TimeUnit::Millisecond, None),
2715    )?;
2716    let value_dict = extract_range_dict(
2717        &input[1],
2718        func_name,
2719        "value range vector",
2720        &native_histogram_arrow_type(),
2721    )?;
2722    let eval_ts = extract_array(&input[2])?;
2723    let eval_ts = eval_ts
2724        .as_any()
2725        .downcast_ref::<TimestampMillisecondArray>()
2726        .ok_or_else(|| {
2727            DataFusionError::Execution(format!(
2728                "{func_name}: expect evaluation timestamp vector as Timestamp(Millisecond), found {}",
2729                eval_ts.data_type()
2730            ))
2731        })?;
2732
2733    let keys = ts_dict.keys().values();
2734    if value_dict.keys().values() != keys || eval_ts.len() != keys.len() {
2735        return Err(DataFusionError::Execution(format!(
2736            "{func_name}: timestamp, value, and evaluation ranges should have the same layout"
2737        )));
2738    }
2739
2740    let all_timestamps = ts_dict
2741        .values()
2742        .as_any()
2743        .downcast_ref::<TimestampMillisecondArray>()
2744        .expect("validated timestamp range")
2745        .values();
2746    let all_histograms = value_dict
2747        .values()
2748        .as_any()
2749        .downcast_ref::<StructArray>()
2750        .expect("validated native histogram range");
2751    let range_length_secs = range_length as f64 / 1000.0;
2752    let mut result = Vec::with_capacity(keys.len());
2753
2754    for index in 0..keys.len() {
2755        let (raw_offset, raw_length) = unpack(keys[index]);
2756        let offset = raw_offset as usize;
2757        let length = raw_length as usize;
2758        if length == 0 {
2759            result.push(None);
2760            continue;
2761        }
2762
2763        let mut samples = Vec::with_capacity(length);
2764        let mut has_null = false;
2765        for row in offset..offset + length {
2766            let Some(histogram) = read_histogram(all_histograms, row)? else {
2767                has_null = true;
2768                break;
2769            };
2770            samples.push(histogram);
2771        }
2772        if has_null {
2773            result.push(None);
2774            continue;
2775        }
2776
2777        let first_ts = all_timestamps[offset];
2778        let last_ts = all_timestamps[offset + length - 1];
2779        let range_end = eval_ts.value(index);
2780        let range_start = range_end - range_length;
2781        let synthetic_zero_timestamp = IS_COUNTER
2782            .then_some(samples[0].start_timestamp)
2783            .flatten()
2784            .filter(|start| *start != 0 && range_start < *start && *start < first_ts);
2785        let synthetic_zero_start = synthetic_zero_timestamp.is_some();
2786        if length < 2 && !synthetic_zero_start {
2787            result.push(None);
2788            continue;
2789        }
2790
2791        let wrong_flavor = if IS_COUNTER {
2792            samples
2793                .iter()
2794                .any(|histogram| histogram.reset_hint == GAUGE_RESET_HINT)
2795        } else {
2796            samples[0].reset_hint != GAUGE_RESET_HINT
2797                || samples[samples.len() - 1].reset_hint != GAUGE_RESET_HINT
2798        };
2799        if wrong_flavor {
2800            let expected = if IS_COUNTER { "counter" } else { "gauge" };
2801            record_warning(
2802                &collector,
2803                format!("{func_name}: native histogram input should be a {expected} histogram"),
2804            );
2805        }
2806
2807        let timestamps = &all_timestamps[offset..offset + length];
2808        for pair in samples.windows(2) {
2809            record_custom_reconciliation(&collector, func_name, &pair[0], &pair[1]);
2810        }
2811        let mut histogram = if length == 1 {
2812            samples[0].clone()
2813        } else if let Some(histogram) = histogram_delta(&samples, timestamps, IS_COUNTER) {
2814            histogram
2815        } else {
2816            record_warning(
2817                &collector,
2818                format!("{func_name}: dropped native histogram range with incompatible schemas"),
2819            );
2820            result.push(None);
2821            continue;
2822        };
2823        if synthetic_zero_start && length > 1 {
2824            let Some(with_synthetic_zero) = legacy_bridge::add(&histogram, &samples[0]) else {
2825                record_warning(
2826                    &collector,
2827                    format!(
2828                        "{func_name}: dropped native histogram range with incompatible schemas"
2829                    ),
2830                );
2831                result.push(None);
2832                continue;
2833            };
2834            histogram = with_synthetic_zero;
2835        }
2836
2837        let real_sampled_interval_ms = (last_ts - first_ts) as f64;
2838        let sampled_interval_ms = synthetic_zero_timestamp
2839            .map(|start| (last_ts - start) as f64)
2840            .unwrap_or(real_sampled_interval_ms);
2841        if sampled_interval_ms <= 0.0 {
2842            result.push(None);
2843            continue;
2844        }
2845        let average_interval_ms = if length > 1 {
2846            real_sampled_interval_ms / (length - 1) as f64
2847        } else {
2848            0.0
2849        };
2850        let mut duration_to_start_ms = if synthetic_zero_start {
2851            0.0
2852        } else {
2853            (first_ts - range_start) as f64
2854        };
2855        let duration_to_end_ms = (range_end - last_ts) as f64;
2856
2857        if IS_COUNTER && !synthetic_zero_start && histogram.count > 0.0 && samples[0].count >= 0.0 {
2858            let duration_to_zero = sampled_interval_ms * (samples[0].count / histogram.count);
2859            if duration_to_zero < duration_to_start_ms {
2860                duration_to_start_ms = duration_to_zero;
2861            }
2862        }
2863
2864        let extrapolation_threshold = average_interval_ms * 1.1;
2865        let mut extrapolated_interval_ms = sampled_interval_ms;
2866        if duration_to_start_ms < extrapolation_threshold {
2867            extrapolated_interval_ms += duration_to_start_ms;
2868        } else {
2869            extrapolated_interval_ms += average_interval_ms / 2.0;
2870        }
2871        if duration_to_end_ms < extrapolation_threshold {
2872            extrapolated_interval_ms += duration_to_end_ms;
2873        } else {
2874            extrapolated_interval_ms += average_interval_ms / 2.0;
2875        }
2876
2877        let mut factor = extrapolated_interval_ms / sampled_interval_ms;
2878        if IS_RATE {
2879            factor /= range_length_secs;
2880        }
2881        histogram = legacy_bridge::scale(&histogram, factor).into_gauge();
2882        result.push(Some(histogram));
2883    }
2884
2885    Ok(ColumnarValue::Array(build_histogram_array(&result)))
2886}
2887
2888fn create_native_extrapolated_udf<const IS_COUNTER: bool, const IS_RATE: bool>(
2889    name: &'static str,
2890    collector: Option<PromqlAnnotationCollector>,
2891) -> ScalarUDF {
2892    let input_types = vec![
2893        RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
2894        RangeArray::convert_data_type(native_histogram_arrow_type()),
2895        DataType::Timestamp(TimeUnit::Millisecond, None),
2896        DataType::Int64,
2897    ];
2898    create_udf(
2899        name,
2900        input_types,
2901        native_histogram_arrow_type(),
2902        Volatility::Volatile,
2903        Arc::new(move |input: &[ColumnarValue]| {
2904            let range_length = extract_array(&input[3])?;
2905            let range_length = range_length
2906                .as_any()
2907                .downcast_ref::<Int64Array>()
2908                .ok_or_else(|| {
2909                    DataFusionError::Execution(format!(
2910                        "{name}: expect Int64 as range length type, found {}",
2911                        range_length.data_type()
2912                    ))
2913                })?;
2914            if range_length.is_empty() || range_length.is_null(0) {
2915                return Err(DataFusionError::Execution(format!(
2916                    "{name}: range length must contain a non-null Int64 value"
2917                )));
2918            }
2919            native_extrapolated_rate::<IS_COUNTER, IS_RATE>(
2920                input,
2921                range_length.value(0),
2922                name,
2923                collector.clone(),
2924            )
2925        }) as _,
2926    )
2927}
2928
2929pub struct NativeHistogramDelta;
2930pub struct NativeHistogramRate;
2931pub struct NativeHistogramIncrease;
2932
2933impl NativeHistogramDelta {
2934    pub const fn name() -> &'static str {
2935        "prom_native_histogram_delta"
2936    }
2937
2938    pub fn scalar_udf() -> ScalarUDF {
2939        Self::scalar_udf_with_collector(None)
2940    }
2941
2942    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2943        create_native_extrapolated_udf::<false, false>(Self::name(), collector)
2944    }
2945}
2946
2947impl NativeHistogramRate {
2948    pub const fn name() -> &'static str {
2949        "prom_native_histogram_rate"
2950    }
2951
2952    pub fn scalar_udf() -> ScalarUDF {
2953        Self::scalar_udf_with_collector(None)
2954    }
2955
2956    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2957        create_native_extrapolated_udf::<true, true>(Self::name(), collector)
2958    }
2959}
2960
2961impl NativeHistogramIncrease {
2962    pub const fn name() -> &'static str {
2963        "prom_native_histogram_increase"
2964    }
2965
2966    pub fn scalar_udf() -> ScalarUDF {
2967        Self::scalar_udf_with_collector(None)
2968    }
2969
2970    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2971        create_native_extrapolated_udf::<true, false>(Self::name(), collector)
2972    }
2973}
2974
2975fn native_idelta<const IS_RATE: bool>(
2976    input: &[ColumnarValue],
2977    func_name: &'static str,
2978    collector: Option<PromqlAnnotationCollector>,
2979) -> DfResult<ColumnarValue> {
2980    if input.len() != 2 {
2981        return Err(DataFusionError::Plan(format!(
2982            "{func_name} function should have 2 inputs"
2983        )));
2984    }
2985
2986    let ts_range = extract_range_dict(
2987        &input[0],
2988        func_name,
2989        "timestamp range vector",
2990        &DataType::Timestamp(TimeUnit::Millisecond, None),
2991    )?;
2992    let value_range = extract_range_dict(
2993        &input[1],
2994        func_name,
2995        "value range vector",
2996        &native_histogram_arrow_type(),
2997    )?;
2998
2999    if ts_range.keys().values() != value_range.keys().values() {
3000        return Err(DataFusionError::Execution(format!(
3001            "{func_name}: timestamp and value ranges should have the same window layout"
3002        )));
3003    }
3004
3005    let ts_values = ts_range
3006        .values()
3007        .as_any()
3008        .downcast_ref::<TimestampMillisecondArray>()
3009        .expect("validated timestamp range")
3010        .values();
3011    let histograms = value_range
3012        .values()
3013        .as_any()
3014        .downcast_ref::<StructArray>()
3015        .expect("validated native histogram range");
3016    let mut result = Vec::with_capacity(ts_range.keys().len());
3017
3018    for key in ts_range.keys().values() {
3019        let (offset, length) = unpack(*key);
3020        let offset = offset as usize;
3021        let length = length as usize;
3022        if length < 2 {
3023            result.push(None);
3024            continue;
3025        }
3026
3027        let mut samples = Vec::with_capacity(2);
3028        let mut has_null = false;
3029        for row in offset + length - 2..offset + length {
3030            let Some(histogram) = read_histogram(histograms, row)? else {
3031                has_null = true;
3032                break;
3033            };
3034            samples.push(histogram);
3035        }
3036        if has_null {
3037            result.push(None);
3038            continue;
3039        }
3040
3041        let wrong_flavor = samples.iter().any(|histogram| {
3042            if IS_RATE {
3043                histogram.reset_hint == GAUGE_RESET_HINT
3044            } else {
3045                histogram.reset_hint != GAUGE_RESET_HINT
3046            }
3047        });
3048        if wrong_flavor {
3049            let expected = if IS_RATE { "counter" } else { "gauge" };
3050            record_warning(
3051                &collector,
3052                format!("{func_name}: native histogram input should be a {expected} histogram"),
3053            );
3054        }
3055
3056        let sampled_interval_secs =
3057            (ts_values[offset + length - 1] - ts_values[offset + length - 2]) as f64 / 1000.0;
3058        if sampled_interval_secs <= 0.0 {
3059            result.push(None);
3060            continue;
3061        }
3062        record_custom_reconciliation(&collector, func_name, &samples[0], &samples[1]);
3063        let value = idelta_value(
3064            &samples,
3065            IS_RATE,
3066            ts_values[offset + length - 2],
3067            ts_values[offset + length - 1],
3068            sampled_interval_secs,
3069        );
3070        if value.is_none() {
3071            record_warning(
3072                &collector,
3073                format!("{func_name}: dropped native histogram range with incompatible schemas"),
3074            );
3075        }
3076        result.push(value);
3077    }
3078
3079    Ok(ColumnarValue::Array(build_histogram_array(&result)))
3080}
3081
3082fn create_native_idelta_udf<const IS_RATE: bool>(
3083    name: &'static str,
3084    collector: Option<PromqlAnnotationCollector>,
3085) -> ScalarUDF {
3086    create_udf(
3087        name,
3088        vec![
3089            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
3090            RangeArray::convert_data_type(native_histogram_arrow_type()),
3091        ],
3092        native_histogram_arrow_type(),
3093        Volatility::Volatile,
3094        Arc::new(move |input: &[ColumnarValue]| {
3095            native_idelta::<IS_RATE>(input, name, collector.clone())
3096        }) as _,
3097    )
3098}
3099
3100pub struct NativeHistogramIDelta;
3101pub struct NativeHistogramIRate;
3102
3103impl NativeHistogramIDelta {
3104    pub const fn name() -> &'static str {
3105        "prom_native_histogram_idelta"
3106    }
3107
3108    pub fn scalar_udf() -> ScalarUDF {
3109        Self::scalar_udf_with_collector(None)
3110    }
3111
3112    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
3113        create_native_idelta_udf::<false>(Self::name(), collector)
3114    }
3115}
3116
3117impl NativeHistogramIRate {
3118    pub const fn name() -> &'static str {
3119        "prom_native_histogram_irate"
3120    }
3121
3122    pub fn scalar_udf() -> ScalarUDF {
3123        Self::scalar_udf_with_collector(None)
3124    }
3125
3126    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
3127        create_native_idelta_udf::<true>(Self::name(), collector)
3128    }
3129}
3130
3131#[cfg(test)]
3132mod tests {
3133    use datafusion::arrow::datatypes::Field;
3134    use datafusion_common::config::ConfigOptions;
3135    use datafusion_expr::ScalarFunctionArgs;
3136    use datatypes::series::aggregate_state::StatePayload;
3137
3138    use super::*;
3139
3140    fn sample_histogram(count: f64, sum: f64, positive_buckets: Vec<f64>) -> NativeHistogram {
3141        NativeHistogram {
3142            schema: 0,
3143            zero_threshold: 0.0,
3144            sum,
3145            reset_hint: UNKNOWN_COUNTER_RESET_HINT,
3146            start_timestamp: None,
3147            custom_values: Vec::new(),
3148            positive_spans: vec![Span {
3149                offset: 0,
3150                length: positive_buckets.len() as i32,
3151            }],
3152            negative_spans: Vec::new(),
3153            count,
3154            zero_count: 0.0,
3155            positive_buckets,
3156            negative_buckets: Vec::new(),
3157        }
3158    }
3159
3160    fn run_scalar_udf(udf: ScalarUDF, input: Vec<ColumnarValue>) -> f64 {
3161        let result = run_udf(udf, input, DataType::Float64);
3162        extract_array(&result)
3163            .unwrap()
3164            .as_any()
3165            .downcast_ref::<Float64Array>()
3166            .unwrap()
3167            .value(0)
3168    }
3169
3170    fn run_udf(udf: ScalarUDF, input: Vec<ColumnarValue>, return_type: DataType) -> ColumnarValue {
3171        let arg_fields = input
3172            .iter()
3173            .enumerate()
3174            .map(|(idx, input)| Arc::new(Field::new(format!("arg_{idx}"), input.data_type(), true)))
3175            .collect();
3176        let args = ScalarFunctionArgs {
3177            args: input,
3178            arg_fields,
3179            number_rows: 1,
3180            return_field: Arc::new(Field::new("result", return_type, true)),
3181            config_options: Arc::new(ConfigOptions::default()),
3182        };
3183
3184        udf.invoke_with_args(args).unwrap()
3185    }
3186
3187    fn run_histogram_udf(udf: ScalarUDF, input: Vec<ColumnarValue>) -> NativeHistogram {
3188        let result = run_udf(udf, input, native_histogram_arrow_type());
3189        let array = extract_array(&result)
3190            .unwrap()
3191            .as_any()
3192            .downcast_ref::<StructArray>()
3193            .unwrap()
3194            .clone();
3195        read_histogram(&array, 0).unwrap().unwrap()
3196    }
3197
3198    fn evaluated_histogram(
3199        accumulator: &mut NativeHistogramAggregateAccumulator,
3200    ) -> NativeHistogram {
3201        evaluated(accumulator).expect("native histogram accumulator answered nothing")
3202    }
3203
3204    fn evaluated(accumulator: &mut NativeHistogramAggregateAccumulator) -> Option<NativeHistogram> {
3205        let ScalarValue::Struct(array) = accumulator.evaluate().unwrap() else {
3206            panic!("native histogram accumulator returned a non-struct value");
3207        };
3208        read_histogram(&array, 0).unwrap()
3209    }
3210
3211    /// The Arrow arrays one accumulator's state frame spans, one row each.
3212    fn state_arrays(aggregate: &mut NativeHistogramAggregateAccumulator) -> Vec<ArrayRef> {
3213        aggregate
3214            .state()
3215            .unwrap()
3216            .into_iter()
3217            .map(|value| value.to_array_of_size(1).unwrap())
3218            .collect()
3219    }
3220
3221    /// The components of one legacy accumulator's state frame.
3222    struct LegacyState {
3223        histogram: Option<NativeHistogram>,
3224        /// The `UInt64` component; only an average declares one.
3225        count: Option<u64>,
3226        /// The `dropped_incompatible` component.
3227        dropped: bool,
3228        counter_reset_seen: bool,
3229        not_counter_reset_seen: bool,
3230    }
3231
3232    fn legacy_state(aggregate: &mut NativeHistogramAggregateAccumulator) -> LegacyState {
3233        let state = aggregate.state().unwrap();
3234        let ScalarValue::Struct(array) = state[0].clone() else {
3235            panic!("native histogram accumulator state is not a struct");
3236        };
3237        let mut offset = 1;
3238        let count = if aggregate.kind.needs_count() {
3239            let count = match state[offset].clone() {
3240                ScalarValue::UInt64(count) => count,
3241                _ => panic!("native histogram accumulator count state is not UInt64"),
3242            };
3243            offset += 1;
3244            count
3245        } else {
3246            None
3247        };
3248        let boolean = |index: usize| match state[index] {
3249            ScalarValue::Boolean(value) => value.unwrap_or_default(),
3250            _ => panic!("native histogram accumulator state component is not Boolean"),
3251        };
3252        LegacyState {
3253            histogram: read_histogram(&array, 0).unwrap(),
3254            count,
3255            dropped: boolean(offset),
3256            counter_reset_seen: boolean(offset + 1),
3257            not_counter_reset_seen: boolean(offset + 2),
3258        }
3259    }
3260
3261    /// Asserts one legacy frame histogram carries what one fold histogram carries, bit for bit.
3262    fn assert_frame_carries(actual: &NativeHistogram, expected: &FloatHistogram, case: &str) {
3263        assert_eq!(
3264            actual.count.to_bits(),
3265            expected.count.to_bits(),
3266            "{case}: count"
3267        );
3268        assert_eq!(
3269            actual.zero_count.to_bits(),
3270            expected.zero_count.to_bits(),
3271            "{case}: zero count"
3272        );
3273        assert_eq!(actual.sum.to_bits(), expected.sum.to_bits(), "{case}: sum");
3274        assert_eq!(actual.schema, expected.schema, "{case}: schema");
3275        assert_eq!(
3276            actual.zero_threshold.to_bits(),
3277            expected.zero_threshold.to_bits(),
3278            "{case}: zero threshold"
3279        );
3280        assert_eq!(
3281            actual
3282                .custom_values
3283                .iter()
3284                .map(|bound| bound.to_bits())
3285                .collect::<Vec<_>>(),
3286            expected
3287                .custom_values
3288                .iter()
3289                .map(|bound| bound.to_bits())
3290                .collect::<Vec<_>>(),
3291            "{case}: custom bounds"
3292        );
3293        for (side, spans, counts, buckets) in [
3294            (
3295                "positive",
3296                &actual.positive_spans,
3297                &actual.positive_buckets,
3298                &expected.positive,
3299            ),
3300            (
3301                "negative",
3302                &actual.negative_spans,
3303                &actual.negative_buckets,
3304                &expected.negative,
3305            ),
3306        ] {
3307            assert_eq!(
3308                expand_spans(spans),
3309                buckets.iter().map(|&(index, _)| index).collect::<Vec<_>>(),
3310                "{case}: {side} bucket indices"
3311            );
3312            assert_eq!(
3313                counts
3314                    .iter()
3315                    .map(|count| count.to_bits())
3316                    .collect::<Vec<_>>(),
3317                buckets
3318                    .iter()
3319                    .map(|&(_, count)| count.to_bits())
3320                    .collect::<Vec<_>>(),
3321                "{case}: {side} bucket counts"
3322            );
3323        }
3324    }
3325
3326    /// The absolute bucket indices a span list expands to, as the frame's reader expands them.
3327    fn expand_spans(spans: &[Span]) -> Vec<i32> {
3328        let mut indices = Vec::new();
3329        let mut cursor = 0;
3330        for (position, span) in spans.iter().enumerate() {
3331            cursor = if position == 0 {
3332                span.offset
3333            } else {
3334                cursor + span.offset
3335            };
3336            indices.extend(cursor..cursor + span.length);
3337            cursor += span.length;
3338        }
3339        indices
3340    }
3341
3342    fn histogram_range_input(values: Vec<Option<NativeHistogram>>) -> Vec<ColumnarValue> {
3343        let timestamps = Arc::new(TimestampMillisecondArray::from_iter(
3344            (0..values.len()).map(|idx| Some((idx as i64 + 1) * 1000)),
3345        ));
3346        let histograms = build_histogram_array(&values);
3347        let range = [(0, values.len() as u32)];
3348        let ts_range = RangeArray::from_ranges(timestamps, range).unwrap();
3349        let value_range = RangeArray::from_ranges(histograms, range).unwrap();
3350
3351        vec![
3352            ColumnarValue::Array(Arc::new(ts_range.into_dict())),
3353            ColumnarValue::Array(Arc::new(value_range.into_dict())),
3354        ]
3355    }
3356
3357    fn mixed_range_input(
3358        name: &str,
3359        floats: Vec<Option<f64>>,
3360        histograms: Vec<Option<NativeHistogram>>,
3361    ) -> Vec<ColumnarValue> {
3362        assert_eq!(floats.len(), histograms.len());
3363        let timestamps = Arc::new(TimestampMillisecondArray::from_iter(
3364            (0..floats.len()).map(|idx| Some((idx as i64 + 1) * 1000)),
3365        ));
3366        let floats = Arc::new(Float64Array::from(floats));
3367        let histograms = build_histogram_array(&histograms);
3368        let range = [(0, u32::try_from(floats.len()).unwrap())];
3369        vec![
3370            ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string()))),
3371            ColumnarValue::Array(Arc::new(
3372                RangeArray::from_ranges(timestamps, range)
3373                    .unwrap()
3374                    .into_dict(),
3375            )),
3376            ColumnarValue::Array(Arc::new(
3377                RangeArray::from_ranges(floats, range).unwrap().into_dict(),
3378            )),
3379            ColumnarValue::Array(Arc::new(
3380                RangeArray::from_ranges(histograms, range)
3381                    .unwrap()
3382                    .into_dict(),
3383            )),
3384        ]
3385    }
3386
3387    fn mixed_float_result(udf: ScalarUDF, input: Vec<ColumnarValue>) -> Option<f64> {
3388        let result = run_udf(udf, input, DataType::Float64);
3389        let result = extract_array(&result).unwrap();
3390        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
3391        result.is_valid(0).then(|| result.value(0))
3392    }
3393
3394    fn mixed_histogram_result(
3395        udf: ScalarUDF,
3396        input: Vec<ColumnarValue>,
3397    ) -> Option<NativeHistogram> {
3398        let result = run_udf(udf, input, native_histogram_arrow_type());
3399        let result = extract_array(&result).unwrap();
3400        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
3401        read_histogram(result, 0).unwrap()
3402    }
3403
3404    fn run_histogram_range_udf(
3405        udf: ScalarUDF,
3406        histograms: Vec<NativeHistogram>,
3407    ) -> NativeHistogram {
3408        run_histogram_udf(
3409            udf,
3410            histogram_range_input(histograms.into_iter().map(Some).collect()),
3411        )
3412    }
3413
3414    fn run_float_range_udf(
3415        udf: ScalarUDF,
3416        histograms: Vec<Option<NativeHistogram>>,
3417    ) -> Option<f64> {
3418        let result = run_udf(udf, histogram_range_input(histograms), DataType::Float64);
3419        let result = extract_array(&result).unwrap();
3420        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
3421        (!result.is_null(0)).then(|| result.value(0))
3422    }
3423
3424    fn run_extrapolated_histogram_udf(
3425        udf: ScalarUDF,
3426        histograms: Vec<NativeHistogram>,
3427    ) -> NativeHistogram {
3428        let range_length = histograms.len() as i64 * 1000;
3429        let timestamps = (0..histograms.len())
3430            .map(|idx| (idx as i64 + 1) * 1000)
3431            .collect();
3432        extrapolated_histogram_result(udf, timestamps, histograms, range_length, range_length)
3433            .unwrap()
3434    }
3435
3436    fn extrapolated_histogram_result(
3437        udf: ScalarUDF,
3438        timestamps: Vec<i64>,
3439        histograms: Vec<NativeHistogram>,
3440        range_end: i64,
3441        range_length: i64,
3442    ) -> Option<NativeHistogram> {
3443        assert_eq!(timestamps.len(), histograms.len());
3444        let range = [(0, u32::try_from(histograms.len()).unwrap())];
3445        let timestamps = Arc::new(TimestampMillisecondArray::from(timestamps));
3446        let histograms =
3447            build_histogram_array(&histograms.into_iter().map(Some).collect::<Vec<_>>());
3448        let mut input = vec![
3449            ColumnarValue::Array(Arc::new(
3450                RangeArray::from_ranges(timestamps, range)
3451                    .unwrap()
3452                    .into_dict(),
3453            )),
3454            ColumnarValue::Array(Arc::new(
3455                RangeArray::from_ranges(histograms, range)
3456                    .unwrap()
3457                    .into_dict(),
3458            )),
3459        ];
3460        input.push(ColumnarValue::Array(Arc::new(
3461            TimestampMillisecondArray::from(vec![range_end]),
3462        )));
3463        input.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![
3464            range_length,
3465        ]))));
3466        let result = run_udf(udf, input, native_histogram_arrow_type());
3467        let result = extract_array(&result).unwrap();
3468        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
3469        read_histogram(result, 0).unwrap()
3470    }
3471
3472    fn collected_warnings(collector: &PromqlAnnotationCollector) -> Vec<String> {
3473        let mut warnings = Vec::new();
3474        collector.append_to(&mut warnings, &mut Vec::new());
3475        warnings
3476    }
3477
3478    fn collected_infos(collector: &PromqlAnnotationCollector) -> Vec<String> {
3479        let mut infos = Vec::new();
3480        collector.append_to(&mut Vec::new(), &mut infos);
3481        infos
3482    }
3483
3484    #[test]
3485    fn quantile_and_fraction_report_nan_observations() {
3486        let histogram = sample_histogram(10.0, f64::NAN, vec![8.0]);
3487        let histogram_arg =
3488            || ColumnarValue::Array(build_histogram_array(&[Some(histogram.clone())]));
3489
3490        let quantile_collector = PromqlAnnotationCollector::default();
3491        let skewed = run_scalar_udf(
3492            NativeHistogramQuantile::scalar_udf_with_collector(Some(quantile_collector.clone())),
3493            vec![
3494                histogram_arg(),
3495                ColumnarValue::Scalar(ScalarValue::Float64(Some(0.5))),
3496            ],
3497        );
3498        assert!(skewed.is_finite());
3499        let nan = run_scalar_udf(
3500            NativeHistogramQuantile::scalar_udf_with_collector(Some(quantile_collector.clone())),
3501            vec![
3502                histogram_arg(),
3503                ColumnarValue::Scalar(ScalarValue::Float64(Some(0.9))),
3504            ],
3505        );
3506        assert!(nan.is_nan());
3507        let infos = collected_infos(&quantile_collector);
3508        assert!(
3509            infos
3510                .iter()
3511                .any(|info| info.ends_with("result is skewed higher"))
3512        );
3513        assert!(infos.iter().any(|info| info.ends_with("result is NaN")));
3514
3515        let fraction_collector = PromqlAnnotationCollector::default();
3516        assert_eq!(
3517            run_scalar_udf(
3518                NativeHistogramFraction::scalar_udf_with_collector(Some(
3519                    fraction_collector.clone(),
3520                )),
3521                vec![
3522                    histogram_arg(),
3523                    ColumnarValue::Scalar(ScalarValue::Float64(Some(f64::NEG_INFINITY))),
3524                    ColumnarValue::Scalar(ScalarValue::Float64(Some(f64::INFINITY))),
3525                ],
3526            ),
3527            0.8
3528        );
3529        assert_eq!(
3530            collected_infos(&fraction_collector),
3531            vec![
3532                "input to histogram_fraction has NaN observations, which are excluded from all fractions"
3533                    .to_string()
3534            ]
3535        );
3536    }
3537
3538    #[test]
3539    fn mixed_ranges_follow_prometheus_sample_type_semantics() {
3540        let first = sample_histogram(1.0, 1.0, vec![1.0]);
3541        let second = sample_histogram(3.0, 3.0, vec![3.0]);
3542        let collector = PromqlAnnotationCollector::default();
3543
3544        let mut rate = mixed_range_input(
3545            "rate",
3546            vec![Some(1.0), None, Some(3.0)],
3547            vec![None, Some(first.clone()), None],
3548        );
3549        rate.push(ColumnarValue::Array(Arc::new(
3550            TimestampMillisecondArray::from(vec![3000]),
3551        )));
3552        rate.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![3000]))));
3553        assert_eq!(
3554            mixed_float_result(MixedRange::float_udf(Some(collector.clone())), rate.clone()),
3555            None
3556        );
3557        assert_eq!(
3558            mixed_histogram_result(MixedRange::histogram_udf(Some(collector.clone())), rate),
3559            None
3560        );
3561        assert!(
3562            collected_warnings(&collector)
3563                .iter()
3564                .any(|warning| warning.contains("mix of float and native histogram"))
3565        );
3566
3567        let pure_rate = |floats, histograms| {
3568            let mut input = mixed_range_input("rate", floats, histograms);
3569            input.push(ColumnarValue::Array(Arc::new(
3570                TimestampMillisecondArray::from(vec![3000]),
3571            )));
3572            input.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![3000]))));
3573            input
3574        };
3575        let pure_float = pure_rate(
3576            vec![Some(1.0), Some(2.0), Some(3.0)],
3577            vec![None, None, None],
3578        );
3579        assert_eq!(
3580            mixed_float_result(MixedRange::float_udf(None), pure_float.clone()),
3581            Some(1.0)
3582        );
3583        assert_eq!(
3584            mixed_histogram_result(MixedRange::histogram_udf(None), pure_float),
3585            None
3586        );
3587        let pure_histogram = pure_rate(
3588            vec![None, None, None],
3589            vec![
3590                Some(sample_histogram(1.0, 1.0, vec![1.0])),
3591                Some(sample_histogram(2.0, 2.0, vec![2.0])),
3592                Some(sample_histogram(3.0, 3.0, vec![3.0])),
3593            ],
3594        );
3595        assert_eq!(
3596            mixed_float_result(MixedRange::float_udf(None), pure_histogram.clone()),
3597            None
3598        );
3599        assert_eq!(
3600            mixed_histogram_result(MixedRange::histogram_udf(None), pure_histogram)
3601                .unwrap()
3602                .count,
3603            1.0
3604        );
3605
3606        let idelta = mixed_range_input(
3607            "idelta",
3608            vec![Some(10.0), None, None],
3609            vec![None, Some(first.clone()), Some(second.clone())],
3610        );
3611        assert_eq!(
3612            mixed_float_result(MixedRange::float_udf(None), idelta.clone()),
3613            None
3614        );
3615        assert_eq!(
3616            mixed_histogram_result(MixedRange::histogram_udf(None), idelta)
3617                .unwrap()
3618                .count,
3619            2.0
3620        );
3621
3622        let alternating = || {
3623            mixed_range_input(
3624                "changes",
3625                vec![Some(1.0), None, None, Some(1.0)],
3626                vec![None, Some(first.clone()), Some(first.clone()), None],
3627            )
3628        };
3629        assert_eq!(
3630            mixed_float_result(MixedRange::float_udf(None), alternating()),
3631            Some(2.0)
3632        );
3633        let mut resets = alternating();
3634        resets[0] = ColumnarValue::Scalar(ScalarValue::Utf8(Some("resets".to_string())));
3635        assert_eq!(
3636            mixed_float_result(MixedRange::float_udf(None), resets),
3637            Some(2.0)
3638        );
3639
3640        for (name, expected) in [
3641            ("count_over_time", Some(4.0)),
3642            ("present_over_time", Some(1.0)),
3643            ("absent_over_time", None),
3644        ] {
3645            let mut input = alternating();
3646            input[0] = ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string())));
3647            assert_eq!(
3648                mixed_float_result(MixedRange::float_udf(None), input),
3649                expected,
3650                "{name}"
3651            );
3652        }
3653
3654        let last = mixed_range_input(
3655            "last_over_time",
3656            vec![None, Some(4.0)],
3657            vec![Some(first.clone()), None],
3658        );
3659        assert_eq!(
3660            mixed_float_result(MixedRange::float_udf(None), last.clone()),
3661            Some(4.0)
3662        );
3663        assert_eq!(
3664            mixed_histogram_result(MixedRange::histogram_udf(None), last),
3665            None
3666        );
3667
3668        let collector = PromqlAnnotationCollector::default();
3669        let histogram_only_min =
3670            mixed_range_input("min_over_time", vec![None], vec![Some(first.clone())]);
3671        assert_eq!(
3672            mixed_float_result(
3673                MixedRange::float_udf(Some(collector.clone())),
3674                histogram_only_min,
3675            ),
3676            None
3677        );
3678        assert!(collected_infos(&collector).is_empty());
3679
3680        let min = mixed_range_input(
3681            "min_over_time",
3682            vec![Some(3.0), None, Some(1.0)],
3683            vec![None, Some(first), None],
3684        );
3685        assert_eq!(
3686            mixed_float_result(MixedRange::float_udf(Some(collector.clone())), min),
3687            Some(1.0)
3688        );
3689        assert!(
3690            collected_infos(&collector)
3691                .iter()
3692                .any(|info| info.contains("ignored native histogram"))
3693        );
3694    }
3695
3696    #[test]
3697    fn count_sum_and_avg_read_struct() {
3698        let histograms = vec![Some(sample_histogram(6.0, 10.0, vec![2.0, 4.0]))];
3699        let array = build_histogram_array(&histograms);
3700        let input = vec![ColumnarValue::Array(array)];
3701
3702        let count = run_scalar_udf(NativeHistogramCount::scalar_udf(), input.clone());
3703        assert_eq!(count, 6.0);
3704
3705        let sum = run_scalar_udf(NativeHistogramSum::scalar_udf(), input.clone());
3706        assert_eq!(sum, 10.0);
3707
3708        let avg = run_scalar_udf(NativeHistogramAvg::scalar_udf(), input);
3709        assert_eq!(avg, 10.0 / 6.0);
3710    }
3711
3712    #[test]
3713    fn quantile_uses_bucket_bounds() {
3714        let histogram = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
3715        assert_eq!(histogram.quantile(0.0), 0.5);
3716        assert!(histogram.quantile(0.5) > 1.0);
3717        assert!(histogram.quantile(0.5) < 2.0);
3718    }
3719
3720    #[test]
3721    fn an_illegally_shaped_histogram_drops_its_position_rather_than_failing_the_query() {
3722        // The spans claim two buckets and the row carries one, which is a layout this crate cannot
3723        // read: it drops the position instead of failing the query. A single sample is enough to
3724        // drop it, because the position goes as a whole, with the warning below.
3725        let collector = PromqlAnnotationCollector::default();
3726        for kind in [
3727            NativeHistogramAggregateKind::Sum,
3728            NativeHistogramAggregateKind::Avg,
3729        ] {
3730            let mut aggregate =
3731                NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
3732            let mut invalid = sample_histogram(2.0, 3.0, vec![2.0]);
3733            invalid.positive_spans = vec![Span {
3734                offset: 0,
3735                length: 2,
3736            }];
3737
3738            aggregate.push_histogram(invalid, 1).expect(
3739                "a histogram this crate cannot read drops its position, it does not fail the query",
3740            );
3741
3742            assert!(aggregate.evidence.poisoned, "{}: poisoned", kind.name());
3743            assert!(
3744                aggregate.state_histogram().unwrap().is_none(),
3745                "{}: the position answers nothing",
3746                kind.name()
3747            );
3748            let warnings = collected_warnings(&collector);
3749            assert!(
3750                warnings.contains(&format!(
3751                    "{}: dropped native histogram aggregate with incompatible schemas",
3752                    kind.name()
3753                )),
3754                "{}: {warnings:?}",
3755                kind.name()
3756            );
3757        }
3758    }
3759
3760    #[test]
3761    fn sum_aggregate_exports_no_start_timestamp_of_its_own() {
3762        let mut histogram = sample_histogram(2.0, 3.0, vec![2.0]);
3763        histogram.start_timestamp = Some(1_234);
3764
3765        let mut accumulator =
3766            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
3767        accumulator.push_histogram(histogram, 1).unwrap();
3768
3769        // The answer is a derived histogram, not the sample that was pushed: it is read out of the
3770        // fold the way the native kernel reads one, and that clears the timestamp along with the
3771        // empty buckets it compacts away. The sample's own timestamp stays inside the fold.
3772        assert_eq!(
3773            accumulator
3774                .state_histogram()
3775                .unwrap()
3776                .unwrap()
3777                .start_timestamp,
3778            None,
3779            "a derived sum carries no start timestamp, not even from a single sample"
3780        );
3781    }
3782
3783    #[test]
3784    fn sum_aggregate_clears_the_start_timestamp_once_it_combines_two_samples() {
3785        let mut first = sample_histogram(2.0, 3.0, vec![2.0]);
3786        first.start_timestamp = Some(1_234);
3787        let mut second = sample_histogram(2.0, 3.0, vec![2.0]);
3788        second.start_timestamp = Some(5_678);
3789
3790        let mut accumulator =
3791            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
3792        accumulator.push_histogram(first, 1).unwrap();
3793        accumulator.push_histogram(second, 1).unwrap();
3794
3795        assert_eq!(
3796            accumulator
3797                .state_histogram()
3798                .unwrap()
3799                .unwrap()
3800                .start_timestamp,
3801            None,
3802            "a derived sum carries no start timestamp of its own"
3803        );
3804    }
3805
3806    #[test]
3807    fn comparison_observes_explicit_sparse_zero_buckets() {
3808        let mut left = sample_histogram(1.0, 1.0, vec![1.0, 0.0]);
3809        left.reset_hint = COUNTER_RESET_HINT;
3810        left.start_timestamp = Some(1000);
3811        let mut right = sample_histogram(1.0, 1.0, vec![1.0]);
3812        right.reset_hint = NOT_COUNTER_RESET_HINT;
3813        right.start_timestamp = Some(2000);
3814
3815        let result = run_udf(
3816            NativeHistogramEq::scalar_udf(),
3817            vec![
3818                ColumnarValue::Array(build_histogram_array(&[Some(left)])),
3819                ColumnarValue::Array(build_histogram_array(&[Some(right)])),
3820            ],
3821            DataType::Boolean,
3822        );
3823        let values = extract_array(&result).unwrap();
3824        let values = values.as_any().downcast_ref::<BooleanArray>().unwrap();
3825        assert!(!values.value(0));
3826    }
3827
3828    /// The one sample the two tests below fold: one bucket holding observations and one explicit
3829    /// empty bucket beside it.
3830    ///
3831    /// The answer keeps the bucket with observations and drops the empty one, which is a difference
3832    /// [`NativeHistogramEq`] can tell apart from the input.
3833    fn one_explicit_zero_bucket() -> NativeHistogram {
3834        sample_histogram(1.0, 1.0, vec![1.0, 0.0])
3835    }
3836
3837    /// A `sum` or `avg` over one sample answers `[1]` where the sample carried `[1, 0]`.
3838    ///
3839    /// The comparison change is intended. The answer is the fold's, not the sample's:
3840    /// [`finished_histogram`] compacts the empty bucket away, and the native `Aggregate` node reads
3841    /// its answers through that same function, so both paths answer `[1]` -- a one-sample group
3842    /// included. `promql_eq` tells an explicit zero bucket from an absent one (see
3843    /// [`comparison_observes_explicit_sparse_zero_buckets`]), so `sum(h)` is no longer equal to the
3844    /// single sample `h` it folded.
3845    #[test]
3846    fn sum_and_avg_compact_a_single_samples_explicit_zero_bucket() {
3847        for kind in [
3848            NativeHistogramAggregateKind::Sum,
3849            NativeHistogramAggregateKind::Avg,
3850        ] {
3851            let mut aggregate = NativeHistogramAggregateAccumulator::new(kind, None);
3852            aggregate
3853                .push_histogram(one_explicit_zero_bucket(), 1)
3854                .unwrap();
3855
3856            // The answer the state hands over is where the bucket list is decided.
3857            let answered = aggregate
3858                .state_histogram()
3859                .unwrap()
3860                .expect("a single sample answers");
3861            assert_eq!(
3862                answered.positive_buckets,
3863                vec![1.0],
3864                "{}: the empty bucket is compacted away",
3865                kind.name()
3866            );
3867            assert_eq!(answered.count, 1.0, "{}: the count", kind.name());
3868            assert_eq!(answered.sum, 1.0, "{}: the sum", kind.name());
3869
3870            let evaluated = evaluated_histogram(&mut aggregate);
3871            assert_eq!(
3872                evaluated.positive_buckets,
3873                vec![1.0],
3874                "{}: reading the answer back keeps the empty bucket out",
3875                kind.name()
3876            );
3877        }
3878    }
3879
3880    /// A partial state round trip answers what the direct evaluation answers: `[1]`.
3881    ///
3882    /// The exported state carries the fold's answer, which has already lost the explicit zero
3883    /// bucket, so merging it into an empty accumulator cannot put the bucket back: a state boundary
3884    /// does not restore what the fold compacted away. The comparison change is the direct
3885    /// evaluation's -- `promql_eq` tells `[1]` from the input's `[1, 0]` -- and it survives the
3886    /// state the same way.
3887    #[test]
3888    fn a_partial_state_round_trip_answers_the_compacted_explicit_zero_bucket() {
3889        for kind in [
3890            NativeHistogramAggregateKind::Sum,
3891            NativeHistogramAggregateKind::Avg,
3892        ] {
3893            let mut direct = NativeHistogramAggregateAccumulator::new(kind, None);
3894            direct
3895                .push_histogram(one_explicit_zero_bucket(), 1)
3896                .unwrap();
3897            let evaluated = evaluated_histogram(&mut direct);
3898
3899            let state = state_arrays(&mut direct);
3900            let mut merged = NativeHistogramAggregateAccumulator::new(kind, None);
3901            merged.merge_batch(&state).unwrap();
3902            let round_tripped = evaluated_histogram(&mut merged);
3903
3904            assert_eq!(
3905                round_tripped.positive_buckets,
3906                vec![1.0],
3907                "{}: the round trip keeps the empty bucket out",
3908                kind.name()
3909            );
3910            assert_eq!(
3911                round_tripped.positive_buckets,
3912                evaluated.positive_buckets,
3913                "{}: the round trip answers the direct buckets",
3914                kind.name()
3915            );
3916            assert_eq!(
3917                round_tripped.count,
3918                evaluated.count,
3919                "{}: the round trip answers the direct count",
3920                kind.name()
3921            );
3922            assert_eq!(
3923                round_tripped.sum,
3924                evaluated.sum,
3925                "{}: the round trip answers the direct sum",
3926                kind.name()
3927            );
3928        }
3929    }
3930
3931    #[test]
3932    fn unary_minus_returns_gauge_histogram() {
3933        let result = run_histogram_udf(
3934            NativeHistogramNeg::scalar_udf(),
3935            vec![ColumnarValue::Array(build_histogram_array(&[Some(
3936                sample_histogram(2.0, 3.0, vec![2.0]),
3937            )]))],
3938        );
3939
3940        assert_eq!(result.reset_hint, GAUGE_RESET_HINT);
3941        assert_eq!(result.count, -2.0);
3942        assert_eq!(result.sum, -3.0);
3943        assert_eq!(result.positive_buckets, vec![-2.0]);
3944    }
3945
3946    #[test]
3947    fn histogram_over_time_functions_preserve_reset_hints() {
3948        let mut first = sample_histogram(1.0, 1.0, vec![1.0]);
3949        first.reset_hint = COUNTER_RESET_HINT;
3950        let mut second = sample_histogram(2.0, 2.0, vec![2.0]);
3951        second.reset_hint = COUNTER_RESET_HINT;
3952
3953        let result = run_histogram_range_udf(
3954            NativeHistogramSumOverTime::scalar_udf(),
3955            vec![first.clone(), second.clone()],
3956        );
3957        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3958        assert_eq!(result.count, 3.0);
3959        assert_eq!(result.sum, 3.0);
3960        assert_eq!(result.positive_buckets, vec![3.0]);
3961
3962        let result = run_histogram_range_udf(
3963            NativeHistogramAvgOverTime::scalar_udf(),
3964            vec![first.clone(), second.clone()],
3965        );
3966        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3967        assert_eq!(result.count, 1.5);
3968        assert_eq!(result.sum, 1.5);
3969        assert_eq!(result.positive_buckets, vec![1.5]);
3970
3971        let result = run_histogram_range_udf(
3972            NativeHistogramLastOverTime::scalar_udf(),
3973            vec![first, second],
3974        );
3975        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3976        assert_eq!(result.count, 2.0);
3977        assert_eq!(result.sum, 2.0);
3978        assert_eq!(result.positive_buckets, vec![2.0]);
3979    }
3980
3981    #[test]
3982    fn range_folds_preserve_singletons_and_compact_combined_buckets() {
3983        let mut sample = one_explicit_zero_bucket();
3984        sample.reset_hint = GAUGE_RESET_HINT;
3985        sample.start_timestamp = Some(100);
3986        // Both buckets cancel. Only the first has a correction when compaction runs.
3987        let window: Vec<_> = (1..)
3988            .zip([(1e16, 1.0), (1.0, 0.0), (-1e16, -1.0), (0.0, 0.0)])
3989            .map(|(offset, (count, adjacent))| NativeHistogram {
3990                count: count + adjacent,
3991                sum: count,
3992                positive_spans: vec![
3993                    Span {
3994                        offset: 0,
3995                        length: 2,
3996                    },
3997                    Span { offset, length: 1 },
3998                ],
3999                positive_buckets: vec![count, adjacent, 0.0],
4000                ..sample.clone()
4001            })
4002            .collect();
4003        for (udf, expected_bucket) in [
4004            (NativeHistogramSumOverTime::scalar_udf(), 1.0),
4005            (NativeHistogramAvgOverTime::scalar_udf(), 0.25),
4006        ] {
4007            let single = run_histogram_range_udf(udf.clone(), vec![sample.clone()]);
4008            assert_eq!(single, sample);
4009
4010            let combined = run_histogram_range_udf(udf, window.clone());
4011            assert_eq!(combined.positive_buckets, vec![expected_bucket]);
4012            assert_eq!(combined.start_timestamp, None);
4013        }
4014    }
4015
4016    #[test]
4017    fn range_folds_keep_the_correction_at_every_downscale_position() {
4018        for schemas in [
4019            [8, 7, 7, 7, 7],
4020            [8, 8, 7, 7, 7],
4021            [8, 8, 8, 8, 7],
4022            [8, 7, 8, 7, 8],
4023        ] {
4024            let samples: Vec<_> = schemas
4025                .into_iter()
4026                .zip([1e16, 1.0, -1e16, 0.0, 0.0])
4027                .zip(1..)
4028                .map(|((schema, count), gap)| NativeHistogram {
4029                    schema,
4030                    reset_hint: GAUGE_RESET_HINT,
4031                    positive_spans: vec![
4032                        Span {
4033                            offset: 0,
4034                            length: 1,
4035                        },
4036                        Span {
4037                            offset: gap,
4038                            length: 1,
4039                        },
4040                    ],
4041                    ..sample_histogram(count, count, vec![count, 0.0])
4042                })
4043                .collect();
4044
4045            for (op, expected) in [
4046                (HistogramAggregate::Sum, 1.0),
4047                (HistogramAggregate::Avg, 0.2),
4048            ] {
4049                let (value, _) = histogram_eval::sum_or_avg(
4050                    op,
4051                    samples.iter().map(legacy_bridge::float_histogram),
4052                    range_last_rebin(&samples),
4053                )
4054                .unwrap();
4055                // Before the caller compacts the result, only the bucket with the correction survives.
4056                assert_eq!(
4057                    value.unwrap().positive,
4058                    [(0, expected)],
4059                    "{op:?} {schemas:?}"
4060                );
4061            }
4062        }
4063    }
4064
4065    #[test]
4066    fn sparse_range_average_copies_linearly_across_schema_changes() {
4067        use crate::histogram_eval::float_histogram::copies::take_cloned_buckets;
4068
4069        let check = |window: Vec<NativeHistogram>, expected| {
4070            let len = window.len();
4071            let input = histogram_range_input(window.into_iter().map(Some).collect());
4072            take_cloned_buckets();
4073            let avg = mixed_histogram_result(NativeHistogramAvgOverTime::scalar_udf(), input);
4074            let copied = take_cloned_buckets();
4075            assert_eq!(avg.map(|h| h.positive_buckets), expected);
4076            // A downscale can copy the whole prefix once. Repeating that copy would be quadratic.
4077            assert!(
4078                copied <= 8 * len,
4079                "{copied} buckets copied for {len} samples"
4080            );
4081        };
4082        let mut custom = NativeHistogram {
4083            schema: CUSTOM_BUCKETS_SCHEMA,
4084            custom_values: (1..32).map(f64::from).collect(),
4085            ..sample_histogram(1.0, 1.0, vec![0.0; 32])
4086        };
4087        custom.positive_buckets[0] = 1.0;
4088        let length = 256;
4089        for first_coarse in [1, length / 2, length - 1, length] {
4090            let mut samples: Vec<_> = (0..length)
4091                .map(|i| NativeHistogram {
4092                    schema: if i < first_coarse { 8 } else { 7 },
4093                    positive_spans: vec![
4094                        Span {
4095                            offset: 0,
4096                            length: 1,
4097                        },
4098                        Span {
4099                            offset: i + 1,
4100                            length: 1,
4101                        },
4102                    ],
4103                    ..sample_histogram(1.0, 1.0, vec![1.0, 0.0])
4104                })
4105                .collect();
4106            check(samples.clone(), Some(vec![1.0]));
4107            samples.push(custom.clone());
4108            check(samples, None);
4109        }
4110        check(
4111            vec![
4112                custom.clone(),
4113                custom,
4114                sample_histogram(1.0, 1.0, vec![1.0]),
4115            ],
4116            None,
4117        );
4118    }
4119
4120    #[test]
4121    fn range_sum_preserves_empty_buckets_when_reducing_the_accumulator() {
4122        for (prefix, expected) in [
4123            (vec![0.0, 0.0, 0.0, 1e16], 10_000_000_000_000_002.0),
4124            (vec![1e16], 10_000_000_000_000_004.0),
4125        ] {
4126            let mut first = sample_histogram(1e16, 1e16, prefix);
4127            first.schema = 2;
4128            first.positive_spans[0].offset = 1 - first.positive_spans[0].length;
4129            let one = NativeHistogram {
4130                schema: 2,
4131                ..sample_histogram(1.0, 1.0, vec![1.0])
4132            };
4133            let count = 1.0_f64.next_down();
4134            let last = sample_histogram(count, count, vec![count]);
4135            let mut window = vec![first, one.clone(), one, last];
4136            // Index 0 has a correction of 2. An earlier empty index in its new bucket changes
4137            // when that correction is added. Mirror both sides to exercise both layouts.
4138            for h in &mut window {
4139                h.negative_spans.clone_from(&h.positive_spans);
4140                h.negative_buckets.clone_from(&h.positive_buckets);
4141                h.count *= 2.0;
4142                h.sum = 0.0;
4143            }
4144            let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window);
4145            assert_eq!(sum.positive_buckets, [expected]);
4146            assert_eq!(sum.negative_buckets, [expected]);
4147        }
4148    }
4149
4150    #[test]
4151    fn widening_the_zero_bucket_discards_previous_empty_positions() {
4152        let mut fine = sample_histogram(1e16 + 2.0, 5.5e16, vec![1e16, 1.0, 1.0]);
4153        fine.schema = 2;
4154        fine.positive_spans[0].offset = 9;
4155        let count = 1.0_f64.next_down();
4156        let mut last = sample_histogram(count, 6.0 * count, vec![count]);
4157        last.positive_spans[0].offset = 3;
4158        // The second case widens indirectly: the incoming (1, 2] bucket straddles 1.5.
4159        let mut crossing = sample_histogram(1.0, 1.75, vec![1.0]);
4160        crossing.positive_spans[0].offset = 1;
4161        let direct = NativeHistogram {
4162            zero_threshold: 0.5,
4163            ..sample_histogram(0.0, 0.0, vec![])
4164        };
4165        for (threshold, wider) in [(0.0, direct), (1.5, crossing)] {
4166            let mut empty = sample_histogram(0.0, 0.0, vec![0.0]);
4167            empty.zero_threshold = threshold;
4168            empty.positive_spans[0].offset = 3;
4169            let window = vec![empty.clone(), empty, wider, fine.clone(), last.clone()];
4170            let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window);
4171            // All three fine indices map to index 3, which the widening removed from the layout.
4172            assert_eq!(sum.positive_buckets, [10_000_000_000_000_004.0]);
4173        }
4174    }
4175
4176    #[test]
4177    fn range_sum_preserves_an_empty_bucket_in_a_mixed_schema_window() {
4178        let total = 10_000_000_000_000_002.0;
4179        let mut fine = sample_histogram(total, 5.5e15, vec![1e16, 1.0, 1.0]);
4180        fine.schema = 2;
4181        // These three buckets all map to the explicit zero at index 0 of the first sample.
4182        fine.positive_spans[0].offset = -3;
4183        let empty = sample_histogram(0.0, 0.0, vec![0.0]);
4184        let count = 1.0_f64.next_down();
4185        let last = sample_histogram(count, 0.75 * count, vec![count]);
4186        // Consecutive fine samples still need reduction when the accumulator is coarse.
4187        let empty_fine = NativeHistogram {
4188            schema: 2,
4189            ..empty.clone()
4190        };
4191        let last_fine = NativeHistogram {
4192            schema: 2,
4193            ..last.clone()
4194        };
4195        for window in [
4196            vec![empty.clone(), fine.clone(), last],
4197            vec![empty, empty_fine, fine, last_fine],
4198        ] {
4199            let sum = run_histogram_range_udf(NativeHistogramSumOverTime::scalar_udf(), window);
4200            assert_eq!(sum.count, total);
4201            assert_eq!(sum.positive_buckets, vec![total]);
4202        }
4203    }
4204
4205    #[test]
4206    fn range_avg_preserves_a_cancelled_bucket_in_a_mixed_schema_window() {
4207        let gain = sample_histogram(1.0, 0.75, vec![1.0]);
4208        let loss = legacy_bridge::scale(&gain, -1.0);
4209        let mut fine = sample_histogram(
4210            10_000_000_000_000_009_i64 as f64,
4211            5.5e15,
4212            vec![1e16 + 4.0, 2.0, 1.0, 2.0],
4213        );
4214        fine.schema = 2;
4215        // All four fine buckets merge into the bucket that the two coarse samples cancelled.
4216        fine.positive_spans[0].offset = -3;
4217        let avg = run_histogram_range_udf(
4218            NativeHistogramAvgOverTime::scalar_udf(),
4219            vec![gain, loss, fine],
4220        );
4221        assert_eq!(avg.positive_buckets, vec![3_333_333_333_333_336.5]);
4222    }
4223
4224    #[test]
4225    fn range_fold_reports_layout_errors_and_custom_reconciliation() {
4226        let mut first = sample_histogram(2.0, 3.0, vec![1.0, 1.0]);
4227        first.schema = CUSTOM_BUCKETS_SCHEMA;
4228        first.custom_values = vec![1.0, 2.0];
4229        let mut second = first.clone();
4230        second.custom_values = vec![2.0];
4231        let mut invalid = first.clone();
4232        invalid.positive_spans = vec![
4233            Span {
4234                offset: 0,
4235                length: 1,
4236            },
4237            Span {
4238                offset: -1,
4239                length: 1,
4240            },
4241        ];
4242        let mut unsupported = sample_histogram(0.0, 0.0, vec![]);
4243        unsupported.schema = -5;
4244        let exponential = sample_histogram(1.0, 1.0, vec![1.0]);
4245
4246        let name = NativeHistogramSumOverTime::name();
4247        for (samples, expected_bounds, reconciled) in [
4248            (vec![first.clone(), second.clone()], Some(vec![2.0]), true),
4249            (
4250                vec![first.clone(), second.clone(), exponential.clone()],
4251                None,
4252                true,
4253            ),
4254            (
4255                vec![exponential, first.clone(), second.clone()],
4256                None,
4257                false,
4258            ),
4259            (
4260                vec![first.clone(), second.clone(), invalid.clone()],
4261                None,
4262                true,
4263            ),
4264            (vec![invalid.clone(), second.clone()], None, true),
4265            (vec![first, invalid, second], None, false),
4266            (
4267                vec![unsupported, sample_histogram(0.0, 0.0, vec![0.0])],
4268                None,
4269                false,
4270            ),
4271        ] {
4272            let collector = PromqlAnnotationCollector::default();
4273            let result = range_fold_histograms(
4274                samples,
4275                HistogramAggregate::Sum,
4276                name,
4277                &Some(collector.clone()),
4278            );
4279            assert_eq!(result.map(|h| h.custom_values), expected_bounds);
4280            assert_eq!(
4281                collected_infos(&collector).contains(&format!(
4282                    "{name}: reconciled native histograms with different custom buckets"
4283                )),
4284                reconciled,
4285            );
4286            assert_eq!(
4287                collected_warnings(&collector).contains(&format!(
4288                    "{name}: dropped native histogram range with incompatible schemas"
4289                )),
4290                expected_bounds.is_none(),
4291            );
4292        }
4293    }
4294
4295    #[test]
4296    fn histogram_averages_avoid_sum_overflow() {
4297        let large = sample_histogram(1.0e308, 1.0e308, vec![1.0e308]);
4298
4299        let range_average = run_histogram_range_udf(
4300            NativeHistogramAvgOverTime::scalar_udf(),
4301            vec![large.clone(), large.clone()],
4302        );
4303        assert_eq!(range_average.count, 1.0e308);
4304        assert_eq!(range_average.sum, 1.0e308);
4305        assert_eq!(range_average.positive_buckets, vec![1.0e308]);
4306
4307        let mut aggregate =
4308            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4309        aggregate.push_histogram(large.clone(), 1).unwrap();
4310        aggregate.push_histogram(large, 1).unwrap();
4311        let aggregate_average = evaluated_histogram(&mut aggregate);
4312        assert_eq!(aggregate_average.count, 1.0e308);
4313        assert_eq!(aggregate_average.sum, 1.0e308);
4314        assert_eq!(aggregate_average.positive_buckets, vec![1.0e308]);
4315    }
4316
4317    #[test]
4318    fn range_average_preserves_deferred_empty_buckets_when_it_overflows_before_a_downscale() {
4319        let sample = |schema, sum, offset, buckets: Vec<f64>| {
4320            let mut h = sample_histogram(2.0 * buckets.iter().sum::<f64>(), sum, buckets);
4321            h.schema = schema;
4322            h.positive_spans[0].offset = offset;
4323            h.negative_spans.clone_from(&h.positive_spans);
4324            h.negative_buckets.clone_from(&h.positive_buckets);
4325            h
4326        };
4327        let tiny = f64::from_bits(1);
4328        let mut first = sample(8, f64::MAX, -1, vec![0.0, 1e16, tiny]);
4329        first.negative_buckets.swap(0, 2);
4330        // At index -1 the positive zero is deferred on sample two. The negative bucket
4331        // underflows to zero when sample three overflows the sum and scales the running mean.
4332        let samples = vec![
4333            first,
4334            sample(8, 0.0, 0, vec![3.0]),
4335            sample(8, f64::MAX, 0, vec![3.0]),
4336            sample(7, 0.0, 0, vec![f64::EPSILON / 2.0]),
4337        ];
4338        let (reference, _) = histogram_eval::sum_or_avg(
4339            HistogramAggregate::Avg,
4340            samples.iter().map(legacy_bridge::float_histogram),
4341            None,
4342        )
4343        .unwrap();
4344        let mut reference = reference.unwrap();
4345        reference.compact();
4346
4347        let avg = run_histogram_range_udf(NativeHistogramAvgOverTime::scalar_udf(), samples);
4348        assert_eq!(avg, legacy_bridge::legacy_histogram(&reference));
4349        // Downscaling indices -1 and 0 folds the leading zero before the live bucket's correction.
4350        assert_eq!(avg.positive_buckets, [2_500_000_000_000_001.0]);
4351        assert_eq!(avg.negative_buckets, avg.positive_buckets);
4352    }
4353
4354    #[test]
4355    fn range_average_matches_prometheus_at_the_largest_finite_sum() {
4356        let mut sample = sample_histogram(1.0, f64::MAX, vec![1.0]);
4357        sample.schema = CUSTOM_BUCKETS_SCHEMA;
4358        sample.custom_values = vec![0.0];
4359        sample.positive_spans[0].offset = 1;
4360        // Prometheus v3.15.0 overflows when it adds the final correction at 110 samples.
4361        for (length, expected) in [(109, f64::MAX), (110, f64::INFINITY)] {
4362            let avg = run_histogram_range_udf(
4363                NativeHistogramAvgOverTime::scalar_udf(),
4364                vec![sample.clone(); length],
4365            );
4366            assert_eq!(avg.sum, expected);
4367        }
4368    }
4369
4370    #[test]
4371    fn range_average_switches_to_a_running_mean_for_an_infinite_custom_bound() {
4372        for (bound, expected) in [(0.0, 1.0 / 3.0), (f64::NEG_INFINITY, -0.16666666666666669)] {
4373            let samples = [1e16, 1.0, -1e16].map(|sum| NativeHistogram {
4374                schema: CUSTOM_BUCKETS_SCHEMA,
4375                custom_values: vec![bound],
4376                positive_spans: vec![Span {
4377                    offset: i32::from(sum > bound),
4378                    length: 1,
4379                }],
4380                ..sample_histogram(1.0, sum, vec![1.0])
4381            });
4382            let avg =
4383                run_histogram_range_udf(NativeHistogramAvgOverTime::scalar_udf(), samples.into());
4384            assert_eq!(avg.sum, expected);
4385        }
4386    }
4387
4388    #[test]
4389    fn range_sum_matches_prometheus_when_the_zero_bucket_widens_twice() {
4390        let mut sample = sample_histogram(10_000_000_000_000_005_i64 as f64, -6.0, vec![1.0]);
4391        sample.zero_count = 1e16;
4392        sample.negative_spans = vec![Span {
4393            offset: 1,
4394            length: 1,
4395        }];
4396        sample.negative_buckets = vec![4.0];
4397        let mut empty = sample_histogram(0.0, 0.0, vec![]);
4398        empty.zero_threshold = 1.5;
4399
4400        let sum = run_histogram_range_udf(
4401            NativeHistogramSumOverTime::scalar_udf(),
4402            vec![sample, empty],
4403        );
4404        assert_eq!(sum.zero_threshold, 2.0);
4405        assert!(sum.positive_buckets.is_empty() && sum.negative_buckets.is_empty());
4406        // Prometheus v3.15.0 carries the first pass's correction into the second pass.
4407        assert_eq!(sum.count, 10_000_000_000_000_004.0);
4408        assert_eq!(sum.zero_count, 10_000_000_000_000_006.0);
4409    }
4410
4411    #[test]
4412    fn histogram_average_partial_states_are_weighted() {
4413        let mut first =
4414            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4415        first
4416            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4417            .unwrap();
4418        first
4419            .push_histogram(sample_histogram(3.0, 3.0, vec![3.0]), 1)
4420            .unwrap();
4421        let first_state = first
4422            .state()
4423            .unwrap()
4424            .into_iter()
4425            .map(|value| value.to_array_of_size(1).unwrap())
4426            .collect::<Vec<_>>();
4427
4428        let mut second =
4429            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4430        second
4431            .push_histogram(sample_histogram(8.0, 8.0, vec![8.0]), 1)
4432            .unwrap();
4433        let second_state = second
4434            .state()
4435            .unwrap()
4436            .into_iter()
4437            .map(|value| value.to_array_of_size(1).unwrap())
4438            .collect::<Vec<_>>();
4439
4440        let mut merged =
4441            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4442        merged.merge_batch(&first_state).unwrap();
4443        merged.merge_batch(&second_state).unwrap();
4444        let average = evaluated_histogram(&mut merged);
4445        assert_eq!(average.count, 4.0);
4446        assert_eq!(average.sum, 4.0);
4447        assert_eq!(average.positive_buckets, vec![4.0]);
4448    }
4449
4450    #[test]
4451    fn histogram_average_rejects_sample_count_overflow() {
4452        let mut aggregate =
4453            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4454        aggregate
4455            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4456            .unwrap();
4457        aggregate.count = u64::MAX;
4458
4459        let error = aggregate
4460            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4461            .unwrap_err();
4462        assert!(error.to_string().contains("sample count overflow"));
4463    }
4464
4465    /// The legacy frame and the canonical fold answer the same thing, bit for bit.
4466    ///
4467    /// The same inputs are folded twice: once through the legacy accumulator, whose state frame is
4468    /// the Arrow partial a distributed aggregate hands over, and once through the kernel's own
4469    /// [`HistogramAccumulator`], whose `payload` is the canonical partial state. The frame declares
4470    /// one native histogram, an average's count and three Booleans, so what it can carry is the
4471    /// fold's *answer* -- `finished_histogram`, the running sum with its compensation folded in or
4472    /// the average's mean -- and that is what it is compared on. The count and the evidence are
4473    /// compared against the payload, which is where they come from, and a state boundary is then
4474    /// expected to keep the answer: merging an exported state into an empty accumulator answers
4475    /// what the accumulator that exported it answered.
4476    #[test]
4477    fn legacy_state_carries_the_canonical_histogram_fold() {
4478        for (case, inputs) in aggregate_agreement_cases() {
4479            let samples = inputs
4480                .iter()
4481                .map(|histogram| float_histogram(histogram).unwrap())
4482                .collect::<Vec<_>>();
4483            for kind in [
4484                NativeHistogramAggregateKind::Sum,
4485                NativeHistogramAggregateKind::Avg,
4486            ] {
4487                let op = match kind {
4488                    NativeHistogramAggregateKind::Sum => AggregateOp::Sum,
4489                    NativeHistogramAggregateKind::Avg => AggregateOp::Avg,
4490                };
4491                let mut legacy = NativeHistogramAggregateAccumulator::new(kind, None);
4492                for histogram in &inputs {
4493                    legacy.push_histogram(histogram.clone(), 1).unwrap();
4494                }
4495                let frame = legacy_state(&mut legacy);
4496                let fold = canonical_fold(op, &samples);
4497                let StatePayload::Histogram(payload) = fold.payload(op).unwrap() else {
4498                    panic!("{case}: the canonical fold exported a non-histogram payload");
4499                };
4500
4501                // The three Booleans of the frame are the payload's own evidence.
4502                assert_eq!(frame.dropped, payload.poisoned, "{case}: poisoned");
4503                assert_eq!(
4504                    frame.counter_reset_seen, payload.counter_reset_seen,
4505                    "{case}: counter reset seen"
4506                );
4507                assert_eq!(
4508                    frame.not_counter_reset_seen, payload.not_counter_reset_seen,
4509                    "{case}: not-counter-reset seen"
4510                );
4511                assert_eq!(
4512                    legacy.evidence.poisoned, payload.poisoned,
4513                    "{case}: poisoned evidence"
4514                );
4515                assert_eq!(
4516                    legacy.evidence.incompatible_layout, payload.incompatible_layout,
4517                    "{case}: incompatible layout"
4518                );
4519
4520                // The count the frame declares is the samples it folded, as a `UInt64` -- except
4521                // on a dropped position, whose count goes with its answer.
4522                if kind.needs_count() {
4523                    let folded = if frame.dropped {
4524                        0
4525                    } else {
4526                        inputs.len() as u64
4527                    };
4528                    assert_eq!(frame.count, Some(folded), "{case}: count");
4529                    assert_eq!(
4530                        frame.count.map(|count| count as f64),
4531                        Some(payload.count),
4532                        "{case}: payload count"
4533                    );
4534                } else {
4535                    assert_eq!(frame.count, None, "{case}: a sum declares no count");
4536                }
4537
4538                // The histogram component is the fold's answer, bit for bit.
4539                let answer = finished_histogram(op, &fold).unwrap();
4540                match (&frame.histogram, &answer) {
4541                    (Some(actual), Some(expected)) => assert_frame_carries(actual, expected, case),
4542                    (None, None) => {}
4543                    _ => panic!(
4544                        "{case}: the frame and the fold disagree on whether the point answers"
4545                    ),
4546                }
4547
4548                // A state boundary keeps that answer.
4549                let mut merged = NativeHistogramAggregateAccumulator::new(kind, None);
4550                merged.merge_batch(&state_arrays(&mut legacy)).unwrap();
4551                let merged = evaluated(&mut merged);
4552                let direct = evaluated(&mut legacy);
4553                match (merged, direct) {
4554                    (Some(merged), Some(direct)) => assert_frame_carries(
4555                        &merged,
4556                        &float_histogram(&direct).unwrap(),
4557                        &format!("{case}, merged"),
4558                    ),
4559                    (None, None) => {}
4560                    _ => panic!("{case}: a merged state answers where its source did not"),
4561                }
4562            }
4563        }
4564    }
4565
4566    /// The compensated sum's residual belongs to the state, not to one partition's fold.
4567    ///
4568    /// `1e16 + 1 - 1e16` answers `1` only because the Kahan compensation carries what the running sum
4569    /// lost. The legacy frame has no compensation component, so it carries the answer instead: a
4570    /// merge of the exported state answers `1` too, which a frame exporting the running sum could
4571    /// not do.
4572    ///
4573    /// The guarantee stops at samples already folded into one position. Splitting those same samples
4574    /// across two partitions loses the residual, because exporting folds the compensation back into
4575    /// a single `f64`: `[1e16, 1]` exports `1e16`, and merging it with `[-1e16]` answers `0`.
4576    #[test]
4577    fn legacy_state_keeps_the_compensated_sum() {
4578        let mut aggregate =
4579            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
4580        for histogram in [
4581            sample_histogram(1.0, 1.0e16, vec![1.0e16]),
4582            sample_histogram(1.0, 1.0, vec![1.0]),
4583            sample_histogram(1.0, -1.0e16, vec![-1.0e16]),
4584        ] {
4585            aggregate.push_histogram(histogram, 1).unwrap();
4586        }
4587        let direct = evaluated_histogram(&mut aggregate);
4588        assert_eq!(direct.count, 3.0);
4589        assert_eq!(direct.sum, 1.0);
4590        assert_eq!(direct.positive_buckets, vec![1.0]);
4591
4592        let state = state_arrays(&mut aggregate);
4593        let mut merged =
4594            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
4595        merged.merge_batch(&state).unwrap();
4596        let merged = evaluated_histogram(&mut merged);
4597        assert_eq!(merged.count, 3.0);
4598        assert_eq!(merged.sum, 1.0);
4599        assert_eq!(merged.positive_buckets, vec![1.0]);
4600    }
4601
4602    /// The inputs the two accumulators are compared on: two exponential resolutions, two custom
4603    /// layouts with different bounds, exponential meeting custom, and a compensated sum whose
4604    /// residual lives in the compensation alone.
4605    fn aggregate_agreement_cases() -> Vec<(&'static str, Vec<NativeHistogram>)> {
4606        let mut coarse = sample_histogram(2.0, 3.0, vec![1.0, 1.0]);
4607        coarse.schema = 2;
4608        coarse.reset_hint = NOT_COUNTER_RESET_HINT;
4609        let mut fine = sample_histogram(1.0, 1.0, vec![1.0]);
4610        fine.reset_hint = COUNTER_RESET_HINT;
4611
4612        let mut custom = sample_histogram(2.0, 3.0, vec![1.0, 1.0, 0.0]);
4613        custom.schema = CUSTOM_BUCKETS_SCHEMA;
4614        custom.custom_values = vec![1.0, 2.0, 3.0];
4615        let mut narrower = sample_histogram(2.0, 5.0, vec![1.0, 1.0]);
4616        narrower.schema = CUSTOM_BUCKETS_SCHEMA;
4617        narrower.custom_values = vec![2.0, 3.0];
4618
4619        let mut custom_only = sample_histogram(1.0, 1.0, vec![1.0]);
4620        custom_only.schema = CUSTOM_BUCKETS_SCHEMA;
4621        custom_only.custom_values = vec![1.0];
4622
4623        vec![
4624            (
4625                "two exponential resolutions",
4626                vec![fine, coarse.clone(), coarse],
4627            ),
4628            (
4629                "custom bounds reconciled",
4630                vec![custom, narrower.clone(), narrower],
4631            ),
4632            (
4633                "exponential meeting custom",
4634                vec![
4635                    sample_histogram(1.0, 1.0, vec![1.0]),
4636                    custom_only,
4637                    sample_histogram(1.0, 1.0, vec![1.0, 1.0]),
4638                ],
4639            ),
4640            (
4641                "compensated sum",
4642                vec![
4643                    sample_histogram(1.0, 1.0e16, vec![1.0e16]),
4644                    sample_histogram(1.0, 1.0, vec![1.0]),
4645                    sample_histogram(1.0, -1.0e16, vec![-1.0e16]),
4646                ],
4647            ),
4648        ]
4649    }
4650
4651    /// One case's inputs folded through the kernel's own accumulator, as `fold_histogram` folds
4652    /// them: reset evidence per sample, and a layout disagreement poisoning the position instead of
4653    /// failing it.
4654    fn canonical_fold(op: AggregateOp, samples: &[FloatHistogram]) -> HistogramAccumulator {
4655        let mut fold = HistogramAccumulator::from_sample(&samples[0]);
4656        for sample in samples {
4657            fold.evidence.counter_reset_seen |= sample.reset_hint == CounterResetHint::CounterReset;
4658            fold.evidence.not_counter_reset_seen |=
4659                sample.reset_hint == CounterResetHint::NotCounterReset;
4660        }
4661        for sample in &samples[1..] {
4662            if fold.evidence.poisoned {
4663                break;
4664            }
4665            if fold.uses_custom_buckets() != sample.uses_custom_buckets() {
4666                fold.poison();
4667                break;
4668            }
4669            match op {
4670                AggregateOp::Sum => fold.fold_sum(sample).unwrap(),
4671                AggregateOp::Avg => fold.fold_avg(sample).unwrap(),
4672                op => unreachable!("{op:?} does not fold a histogram payload"),
4673            }
4674        }
4675        fold
4676    }
4677
4678    #[test]
4679    fn presence_only_range_functions_preserve_null_semantics() {
4680        let first = sample_histogram(1.0, 1.0, vec![1.0]);
4681        let second = sample_histogram(2.0, 2.0, vec![2.0]);
4682        assert_eq!(
4683            run_float_range_udf(
4684                NativeHistogramCountOverTime::scalar_udf(),
4685                vec![Some(first.clone()), Some(second.clone())],
4686            ),
4687            Some(2.0)
4688        );
4689        assert_eq!(
4690            run_float_range_udf(
4691                NativeHistogramPresentOverTime::scalar_udf(),
4692                vec![Some(first.clone()), Some(second.clone())],
4693            ),
4694            Some(1.0)
4695        );
4696        assert_eq!(
4697            run_float_range_udf(
4698                NativeHistogramCountOverTime::scalar_udf(),
4699                vec![None, Some(second.clone())],
4700            ),
4701            None
4702        );
4703
4704        let result = run_udf(
4705            NativeHistogramLastOverTime::scalar_udf(),
4706            histogram_range_input(vec![None, Some(second)]),
4707            native_histogram_arrow_type(),
4708        );
4709        let result = extract_array(&result).unwrap();
4710        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
4711        assert!(result.is_null(0));
4712    }
4713
4714    #[test]
4715    fn resets_counts_histogram_flavor_transitions() {
4716        let mut counter = sample_histogram(1.0, 1.0, vec![1.0]);
4717        counter.reset_hint = NOT_COUNTER_RESET_HINT;
4718        let mut gauge = sample_histogram(2.0, 2.0, vec![2.0]);
4719        gauge.reset_hint = GAUGE_RESET_HINT;
4720        assert_eq!(
4721            run_float_range_udf(
4722                NativeHistogramResets::scalar_udf(),
4723                vec![Some(counter), Some(gauge)],
4724            ),
4725            Some(1.0)
4726        );
4727
4728        let mut gauge = sample_histogram(1.0, 1.0, vec![1.0]);
4729        gauge.reset_hint = GAUGE_RESET_HINT;
4730        let mut counter = sample_histogram(2.0, 2.0, vec![2.0]);
4731        counter.reset_hint = NOT_COUNTER_RESET_HINT;
4732        assert_eq!(
4733            run_float_range_udf(
4734                NativeHistogramResets::scalar_udf(),
4735                vec![Some(gauge), Some(counter)],
4736            ),
4737            Some(1.0)
4738        );
4739    }
4740
4741    #[test]
4742    fn wrong_flavor_functions_record_warnings() {
4743        let mut gauge_first = sample_histogram(1.0, 1.0, vec![1.0]);
4744        gauge_first.reset_hint = GAUGE_RESET_HINT;
4745        let mut gauge_last = sample_histogram(2.0, 2.0, vec![2.0]);
4746        gauge_last.reset_hint = GAUGE_RESET_HINT;
4747        let mut counter_first = sample_histogram(1.0, 1.0, vec![1.0]);
4748        counter_first.reset_hint = NOT_COUNTER_RESET_HINT;
4749        let mut counter_last = sample_histogram(2.0, 2.0, vec![2.0]);
4750        counter_last.reset_hint = NOT_COUNTER_RESET_HINT;
4751        let collector = PromqlAnnotationCollector::default();
4752
4753        run_extrapolated_histogram_udf(
4754            NativeHistogramRate::scalar_udf_with_collector(Some(collector.clone())),
4755            vec![gauge_first.clone(), gauge_last.clone()],
4756        );
4757        run_extrapolated_histogram_udf(
4758            NativeHistogramDelta::scalar_udf_with_collector(Some(collector.clone())),
4759            vec![counter_first.clone(), counter_last.clone()],
4760        );
4761        run_histogram_range_udf(
4762            NativeHistogramIRate::scalar_udf_with_collector(Some(collector.clone())),
4763            vec![gauge_first, gauge_last],
4764        );
4765        run_histogram_range_udf(
4766            NativeHistogramIDelta::scalar_udf_with_collector(Some(collector.clone())),
4767            vec![counter_first, counter_last],
4768        );
4769
4770        let warnings = collected_warnings(&collector);
4771        for expected in [
4772            format!(
4773                "{}: native histogram input should be a counter histogram",
4774                NativeHistogramRate::name()
4775            ),
4776            format!(
4777                "{}: native histogram input should be a gauge histogram",
4778                NativeHistogramDelta::name()
4779            ),
4780            format!(
4781                "{}: native histogram input should be a counter histogram",
4782                NativeHistogramIRate::name()
4783            ),
4784            format!(
4785                "{}: native histogram input should be a gauge histogram",
4786                NativeHistogramIDelta::name()
4787            ),
4788        ] {
4789            assert!(warnings.contains(&expected), "missing warning: {expected}");
4790        }
4791    }
4792
4793    #[test]
4794    fn subtraction_reports_a_reset_hint_contradiction_only_between_compatible_histograms() {
4795        // Prometheus reports a pair whose bucket layouts cannot be combined before it looks at the
4796        // reset hints, so the collision warning belongs to the pairs the operation can answer.
4797        for incompatible in [false, true] {
4798            let mut left = sample_histogram(2.0, 2.0, vec![2.0]);
4799            left.reset_hint = COUNTER_RESET_HINT;
4800            let mut right = sample_histogram(1.0, 1.0, vec![1.0]);
4801            right.reset_hint = NOT_COUNTER_RESET_HINT;
4802            if incompatible {
4803                right.schema = CUSTOM_BUCKETS_SCHEMA;
4804                right.custom_values = vec![1.0];
4805            }
4806            let collector = PromqlAnnotationCollector::default();
4807
4808            run_udf(
4809                NativeHistogramSub::scalar_udf_with_collector(Some(collector.clone())),
4810                vec![
4811                    ColumnarValue::Array(build_histogram_array(&[Some(left)])),
4812                    ColumnarValue::Array(build_histogram_array(&[Some(right)])),
4813                ],
4814                native_histogram_arrow_type(),
4815            );
4816
4817            let warnings = collected_warnings(&collector);
4818            let name = NativeHistogramSub::name();
4819            assert_eq!(
4820                warnings.contains(&format!(
4821                    "{name}: native histogram counter reset hints contradict"
4822                )),
4823                !incompatible,
4824                "{incompatible}: {warnings:?}"
4825            );
4826            if incompatible {
4827                assert!(
4828                    warnings.contains(&format!(
4829                        "{name}: dropped native histogram sample with incompatible schemas"
4830                    )),
4831                    "{warnings:?}"
4832                );
4833            }
4834        }
4835    }
4836
4837    #[test]
4838    fn counter_reset_hint_history_survives_folds_and_state_merges() {
4839        let mut reset = sample_histogram(1.0, 1.0, vec![1.0]);
4840        reset.reset_hint = COUNTER_RESET_HINT;
4841        let mut unknown = sample_histogram(2.0, 2.0, vec![2.0]);
4842        unknown.reset_hint = UNKNOWN_COUNTER_RESET_HINT;
4843        let mut not_reset = sample_histogram(3.0, 3.0, vec![3.0]);
4844        not_reset.reset_hint = NOT_COUNTER_RESET_HINT;
4845
4846        let range_collector = PromqlAnnotationCollector::default();
4847        assert!(
4848            range_fold_histograms(
4849                vec![reset.clone(), unknown.clone(), not_reset.clone()],
4850                HistogramAggregate::Sum,
4851                NativeHistogramSumOverTime::name(),
4852                &Some(range_collector.clone()),
4853            )
4854            .is_some()
4855        );
4856        assert!(collected_warnings(&range_collector).contains(&format!(
4857            "{}: native histogram counter reset hints contradict",
4858            NativeHistogramSumOverTime::name()
4859        )));
4860
4861        for kind in [
4862            NativeHistogramAggregateKind::Sum,
4863            NativeHistogramAggregateKind::Avg,
4864        ] {
4865            let mut first_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4866            first_partial.push_histogram(reset.clone(), 1).unwrap();
4867            first_partial.push_histogram(unknown.clone(), 1).unwrap();
4868            let first_states = first_partial
4869                .state()
4870                .unwrap()
4871                .into_iter()
4872                .map(|value| value.to_array_of_size(1).unwrap())
4873                .collect::<Vec<_>>();
4874
4875            let mut second_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4876            second_partial.push_histogram(not_reset.clone(), 1).unwrap();
4877            let second_states = second_partial
4878                .state()
4879                .unwrap()
4880                .into_iter()
4881                .map(|value| value.to_array_of_size(1).unwrap())
4882                .collect::<Vec<_>>();
4883
4884            let collector = PromqlAnnotationCollector::default();
4885            let mut merged =
4886                NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4887            merged.merge_batch(&first_states).unwrap();
4888            merged.merge_batch(&second_states).unwrap();
4889            assert!(collected_warnings(&collector).contains(&format!(
4890                "{}: native histogram counter reset hints contradict",
4891                kind.name()
4892            )));
4893        }
4894    }
4895
4896    #[test]
4897    fn incompatible_aggregates_do_not_hide_reset_hint_contradictions() {
4898        let mut reset = sample_histogram(1.0, 1.0, vec![1.0]);
4899        reset.reset_hint = COUNTER_RESET_HINT;
4900        let mut incompatible_reset = sample_histogram(2.0, 2.0, vec![2.0]);
4901        incompatible_reset.schema = CUSTOM_BUCKETS_SCHEMA;
4902        incompatible_reset.custom_values = vec![1.0];
4903        incompatible_reset.reset_hint = COUNTER_RESET_HINT;
4904        let mut not_reset = sample_histogram(3.0, 3.0, vec![3.0]);
4905        not_reset.reset_hint = NOT_COUNTER_RESET_HINT;
4906
4907        for kind in [
4908            NativeHistogramAggregateKind::Sum,
4909            NativeHistogramAggregateKind::Avg,
4910        ] {
4911            for histograms in [
4912                [reset.clone(), incompatible_reset.clone(), not_reset.clone()],
4913                [reset.clone(), not_reset.clone(), incompatible_reset.clone()],
4914            ] {
4915                let collector = PromqlAnnotationCollector::default();
4916                let mut aggregate =
4917                    NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4918                for histogram in histograms {
4919                    aggregate.push_histogram(histogram, 1).unwrap();
4920                }
4921
4922                assert!(aggregate.evidence.poisoned);
4923                let warnings = collected_warnings(&collector);
4924                assert!(warnings.contains(&format!(
4925                    "{}: dropped native histogram aggregate with incompatible schemas",
4926                    kind.name()
4927                )));
4928                assert!(warnings.contains(&format!(
4929                    "{}: native histogram counter reset hints contradict",
4930                    kind.name()
4931                )));
4932            }
4933
4934            let mut dropped_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4935            dropped_partial.push_histogram(reset.clone(), 1).unwrap();
4936            dropped_partial
4937                .push_histogram(incompatible_reset.clone(), 1)
4938                .unwrap();
4939            let dropped_states = dropped_partial
4940                .state()
4941                .unwrap()
4942                .into_iter()
4943                .map(|value| value.to_array_of_size(1).unwrap())
4944                .collect::<Vec<_>>();
4945
4946            let mut opposing_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4947            opposing_partial
4948                .push_histogram(not_reset.clone(), 1)
4949                .unwrap();
4950            let opposing_states = opposing_partial
4951                .state()
4952                .unwrap()
4953                .into_iter()
4954                .map(|value| value.to_array_of_size(1).unwrap())
4955                .collect::<Vec<_>>();
4956
4957            for (first, second) in [
4958                (&dropped_states, &opposing_states),
4959                (&opposing_states, &dropped_states),
4960            ] {
4961                let collector = PromqlAnnotationCollector::default();
4962                let mut merged =
4963                    NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4964                merged.merge_batch(first).unwrap();
4965                merged.merge_batch(second).unwrap();
4966
4967                assert!(merged.evidence.poisoned);
4968                assert!(collected_warnings(&collector).contains(&format!(
4969                    "{}: native histogram counter reset hints contradict",
4970                    kind.name()
4971                )));
4972            }
4973        }
4974
4975        for (kind, name) in [
4976            (HistogramAggregate::Sum, NativeHistogramSumOverTime::name()),
4977            (HistogramAggregate::Avg, NativeHistogramAvgOverTime::name()),
4978        ] {
4979            let collector = PromqlAnnotationCollector::default();
4980            assert!(
4981                range_fold_histograms(
4982                    vec![reset.clone(), incompatible_reset.clone(), not_reset.clone()],
4983                    kind,
4984                    name,
4985                    &Some(collector.clone()),
4986                )
4987                .is_none()
4988            );
4989            let warnings = collected_warnings(&collector);
4990            assert!(warnings.contains(&format!(
4991                "{name}: dropped native histogram range with incompatible schemas"
4992            )));
4993            assert!(warnings.contains(&format!(
4994                "{name}: native histogram counter reset hints contradict"
4995            )));
4996        }
4997    }
4998
4999    #[test]
5000    fn histogram_aggregate_accumulator_accounts_for_heap_allocations() {
5001        let histogram = sample_histogram(3.0, 3.0, vec![1.0, 2.0]);
5002        let sample = float_histogram(&histogram).unwrap();
5003        let mut accumulator =
5004            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
5005        let empty_size = accumulator.size();
5006
5007        accumulator.push_histogram(histogram, 1).unwrap();
5008
5009        // The fold keeps the sample's buckets and a compensation carrying the same layout, so at
5010        // least the sample's own heap is counted beyond the accumulator struct that holds it.
5011        assert!(sample.heap_bytes() > 0);
5012        assert!(accumulator.size() >= empty_size + sample.heap_bytes());
5013    }
5014
5015    #[test]
5016    fn absent_over_time_handles_histogram_ranges() {
5017        let values = vec![Some(sample_histogram(1.0, 1.0, vec![1.0]))];
5018        let timestamps = Arc::new(TimestampMillisecondArray::from_iter([Some(1000)]));
5019        let histograms = build_histogram_array(&values);
5020        let ranges = [(0, 1), (0, 0)];
5021        let ts_range = RangeArray::from_ranges(timestamps, ranges).unwrap();
5022        let value_range = RangeArray::from_ranges(histograms, ranges).unwrap();
5023
5024        let result = run_udf(
5025            NativeHistogramAbsentOverTime::scalar_udf(),
5026            vec![
5027                ColumnarValue::Array(Arc::new(ts_range.into_dict())),
5028                ColumnarValue::Array(Arc::new(value_range.into_dict())),
5029            ],
5030            DataType::Float64,
5031        );
5032        let result = extract_array(&result).unwrap();
5033        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
5034
5035        assert!(result.is_null(0));
5036        assert_eq!(result.value(1), 1.0);
5037    }
5038
5039    #[test]
5040    fn delta_requires_exact_layout() {
5041        let first = sample_histogram(2.0, 3.0, vec![1.0, 1.0]);
5042        let last = sample_histogram(5.0, 8.0, vec![2.0, 3.0]);
5043        let delta = histogram_delta(&[first, last], &[0, 1], false).unwrap();
5044        assert_eq!(delta.count, 3.0);
5045        assert_eq!(delta.sum, 5.0);
5046        assert_eq!(delta.reset_hint, GAUGE_RESET_HINT);
5047        assert_eq!(delta.positive_buckets, vec![1.0, 2.0]);
5048    }
5049
5050    #[test]
5051    fn reset_hint_shortcuts_detection() {
5052        let previous = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
5053
5054        let mut current = sample_histogram(7.0, 12.0, vec![3.0, 4.0]);
5055        current.reset_hint = COUNTER_RESET_HINT;
5056        assert!(current.detect_reset(&previous));
5057
5058        let mut current = sample_histogram(5.0, 8.0, vec![1.0, 4.0]);
5059        current.reset_hint = NOT_COUNTER_RESET_HINT;
5060        assert!(!current.detect_reset(&previous));
5061    }
5062
5063    #[test]
5064    fn start_timestamp_detects_counter_reset() {
5065        let first = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
5066        let mut last = sample_histogram(7.0, 12.0, vec![3.0, 4.0]);
5067        last.start_timestamp = Some(1500);
5068
5069        let delta = histogram_delta(&[first.clone(), last.clone()], &[1000, 2000], true).unwrap();
5070        assert_eq!(delta.count, 7.0);
5071        assert_eq!(delta.sum, 12.0);
5072
5073        let idelta = idelta_value(&[first, last], true, 1000, 2000, 1.0).unwrap();
5074        assert_eq!(idelta.count, 7.0);
5075        assert_eq!(idelta.sum, 12.0);
5076    }
5077
5078    /// Same samples as the native route's `equal_histogram_start_timestamps_are_not_a_reset`:
5079    /// both routes must agree that a shared start timestamp is no reset, and that a bucket drop
5080    /// under that start still is one.
5081    #[test]
5082    fn equal_start_timestamps_are_not_a_reset() {
5083        let mut earlier = sample_histogram(2.0, 2.0, vec![1.0, 1.0]);
5084        earlier.start_timestamp = Some(1500);
5085        let mut dropped = sample_histogram(1.0, 1.0, vec![1.0]);
5086        dropped.start_timestamp = Some(1500);
5087        for (later, expected) in [(earlier.clone(), 0.0), (dropped, 1.0)] {
5088            assert_eq!(
5089                run_float_range_udf(
5090                    NativeHistogramResets::scalar_udf(),
5091                    vec![Some(earlier.clone()), Some(later)],
5092                ),
5093                Some(expected)
5094            );
5095        }
5096    }
5097
5098    #[test]
5099    fn extrapolated_rate_uses_start_timestamp_synthetic_zero() {
5100        let mut single = sample_histogram(1.0, 1.0, vec![1.0]);
5101        single.start_timestamp = Some(1_000);
5102
5103        let rate = extrapolated_histogram_result(
5104            NativeHistogramRate::scalar_udf(),
5105            vec![2_000],
5106            vec![single.clone()],
5107            3_000,
5108            3_000,
5109        )
5110        .unwrap();
5111        assert_eq!(rate.count, 1.0 / 3.0);
5112        assert_eq!(rate.sum, 1.0 / 3.0);
5113
5114        let increase = extrapolated_histogram_result(
5115            NativeHistogramIncrease::scalar_udf(),
5116            vec![2_000],
5117            vec![single],
5118            3_000,
5119            3_000,
5120        )
5121        .unwrap();
5122        assert_eq!(increase.count, 1.0);
5123        assert_eq!(increase.sum, 1.0);
5124
5125        let mut first = sample_histogram(2.0, 2.0, vec![2.0]);
5126        first.start_timestamp = Some(1_000);
5127        let last = sample_histogram(4.0, 4.0, vec![4.0]);
5128        let increase = extrapolated_histogram_result(
5129            NativeHistogramIncrease::scalar_udf(),
5130            vec![2_000, 3_000],
5131            vec![first, last],
5132            3_000,
5133            3_000,
5134        )
5135        .unwrap();
5136        assert_eq!(increase.count, 4.0);
5137        assert_eq!(increase.sum, 4.0);
5138    }
5139
5140    /// The raw range functions report a derived difference or quotient, so none of them keeps the
5141    /// start timestamp of the samples it read: the field names the start of the window one sample
5142    /// belongs to, and a result that spans several samples has no single such window.
5143    #[test]
5144    fn raw_range_functions_clear_the_start_timestamp() {
5145        let mut first = sample_histogram(2.0, 2.0, vec![2.0]);
5146        first.start_timestamp = Some(1_000);
5147        let mut last = sample_histogram(4.0, 4.0, vec![4.0]);
5148        last.start_timestamp = Some(2_000);
5149
5150        for udf in [
5151            NativeHistogramRate::scalar_udf(),
5152            NativeHistogramIncrease::scalar_udf(),
5153            NativeHistogramDelta::scalar_udf(),
5154        ] {
5155            let name = udf.name().to_string();
5156            let result = run_extrapolated_histogram_udf(udf, vec![first.clone(), last.clone()]);
5157            assert_eq!(
5158                result.start_timestamp, None,
5159                "{name}: the range functions derive a value of their own"
5160            );
5161        }
5162        for udf in [
5163            NativeHistogramIDelta::scalar_udf(),
5164            NativeHistogramIRate::scalar_udf(),
5165        ] {
5166            let name = udf.name().to_string();
5167            let result = run_histogram_range_udf(udf, vec![first.clone(), last.clone()]);
5168            assert_eq!(
5169                result.start_timestamp, None,
5170                "{name}: the range functions derive a value of their own"
5171            );
5172        }
5173    }
5174
5175    #[test]
5176    fn extrapolated_rate_requires_strictly_in_range_start_timestamp() {
5177        for (start_timestamp, range_end, range_length) in [
5178            (0, 3_000, 3_000),
5179            (500, 3_000, 2_000),
5180            (1_000, 3_000, 2_000),
5181            (2_000, 3_000, 3_000),
5182            (2_500, 3_000, 3_000),
5183        ] {
5184            let mut sample = sample_histogram(1.0, 1.0, vec![1.0]);
5185            sample.start_timestamp = Some(start_timestamp);
5186            assert!(
5187                extrapolated_histogram_result(
5188                    NativeHistogramRate::scalar_udf(),
5189                    vec![2_000],
5190                    vec![sample],
5191                    range_end,
5192                    range_length,
5193                )
5194                .is_none(),
5195                "start_timestamp={start_timestamp}"
5196            );
5197        }
5198
5199        let mut gauge = sample_histogram(1.0, 1.0, vec![1.0]);
5200        gauge.start_timestamp = Some(1_000);
5201        gauge.reset_hint = GAUGE_RESET_HINT;
5202        assert!(
5203            extrapolated_histogram_result(
5204                NativeHistogramDelta::scalar_udf(),
5205                vec![2_000],
5206                vec![gauge],
5207                3_000,
5208                3_000,
5209            )
5210            .is_none()
5211        );
5212    }
5213
5214    #[test]
5215    fn first_reset_ignores_incompatible_pre_reset_layout() {
5216        let first = sample_histogram(10.0, 10.0, vec![10.0]);
5217        let second = NativeHistogram {
5218            schema: CUSTOM_BUCKETS_SCHEMA,
5219            zero_threshold: 0.0,
5220            sum: 2.0,
5221            reset_hint: COUNTER_RESET_HINT,
5222            start_timestamp: None,
5223            custom_values: vec![1.0],
5224            positive_spans: vec![Span {
5225                offset: 0,
5226                length: 1,
5227            }],
5228            negative_spans: Vec::new(),
5229            count: 2.0,
5230            zero_count: 0.0,
5231            positive_buckets: vec![2.0],
5232            negative_buckets: Vec::new(),
5233        };
5234
5235        let delta = histogram_delta(&[first, second], &[1_000, 2_000], true).unwrap();
5236        assert_eq!(delta.schema, CUSTOM_BUCKETS_SCHEMA);
5237        assert_eq!(delta.count, 2.0);
5238        assert_eq!(delta.sum, 2.0);
5239        assert_eq!(delta.positive_buckets, vec![2.0]);
5240    }
5241
5242    #[test]
5243    fn counter_delta_handles_reset_segment_boundaries() {
5244        let first = sample_histogram(5.0, 5.0, vec![5.0]);
5245        let second = sample_histogram(7.0, 7.0, vec![7.0]);
5246        let mut reset = sample_histogram(2.0, 2.0, vec![2.0]);
5247        reset.reset_hint = COUNTER_RESET_HINT;
5248        let last = sample_histogram(4.0, 4.0, vec![4.0]);
5249
5250        let delta = histogram_delta(
5251            &[first, second, reset, last],
5252            &[1_000, 2_000, 3_000, 4_000],
5253            true,
5254        )
5255        .unwrap();
5256        assert_eq!(delta.count, 6.0);
5257        assert_eq!(delta.sum, 6.0);
5258        assert_eq!(delta.positive_buckets, vec![6.0]);
5259    }
5260}