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::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
1205fn weighted_histogram_mean(
1206    left: NativeHistogram,
1207    left_count: u64,
1208    right: NativeHistogram,
1209    right_count: u64,
1210    total_count: u64,
1211) -> Option<NativeHistogram> {
1212    let total_count = total_count as f64;
1213    legacy_bridge::add(
1214        &legacy_bridge::scale(&left, left_count as f64 / total_count),
1215        &legacy_bridge::scale(&right, right_count as f64 / total_count),
1216    )
1217}
1218
1219fn range_fold_histograms(
1220    samples: Vec<NativeHistogram>,
1221    kind: NativeHistogramAggregateKind,
1222    name: &'static str,
1223    collector: &Option<PromqlAnnotationCollector>,
1224) -> Option<NativeHistogram> {
1225    if samples
1226        .iter()
1227        .any(|histogram| histogram.reset_hint == COUNTER_RESET_HINT)
1228        && samples
1229            .iter()
1230            .any(|histogram| histogram.reset_hint == NOT_COUNTER_RESET_HINT)
1231    {
1232        record_counter_reset_contradiction_warning(collector, name);
1233    }
1234
1235    let mut value = None;
1236    let mut count = 0u64;
1237    for histogram in samples {
1238        value = match value {
1239            Some(value) => {
1240                record_custom_reconciliation(collector, name, &value, &histogram);
1241                let next_count = count.checked_add(1)?;
1242                let combined = match kind {
1243                    NativeHistogramAggregateKind::Sum => legacy_bridge::add(&value, &histogram),
1244                    NativeHistogramAggregateKind::Avg => {
1245                        weighted_histogram_mean(value, count, histogram, 1, next_count)
1246                    }
1247                };
1248                match combined {
1249                    Some(value) => Some(value),
1250                    None => {
1251                        record_warning(
1252                            collector,
1253                            format!(
1254                                "{name}: dropped native histogram range with incompatible schemas"
1255                            ),
1256                        );
1257                        return None;
1258                    }
1259                }
1260            }
1261            None => Some(histogram),
1262        };
1263        count = count.checked_add(1)?;
1264    }
1265    value
1266}
1267
1268#[derive(Debug, Clone, Copy)]
1269enum NativeHistogramRangeHistogramKind {
1270    Sum,
1271    Avg,
1272    Last,
1273}
1274
1275#[derive(Debug, Clone, Copy)]
1276enum NativeHistogramRangeFloatKind {
1277    Absent,
1278    Count,
1279    Present,
1280    Changes,
1281    Resets,
1282}
1283
1284fn collect_window_histograms(
1285    histograms: &StructArray,
1286    offset: usize,
1287    length: usize,
1288) -> DfResult<Option<Vec<NativeHistogram>>> {
1289    let mut samples = Vec::with_capacity(length);
1290    for row in offset..offset + length {
1291        let Some(histogram) = read_histogram(histograms, row)? else {
1292            return Ok(None);
1293        };
1294        samples.push(histogram);
1295    }
1296    Ok(Some(samples))
1297}
1298
1299fn native_histogram_range_histogram(
1300    input: &[ColumnarValue],
1301    kind: NativeHistogramRangeHistogramKind,
1302    func_name: &'static str,
1303    collector: Option<PromqlAnnotationCollector>,
1304) -> DfResult<ColumnarValue> {
1305    if input.len() != 2 {
1306        return Err(DataFusionError::Plan(format!(
1307            "{func_name} function should have 2 inputs"
1308        )));
1309    }
1310
1311    let ts_range = extract_range_dict(
1312        &input[0],
1313        func_name,
1314        "timestamp range vector",
1315        &DataType::Timestamp(TimeUnit::Millisecond, None),
1316    )?;
1317    let value_range = extract_range_dict(
1318        &input[1],
1319        func_name,
1320        "value range vector",
1321        &native_histogram_arrow_type(),
1322    )?;
1323    if ts_range.keys().values() != value_range.keys().values() {
1324        return Err(DataFusionError::Execution(format!(
1325            "{func_name}: timestamp and value ranges should have the same window layout"
1326        )));
1327    }
1328
1329    let histograms = value_range
1330        .values()
1331        .as_any()
1332        .downcast_ref::<StructArray>()
1333        .expect("validated native histogram range");
1334    let mut result = Vec::with_capacity(value_range.keys().len());
1335    for key in value_range.keys().values() {
1336        let (offset, length) = unpack(*key);
1337        let offset = offset as usize;
1338        let length = length as usize;
1339        if length == 0 {
1340            result.push(None);
1341            continue;
1342        }
1343        if matches!(kind, NativeHistogramRangeHistogramKind::Last) {
1344            let histogram = if (offset..offset + length).any(|row| histograms.is_null(row)) {
1345                None
1346            } else {
1347                read_histogram(histograms, offset + length - 1)?
1348            };
1349            result.push(histogram);
1350            continue;
1351        }
1352        let Some(samples) = collect_window_histograms(histograms, offset, length)? else {
1353            result.push(None);
1354            continue;
1355        };
1356        let histogram = match kind {
1357            NativeHistogramRangeHistogramKind::Sum => range_fold_histograms(
1358                samples,
1359                NativeHistogramAggregateKind::Sum,
1360                func_name,
1361                &collector,
1362            ),
1363            NativeHistogramRangeHistogramKind::Avg => range_fold_histograms(
1364                samples,
1365                NativeHistogramAggregateKind::Avg,
1366                func_name,
1367                &collector,
1368            ),
1369            NativeHistogramRangeHistogramKind::Last => samples.last().cloned(),
1370        };
1371        result.push(histogram);
1372    }
1373
1374    Ok(ColumnarValue::Array(build_histogram_array(&result)))
1375}
1376
1377fn native_histogram_range_float(
1378    input: &[ColumnarValue],
1379    kind: NativeHistogramRangeFloatKind,
1380    func_name: &'static str,
1381) -> DfResult<ColumnarValue> {
1382    if input.len() != 2 {
1383        return Err(DataFusionError::Plan(format!(
1384            "{func_name} function should have 2 inputs"
1385        )));
1386    }
1387
1388    let ts_range = extract_range_dict(
1389        &input[0],
1390        func_name,
1391        "timestamp range vector",
1392        &DataType::Timestamp(TimeUnit::Millisecond, None),
1393    )?;
1394    let value_range = extract_range_dict(
1395        &input[1],
1396        func_name,
1397        "value range vector",
1398        &native_histogram_arrow_type(),
1399    )?;
1400    if ts_range.keys().values() != value_range.keys().values() {
1401        return Err(DataFusionError::Execution(format!(
1402            "{func_name}: timestamp and value ranges should have the same window layout"
1403        )));
1404    }
1405
1406    let timestamps = ts_range
1407        .values()
1408        .as_any()
1409        .downcast_ref::<TimestampMillisecondArray>()
1410        .expect("validated timestamp range")
1411        .values();
1412    let histograms = value_range
1413        .values()
1414        .as_any()
1415        .downcast_ref::<StructArray>()
1416        .expect("validated native histogram range");
1417    let mut result = Float64Builder::with_capacity(value_range.keys().len());
1418    for key in value_range.keys().values() {
1419        let (offset, length) = unpack(*key);
1420        let offset = offset as usize;
1421        let length = length as usize;
1422        if length == 0 {
1423            match kind {
1424                NativeHistogramRangeFloatKind::Absent => result.append_value(1.0),
1425                _ => result.append_null(),
1426            }
1427            continue;
1428        }
1429        if matches!(kind, NativeHistogramRangeFloatKind::Absent) {
1430            result.append_null();
1431            continue;
1432        }
1433        if matches!(
1434            kind,
1435            NativeHistogramRangeFloatKind::Count | NativeHistogramRangeFloatKind::Present
1436        ) {
1437            if (offset..offset + length).any(|row| histograms.is_null(row)) {
1438                result.append_null();
1439            } else if matches!(kind, NativeHistogramRangeFloatKind::Count) {
1440                result.append_value(length as f64);
1441            } else {
1442                result.append_value(1.0);
1443            }
1444            continue;
1445        }
1446        let Some(samples) = collect_window_histograms(histograms, offset, length)? else {
1447            result.append_null();
1448            continue;
1449        };
1450        let value = match kind {
1451            NativeHistogramRangeFloatKind::Absent => {
1452                result.append_null();
1453                continue;
1454            }
1455            NativeHistogramRangeFloatKind::Count => length as f64,
1456            NativeHistogramRangeFloatKind::Present => 1.0,
1457            NativeHistogramRangeFloatKind::Changes => samples
1458                .windows(2)
1459                .filter(|pair| !pair[0].promql_eq(&pair[1]))
1460                .count() as f64,
1461            NativeHistogramRangeFloatKind::Resets => samples
1462                .windows(2)
1463                .zip(timestamps[offset..offset + length].windows(2))
1464                .filter(|(pair, ts_pair)| {
1465                    (pair[0].reset_hint == GAUGE_RESET_HINT)
1466                        != (pair[1].reset_hint == GAUGE_RESET_HINT)
1467                        || pair[1].detect_counter_reset(&pair[0], ts_pair[0], ts_pair[1])
1468                })
1469                .count() as f64,
1470        };
1471        result.append_value(value);
1472    }
1473
1474    Ok(ColumnarValue::Array(Arc::new(result.finish())))
1475}
1476
1477fn create_native_range_histogram_udf(
1478    name: &'static str,
1479    kind: NativeHistogramRangeHistogramKind,
1480    collector: Option<PromqlAnnotationCollector>,
1481) -> ScalarUDF {
1482    create_udf(
1483        name,
1484        vec![
1485            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
1486            RangeArray::convert_data_type(native_histogram_arrow_type()),
1487        ],
1488        native_histogram_arrow_type(),
1489        Volatility::Volatile,
1490        Arc::new(move |input: &[ColumnarValue]| {
1491            native_histogram_range_histogram(input, kind, name, collector.clone())
1492        }) as _,
1493    )
1494}
1495
1496fn create_native_range_float_udf(
1497    name: &'static str,
1498    kind: NativeHistogramRangeFloatKind,
1499) -> ScalarUDF {
1500    create_udf(
1501        name,
1502        vec![
1503            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
1504            RangeArray::convert_data_type(native_histogram_arrow_type()),
1505        ],
1506        DataType::Float64,
1507        Volatility::Volatile,
1508        Arc::new(move |input: &[ColumnarValue]| native_histogram_range_float(input, kind, name))
1509            as _,
1510    )
1511}
1512
1513pub struct NativeHistogramSumOverTime;
1514pub struct NativeHistogramAvgOverTime;
1515pub struct NativeHistogramAbsentOverTime;
1516pub struct NativeHistogramCountOverTime;
1517pub struct NativeHistogramLastOverTime;
1518pub struct NativeHistogramPresentOverTime;
1519pub struct NativeHistogramChanges;
1520pub struct NativeHistogramResets;
1521
1522impl NativeHistogramSumOverTime {
1523    pub const fn name() -> &'static str {
1524        "prom_native_histogram_sum_over_time"
1525    }
1526
1527    pub fn scalar_udf() -> ScalarUDF {
1528        Self::scalar_udf_with_collector(None)
1529    }
1530
1531    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1532        create_native_range_histogram_udf(
1533            Self::name(),
1534            NativeHistogramRangeHistogramKind::Sum,
1535            collector,
1536        )
1537    }
1538}
1539
1540impl NativeHistogramAvgOverTime {
1541    pub const fn name() -> &'static str {
1542        "prom_native_histogram_avg_over_time"
1543    }
1544
1545    pub fn scalar_udf() -> ScalarUDF {
1546        Self::scalar_udf_with_collector(None)
1547    }
1548
1549    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1550        create_native_range_histogram_udf(
1551            Self::name(),
1552            NativeHistogramRangeHistogramKind::Avg,
1553            collector,
1554        )
1555    }
1556}
1557
1558impl NativeHistogramAbsentOverTime {
1559    pub const fn name() -> &'static str {
1560        "prom_native_histogram_absent_over_time"
1561    }
1562
1563    pub fn scalar_udf() -> ScalarUDF {
1564        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Absent)
1565    }
1566}
1567
1568impl NativeHistogramCountOverTime {
1569    pub const fn name() -> &'static str {
1570        "prom_native_histogram_count_over_time"
1571    }
1572
1573    pub fn scalar_udf() -> ScalarUDF {
1574        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Count)
1575    }
1576}
1577
1578impl NativeHistogramLastOverTime {
1579    pub const fn name() -> &'static str {
1580        "prom_native_histogram_last_over_time"
1581    }
1582
1583    pub fn scalar_udf() -> ScalarUDF {
1584        create_native_range_histogram_udf(
1585            Self::name(),
1586            NativeHistogramRangeHistogramKind::Last,
1587            None,
1588        )
1589    }
1590}
1591
1592impl NativeHistogramPresentOverTime {
1593    pub const fn name() -> &'static str {
1594        "prom_native_histogram_present_over_time"
1595    }
1596
1597    pub fn scalar_udf() -> ScalarUDF {
1598        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Present)
1599    }
1600}
1601
1602impl NativeHistogramChanges {
1603    pub const fn name() -> &'static str {
1604        "prom_native_histogram_changes"
1605    }
1606
1607    pub fn scalar_udf() -> ScalarUDF {
1608        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Changes)
1609    }
1610}
1611
1612impl NativeHistogramResets {
1613    pub const fn name() -> &'static str {
1614        "prom_native_histogram_resets"
1615    }
1616
1617    pub fn scalar_udf() -> ScalarUDF {
1618        create_native_range_float_udf(Self::name(), NativeHistogramRangeFloatKind::Resets)
1619    }
1620}
1621
1622/// Coordinated float/native-histogram range evaluation.
1623///
1624/// The function name is passed as the first scalar argument so these two UDF names are enough for
1625/// distributed plan decoding. The remaining leading arguments are timestamp, float, and histogram
1626/// ranges, followed by the ordinary function arguments.
1627pub struct MixedRange;
1628
1629impl MixedRange {
1630    const fn float_name() -> &'static str {
1631        "prom_mixed_range_float"
1632    }
1633
1634    const fn histogram_name() -> &'static str {
1635        "prom_mixed_range_histogram"
1636    }
1637
1638    pub fn float_udf(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1639        ScalarUDF::new_from_impl(MixedRangeUdf::new(MixedRangeOutput::Float, collector))
1640    }
1641
1642    pub fn histogram_udf(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
1643        ScalarUDF::new_from_impl(MixedRangeUdf::new(MixedRangeOutput::Histogram, collector))
1644    }
1645}
1646
1647#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1648enum MixedRangeOutput {
1649    Float,
1650    Histogram,
1651}
1652
1653impl MixedRangeOutput {
1654    fn name(self) -> &'static str {
1655        match self {
1656            Self::Float => MixedRange::float_name(),
1657            Self::Histogram => MixedRange::histogram_name(),
1658        }
1659    }
1660
1661    fn data_type(self) -> DataType {
1662        match self {
1663            Self::Float => DataType::Float64,
1664            Self::Histogram => native_histogram_arrow_type(),
1665        }
1666    }
1667}
1668
1669#[derive(Debug, Clone)]
1670struct MixedRangeUdf {
1671    output: MixedRangeOutput,
1672    signature: Signature,
1673    collector: Option<PromqlAnnotationCollector>,
1674}
1675
1676impl MixedRangeUdf {
1677    fn new(output: MixedRangeOutput, collector: Option<PromqlAnnotationCollector>) -> Self {
1678        Self {
1679            output,
1680            signature: Signature::variadic_any(Volatility::Volatile),
1681            collector,
1682        }
1683    }
1684}
1685
1686impl PartialEq for MixedRangeUdf {
1687    fn eq(&self, other: &Self) -> bool {
1688        self.output == other.output
1689    }
1690}
1691
1692impl Eq for MixedRangeUdf {}
1693
1694impl Hash for MixedRangeUdf {
1695    fn hash<H: Hasher>(&self, state: &mut H) {
1696        self.output.hash(state);
1697    }
1698}
1699
1700impl ScalarUDFImpl for MixedRangeUdf {
1701    fn name(&self) -> &str {
1702        self.output.name()
1703    }
1704
1705    fn signature(&self) -> &Signature {
1706        &self.signature
1707    }
1708
1709    fn return_type(&self, _arg_types: &[DataType]) -> DfResult<DataType> {
1710        Ok(self.output.data_type())
1711    }
1712
1713    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DfResult<ColumnarValue> {
1714        let collector = args
1715            .config_options
1716            .extensions
1717            .get::<PromqlAnnotationCollector>()
1718            .cloned()
1719            .or_else(|| self.collector.clone());
1720        mixed_range(&args, self.output, collector)
1721    }
1722}
1723
1724#[derive(Debug, Clone, Copy)]
1725enum MixedRangeFunction {
1726    Rate,
1727    Increase,
1728    // Raw-delta modes sum floats while preserving mixed-range drop/warning semantics.
1729    RawDeltaRate,
1730    RawDeltaIncrease,
1731    Delta,
1732    IDelta,
1733    IRate,
1734    Changes,
1735    Resets,
1736    AvgOverTime,
1737    MinOverTime,
1738    MaxOverTime,
1739    SumOverTime,
1740    CountOverTime,
1741    LastOverTime,
1742    AbsentOverTime,
1743    PresentOverTime,
1744    StddevOverTime,
1745    StdvarOverTime,
1746    QuantileOverTime,
1747    Deriv,
1748    PredictLinear,
1749    DoubleExponentialSmoothing,
1750    HoltWinters,
1751}
1752
1753impl MixedRangeFunction {
1754    fn parse(value: &ColumnarValue) -> DfResult<Self> {
1755        let name = match value {
1756            ColumnarValue::Scalar(ScalarValue::Utf8(Some(name)))
1757            | ColumnarValue::Scalar(ScalarValue::LargeUtf8(Some(name)))
1758            | ColumnarValue::Scalar(ScalarValue::Utf8View(Some(name))) => name.as_str(),
1759            other => {
1760                return Err(DataFusionError::Execution(format!(
1761                    "mixed range function name must be a non-null string scalar, found {}",
1762                    other.data_type()
1763                )));
1764            }
1765        };
1766
1767        match name {
1768            "rate" => Ok(Self::Rate),
1769            "increase" => Ok(Self::Increase),
1770            "raw_delta_rate" => Ok(Self::RawDeltaRate),
1771            "raw_delta_increase" => Ok(Self::RawDeltaIncrease),
1772            "delta" => Ok(Self::Delta),
1773            "idelta" => Ok(Self::IDelta),
1774            "irate" => Ok(Self::IRate),
1775            "changes" => Ok(Self::Changes),
1776            "resets" => Ok(Self::Resets),
1777            "avg_over_time" => Ok(Self::AvgOverTime),
1778            "min_over_time" => Ok(Self::MinOverTime),
1779            "max_over_time" => Ok(Self::MaxOverTime),
1780            "sum_over_time" => Ok(Self::SumOverTime),
1781            "count_over_time" => Ok(Self::CountOverTime),
1782            "last_over_time" => Ok(Self::LastOverTime),
1783            "absent_over_time" => Ok(Self::AbsentOverTime),
1784            "present_over_time" => Ok(Self::PresentOverTime),
1785            "stddev_over_time" => Ok(Self::StddevOverTime),
1786            "stdvar_over_time" => Ok(Self::StdvarOverTime),
1787            "quantile_over_time" => Ok(Self::QuantileOverTime),
1788            "deriv" => Ok(Self::Deriv),
1789            "predict_linear" => Ok(Self::PredictLinear),
1790            "double_exponential_smoothing" => Ok(Self::DoubleExponentialSmoothing),
1791            "holt_winters" => Ok(Self::HoltWinters),
1792            _ => Err(DataFusionError::Execution(format!(
1793                "unsupported mixed range function: {name}"
1794            ))),
1795        }
1796    }
1797
1798    fn name(self) -> &'static str {
1799        match self {
1800            Self::Rate => "rate",
1801            Self::Increase => "increase",
1802            Self::RawDeltaRate => "rate",
1803            Self::RawDeltaIncrease => "increase",
1804            Self::Delta => "delta",
1805            Self::IDelta => "idelta",
1806            Self::IRate => "irate",
1807            Self::Changes => "changes",
1808            Self::Resets => "resets",
1809            Self::AvgOverTime => "avg_over_time",
1810            Self::MinOverTime => "min_over_time",
1811            Self::MaxOverTime => "max_over_time",
1812            Self::SumOverTime => "sum_over_time",
1813            Self::CountOverTime => "count_over_time",
1814            Self::LastOverTime => "last_over_time",
1815            Self::AbsentOverTime => "absent_over_time",
1816            Self::PresentOverTime => "present_over_time",
1817            Self::StddevOverTime => "stddev_over_time",
1818            Self::StdvarOverTime => "stdvar_over_time",
1819            Self::QuantileOverTime => "quantile_over_time",
1820            Self::Deriv => "deriv",
1821            Self::PredictLinear => "predict_linear",
1822            Self::DoubleExponentialSmoothing => "double_exponential_smoothing",
1823            Self::HoltWinters => "holt_winters",
1824        }
1825    }
1826
1827    fn policy(self) -> MixedRangePolicy {
1828        match self {
1829            Self::Rate
1830            | Self::Increase
1831            | Self::RawDeltaRate
1832            | Self::RawDeltaIncrease
1833            | Self::Delta
1834            | Self::AvgOverTime
1835            | Self::SumOverTime => MixedRangePolicy::DropMixed,
1836            Self::IDelta | Self::IRate => MixedRangePolicy::LastTwo,
1837            Self::LastOverTime => MixedRangePolicy::Last,
1838            Self::Changes
1839            | Self::Resets
1840            | Self::CountOverTime
1841            | Self::AbsentOverTime
1842            | Self::PresentOverTime => MixedRangePolicy::Combined,
1843            Self::MinOverTime
1844            | Self::MaxOverTime
1845            | Self::StddevOverTime
1846            | Self::StdvarOverTime
1847            | Self::QuantileOverTime
1848            | Self::Deriv
1849            | Self::PredictLinear
1850            | Self::DoubleExponentialSmoothing
1851            | Self::HoltWinters => MixedRangePolicy::FloatOnly,
1852        }
1853    }
1854
1855    fn float_udf(self) -> Option<ScalarUDF> {
1856        match self {
1857            Self::Rate => Some(Rate::scalar_udf()),
1858            Self::Increase => Some(Increase::scalar_udf()),
1859            Self::RawDeltaRate | Self::RawDeltaIncrease => Some(SumOverTime::scalar_udf()),
1860            Self::Delta => Some(crate::functions::Delta::scalar_udf()),
1861            Self::IDelta => Some(IDelta::<false>::scalar_udf()),
1862            Self::IRate => Some(IDelta::<true>::scalar_udf()),
1863            Self::AvgOverTime => Some(AvgOverTime::scalar_udf()),
1864            Self::MinOverTime => Some(MinOverTime::scalar_udf()),
1865            Self::MaxOverTime => Some(MaxOverTime::scalar_udf()),
1866            Self::SumOverTime => Some(SumOverTime::scalar_udf()),
1867            Self::LastOverTime => Some(LastOverTime::scalar_udf()),
1868            Self::StddevOverTime => Some(StddevOverTime::scalar_udf()),
1869            Self::StdvarOverTime => Some(StdvarOverTime::scalar_udf()),
1870            Self::QuantileOverTime => Some(QuantileOverTime::scalar_udf()),
1871            Self::Deriv => Some(Deriv::scalar_udf()),
1872            Self::PredictLinear => Some(PredictLinear::scalar_udf()),
1873            Self::DoubleExponentialSmoothing | Self::HoltWinters => {
1874                Some(DoubleExponentialSmoothing::scalar_udf())
1875            }
1876            Self::Changes
1877            | Self::Resets
1878            | Self::CountOverTime
1879            | Self::AbsentOverTime
1880            | Self::PresentOverTime => None,
1881        }
1882    }
1883
1884    fn histogram_udf(self, collector: Option<PromqlAnnotationCollector>) -> Option<ScalarUDF> {
1885        match self {
1886            Self::Rate => Some(NativeHistogramRate::scalar_udf_with_collector(collector)),
1887            Self::Increase => Some(NativeHistogramIncrease::scalar_udf_with_collector(
1888                collector,
1889            )),
1890            Self::Delta => Some(NativeHistogramDelta::scalar_udf_with_collector(collector)),
1891            Self::IDelta => Some(NativeHistogramIDelta::scalar_udf_with_collector(collector)),
1892            Self::IRate => Some(NativeHistogramIRate::scalar_udf_with_collector(collector)),
1893            Self::AvgOverTime => Some(NativeHistogramAvgOverTime::scalar_udf_with_collector(
1894                collector,
1895            )),
1896            Self::SumOverTime => Some(NativeHistogramSumOverTime::scalar_udf_with_collector(
1897                collector,
1898            )),
1899            Self::LastOverTime => Some(NativeHistogramLastOverTime::scalar_udf()),
1900            Self::RawDeltaRate | Self::RawDeltaIncrease => None,
1901            _ => None,
1902        }
1903    }
1904}
1905
1906#[derive(Debug, Clone, Copy)]
1907enum MixedRangePolicy {
1908    DropMixed,
1909    LastTwo,
1910    Last,
1911    Combined,
1912    FloatOnly,
1913}
1914
1915#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1916enum SampleLane {
1917    Float,
1918    Histogram,
1919}
1920
1921fn mixed_range(
1922    args: &ScalarFunctionArgs,
1923    output: MixedRangeOutput,
1924    collector: Option<PromqlAnnotationCollector>,
1925) -> DfResult<ColumnarValue> {
1926    if args.args.len() < 4 {
1927        return Err(DataFusionError::Plan(format!(
1928            "{} function should have at least 4 inputs",
1929            output.name()
1930        )));
1931    }
1932    let function = MixedRangeFunction::parse(&args.args[0])?;
1933    let name = function.name();
1934    let ts_range = extract_range_dict(
1935        &args.args[1],
1936        name,
1937        "timestamp range vector",
1938        &DataType::Timestamp(TimeUnit::Millisecond, None),
1939    )?;
1940    let float_range = extract_range_dict(
1941        &args.args[2],
1942        name,
1943        "float range vector",
1944        &DataType::Float64,
1945    )?;
1946    let histogram_range = extract_range_dict(
1947        &args.args[3],
1948        name,
1949        "native histogram range vector",
1950        &native_histogram_arrow_type(),
1951    )?;
1952    let keys = ts_range.keys().values();
1953    if float_range.keys().values() != keys || histogram_range.keys().values() != keys {
1954        return Err(DataFusionError::Execution(format!(
1955            "{name}: timestamp, float, and native histogram ranges should have the same layout"
1956        )));
1957    }
1958    if args.number_rows != keys.len() {
1959        return Err(DataFusionError::Execution(format!(
1960            "{name}: range inputs have {} windows but the batch has {} rows",
1961            keys.len(),
1962            args.number_rows
1963        )));
1964    }
1965
1966    let timestamps = ts_range
1967        .values()
1968        .as_any()
1969        .downcast_ref::<TimestampMillisecondArray>()
1970        .expect("validated timestamp range");
1971    let floats = float_range
1972        .values()
1973        .as_any()
1974        .downcast_ref::<Float64Array>()
1975        .expect("validated float range");
1976    let histograms = histogram_range
1977        .values()
1978        .as_any()
1979        .downcast_ref::<StructArray>()
1980        .expect("validated native histogram range");
1981    if floats.len() != timestamps.len() || histograms.len() != timestamps.len() {
1982        return Err(DataFusionError::Execution(format!(
1983            "{name}: timestamp, float, and native histogram values should be row-aligned"
1984        )));
1985    }
1986
1987    let bounds = checked_window_bounds(keys, timestamps.len(), name)?;
1988    let float_valid = (0..floats.len())
1989        .map(|row| floats.is_valid(row))
1990        .collect::<Vec<_>>();
1991    let histogram_valid = (0..histograms.len())
1992        .map(|row| histograms.is_valid(row))
1993        .collect::<Vec<_>>();
1994    let float_prefix = validity_prefix(&float_valid, name)?;
1995    let histogram_prefix = validity_prefix(&histogram_valid, name)?;
1996
1997    if matches!(function.policy(), MixedRangePolicy::Combined) {
1998        if output != MixedRangeOutput::Float {
1999            return Err(DataFusionError::Execution(format!(
2000                "{name} does not return native histograms"
2001            )));
2002        }
2003        return combined_range_float(
2004            function,
2005            &bounds,
2006            timestamps,
2007            floats,
2008            histograms,
2009            &float_valid,
2010            &histogram_valid,
2011            &float_prefix,
2012            &histogram_prefix,
2013        );
2014    }
2015
2016    let selections = select_mixed_range_lanes(
2017        function,
2018        &bounds,
2019        timestamps,
2020        &float_valid,
2021        &histogram_valid,
2022        &float_prefix,
2023        &histogram_prefix,
2024        &collector,
2025    );
2026    let (lane, values, valid, prefix) = match output {
2027        MixedRangeOutput::Float => (
2028            SampleLane::Float,
2029            floats as &dyn Array,
2030            float_valid.as_slice(),
2031            float_prefix.as_slice(),
2032        ),
2033        MixedRangeOutput::Histogram => (
2034            SampleLane::Histogram,
2035            histograms as &dyn Array,
2036            histogram_valid.as_slice(),
2037            histogram_prefix.as_slice(),
2038        ),
2039    };
2040    let input = compact_lane_input(
2041        timestamps,
2042        values,
2043        valid,
2044        prefix,
2045        &bounds,
2046        &selections,
2047        lane,
2048        name,
2049    )?;
2050
2051    let udf = match output {
2052        MixedRangeOutput::Float => function.float_udf(),
2053        MixedRangeOutput::Histogram => function.histogram_udf(collector),
2054    }
2055    .ok_or_else(|| {
2056        DataFusionError::Execution(format!(
2057            "{name} does not return {} values",
2058            match output {
2059                MixedRangeOutput::Float => "float",
2060                MixedRangeOutput::Histogram => "native histogram",
2061            }
2062        ))
2063    })?;
2064    let mut input = input;
2065    input.extend_from_slice(&args.args[4..]);
2066    invoke_range_udf(udf, input, args, bounds.len())
2067}
2068
2069/// Decodes packed range keys into validated half-open `(offset, end)` bounds.
2070fn checked_window_bounds(
2071    keys: &[i64],
2072    value_len: usize,
2073    name: &str,
2074) -> DfResult<Vec<(usize, usize)>> {
2075    keys.iter()
2076        .map(|key| {
2077            let (offset, length) = unpack(*key);
2078            let offset = offset as usize;
2079            let end = offset
2080                .checked_add(length as usize)
2081                .filter(|end| *end <= value_len)
2082                .ok_or_else(|| {
2083                    DataFusionError::Execution(format!(
2084                        "{name}: invalid range ({offset}, {length}) for {value_len} values"
2085                    ))
2086                })?;
2087            Ok((offset, end))
2088        })
2089        .collect()
2090}
2091
2092/// Builds prefix counts where `prefix[i]` is the number of valid samples in `valid[..i]`.
2093fn validity_prefix(valid: &[bool], name: &str) -> DfResult<Vec<usize>> {
2094    let capacity = valid.len().checked_add(1).ok_or_else(|| {
2095        DataFusionError::Execution(format!("{name}: sample validity length overflow"))
2096    })?;
2097    let mut prefix = Vec::with_capacity(capacity);
2098    prefix.push(0usize);
2099    for is_valid in valid {
2100        prefix.push(
2101            prefix
2102                .last()
2103                .copied()
2104                .unwrap()
2105                .checked_add(usize::from(*is_valid))
2106                .ok_or_else(|| {
2107                    DataFusionError::Execution(format!("{name}: sample count overflow"))
2108                })?,
2109        );
2110    }
2111    Ok(prefix)
2112}
2113
2114/// Returns the number of valid samples in the half-open window `[offset, end)`.
2115fn valid_count(prefix: &[usize], offset: usize, end: usize) -> usize {
2116    prefix[end]
2117        .checked_sub(prefix[offset])
2118        .expect("validity prefix is monotonic")
2119}
2120
2121/// Selects the sample lane for each window and records policy-required annotations.
2122#[allow(clippy::too_many_arguments)]
2123fn select_mixed_range_lanes(
2124    function: MixedRangeFunction,
2125    bounds: &[(usize, usize)],
2126    timestamps: &TimestampMillisecondArray,
2127    float_valid: &[bool],
2128    histogram_valid: &[bool],
2129    float_prefix: &[usize],
2130    histogram_prefix: &[usize],
2131    collector: &Option<PromqlAnnotationCollector>,
2132) -> Vec<Option<SampleLane>> {
2133    bounds
2134        .iter()
2135        .map(|(offset, end)| {
2136            let float_count = valid_count(float_prefix, *offset, *end);
2137            let histogram_count = valid_count(histogram_prefix, *offset, *end);
2138            match function.policy() {
2139                MixedRangePolicy::DropMixed => match (float_count > 0, histogram_count > 0) {
2140                    (true, true) => {
2141                        record_warning(
2142                            collector,
2143                            format!(
2144                                "{}: encountered a mix of float and native histogram samples",
2145                                function.name()
2146                            ),
2147                        );
2148                        None
2149                    }
2150                    (true, false) => Some(SampleLane::Float),
2151                    (false, true) => Some(SampleLane::Histogram),
2152                    (false, false) => None,
2153                },
2154                MixedRangePolicy::FloatOnly => {
2155                    if float_count > 0 && histogram_count > 0 {
2156                        record_info(
2157                            collector,
2158                            format!(
2159                                "{}: ignored native histogram samples",
2160                                function.name()
2161                            ),
2162                        );
2163                    }
2164                    (float_count > 0).then_some(SampleLane::Float)
2165                }
2166                MixedRangePolicy::Last => (*offset..*end).rev().find_map(|row| {
2167                    if histogram_valid[row] {
2168                        Some(SampleLane::Histogram)
2169                    } else if float_valid[row] {
2170                        Some(SampleLane::Float)
2171                    } else {
2172                        None
2173                    }
2174                }),
2175                MixedRangePolicy::LastTwo => {
2176                    let mut last_two = Vec::with_capacity(2);
2177                    for row in (*offset..*end).rev() {
2178                        // Prometheus keeps a float as the newest sample if both lanes have the
2179                        // same timestamp, while the histogram becomes the preceding sample.
2180                        if float_valid[row] {
2181                            last_two.push((SampleLane::Float, timestamps.value(row)));
2182                        }
2183                        if last_two.len() < 2 && histogram_valid[row] {
2184                            last_two.push((SampleLane::Histogram, timestamps.value(row)));
2185                        }
2186                        if last_two.len() == 2 {
2187                            break;
2188                        }
2189                    }
2190                    if last_two.len() < 2 || last_two[0].1 == last_two[1].1 {
2191                        None
2192                    } else if last_two[0].0 == last_two[1].0 {
2193                        Some(last_two[0].0)
2194                    } else {
2195                        record_warning(
2196                            collector,
2197                            format!(
2198                                "{}: encountered a mix of float and native histogram samples in the last two points",
2199                                function.name()
2200                            ),
2201                        );
2202                        None
2203                    }
2204                }
2205                MixedRangePolicy::Combined => unreachable!(),
2206            }
2207        })
2208        .collect()
2209}
2210
2211/// Filters null placeholders from one sample lane and remaps its selected windows.
2212/// Windows assigned to the other lane become empty.
2213#[allow(clippy::too_many_arguments)]
2214fn compact_lane_input(
2215    timestamps: &TimestampMillisecondArray,
2216    values: &dyn Array,
2217    valid: &[bool],
2218    prefix: &[usize],
2219    bounds: &[(usize, usize)],
2220    selections: &[Option<SampleLane>],
2221    lane: SampleLane,
2222    name: &str,
2223) -> DfResult<Vec<ColumnarValue>> {
2224    let mask = BooleanArray::from(valid.to_vec());
2225    let filtered_timestamps = filter(timestamps, &mask)?;
2226    let filtered_values = filter(values, &mask)?;
2227    let ranges = bounds
2228        .iter()
2229        .zip(selections)
2230        .map(|((offset, end), selected)| {
2231            let compact_offset = prefix[*offset];
2232            let compact_length = if *selected == Some(lane) {
2233                valid_count(prefix, *offset, *end)
2234            } else {
2235                0
2236            };
2237            Ok((
2238                u32::try_from(compact_offset).map_err(|_| {
2239                    DataFusionError::Execution(format!(
2240                        "{name}: compacted range offset exceeds u32"
2241                    ))
2242                })?,
2243                u32::try_from(compact_length).map_err(|_| {
2244                    DataFusionError::Execution(format!(
2245                        "{name}: compacted range length exceeds u32"
2246                    ))
2247                })?,
2248            ))
2249        })
2250        .collect::<DfResult<Vec<_>>>()?;
2251    let timestamp_range = RangeArray::from_ranges(filtered_timestamps, ranges.clone())
2252        .map_err(DataFusionError::from)?;
2253    let value_range =
2254        RangeArray::from_ranges(filtered_values, ranges).map_err(DataFusionError::from)?;
2255    Ok(vec![
2256        ColumnarValue::Array(Arc::new(timestamp_range.into_dict())),
2257        ColumnarValue::Array(Arc::new(value_range.into_dict())),
2258    ])
2259}
2260
2261fn invoke_range_udf(
2262    udf: ScalarUDF,
2263    input: Vec<ColumnarValue>,
2264    outer_args: &ScalarFunctionArgs,
2265    number_rows: usize,
2266) -> DfResult<ColumnarValue> {
2267    let arg_fields = input
2268        .iter()
2269        .enumerate()
2270        .map(|(index, value)| Arc::new(Field::new(format!("arg_{index}"), value.data_type(), true)))
2271        .collect();
2272    udf.invoke_with_args(ScalarFunctionArgs {
2273        args: input,
2274        arg_fields,
2275        number_rows,
2276        return_field: outer_args.return_field.clone(),
2277        config_options: outer_args.config_options.clone(),
2278    })
2279}
2280
2281enum MixedSample {
2282    Float(f64),
2283    Histogram(NativeHistogram),
2284}
2285
2286#[allow(clippy::too_many_arguments)]
2287fn combined_range_float(
2288    function: MixedRangeFunction,
2289    bounds: &[(usize, usize)],
2290    timestamps: &TimestampMillisecondArray,
2291    floats: &Float64Array,
2292    histograms: &StructArray,
2293    float_valid: &[bool],
2294    histogram_valid: &[bool],
2295    float_prefix: &[usize],
2296    histogram_prefix: &[usize],
2297) -> DfResult<ColumnarValue> {
2298    let mut result = Float64Builder::with_capacity(bounds.len());
2299    for (offset, end) in bounds {
2300        let sample_count = valid_count(float_prefix, *offset, *end)
2301            .checked_add(valid_count(histogram_prefix, *offset, *end))
2302            .ok_or_else(|| {
2303                DataFusionError::Execution(format!("{}: sample count overflow", function.name()))
2304            })?;
2305        match function {
2306            MixedRangeFunction::CountOverTime => {
2307                if sample_count == 0 {
2308                    result.append_null();
2309                } else {
2310                    result.append_value(sample_count as f64);
2311                }
2312            }
2313            MixedRangeFunction::AbsentOverTime => {
2314                if sample_count == 0 {
2315                    result.append_value(1.0);
2316                } else {
2317                    result.append_null();
2318                }
2319            }
2320            MixedRangeFunction::PresentOverTime => {
2321                if sample_count == 0 {
2322                    result.append_null();
2323                } else {
2324                    result.append_value(1.0);
2325                }
2326            }
2327            MixedRangeFunction::Changes | MixedRangeFunction::Resets => {
2328                if sample_count == 0 {
2329                    result.append_null();
2330                    continue;
2331                }
2332                let mut count = 0usize;
2333                let mut previous = None;
2334                for row in *offset..*end {
2335                    if float_valid[row] {
2336                        count += mixed_transition(
2337                            function,
2338                            &mut previous,
2339                            timestamps.value(row),
2340                            MixedSample::Float(floats.value(row)),
2341                        );
2342                    }
2343                    if histogram_valid[row] {
2344                        let histogram = read_histogram(histograms, row)?
2345                            .expect("validated native histogram sample");
2346                        count += mixed_transition(
2347                            function,
2348                            &mut previous,
2349                            timestamps.value(row),
2350                            MixedSample::Histogram(histogram),
2351                        );
2352                    }
2353                }
2354                result.append_value(count as f64);
2355            }
2356            _ => {
2357                return Err(DataFusionError::Internal(format!(
2358                    "{} does not support combined range evaluation",
2359                    function.name()
2360                )));
2361            }
2362        }
2363    }
2364    Ok(ColumnarValue::Array(Arc::new(result.finish())))
2365}
2366
2367fn mixed_transition(
2368    function: MixedRangeFunction,
2369    previous: &mut Option<(i64, MixedSample)>,
2370    timestamp: i64,
2371    current: MixedSample,
2372) -> usize {
2373    let changed = previous.as_ref().is_some_and(|(previous_ts, previous)| {
2374        match (function, previous, &current) {
2375            (
2376                MixedRangeFunction::Changes,
2377                MixedSample::Float(previous),
2378                MixedSample::Float(current),
2379            ) => current != previous && !(current.is_nan() && previous.is_nan()),
2380            (
2381                MixedRangeFunction::Changes,
2382                MixedSample::Histogram(previous),
2383                MixedSample::Histogram(current),
2384            ) => !current.promql_eq(previous),
2385            (MixedRangeFunction::Changes, _, _) => true,
2386            (
2387                MixedRangeFunction::Resets,
2388                MixedSample::Float(previous),
2389                MixedSample::Float(current),
2390            ) => current < previous,
2391            (
2392                MixedRangeFunction::Resets,
2393                MixedSample::Histogram(previous),
2394                MixedSample::Histogram(current),
2395            ) => {
2396                (previous.reset_hint == GAUGE_RESET_HINT)
2397                    != (current.reset_hint == GAUGE_RESET_HINT)
2398                    || current.detect_counter_reset(previous, *previous_ts, timestamp)
2399            }
2400            (MixedRangeFunction::Resets, _, _) => true,
2401            _ => unreachable!(),
2402        }
2403    });
2404    *previous = Some((timestamp, current));
2405    usize::from(changed)
2406}
2407
2408fn native_histogram_scalar(histogram: Option<NativeHistogram>) -> ScalarValue {
2409    let array = build_histogram_array(&[histogram]);
2410    let histogram = array
2411        .as_any()
2412        .downcast_ref::<StructArray>()
2413        .expect("native histogram array is a StructArray")
2414        .clone();
2415    ScalarValue::Struct(Arc::new(histogram))
2416}
2417
2418fn native_histogram_aggregate_udf(
2419    kind: NativeHistogramAggregateKind,
2420    collector: Option<PromqlAnnotationCollector>,
2421) -> AggregateUDF {
2422    let state_types = if kind.needs_count() {
2423        vec![
2424            native_histogram_arrow_type(),
2425            DataType::UInt64,
2426            DataType::Boolean,
2427            DataType::Boolean,
2428            DataType::Boolean,
2429        ]
2430    } else {
2431        vec![
2432            native_histogram_arrow_type(),
2433            DataType::Boolean,
2434            DataType::Boolean,
2435            DataType::Boolean,
2436        ]
2437    };
2438
2439    create_udaf(
2440        kind.name(),
2441        vec![native_histogram_arrow_type()],
2442        Arc::new(native_histogram_arrow_type()),
2443        Volatility::Volatile,
2444        Arc::new(move |args| {
2445            NativeHistogramAggregateAccumulator::from_args(kind, collector.clone(), args)
2446        }),
2447        Arc::new(state_types),
2448    )
2449}
2450
2451impl DfAccumulator for NativeHistogramAggregateAccumulator {
2452    fn update_batch(&mut self, values: &[ArrayRef]) -> DfResult<()> {
2453        let histograms = values
2454            .first()
2455            .and_then(|array| array.as_any().downcast_ref::<StructArray>())
2456            .ok_or_else(|| {
2457                DataFusionError::Execution(format!(
2458                    "{}: expected native histogram struct input",
2459                    self.kind.name()
2460                ))
2461            })?;
2462
2463        for row in 0..histograms.len() {
2464            let Some(histogram) = read_histogram(histograms, row)? else {
2465                continue;
2466            };
2467            self.push_histogram(histogram, 1)?;
2468        }
2469
2470        Ok(())
2471    }
2472
2473    fn evaluate(&mut self) -> DfResult<ScalarValue> {
2474        Ok(native_histogram_scalar(self.state_histogram()?))
2475    }
2476
2477    fn size(&self) -> usize {
2478        // The fold sits inline in this struct, so only the histograms it owns are counted on top of
2479        // it.
2480        size_of::<Self>()
2481            + self.fold.as_ref().map_or(0, |fold| {
2482                accumulator_bytes(fold).saturating_sub(size_of::<HistogramAccumulator>())
2483            })
2484    }
2485
2486    fn state(&mut self) -> DfResult<Vec<ScalarValue>> {
2487        let mut state = vec![native_histogram_scalar(self.state_histogram()?)];
2488        if self.kind.needs_count() {
2489            state.push(ScalarValue::UInt64(Some(self.count)));
2490        }
2491        state.push(ScalarValue::Boolean(Some(self.evidence.poisoned)));
2492        state.push(ScalarValue::Boolean(Some(self.evidence.counter_reset_seen)));
2493        state.push(ScalarValue::Boolean(Some(
2494            self.evidence.not_counter_reset_seen,
2495        )));
2496        Ok(state)
2497    }
2498
2499    fn merge_batch(&mut self, states: &[ArrayRef]) -> DfResult<()> {
2500        if states.is_empty() {
2501            return Ok(());
2502        }
2503
2504        let histograms = states[0]
2505            .as_any()
2506            .downcast_ref::<StructArray>()
2507            .ok_or_else(|| {
2508                DataFusionError::Execution(format!(
2509                    "{}: expected native histogram struct state",
2510                    self.kind.name()
2511                ))
2512            })?;
2513        let counts = if self.kind.needs_count() {
2514            Some(
2515                states
2516                    .get(1)
2517                    .and_then(|array| array.as_any().downcast_ref::<UInt64Array>())
2518                    .ok_or_else(|| {
2519                        DataFusionError::Execution(format!(
2520                            "{}: expected UInt64 count state",
2521                            self.kind.name()
2522                        ))
2523                    })?,
2524            )
2525        } else {
2526            None
2527        };
2528        let dropped_index = if self.kind.needs_count() { 2 } else { 1 };
2529        let dropped = states
2530            .get(dropped_index)
2531            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2532            .ok_or_else(|| {
2533                DataFusionError::Execution(format!(
2534                    "{}: expected Boolean dropped state",
2535                    self.kind.name()
2536                ))
2537            })?;
2538        let counter_reset_seen = states
2539            .get(dropped_index + 1)
2540            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2541            .ok_or_else(|| {
2542                DataFusionError::Execution(format!(
2543                    "{}: expected Boolean counter reset state",
2544                    self.kind.name()
2545                ))
2546            })?;
2547        let not_counter_reset_seen = states
2548            .get(dropped_index + 2)
2549            .and_then(|array| array.as_any().downcast_ref::<BooleanArray>())
2550            .ok_or_else(|| {
2551                DataFusionError::Execution(format!(
2552                    "{}: expected Boolean not-counter-reset state",
2553                    self.kind.name()
2554                ))
2555            })?;
2556
2557        let op = self.op();
2558        for row in 0..histograms.len() {
2559            self.observe_reset_hints(
2560                counter_reset_seen.value(row),
2561                not_counter_reset_seen.value(row),
2562            );
2563            if dropped.value(row) {
2564                // A dropped partition answers nothing, so only its poison crosses the boundary.
2565                self.mark_incompatible();
2566            }
2567            if self.evidence.poisoned {
2568                continue;
2569            }
2570            let Some(histogram) = read_histogram(histograms, row)? else {
2571                continue;
2572            };
2573            let count = counts.map(|counts| counts.value(row)).unwrap_or(1);
2574            if self.kind.needs_count() && count == 0 {
2575                continue;
2576            }
2577            let combined_count = self.combined_count(count)?;
2578            // The same disagreement `push_histogram` drops a position for, met through a state
2579            // frame: a layout this crate cannot read drops the partition's state instead of failing
2580            // the statement, and with it the position the state was headed into.
2581            let sample = match float_histogram(&histogram) {
2582                Ok(sample) => sample,
2583                Err(_) => {
2584                    self.record_incompatible();
2585                    continue;
2586                }
2587            };
2588            // The incoming side carries what its frame could: its answer, its count and its
2589            // evidence. It has no compensation component, so the compensation it brings is the
2590            // layout-carrying zero -- the residual it exported is already inside its answer.
2591            let payload = HistogramState {
2592                value: histogram_batch(&sample)?,
2593                compensation: histogram_batch(&sample.new_compensation())?,
2594                count: count as f64,
2595                // A legacy average exports the mean of its `count` samples, because its frame has
2596                // no mean mode to export instead; a sum exports a sum.
2597                incremental_mean: self.kind.needs_count(),
2598                poisoned: false,
2599                incompatible_layout: false,
2600                custom_bounds_reconciled: false,
2601                counter_reset_seen: false,
2602                not_counter_reset_seen: false,
2603            };
2604            let recorded = self.evidence;
2605            if let Some(mut fold) = self.fold.take() {
2606                fold.evidence = recorded;
2607                let merged = fold.merge_state(op, &payload);
2608                self.evidence = fold.evidence;
2609                self.fold = Some(fold);
2610                merged?;
2611            } else {
2612                // Nothing folded here yet, so the incoming state is this position's state.
2613                let mut fold = HistogramAccumulator::from_payload(op, &payload)?;
2614                fold.evidence = recorded;
2615                self.fold = Some(fold);
2616            }
2617            let evidence = self.fold.as_ref().map_or(recorded, |fold| fold.evidence);
2618            self.evidence = evidence;
2619            if evidence.poisoned {
2620                // Two partitions can each be valid on their own and still disagree on their bucket
2621                // layout, which the merge reports the way a fold inside one partition reports it.
2622                self.record_incompatible();
2623                continue;
2624            }
2625            self.count = combined_count;
2626            if evidence.custom_bounds_reconciled && !recorded.custom_bounds_reconciled {
2627                record_reconciled_custom_buckets(&self.collector, self.kind.name());
2628            }
2629        }
2630
2631        Ok(())
2632    }
2633}
2634
2635fn histogram_delta(
2636    samples: &[NativeHistogram],
2637    timestamps: &[i64],
2638    is_counter: bool,
2639) -> Option<NativeHistogram> {
2640    if samples.len() < 2 || samples.len() != timestamps.len() {
2641        return None;
2642    }
2643
2644    if !is_counter {
2645        return legacy_bridge::sub(samples.last()?, samples.first()?)
2646            .map(NativeHistogram::into_gauge);
2647    }
2648
2649    let first_reset = samples[1].detect_counter_reset(&samples[0], timestamps[0], timestamps[1]);
2650    let (initial, reset_scan_start) = if first_reset {
2651        // The first sample is irrelevant after an immediate reset. Adopt the
2652        // second sample's layout so an incompatible pre-reset layout is ignored.
2653        (samples[1].zero_like(), 2)
2654    } else {
2655        (samples[0].clone(), 1)
2656    };
2657    let mut result = legacy_bridge::sub(samples.last()?, &initial)?;
2658    for index in reset_scan_start..samples.len() {
2659        if samples[index].detect_counter_reset(
2660            &samples[index - 1],
2661            timestamps[index - 1],
2662            timestamps[index],
2663        ) {
2664            result = legacy_bridge::add(&result, &samples[index - 1])?;
2665        }
2666    }
2667    Some(result.into_gauge())
2668}
2669
2670fn idelta_value(
2671    samples: &[NativeHistogram],
2672    is_rate: bool,
2673    previous_ts: i64,
2674    current_ts: i64,
2675    sampled_interval_secs: f64,
2676) -> Option<NativeHistogram> {
2677    if samples.len() < 2 {
2678        return None;
2679    }
2680    let previous = &samples[samples.len() - 2];
2681    let current = samples.last()?;
2682    let result = if is_rate && current.detect_counter_reset(previous, previous_ts, current_ts) {
2683        current.clone()
2684    } else {
2685        legacy_bridge::sub(current, previous)?
2686    };
2687    Some(
2688        if is_rate {
2689            legacy_bridge::scale(&result, 1.0 / sampled_interval_secs)
2690        } else {
2691            result
2692        }
2693        .into_gauge(),
2694    )
2695}
2696
2697fn native_extrapolated_rate<const IS_COUNTER: bool, const IS_RATE: bool>(
2698    input: &[ColumnarValue],
2699    range_length: i64,
2700    func_name: &'static str,
2701    collector: Option<PromqlAnnotationCollector>,
2702) -> DfResult<ColumnarValue> {
2703    if input.len() != 4 {
2704        return Err(DataFusionError::Plan(format!(
2705            "{func_name} function should have 4 inputs"
2706        )));
2707    }
2708
2709    let ts_dict = extract_range_dict(
2710        &input[0],
2711        func_name,
2712        "timestamp range vector",
2713        &DataType::Timestamp(TimeUnit::Millisecond, None),
2714    )?;
2715    let value_dict = extract_range_dict(
2716        &input[1],
2717        func_name,
2718        "value range vector",
2719        &native_histogram_arrow_type(),
2720    )?;
2721    let eval_ts = extract_array(&input[2])?;
2722    let eval_ts = eval_ts
2723        .as_any()
2724        .downcast_ref::<TimestampMillisecondArray>()
2725        .ok_or_else(|| {
2726            DataFusionError::Execution(format!(
2727                "{func_name}: expect evaluation timestamp vector as Timestamp(Millisecond), found {}",
2728                eval_ts.data_type()
2729            ))
2730        })?;
2731
2732    let keys = ts_dict.keys().values();
2733    if value_dict.keys().values() != keys || eval_ts.len() != keys.len() {
2734        return Err(DataFusionError::Execution(format!(
2735            "{func_name}: timestamp, value, and evaluation ranges should have the same layout"
2736        )));
2737    }
2738
2739    let all_timestamps = ts_dict
2740        .values()
2741        .as_any()
2742        .downcast_ref::<TimestampMillisecondArray>()
2743        .expect("validated timestamp range")
2744        .values();
2745    let all_histograms = value_dict
2746        .values()
2747        .as_any()
2748        .downcast_ref::<StructArray>()
2749        .expect("validated native histogram range");
2750    let range_length_secs = range_length as f64 / 1000.0;
2751    let mut result = Vec::with_capacity(keys.len());
2752
2753    for index in 0..keys.len() {
2754        let (raw_offset, raw_length) = unpack(keys[index]);
2755        let offset = raw_offset as usize;
2756        let length = raw_length as usize;
2757        if length == 0 {
2758            result.push(None);
2759            continue;
2760        }
2761
2762        let mut samples = Vec::with_capacity(length);
2763        let mut has_null = false;
2764        for row in offset..offset + length {
2765            let Some(histogram) = read_histogram(all_histograms, row)? else {
2766                has_null = true;
2767                break;
2768            };
2769            samples.push(histogram);
2770        }
2771        if has_null {
2772            result.push(None);
2773            continue;
2774        }
2775
2776        let first_ts = all_timestamps[offset];
2777        let last_ts = all_timestamps[offset + length - 1];
2778        let range_end = eval_ts.value(index);
2779        let range_start = range_end - range_length;
2780        let synthetic_zero_timestamp = IS_COUNTER
2781            .then_some(samples[0].start_timestamp)
2782            .flatten()
2783            .filter(|start| *start != 0 && range_start < *start && *start < first_ts);
2784        let synthetic_zero_start = synthetic_zero_timestamp.is_some();
2785        if length < 2 && !synthetic_zero_start {
2786            result.push(None);
2787            continue;
2788        }
2789
2790        let wrong_flavor = if IS_COUNTER {
2791            samples
2792                .iter()
2793                .any(|histogram| histogram.reset_hint == GAUGE_RESET_HINT)
2794        } else {
2795            samples[0].reset_hint != GAUGE_RESET_HINT
2796                || samples[samples.len() - 1].reset_hint != GAUGE_RESET_HINT
2797        };
2798        if wrong_flavor {
2799            let expected = if IS_COUNTER { "counter" } else { "gauge" };
2800            record_warning(
2801                &collector,
2802                format!("{func_name}: native histogram input should be a {expected} histogram"),
2803            );
2804        }
2805
2806        let timestamps = &all_timestamps[offset..offset + length];
2807        for pair in samples.windows(2) {
2808            record_custom_reconciliation(&collector, func_name, &pair[0], &pair[1]);
2809        }
2810        let mut histogram = if length == 1 {
2811            samples[0].clone()
2812        } else if let Some(histogram) = histogram_delta(&samples, timestamps, IS_COUNTER) {
2813            histogram
2814        } else {
2815            record_warning(
2816                &collector,
2817                format!("{func_name}: dropped native histogram range with incompatible schemas"),
2818            );
2819            result.push(None);
2820            continue;
2821        };
2822        if synthetic_zero_start && length > 1 {
2823            let Some(with_synthetic_zero) = legacy_bridge::add(&histogram, &samples[0]) else {
2824                record_warning(
2825                    &collector,
2826                    format!(
2827                        "{func_name}: dropped native histogram range with incompatible schemas"
2828                    ),
2829                );
2830                result.push(None);
2831                continue;
2832            };
2833            histogram = with_synthetic_zero;
2834        }
2835
2836        let real_sampled_interval_ms = (last_ts - first_ts) as f64;
2837        let sampled_interval_ms = synthetic_zero_timestamp
2838            .map(|start| (last_ts - start) as f64)
2839            .unwrap_or(real_sampled_interval_ms);
2840        if sampled_interval_ms <= 0.0 {
2841            result.push(None);
2842            continue;
2843        }
2844        let average_interval_ms = if length > 1 {
2845            real_sampled_interval_ms / (length - 1) as f64
2846        } else {
2847            0.0
2848        };
2849        let mut duration_to_start_ms = if synthetic_zero_start {
2850            0.0
2851        } else {
2852            (first_ts - range_start) as f64
2853        };
2854        let duration_to_end_ms = (range_end - last_ts) as f64;
2855
2856        if IS_COUNTER && !synthetic_zero_start && histogram.count > 0.0 && samples[0].count >= 0.0 {
2857            let duration_to_zero = sampled_interval_ms * (samples[0].count / histogram.count);
2858            if duration_to_zero < duration_to_start_ms {
2859                duration_to_start_ms = duration_to_zero;
2860            }
2861        }
2862
2863        let extrapolation_threshold = average_interval_ms * 1.1;
2864        let mut extrapolated_interval_ms = sampled_interval_ms;
2865        if duration_to_start_ms < extrapolation_threshold {
2866            extrapolated_interval_ms += duration_to_start_ms;
2867        } else {
2868            extrapolated_interval_ms += average_interval_ms / 2.0;
2869        }
2870        if duration_to_end_ms < extrapolation_threshold {
2871            extrapolated_interval_ms += duration_to_end_ms;
2872        } else {
2873            extrapolated_interval_ms += average_interval_ms / 2.0;
2874        }
2875
2876        let mut factor = extrapolated_interval_ms / sampled_interval_ms;
2877        if IS_RATE {
2878            factor /= range_length_secs;
2879        }
2880        histogram = legacy_bridge::scale(&histogram, factor).into_gauge();
2881        result.push(Some(histogram));
2882    }
2883
2884    Ok(ColumnarValue::Array(build_histogram_array(&result)))
2885}
2886
2887fn create_native_extrapolated_udf<const IS_COUNTER: bool, const IS_RATE: bool>(
2888    name: &'static str,
2889    collector: Option<PromqlAnnotationCollector>,
2890) -> ScalarUDF {
2891    let input_types = vec![
2892        RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
2893        RangeArray::convert_data_type(native_histogram_arrow_type()),
2894        DataType::Timestamp(TimeUnit::Millisecond, None),
2895        DataType::Int64,
2896    ];
2897    create_udf(
2898        name,
2899        input_types,
2900        native_histogram_arrow_type(),
2901        Volatility::Volatile,
2902        Arc::new(move |input: &[ColumnarValue]| {
2903            let range_length = extract_array(&input[3])?;
2904            let range_length = range_length
2905                .as_any()
2906                .downcast_ref::<Int64Array>()
2907                .ok_or_else(|| {
2908                    DataFusionError::Execution(format!(
2909                        "{name}: expect Int64 as range length type, found {}",
2910                        range_length.data_type()
2911                    ))
2912                })?;
2913            if range_length.is_empty() || range_length.is_null(0) {
2914                return Err(DataFusionError::Execution(format!(
2915                    "{name}: range length must contain a non-null Int64 value"
2916                )));
2917            }
2918            native_extrapolated_rate::<IS_COUNTER, IS_RATE>(
2919                input,
2920                range_length.value(0),
2921                name,
2922                collector.clone(),
2923            )
2924        }) as _,
2925    )
2926}
2927
2928pub struct NativeHistogramDelta;
2929pub struct NativeHistogramRate;
2930pub struct NativeHistogramIncrease;
2931
2932impl NativeHistogramDelta {
2933    pub const fn name() -> &'static str {
2934        "prom_native_histogram_delta"
2935    }
2936
2937    pub fn scalar_udf() -> ScalarUDF {
2938        Self::scalar_udf_with_collector(None)
2939    }
2940
2941    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2942        create_native_extrapolated_udf::<false, false>(Self::name(), collector)
2943    }
2944}
2945
2946impl NativeHistogramRate {
2947    pub const fn name() -> &'static str {
2948        "prom_native_histogram_rate"
2949    }
2950
2951    pub fn scalar_udf() -> ScalarUDF {
2952        Self::scalar_udf_with_collector(None)
2953    }
2954
2955    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2956        create_native_extrapolated_udf::<true, true>(Self::name(), collector)
2957    }
2958}
2959
2960impl NativeHistogramIncrease {
2961    pub const fn name() -> &'static str {
2962        "prom_native_histogram_increase"
2963    }
2964
2965    pub fn scalar_udf() -> ScalarUDF {
2966        Self::scalar_udf_with_collector(None)
2967    }
2968
2969    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
2970        create_native_extrapolated_udf::<true, false>(Self::name(), collector)
2971    }
2972}
2973
2974fn native_idelta<const IS_RATE: bool>(
2975    input: &[ColumnarValue],
2976    func_name: &'static str,
2977    collector: Option<PromqlAnnotationCollector>,
2978) -> DfResult<ColumnarValue> {
2979    if input.len() != 2 {
2980        return Err(DataFusionError::Plan(format!(
2981            "{func_name} function should have 2 inputs"
2982        )));
2983    }
2984
2985    let ts_range = extract_range_dict(
2986        &input[0],
2987        func_name,
2988        "timestamp range vector",
2989        &DataType::Timestamp(TimeUnit::Millisecond, None),
2990    )?;
2991    let value_range = extract_range_dict(
2992        &input[1],
2993        func_name,
2994        "value range vector",
2995        &native_histogram_arrow_type(),
2996    )?;
2997
2998    if ts_range.keys().values() != value_range.keys().values() {
2999        return Err(DataFusionError::Execution(format!(
3000            "{func_name}: timestamp and value ranges should have the same window layout"
3001        )));
3002    }
3003
3004    let ts_values = ts_range
3005        .values()
3006        .as_any()
3007        .downcast_ref::<TimestampMillisecondArray>()
3008        .expect("validated timestamp range")
3009        .values();
3010    let histograms = value_range
3011        .values()
3012        .as_any()
3013        .downcast_ref::<StructArray>()
3014        .expect("validated native histogram range");
3015    let mut result = Vec::with_capacity(ts_range.keys().len());
3016
3017    for key in ts_range.keys().values() {
3018        let (offset, length) = unpack(*key);
3019        let offset = offset as usize;
3020        let length = length as usize;
3021        if length < 2 {
3022            result.push(None);
3023            continue;
3024        }
3025
3026        let mut samples = Vec::with_capacity(2);
3027        let mut has_null = false;
3028        for row in offset + length - 2..offset + length {
3029            let Some(histogram) = read_histogram(histograms, row)? else {
3030                has_null = true;
3031                break;
3032            };
3033            samples.push(histogram);
3034        }
3035        if has_null {
3036            result.push(None);
3037            continue;
3038        }
3039
3040        let wrong_flavor = samples.iter().any(|histogram| {
3041            if IS_RATE {
3042                histogram.reset_hint == GAUGE_RESET_HINT
3043            } else {
3044                histogram.reset_hint != GAUGE_RESET_HINT
3045            }
3046        });
3047        if wrong_flavor {
3048            let expected = if IS_RATE { "counter" } else { "gauge" };
3049            record_warning(
3050                &collector,
3051                format!("{func_name}: native histogram input should be a {expected} histogram"),
3052            );
3053        }
3054
3055        let sampled_interval_secs =
3056            (ts_values[offset + length - 1] - ts_values[offset + length - 2]) as f64 / 1000.0;
3057        if sampled_interval_secs <= 0.0 {
3058            result.push(None);
3059            continue;
3060        }
3061        record_custom_reconciliation(&collector, func_name, &samples[0], &samples[1]);
3062        let value = idelta_value(
3063            &samples,
3064            IS_RATE,
3065            ts_values[offset + length - 2],
3066            ts_values[offset + length - 1],
3067            sampled_interval_secs,
3068        );
3069        if value.is_none() {
3070            record_warning(
3071                &collector,
3072                format!("{func_name}: dropped native histogram range with incompatible schemas"),
3073            );
3074        }
3075        result.push(value);
3076    }
3077
3078    Ok(ColumnarValue::Array(build_histogram_array(&result)))
3079}
3080
3081fn create_native_idelta_udf<const IS_RATE: bool>(
3082    name: &'static str,
3083    collector: Option<PromqlAnnotationCollector>,
3084) -> ScalarUDF {
3085    create_udf(
3086        name,
3087        vec![
3088            RangeArray::convert_data_type(DataType::Timestamp(TimeUnit::Millisecond, None)),
3089            RangeArray::convert_data_type(native_histogram_arrow_type()),
3090        ],
3091        native_histogram_arrow_type(),
3092        Volatility::Volatile,
3093        Arc::new(move |input: &[ColumnarValue]| {
3094            native_idelta::<IS_RATE>(input, name, collector.clone())
3095        }) as _,
3096    )
3097}
3098
3099pub struct NativeHistogramIDelta;
3100pub struct NativeHistogramIRate;
3101
3102impl NativeHistogramIDelta {
3103    pub const fn name() -> &'static str {
3104        "prom_native_histogram_idelta"
3105    }
3106
3107    pub fn scalar_udf() -> ScalarUDF {
3108        Self::scalar_udf_with_collector(None)
3109    }
3110
3111    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
3112        create_native_idelta_udf::<false>(Self::name(), collector)
3113    }
3114}
3115
3116impl NativeHistogramIRate {
3117    pub const fn name() -> &'static str {
3118        "prom_native_histogram_irate"
3119    }
3120
3121    pub fn scalar_udf() -> ScalarUDF {
3122        Self::scalar_udf_with_collector(None)
3123    }
3124
3125    pub fn scalar_udf_with_collector(collector: Option<PromqlAnnotationCollector>) -> ScalarUDF {
3126        create_native_idelta_udf::<true>(Self::name(), collector)
3127    }
3128}
3129
3130#[cfg(test)]
3131mod tests {
3132    use datafusion::arrow::datatypes::Field;
3133    use datafusion_common::config::ConfigOptions;
3134    use datafusion_expr::ScalarFunctionArgs;
3135    use datatypes::series::aggregate_state::StatePayload;
3136
3137    use super::*;
3138
3139    fn sample_histogram(count: f64, sum: f64, positive_buckets: Vec<f64>) -> NativeHistogram {
3140        NativeHistogram {
3141            schema: 0,
3142            zero_threshold: 0.0,
3143            sum,
3144            reset_hint: UNKNOWN_COUNTER_RESET_HINT,
3145            start_timestamp: None,
3146            custom_values: Vec::new(),
3147            positive_spans: vec![Span {
3148                offset: 0,
3149                length: positive_buckets.len() as i32,
3150            }],
3151            negative_spans: Vec::new(),
3152            count,
3153            zero_count: 0.0,
3154            positive_buckets,
3155            negative_buckets: Vec::new(),
3156        }
3157    }
3158
3159    fn run_scalar_udf(udf: ScalarUDF, input: Vec<ColumnarValue>) -> f64 {
3160        let result = run_udf(udf, input, DataType::Float64);
3161        extract_array(&result)
3162            .unwrap()
3163            .as_any()
3164            .downcast_ref::<Float64Array>()
3165            .unwrap()
3166            .value(0)
3167    }
3168
3169    fn run_udf(udf: ScalarUDF, input: Vec<ColumnarValue>, return_type: DataType) -> ColumnarValue {
3170        let arg_fields = input
3171            .iter()
3172            .enumerate()
3173            .map(|(idx, input)| Arc::new(Field::new(format!("arg_{idx}"), input.data_type(), true)))
3174            .collect();
3175        let args = ScalarFunctionArgs {
3176            args: input,
3177            arg_fields,
3178            number_rows: 1,
3179            return_field: Arc::new(Field::new("result", return_type, true)),
3180            config_options: Arc::new(ConfigOptions::default()),
3181        };
3182
3183        udf.invoke_with_args(args).unwrap()
3184    }
3185
3186    fn run_histogram_udf(udf: ScalarUDF, input: Vec<ColumnarValue>) -> NativeHistogram {
3187        let result = run_udf(udf, input, native_histogram_arrow_type());
3188        let array = extract_array(&result)
3189            .unwrap()
3190            .as_any()
3191            .downcast_ref::<StructArray>()
3192            .unwrap()
3193            .clone();
3194        read_histogram(&array, 0).unwrap().unwrap()
3195    }
3196
3197    fn evaluated_histogram(
3198        accumulator: &mut NativeHistogramAggregateAccumulator,
3199    ) -> NativeHistogram {
3200        evaluated(accumulator).expect("native histogram accumulator answered nothing")
3201    }
3202
3203    fn evaluated(accumulator: &mut NativeHistogramAggregateAccumulator) -> Option<NativeHistogram> {
3204        let ScalarValue::Struct(array) = accumulator.evaluate().unwrap() else {
3205            panic!("native histogram accumulator returned a non-struct value");
3206        };
3207        read_histogram(&array, 0).unwrap()
3208    }
3209
3210    /// The Arrow arrays one accumulator's state frame spans, one row each.
3211    fn state_arrays(aggregate: &mut NativeHistogramAggregateAccumulator) -> Vec<ArrayRef> {
3212        aggregate
3213            .state()
3214            .unwrap()
3215            .into_iter()
3216            .map(|value| value.to_array_of_size(1).unwrap())
3217            .collect()
3218    }
3219
3220    /// The components of one legacy accumulator's state frame.
3221    struct LegacyState {
3222        histogram: Option<NativeHistogram>,
3223        /// The `UInt64` component; only an average declares one.
3224        count: Option<u64>,
3225        /// The `dropped_incompatible` component.
3226        dropped: bool,
3227        counter_reset_seen: bool,
3228        not_counter_reset_seen: bool,
3229    }
3230
3231    fn legacy_state(aggregate: &mut NativeHistogramAggregateAccumulator) -> LegacyState {
3232        let state = aggregate.state().unwrap();
3233        let ScalarValue::Struct(array) = state[0].clone() else {
3234            panic!("native histogram accumulator state is not a struct");
3235        };
3236        let mut offset = 1;
3237        let count = if aggregate.kind.needs_count() {
3238            let count = match state[offset].clone() {
3239                ScalarValue::UInt64(count) => count,
3240                _ => panic!("native histogram accumulator count state is not UInt64"),
3241            };
3242            offset += 1;
3243            count
3244        } else {
3245            None
3246        };
3247        let boolean = |index: usize| match state[index] {
3248            ScalarValue::Boolean(value) => value.unwrap_or_default(),
3249            _ => panic!("native histogram accumulator state component is not Boolean"),
3250        };
3251        LegacyState {
3252            histogram: read_histogram(&array, 0).unwrap(),
3253            count,
3254            dropped: boolean(offset),
3255            counter_reset_seen: boolean(offset + 1),
3256            not_counter_reset_seen: boolean(offset + 2),
3257        }
3258    }
3259
3260    /// Asserts one legacy frame histogram carries what one fold histogram carries, bit for bit.
3261    fn assert_frame_carries(actual: &NativeHistogram, expected: &FloatHistogram, case: &str) {
3262        assert_eq!(
3263            actual.count.to_bits(),
3264            expected.count.to_bits(),
3265            "{case}: count"
3266        );
3267        assert_eq!(
3268            actual.zero_count.to_bits(),
3269            expected.zero_count.to_bits(),
3270            "{case}: zero count"
3271        );
3272        assert_eq!(actual.sum.to_bits(), expected.sum.to_bits(), "{case}: sum");
3273        assert_eq!(actual.schema, expected.schema, "{case}: schema");
3274        assert_eq!(
3275            actual.zero_threshold.to_bits(),
3276            expected.zero_threshold.to_bits(),
3277            "{case}: zero threshold"
3278        );
3279        assert_eq!(
3280            actual
3281                .custom_values
3282                .iter()
3283                .map(|bound| bound.to_bits())
3284                .collect::<Vec<_>>(),
3285            expected
3286                .custom_values
3287                .iter()
3288                .map(|bound| bound.to_bits())
3289                .collect::<Vec<_>>(),
3290            "{case}: custom bounds"
3291        );
3292        for (side, spans, counts, buckets) in [
3293            (
3294                "positive",
3295                &actual.positive_spans,
3296                &actual.positive_buckets,
3297                &expected.positive,
3298            ),
3299            (
3300                "negative",
3301                &actual.negative_spans,
3302                &actual.negative_buckets,
3303                &expected.negative,
3304            ),
3305        ] {
3306            assert_eq!(
3307                expand_spans(spans),
3308                buckets.iter().map(|&(index, _)| index).collect::<Vec<_>>(),
3309                "{case}: {side} bucket indices"
3310            );
3311            assert_eq!(
3312                counts
3313                    .iter()
3314                    .map(|count| count.to_bits())
3315                    .collect::<Vec<_>>(),
3316                buckets
3317                    .iter()
3318                    .map(|&(_, count)| count.to_bits())
3319                    .collect::<Vec<_>>(),
3320                "{case}: {side} bucket counts"
3321            );
3322        }
3323    }
3324
3325    /// The absolute bucket indices a span list expands to, as the frame's reader expands them.
3326    fn expand_spans(spans: &[Span]) -> Vec<i32> {
3327        let mut indices = Vec::new();
3328        let mut cursor = 0;
3329        for (position, span) in spans.iter().enumerate() {
3330            cursor = if position == 0 {
3331                span.offset
3332            } else {
3333                cursor + span.offset
3334            };
3335            indices.extend(cursor..cursor + span.length);
3336            cursor += span.length;
3337        }
3338        indices
3339    }
3340
3341    fn histogram_range_input(values: Vec<Option<NativeHistogram>>) -> Vec<ColumnarValue> {
3342        let timestamps = Arc::new(TimestampMillisecondArray::from_iter(
3343            (0..values.len()).map(|idx| Some((idx as i64 + 1) * 1000)),
3344        ));
3345        let histograms = build_histogram_array(&values);
3346        let range = [(0, values.len() as u32)];
3347        let ts_range = RangeArray::from_ranges(timestamps, range).unwrap();
3348        let value_range = RangeArray::from_ranges(histograms, range).unwrap();
3349
3350        vec![
3351            ColumnarValue::Array(Arc::new(ts_range.into_dict())),
3352            ColumnarValue::Array(Arc::new(value_range.into_dict())),
3353        ]
3354    }
3355
3356    fn mixed_range_input(
3357        name: &str,
3358        floats: Vec<Option<f64>>,
3359        histograms: Vec<Option<NativeHistogram>>,
3360    ) -> Vec<ColumnarValue> {
3361        assert_eq!(floats.len(), histograms.len());
3362        let timestamps = Arc::new(TimestampMillisecondArray::from_iter(
3363            (0..floats.len()).map(|idx| Some((idx as i64 + 1) * 1000)),
3364        ));
3365        let floats = Arc::new(Float64Array::from(floats));
3366        let histograms = build_histogram_array(&histograms);
3367        let range = [(0, u32::try_from(floats.len()).unwrap())];
3368        vec![
3369            ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string()))),
3370            ColumnarValue::Array(Arc::new(
3371                RangeArray::from_ranges(timestamps, range)
3372                    .unwrap()
3373                    .into_dict(),
3374            )),
3375            ColumnarValue::Array(Arc::new(
3376                RangeArray::from_ranges(floats, range).unwrap().into_dict(),
3377            )),
3378            ColumnarValue::Array(Arc::new(
3379                RangeArray::from_ranges(histograms, range)
3380                    .unwrap()
3381                    .into_dict(),
3382            )),
3383        ]
3384    }
3385
3386    fn mixed_float_result(udf: ScalarUDF, input: Vec<ColumnarValue>) -> Option<f64> {
3387        let result = run_udf(udf, input, DataType::Float64);
3388        let result = extract_array(&result).unwrap();
3389        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
3390        result.is_valid(0).then(|| result.value(0))
3391    }
3392
3393    fn mixed_histogram_result(
3394        udf: ScalarUDF,
3395        input: Vec<ColumnarValue>,
3396    ) -> Option<NativeHistogram> {
3397        let result = run_udf(udf, input, native_histogram_arrow_type());
3398        let result = extract_array(&result).unwrap();
3399        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
3400        read_histogram(result, 0).unwrap()
3401    }
3402
3403    fn run_histogram_range_udf(
3404        udf: ScalarUDF,
3405        histograms: Vec<NativeHistogram>,
3406    ) -> NativeHistogram {
3407        run_histogram_udf(
3408            udf,
3409            histogram_range_input(histograms.into_iter().map(Some).collect()),
3410        )
3411    }
3412
3413    fn run_float_range_udf(
3414        udf: ScalarUDF,
3415        histograms: Vec<Option<NativeHistogram>>,
3416    ) -> Option<f64> {
3417        let result = run_udf(udf, histogram_range_input(histograms), DataType::Float64);
3418        let result = extract_array(&result).unwrap();
3419        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
3420        (!result.is_null(0)).then(|| result.value(0))
3421    }
3422
3423    fn run_extrapolated_histogram_udf(
3424        udf: ScalarUDF,
3425        histograms: Vec<NativeHistogram>,
3426    ) -> NativeHistogram {
3427        let range_length = histograms.len() as i64 * 1000;
3428        let timestamps = (0..histograms.len())
3429            .map(|idx| (idx as i64 + 1) * 1000)
3430            .collect();
3431        extrapolated_histogram_result(udf, timestamps, histograms, range_length, range_length)
3432            .unwrap()
3433    }
3434
3435    fn extrapolated_histogram_result(
3436        udf: ScalarUDF,
3437        timestamps: Vec<i64>,
3438        histograms: Vec<NativeHistogram>,
3439        range_end: i64,
3440        range_length: i64,
3441    ) -> Option<NativeHistogram> {
3442        assert_eq!(timestamps.len(), histograms.len());
3443        let range = [(0, u32::try_from(histograms.len()).unwrap())];
3444        let timestamps = Arc::new(TimestampMillisecondArray::from(timestamps));
3445        let histograms =
3446            build_histogram_array(&histograms.into_iter().map(Some).collect::<Vec<_>>());
3447        let mut input = vec![
3448            ColumnarValue::Array(Arc::new(
3449                RangeArray::from_ranges(timestamps, range)
3450                    .unwrap()
3451                    .into_dict(),
3452            )),
3453            ColumnarValue::Array(Arc::new(
3454                RangeArray::from_ranges(histograms, range)
3455                    .unwrap()
3456                    .into_dict(),
3457            )),
3458        ];
3459        input.push(ColumnarValue::Array(Arc::new(
3460            TimestampMillisecondArray::from(vec![range_end]),
3461        )));
3462        input.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![
3463            range_length,
3464        ]))));
3465        let result = run_udf(udf, input, native_histogram_arrow_type());
3466        let result = extract_array(&result).unwrap();
3467        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
3468        read_histogram(result, 0).unwrap()
3469    }
3470
3471    fn collected_warnings(collector: &PromqlAnnotationCollector) -> Vec<String> {
3472        let mut warnings = Vec::new();
3473        collector.append_to(&mut warnings, &mut Vec::new());
3474        warnings
3475    }
3476
3477    fn collected_infos(collector: &PromqlAnnotationCollector) -> Vec<String> {
3478        let mut infos = Vec::new();
3479        collector.append_to(&mut Vec::new(), &mut infos);
3480        infos
3481    }
3482
3483    #[test]
3484    fn quantile_and_fraction_report_nan_observations() {
3485        let histogram = sample_histogram(10.0, f64::NAN, vec![8.0]);
3486        let histogram_arg =
3487            || ColumnarValue::Array(build_histogram_array(&[Some(histogram.clone())]));
3488
3489        let quantile_collector = PromqlAnnotationCollector::default();
3490        let skewed = run_scalar_udf(
3491            NativeHistogramQuantile::scalar_udf_with_collector(Some(quantile_collector.clone())),
3492            vec![
3493                histogram_arg(),
3494                ColumnarValue::Scalar(ScalarValue::Float64(Some(0.5))),
3495            ],
3496        );
3497        assert!(skewed.is_finite());
3498        let nan = run_scalar_udf(
3499            NativeHistogramQuantile::scalar_udf_with_collector(Some(quantile_collector.clone())),
3500            vec![
3501                histogram_arg(),
3502                ColumnarValue::Scalar(ScalarValue::Float64(Some(0.9))),
3503            ],
3504        );
3505        assert!(nan.is_nan());
3506        let infos = collected_infos(&quantile_collector);
3507        assert!(
3508            infos
3509                .iter()
3510                .any(|info| info.ends_with("result is skewed higher"))
3511        );
3512        assert!(infos.iter().any(|info| info.ends_with("result is NaN")));
3513
3514        let fraction_collector = PromqlAnnotationCollector::default();
3515        assert_eq!(
3516            run_scalar_udf(
3517                NativeHistogramFraction::scalar_udf_with_collector(Some(
3518                    fraction_collector.clone(),
3519                )),
3520                vec![
3521                    histogram_arg(),
3522                    ColumnarValue::Scalar(ScalarValue::Float64(Some(f64::NEG_INFINITY))),
3523                    ColumnarValue::Scalar(ScalarValue::Float64(Some(f64::INFINITY))),
3524                ],
3525            ),
3526            0.8
3527        );
3528        assert_eq!(
3529            collected_infos(&fraction_collector),
3530            vec![
3531                "input to histogram_fraction has NaN observations, which are excluded from all fractions"
3532                    .to_string()
3533            ]
3534        );
3535    }
3536
3537    #[test]
3538    fn mixed_ranges_follow_prometheus_sample_type_semantics() {
3539        let first = sample_histogram(1.0, 1.0, vec![1.0]);
3540        let second = sample_histogram(3.0, 3.0, vec![3.0]);
3541        let collector = PromqlAnnotationCollector::default();
3542
3543        let mut rate = mixed_range_input(
3544            "rate",
3545            vec![Some(1.0), None, Some(3.0)],
3546            vec![None, Some(first.clone()), None],
3547        );
3548        rate.push(ColumnarValue::Array(Arc::new(
3549            TimestampMillisecondArray::from(vec![3000]),
3550        )));
3551        rate.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![3000]))));
3552        assert_eq!(
3553            mixed_float_result(MixedRange::float_udf(Some(collector.clone())), rate.clone()),
3554            None
3555        );
3556        assert_eq!(
3557            mixed_histogram_result(MixedRange::histogram_udf(Some(collector.clone())), rate),
3558            None
3559        );
3560        assert!(
3561            collected_warnings(&collector)
3562                .iter()
3563                .any(|warning| warning.contains("mix of float and native histogram"))
3564        );
3565
3566        let pure_rate = |floats, histograms| {
3567            let mut input = mixed_range_input("rate", floats, histograms);
3568            input.push(ColumnarValue::Array(Arc::new(
3569                TimestampMillisecondArray::from(vec![3000]),
3570            )));
3571            input.push(ColumnarValue::Array(Arc::new(Int64Array::from(vec![3000]))));
3572            input
3573        };
3574        let pure_float = pure_rate(
3575            vec![Some(1.0), Some(2.0), Some(3.0)],
3576            vec![None, None, None],
3577        );
3578        assert_eq!(
3579            mixed_float_result(MixedRange::float_udf(None), pure_float.clone()),
3580            Some(1.0)
3581        );
3582        assert_eq!(
3583            mixed_histogram_result(MixedRange::histogram_udf(None), pure_float),
3584            None
3585        );
3586        let pure_histogram = pure_rate(
3587            vec![None, None, None],
3588            vec![
3589                Some(sample_histogram(1.0, 1.0, vec![1.0])),
3590                Some(sample_histogram(2.0, 2.0, vec![2.0])),
3591                Some(sample_histogram(3.0, 3.0, vec![3.0])),
3592            ],
3593        );
3594        assert_eq!(
3595            mixed_float_result(MixedRange::float_udf(None), pure_histogram.clone()),
3596            None
3597        );
3598        assert_eq!(
3599            mixed_histogram_result(MixedRange::histogram_udf(None), pure_histogram)
3600                .unwrap()
3601                .count,
3602            1.0
3603        );
3604
3605        let idelta = mixed_range_input(
3606            "idelta",
3607            vec![Some(10.0), None, None],
3608            vec![None, Some(first.clone()), Some(second.clone())],
3609        );
3610        assert_eq!(
3611            mixed_float_result(MixedRange::float_udf(None), idelta.clone()),
3612            None
3613        );
3614        assert_eq!(
3615            mixed_histogram_result(MixedRange::histogram_udf(None), idelta)
3616                .unwrap()
3617                .count,
3618            2.0
3619        );
3620
3621        let alternating = || {
3622            mixed_range_input(
3623                "changes",
3624                vec![Some(1.0), None, None, Some(1.0)],
3625                vec![None, Some(first.clone()), Some(first.clone()), None],
3626            )
3627        };
3628        assert_eq!(
3629            mixed_float_result(MixedRange::float_udf(None), alternating()),
3630            Some(2.0)
3631        );
3632        let mut resets = alternating();
3633        resets[0] = ColumnarValue::Scalar(ScalarValue::Utf8(Some("resets".to_string())));
3634        assert_eq!(
3635            mixed_float_result(MixedRange::float_udf(None), resets),
3636            Some(2.0)
3637        );
3638
3639        for (name, expected) in [
3640            ("count_over_time", Some(4.0)),
3641            ("present_over_time", Some(1.0)),
3642            ("absent_over_time", None),
3643        ] {
3644            let mut input = alternating();
3645            input[0] = ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string())));
3646            assert_eq!(
3647                mixed_float_result(MixedRange::float_udf(None), input),
3648                expected,
3649                "{name}"
3650            );
3651        }
3652
3653        let last = mixed_range_input(
3654            "last_over_time",
3655            vec![None, Some(4.0)],
3656            vec![Some(first.clone()), None],
3657        );
3658        assert_eq!(
3659            mixed_float_result(MixedRange::float_udf(None), last.clone()),
3660            Some(4.0)
3661        );
3662        assert_eq!(
3663            mixed_histogram_result(MixedRange::histogram_udf(None), last),
3664            None
3665        );
3666
3667        let collector = PromqlAnnotationCollector::default();
3668        let histogram_only_min =
3669            mixed_range_input("min_over_time", vec![None], vec![Some(first.clone())]);
3670        assert_eq!(
3671            mixed_float_result(
3672                MixedRange::float_udf(Some(collector.clone())),
3673                histogram_only_min,
3674            ),
3675            None
3676        );
3677        assert!(collected_infos(&collector).is_empty());
3678
3679        let min = mixed_range_input(
3680            "min_over_time",
3681            vec![Some(3.0), None, Some(1.0)],
3682            vec![None, Some(first), None],
3683        );
3684        assert_eq!(
3685            mixed_float_result(MixedRange::float_udf(Some(collector.clone())), min),
3686            Some(1.0)
3687        );
3688        assert!(
3689            collected_infos(&collector)
3690                .iter()
3691                .any(|info| info.contains("ignored native histogram"))
3692        );
3693    }
3694
3695    #[test]
3696    fn count_sum_and_avg_read_struct() {
3697        let histograms = vec![Some(sample_histogram(6.0, 10.0, vec![2.0, 4.0]))];
3698        let array = build_histogram_array(&histograms);
3699        let input = vec![ColumnarValue::Array(array)];
3700
3701        let count = run_scalar_udf(NativeHistogramCount::scalar_udf(), input.clone());
3702        assert_eq!(count, 6.0);
3703
3704        let sum = run_scalar_udf(NativeHistogramSum::scalar_udf(), input.clone());
3705        assert_eq!(sum, 10.0);
3706
3707        let avg = run_scalar_udf(NativeHistogramAvg::scalar_udf(), input);
3708        assert_eq!(avg, 10.0 / 6.0);
3709    }
3710
3711    #[test]
3712    fn quantile_uses_bucket_bounds() {
3713        let histogram = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
3714        assert_eq!(histogram.quantile(0.0), 0.5);
3715        assert!(histogram.quantile(0.5) > 1.0);
3716        assert!(histogram.quantile(0.5) < 2.0);
3717    }
3718
3719    #[test]
3720    fn an_illegally_shaped_histogram_drops_its_position_rather_than_failing_the_query() {
3721        // The spans claim two buckets and the row carries one, which is a layout this crate cannot
3722        // read: it drops the position instead of failing the query. A single sample is enough to
3723        // drop it, because the position goes as a whole, with the warning below.
3724        let collector = PromqlAnnotationCollector::default();
3725        for kind in [
3726            NativeHistogramAggregateKind::Sum,
3727            NativeHistogramAggregateKind::Avg,
3728        ] {
3729            let mut aggregate =
3730                NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
3731            let mut invalid = sample_histogram(2.0, 3.0, vec![2.0]);
3732            invalid.positive_spans = vec![Span {
3733                offset: 0,
3734                length: 2,
3735            }];
3736
3737            aggregate.push_histogram(invalid, 1).expect(
3738                "a histogram this crate cannot read drops its position, it does not fail the query",
3739            );
3740
3741            assert!(aggregate.evidence.poisoned, "{}: poisoned", kind.name());
3742            assert!(
3743                aggregate.state_histogram().unwrap().is_none(),
3744                "{}: the position answers nothing",
3745                kind.name()
3746            );
3747            let warnings = collected_warnings(&collector);
3748            assert!(
3749                warnings.contains(&format!(
3750                    "{}: dropped native histogram aggregate with incompatible schemas",
3751                    kind.name()
3752                )),
3753                "{}: {warnings:?}",
3754                kind.name()
3755            );
3756        }
3757    }
3758
3759    #[test]
3760    fn sum_aggregate_exports_no_start_timestamp_of_its_own() {
3761        let mut histogram = sample_histogram(2.0, 3.0, vec![2.0]);
3762        histogram.start_timestamp = Some(1_234);
3763
3764        let mut accumulator =
3765            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
3766        accumulator.push_histogram(histogram, 1).unwrap();
3767
3768        // The answer is a derived histogram, not the sample that was pushed: it is read out of the
3769        // fold the way the native kernel reads one, and that clears the timestamp along with the
3770        // empty buckets it compacts away. The sample's own timestamp stays inside the fold.
3771        assert_eq!(
3772            accumulator
3773                .state_histogram()
3774                .unwrap()
3775                .unwrap()
3776                .start_timestamp,
3777            None,
3778            "a derived sum carries no start timestamp, not even from a single sample"
3779        );
3780    }
3781
3782    #[test]
3783    fn sum_aggregate_clears_the_start_timestamp_once_it_combines_two_samples() {
3784        let mut first = sample_histogram(2.0, 3.0, vec![2.0]);
3785        first.start_timestamp = Some(1_234);
3786        let mut second = sample_histogram(2.0, 3.0, vec![2.0]);
3787        second.start_timestamp = Some(5_678);
3788
3789        let mut accumulator =
3790            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
3791        accumulator.push_histogram(first, 1).unwrap();
3792        accumulator.push_histogram(second, 1).unwrap();
3793
3794        assert_eq!(
3795            accumulator
3796                .state_histogram()
3797                .unwrap()
3798                .unwrap()
3799                .start_timestamp,
3800            None,
3801            "a derived sum carries no start timestamp of its own"
3802        );
3803    }
3804
3805    #[test]
3806    fn comparison_observes_explicit_sparse_zero_buckets() {
3807        let mut left = sample_histogram(1.0, 1.0, vec![1.0, 0.0]);
3808        left.reset_hint = COUNTER_RESET_HINT;
3809        left.start_timestamp = Some(1000);
3810        let mut right = sample_histogram(1.0, 1.0, vec![1.0]);
3811        right.reset_hint = NOT_COUNTER_RESET_HINT;
3812        right.start_timestamp = Some(2000);
3813
3814        let result = run_udf(
3815            NativeHistogramEq::scalar_udf(),
3816            vec![
3817                ColumnarValue::Array(build_histogram_array(&[Some(left)])),
3818                ColumnarValue::Array(build_histogram_array(&[Some(right)])),
3819            ],
3820            DataType::Boolean,
3821        );
3822        let values = extract_array(&result).unwrap();
3823        let values = values.as_any().downcast_ref::<BooleanArray>().unwrap();
3824        assert!(!values.value(0));
3825    }
3826
3827    /// The one sample the two tests below fold: one bucket holding observations and one explicit
3828    /// empty bucket beside it.
3829    ///
3830    /// The answer keeps the bucket with observations and drops the empty one, which is a difference
3831    /// [`NativeHistogramEq`] can tell apart from the input.
3832    fn one_explicit_zero_bucket() -> NativeHistogram {
3833        sample_histogram(1.0, 1.0, vec![1.0, 0.0])
3834    }
3835
3836    /// A `sum` or `avg` over one sample answers `[1]` where the sample carried `[1, 0]`.
3837    ///
3838    /// The comparison change is intended. The answer is the fold's, not the sample's:
3839    /// [`finished_histogram`] compacts the empty bucket away, and the native `Aggregate` node reads
3840    /// its answers through that same function, so both paths answer `[1]` -- a one-sample group
3841    /// included. `promql_eq` tells an explicit zero bucket from an absent one (see
3842    /// [`comparison_observes_explicit_sparse_zero_buckets`]), so `sum(h)` is no longer equal to the
3843    /// single sample `h` it folded.
3844    #[test]
3845    fn sum_and_avg_compact_a_single_samples_explicit_zero_bucket() {
3846        for kind in [
3847            NativeHistogramAggregateKind::Sum,
3848            NativeHistogramAggregateKind::Avg,
3849        ] {
3850            let mut aggregate = NativeHistogramAggregateAccumulator::new(kind, None);
3851            aggregate
3852                .push_histogram(one_explicit_zero_bucket(), 1)
3853                .unwrap();
3854
3855            // The answer the state hands over is where the bucket list is decided.
3856            let answered = aggregate
3857                .state_histogram()
3858                .unwrap()
3859                .expect("a single sample answers");
3860            assert_eq!(
3861                answered.positive_buckets,
3862                vec![1.0],
3863                "{}: the empty bucket is compacted away",
3864                kind.name()
3865            );
3866            assert_eq!(answered.count, 1.0, "{}: the count", kind.name());
3867            assert_eq!(answered.sum, 1.0, "{}: the sum", kind.name());
3868
3869            let evaluated = evaluated_histogram(&mut aggregate);
3870            assert_eq!(
3871                evaluated.positive_buckets,
3872                vec![1.0],
3873                "{}: reading the answer back keeps the empty bucket out",
3874                kind.name()
3875            );
3876        }
3877    }
3878
3879    /// A partial state round trip answers what the direct evaluation answers: `[1]`.
3880    ///
3881    /// The exported state carries the fold's answer, which has already lost the explicit zero
3882    /// bucket, so merging it into an empty accumulator cannot put the bucket back: a state boundary
3883    /// does not restore what the fold compacted away. The comparison change is the direct
3884    /// evaluation's -- `promql_eq` tells `[1]` from the input's `[1, 0]` -- and it survives the
3885    /// state the same way.
3886    #[test]
3887    fn a_partial_state_round_trip_answers_the_compacted_explicit_zero_bucket() {
3888        for kind in [
3889            NativeHistogramAggregateKind::Sum,
3890            NativeHistogramAggregateKind::Avg,
3891        ] {
3892            let mut direct = NativeHistogramAggregateAccumulator::new(kind, None);
3893            direct
3894                .push_histogram(one_explicit_zero_bucket(), 1)
3895                .unwrap();
3896            let evaluated = evaluated_histogram(&mut direct);
3897
3898            let state = state_arrays(&mut direct);
3899            let mut merged = NativeHistogramAggregateAccumulator::new(kind, None);
3900            merged.merge_batch(&state).unwrap();
3901            let round_tripped = evaluated_histogram(&mut merged);
3902
3903            assert_eq!(
3904                round_tripped.positive_buckets,
3905                vec![1.0],
3906                "{}: the round trip keeps the empty bucket out",
3907                kind.name()
3908            );
3909            assert_eq!(
3910                round_tripped.positive_buckets,
3911                evaluated.positive_buckets,
3912                "{}: the round trip answers the direct buckets",
3913                kind.name()
3914            );
3915            assert_eq!(
3916                round_tripped.count,
3917                evaluated.count,
3918                "{}: the round trip answers the direct count",
3919                kind.name()
3920            );
3921            assert_eq!(
3922                round_tripped.sum,
3923                evaluated.sum,
3924                "{}: the round trip answers the direct sum",
3925                kind.name()
3926            );
3927        }
3928    }
3929
3930    #[test]
3931    fn unary_minus_returns_gauge_histogram() {
3932        let result = run_histogram_udf(
3933            NativeHistogramNeg::scalar_udf(),
3934            vec![ColumnarValue::Array(build_histogram_array(&[Some(
3935                sample_histogram(2.0, 3.0, vec![2.0]),
3936            )]))],
3937        );
3938
3939        assert_eq!(result.reset_hint, GAUGE_RESET_HINT);
3940        assert_eq!(result.count, -2.0);
3941        assert_eq!(result.sum, -3.0);
3942        assert_eq!(result.positive_buckets, vec![-2.0]);
3943    }
3944
3945    #[test]
3946    fn histogram_over_time_functions_preserve_reset_hints() {
3947        let mut first = sample_histogram(1.0, 1.0, vec![1.0]);
3948        first.reset_hint = COUNTER_RESET_HINT;
3949        let mut second = sample_histogram(2.0, 2.0, vec![2.0]);
3950        second.reset_hint = COUNTER_RESET_HINT;
3951
3952        let result = run_histogram_range_udf(
3953            NativeHistogramSumOverTime::scalar_udf(),
3954            vec![first.clone(), second.clone()],
3955        );
3956        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3957        assert_eq!(result.count, 3.0);
3958        assert_eq!(result.sum, 3.0);
3959        assert_eq!(result.positive_buckets, vec![3.0]);
3960
3961        let result = run_histogram_range_udf(
3962            NativeHistogramAvgOverTime::scalar_udf(),
3963            vec![first.clone(), second.clone()],
3964        );
3965        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3966        assert_eq!(result.count, 1.5);
3967        assert_eq!(result.sum, 1.5);
3968        assert_eq!(result.positive_buckets, vec![1.5]);
3969
3970        let result = run_histogram_range_udf(
3971            NativeHistogramLastOverTime::scalar_udf(),
3972            vec![first, second],
3973        );
3974        assert_eq!(result.reset_hint, COUNTER_RESET_HINT);
3975        assert_eq!(result.count, 2.0);
3976        assert_eq!(result.sum, 2.0);
3977        assert_eq!(result.positive_buckets, vec![2.0]);
3978    }
3979
3980    #[test]
3981    fn histogram_averages_avoid_sum_overflow() {
3982        let large = sample_histogram(1.0e308, 1.0e308, vec![1.0e308]);
3983
3984        let range_average = run_histogram_range_udf(
3985            NativeHistogramAvgOverTime::scalar_udf(),
3986            vec![large.clone(), large.clone()],
3987        );
3988        assert_eq!(range_average.count, 1.0e308);
3989        assert_eq!(range_average.sum, 1.0e308);
3990        assert_eq!(range_average.positive_buckets, vec![1.0e308]);
3991
3992        let mut aggregate =
3993            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
3994        aggregate.push_histogram(large.clone(), 1).unwrap();
3995        aggregate.push_histogram(large, 1).unwrap();
3996        let aggregate_average = evaluated_histogram(&mut aggregate);
3997        assert_eq!(aggregate_average.count, 1.0e308);
3998        assert_eq!(aggregate_average.sum, 1.0e308);
3999        assert_eq!(aggregate_average.positive_buckets, vec![1.0e308]);
4000    }
4001
4002    #[test]
4003    fn histogram_average_partial_states_are_weighted() {
4004        let mut first =
4005            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4006        first
4007            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4008            .unwrap();
4009        first
4010            .push_histogram(sample_histogram(3.0, 3.0, vec![3.0]), 1)
4011            .unwrap();
4012        let first_state = first
4013            .state()
4014            .unwrap()
4015            .into_iter()
4016            .map(|value| value.to_array_of_size(1).unwrap())
4017            .collect::<Vec<_>>();
4018
4019        let mut second =
4020            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4021        second
4022            .push_histogram(sample_histogram(8.0, 8.0, vec![8.0]), 1)
4023            .unwrap();
4024        let second_state = second
4025            .state()
4026            .unwrap()
4027            .into_iter()
4028            .map(|value| value.to_array_of_size(1).unwrap())
4029            .collect::<Vec<_>>();
4030
4031        let mut merged =
4032            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4033        merged.merge_batch(&first_state).unwrap();
4034        merged.merge_batch(&second_state).unwrap();
4035        let average = evaluated_histogram(&mut merged);
4036        assert_eq!(average.count, 4.0);
4037        assert_eq!(average.sum, 4.0);
4038        assert_eq!(average.positive_buckets, vec![4.0]);
4039    }
4040
4041    #[test]
4042    fn histogram_average_rejects_sample_count_overflow() {
4043        let mut aggregate =
4044            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Avg, None);
4045        aggregate
4046            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4047            .unwrap();
4048        aggregate.count = u64::MAX;
4049
4050        let error = aggregate
4051            .push_histogram(sample_histogram(1.0, 1.0, vec![1.0]), 1)
4052            .unwrap_err();
4053        assert!(error.to_string().contains("sample count overflow"));
4054    }
4055
4056    /// The legacy frame and the canonical fold answer the same thing, bit for bit.
4057    ///
4058    /// The same inputs are folded twice: once through the legacy accumulator, whose state frame is
4059    /// the Arrow partial a distributed aggregate hands over, and once through the kernel's own
4060    /// [`HistogramAccumulator`], whose `payload` is the canonical partial state. The frame declares
4061    /// one native histogram, an average's count and three Booleans, so what it can carry is the
4062    /// fold's *answer* -- `finished_histogram`, the running sum with its compensation folded in or
4063    /// the average's mean -- and that is what it is compared on. The count and the evidence are
4064    /// compared against the payload, which is where they come from, and a state boundary is then
4065    /// expected to keep the answer: merging an exported state into an empty accumulator answers
4066    /// what the accumulator that exported it answered.
4067    #[test]
4068    fn legacy_state_carries_the_canonical_histogram_fold() {
4069        for (case, inputs) in aggregate_agreement_cases() {
4070            let samples = inputs
4071                .iter()
4072                .map(|histogram| float_histogram(histogram).unwrap())
4073                .collect::<Vec<_>>();
4074            for kind in [
4075                NativeHistogramAggregateKind::Sum,
4076                NativeHistogramAggregateKind::Avg,
4077            ] {
4078                let op = match kind {
4079                    NativeHistogramAggregateKind::Sum => AggregateOp::Sum,
4080                    NativeHistogramAggregateKind::Avg => AggregateOp::Avg,
4081                };
4082                let mut legacy = NativeHistogramAggregateAccumulator::new(kind, None);
4083                for histogram in &inputs {
4084                    legacy.push_histogram(histogram.clone(), 1).unwrap();
4085                }
4086                let frame = legacy_state(&mut legacy);
4087                let fold = canonical_fold(op, &samples);
4088                let StatePayload::Histogram(payload) = fold.payload(op).unwrap() else {
4089                    panic!("{case}: the canonical fold exported a non-histogram payload");
4090                };
4091
4092                // The three Booleans of the frame are the payload's own evidence.
4093                assert_eq!(frame.dropped, payload.poisoned, "{case}: poisoned");
4094                assert_eq!(
4095                    frame.counter_reset_seen, payload.counter_reset_seen,
4096                    "{case}: counter reset seen"
4097                );
4098                assert_eq!(
4099                    frame.not_counter_reset_seen, payload.not_counter_reset_seen,
4100                    "{case}: not-counter-reset seen"
4101                );
4102                assert_eq!(
4103                    legacy.evidence.poisoned, payload.poisoned,
4104                    "{case}: poisoned evidence"
4105                );
4106                assert_eq!(
4107                    legacy.evidence.incompatible_layout, payload.incompatible_layout,
4108                    "{case}: incompatible layout"
4109                );
4110
4111                // The count the frame declares is the samples it folded, as a `UInt64` -- except
4112                // on a dropped position, whose count goes with its answer.
4113                if kind.needs_count() {
4114                    let folded = if frame.dropped {
4115                        0
4116                    } else {
4117                        inputs.len() as u64
4118                    };
4119                    assert_eq!(frame.count, Some(folded), "{case}: count");
4120                    assert_eq!(
4121                        frame.count.map(|count| count as f64),
4122                        Some(payload.count),
4123                        "{case}: payload count"
4124                    );
4125                } else {
4126                    assert_eq!(frame.count, None, "{case}: a sum declares no count");
4127                }
4128
4129                // The histogram component is the fold's answer, bit for bit.
4130                let answer = finished_histogram(op, &fold).unwrap();
4131                match (&frame.histogram, &answer) {
4132                    (Some(actual), Some(expected)) => assert_frame_carries(actual, expected, case),
4133                    (None, None) => {}
4134                    _ => panic!(
4135                        "{case}: the frame and the fold disagree on whether the point answers"
4136                    ),
4137                }
4138
4139                // A state boundary keeps that answer.
4140                let mut merged = NativeHistogramAggregateAccumulator::new(kind, None);
4141                merged.merge_batch(&state_arrays(&mut legacy)).unwrap();
4142                let merged = evaluated(&mut merged);
4143                let direct = evaluated(&mut legacy);
4144                match (merged, direct) {
4145                    (Some(merged), Some(direct)) => assert_frame_carries(
4146                        &merged,
4147                        &float_histogram(&direct).unwrap(),
4148                        &format!("{case}, merged"),
4149                    ),
4150                    (None, None) => {}
4151                    _ => panic!("{case}: a merged state answers where its source did not"),
4152                }
4153            }
4154        }
4155    }
4156
4157    /// The compensated sum's residual belongs to the state, not to one partition's fold.
4158    ///
4159    /// `1e16 + 1 - 1e16` answers `1` only because the Kahan compensation carries what the running sum
4160    /// lost. The legacy frame has no compensation component, so it carries the answer instead: a
4161    /// merge of the exported state answers `1` too, which a frame exporting the running sum could
4162    /// not do.
4163    ///
4164    /// The guarantee stops at samples already folded into one position. Splitting those same samples
4165    /// across two partitions loses the residual, because exporting folds the compensation back into
4166    /// a single `f64`: `[1e16, 1]` exports `1e16`, and merging it with `[-1e16]` answers `0`.
4167    #[test]
4168    fn legacy_state_keeps_the_compensated_sum() {
4169        let mut aggregate =
4170            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
4171        for histogram in [
4172            sample_histogram(1.0, 1.0e16, vec![1.0e16]),
4173            sample_histogram(1.0, 1.0, vec![1.0]),
4174            sample_histogram(1.0, -1.0e16, vec![-1.0e16]),
4175        ] {
4176            aggregate.push_histogram(histogram, 1).unwrap();
4177        }
4178        let direct = evaluated_histogram(&mut aggregate);
4179        assert_eq!(direct.count, 3.0);
4180        assert_eq!(direct.sum, 1.0);
4181        assert_eq!(direct.positive_buckets, vec![1.0]);
4182
4183        let state = state_arrays(&mut aggregate);
4184        let mut merged =
4185            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
4186        merged.merge_batch(&state).unwrap();
4187        let merged = evaluated_histogram(&mut merged);
4188        assert_eq!(merged.count, 3.0);
4189        assert_eq!(merged.sum, 1.0);
4190        assert_eq!(merged.positive_buckets, vec![1.0]);
4191    }
4192
4193    /// The inputs the two accumulators are compared on: two exponential resolutions, two custom
4194    /// layouts with different bounds, exponential meeting custom, and a compensated sum whose
4195    /// residual lives in the compensation alone.
4196    fn aggregate_agreement_cases() -> Vec<(&'static str, Vec<NativeHistogram>)> {
4197        let mut coarse = sample_histogram(2.0, 3.0, vec![1.0, 1.0]);
4198        coarse.schema = 2;
4199        coarse.reset_hint = NOT_COUNTER_RESET_HINT;
4200        let mut fine = sample_histogram(1.0, 1.0, vec![1.0]);
4201        fine.reset_hint = COUNTER_RESET_HINT;
4202
4203        let mut custom = sample_histogram(2.0, 3.0, vec![1.0, 1.0, 0.0]);
4204        custom.schema = CUSTOM_BUCKETS_SCHEMA;
4205        custom.custom_values = vec![1.0, 2.0, 3.0];
4206        let mut narrower = sample_histogram(2.0, 5.0, vec![1.0, 1.0]);
4207        narrower.schema = CUSTOM_BUCKETS_SCHEMA;
4208        narrower.custom_values = vec![2.0, 3.0];
4209
4210        let mut custom_only = sample_histogram(1.0, 1.0, vec![1.0]);
4211        custom_only.schema = CUSTOM_BUCKETS_SCHEMA;
4212        custom_only.custom_values = vec![1.0];
4213
4214        vec![
4215            (
4216                "two exponential resolutions",
4217                vec![fine, coarse.clone(), coarse],
4218            ),
4219            (
4220                "custom bounds reconciled",
4221                vec![custom, narrower.clone(), narrower],
4222            ),
4223            (
4224                "exponential meeting custom",
4225                vec![
4226                    sample_histogram(1.0, 1.0, vec![1.0]),
4227                    custom_only,
4228                    sample_histogram(1.0, 1.0, vec![1.0, 1.0]),
4229                ],
4230            ),
4231            (
4232                "compensated sum",
4233                vec![
4234                    sample_histogram(1.0, 1.0e16, vec![1.0e16]),
4235                    sample_histogram(1.0, 1.0, vec![1.0]),
4236                    sample_histogram(1.0, -1.0e16, vec![-1.0e16]),
4237                ],
4238            ),
4239        ]
4240    }
4241
4242    /// One case's inputs folded through the kernel's own accumulator, as `fold_histogram` folds
4243    /// them: reset evidence per sample, and a layout disagreement poisoning the position instead of
4244    /// failing it.
4245    fn canonical_fold(op: AggregateOp, samples: &[FloatHistogram]) -> HistogramAccumulator {
4246        let mut fold = HistogramAccumulator::from_sample(&samples[0]);
4247        for sample in samples {
4248            fold.evidence.counter_reset_seen |= sample.reset_hint == CounterResetHint::CounterReset;
4249            fold.evidence.not_counter_reset_seen |=
4250                sample.reset_hint == CounterResetHint::NotCounterReset;
4251        }
4252        for sample in &samples[1..] {
4253            if fold.evidence.poisoned {
4254                break;
4255            }
4256            if fold.uses_custom_buckets() != sample.uses_custom_buckets() {
4257                fold.poison();
4258                break;
4259            }
4260            match op {
4261                AggregateOp::Sum => fold.fold_sum(sample).unwrap(),
4262                AggregateOp::Avg => fold.fold_avg(sample).unwrap(),
4263                op => unreachable!("{op:?} does not fold a histogram payload"),
4264            }
4265        }
4266        fold
4267    }
4268
4269    #[test]
4270    fn presence_only_range_functions_preserve_null_semantics() {
4271        let first = sample_histogram(1.0, 1.0, vec![1.0]);
4272        let second = sample_histogram(2.0, 2.0, vec![2.0]);
4273        assert_eq!(
4274            run_float_range_udf(
4275                NativeHistogramCountOverTime::scalar_udf(),
4276                vec![Some(first.clone()), Some(second.clone())],
4277            ),
4278            Some(2.0)
4279        );
4280        assert_eq!(
4281            run_float_range_udf(
4282                NativeHistogramPresentOverTime::scalar_udf(),
4283                vec![Some(first.clone()), Some(second.clone())],
4284            ),
4285            Some(1.0)
4286        );
4287        assert_eq!(
4288            run_float_range_udf(
4289                NativeHistogramCountOverTime::scalar_udf(),
4290                vec![None, Some(second.clone())],
4291            ),
4292            None
4293        );
4294
4295        let result = run_udf(
4296            NativeHistogramLastOverTime::scalar_udf(),
4297            histogram_range_input(vec![None, Some(second)]),
4298            native_histogram_arrow_type(),
4299        );
4300        let result = extract_array(&result).unwrap();
4301        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
4302        assert!(result.is_null(0));
4303    }
4304
4305    #[test]
4306    fn resets_counts_histogram_flavor_transitions() {
4307        let mut counter = sample_histogram(1.0, 1.0, vec![1.0]);
4308        counter.reset_hint = NOT_COUNTER_RESET_HINT;
4309        let mut gauge = sample_histogram(2.0, 2.0, vec![2.0]);
4310        gauge.reset_hint = GAUGE_RESET_HINT;
4311        assert_eq!(
4312            run_float_range_udf(
4313                NativeHistogramResets::scalar_udf(),
4314                vec![Some(counter), Some(gauge)],
4315            ),
4316            Some(1.0)
4317        );
4318
4319        let mut gauge = sample_histogram(1.0, 1.0, vec![1.0]);
4320        gauge.reset_hint = GAUGE_RESET_HINT;
4321        let mut counter = sample_histogram(2.0, 2.0, vec![2.0]);
4322        counter.reset_hint = NOT_COUNTER_RESET_HINT;
4323        assert_eq!(
4324            run_float_range_udf(
4325                NativeHistogramResets::scalar_udf(),
4326                vec![Some(gauge), Some(counter)],
4327            ),
4328            Some(1.0)
4329        );
4330    }
4331
4332    #[test]
4333    fn wrong_flavor_functions_record_warnings() {
4334        let mut gauge_first = sample_histogram(1.0, 1.0, vec![1.0]);
4335        gauge_first.reset_hint = GAUGE_RESET_HINT;
4336        let mut gauge_last = sample_histogram(2.0, 2.0, vec![2.0]);
4337        gauge_last.reset_hint = GAUGE_RESET_HINT;
4338        let mut counter_first = sample_histogram(1.0, 1.0, vec![1.0]);
4339        counter_first.reset_hint = NOT_COUNTER_RESET_HINT;
4340        let mut counter_last = sample_histogram(2.0, 2.0, vec![2.0]);
4341        counter_last.reset_hint = NOT_COUNTER_RESET_HINT;
4342        let collector = PromqlAnnotationCollector::default();
4343
4344        run_extrapolated_histogram_udf(
4345            NativeHistogramRate::scalar_udf_with_collector(Some(collector.clone())),
4346            vec![gauge_first.clone(), gauge_last.clone()],
4347        );
4348        run_extrapolated_histogram_udf(
4349            NativeHistogramDelta::scalar_udf_with_collector(Some(collector.clone())),
4350            vec![counter_first.clone(), counter_last.clone()],
4351        );
4352        run_histogram_range_udf(
4353            NativeHistogramIRate::scalar_udf_with_collector(Some(collector.clone())),
4354            vec![gauge_first, gauge_last],
4355        );
4356        run_histogram_range_udf(
4357            NativeHistogramIDelta::scalar_udf_with_collector(Some(collector.clone())),
4358            vec![counter_first, counter_last],
4359        );
4360
4361        let warnings = collected_warnings(&collector);
4362        for expected in [
4363            format!(
4364                "{}: native histogram input should be a counter histogram",
4365                NativeHistogramRate::name()
4366            ),
4367            format!(
4368                "{}: native histogram input should be a gauge histogram",
4369                NativeHistogramDelta::name()
4370            ),
4371            format!(
4372                "{}: native histogram input should be a counter histogram",
4373                NativeHistogramIRate::name()
4374            ),
4375            format!(
4376                "{}: native histogram input should be a gauge histogram",
4377                NativeHistogramIDelta::name()
4378            ),
4379        ] {
4380            assert!(warnings.contains(&expected), "missing warning: {expected}");
4381        }
4382    }
4383
4384    #[test]
4385    fn subtraction_reports_a_reset_hint_contradiction_only_between_compatible_histograms() {
4386        // Prometheus reports a pair whose bucket layouts cannot be combined before it looks at the
4387        // reset hints, so the collision warning belongs to the pairs the operation can answer.
4388        for incompatible in [false, true] {
4389            let mut left = sample_histogram(2.0, 2.0, vec![2.0]);
4390            left.reset_hint = COUNTER_RESET_HINT;
4391            let mut right = sample_histogram(1.0, 1.0, vec![1.0]);
4392            right.reset_hint = NOT_COUNTER_RESET_HINT;
4393            if incompatible {
4394                right.schema = CUSTOM_BUCKETS_SCHEMA;
4395                right.custom_values = vec![1.0];
4396            }
4397            let collector = PromqlAnnotationCollector::default();
4398
4399            run_udf(
4400                NativeHistogramSub::scalar_udf_with_collector(Some(collector.clone())),
4401                vec![
4402                    ColumnarValue::Array(build_histogram_array(&[Some(left)])),
4403                    ColumnarValue::Array(build_histogram_array(&[Some(right)])),
4404                ],
4405                native_histogram_arrow_type(),
4406            );
4407
4408            let warnings = collected_warnings(&collector);
4409            let name = NativeHistogramSub::name();
4410            assert_eq!(
4411                warnings.contains(&format!(
4412                    "{name}: native histogram counter reset hints contradict"
4413                )),
4414                !incompatible,
4415                "{incompatible}: {warnings:?}"
4416            );
4417            if incompatible {
4418                assert!(
4419                    warnings.contains(&format!(
4420                        "{name}: dropped native histogram sample with incompatible schemas"
4421                    )),
4422                    "{warnings:?}"
4423                );
4424            }
4425        }
4426    }
4427
4428    #[test]
4429    fn counter_reset_hint_history_survives_folds_and_state_merges() {
4430        let mut reset = sample_histogram(1.0, 1.0, vec![1.0]);
4431        reset.reset_hint = COUNTER_RESET_HINT;
4432        let mut unknown = sample_histogram(2.0, 2.0, vec![2.0]);
4433        unknown.reset_hint = UNKNOWN_COUNTER_RESET_HINT;
4434        let mut not_reset = sample_histogram(3.0, 3.0, vec![3.0]);
4435        not_reset.reset_hint = NOT_COUNTER_RESET_HINT;
4436
4437        let range_collector = PromqlAnnotationCollector::default();
4438        assert!(
4439            range_fold_histograms(
4440                vec![reset.clone(), unknown.clone(), not_reset.clone()],
4441                NativeHistogramAggregateKind::Sum,
4442                NativeHistogramSumOverTime::name(),
4443                &Some(range_collector.clone()),
4444            )
4445            .is_some()
4446        );
4447        assert!(collected_warnings(&range_collector).contains(&format!(
4448            "{}: native histogram counter reset hints contradict",
4449            NativeHistogramSumOverTime::name()
4450        )));
4451
4452        for kind in [
4453            NativeHistogramAggregateKind::Sum,
4454            NativeHistogramAggregateKind::Avg,
4455        ] {
4456            let mut first_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4457            first_partial.push_histogram(reset.clone(), 1).unwrap();
4458            first_partial.push_histogram(unknown.clone(), 1).unwrap();
4459            let first_states = first_partial
4460                .state()
4461                .unwrap()
4462                .into_iter()
4463                .map(|value| value.to_array_of_size(1).unwrap())
4464                .collect::<Vec<_>>();
4465
4466            let mut second_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4467            second_partial.push_histogram(not_reset.clone(), 1).unwrap();
4468            let second_states = second_partial
4469                .state()
4470                .unwrap()
4471                .into_iter()
4472                .map(|value| value.to_array_of_size(1).unwrap())
4473                .collect::<Vec<_>>();
4474
4475            let collector = PromqlAnnotationCollector::default();
4476            let mut merged =
4477                NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4478            merged.merge_batch(&first_states).unwrap();
4479            merged.merge_batch(&second_states).unwrap();
4480            assert!(collected_warnings(&collector).contains(&format!(
4481                "{}: native histogram counter reset hints contradict",
4482                kind.name()
4483            )));
4484        }
4485    }
4486
4487    #[test]
4488    fn incompatible_aggregates_do_not_hide_reset_hint_contradictions() {
4489        let mut reset = sample_histogram(1.0, 1.0, vec![1.0]);
4490        reset.reset_hint = COUNTER_RESET_HINT;
4491        let mut incompatible_reset = sample_histogram(2.0, 2.0, vec![2.0]);
4492        incompatible_reset.schema = CUSTOM_BUCKETS_SCHEMA;
4493        incompatible_reset.custom_values = vec![1.0];
4494        incompatible_reset.reset_hint = COUNTER_RESET_HINT;
4495        let mut not_reset = sample_histogram(3.0, 3.0, vec![3.0]);
4496        not_reset.reset_hint = NOT_COUNTER_RESET_HINT;
4497
4498        for kind in [
4499            NativeHistogramAggregateKind::Sum,
4500            NativeHistogramAggregateKind::Avg,
4501        ] {
4502            for histograms in [
4503                [reset.clone(), incompatible_reset.clone(), not_reset.clone()],
4504                [reset.clone(), not_reset.clone(), incompatible_reset.clone()],
4505            ] {
4506                let collector = PromqlAnnotationCollector::default();
4507                let mut aggregate =
4508                    NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4509                for histogram in histograms {
4510                    aggregate.push_histogram(histogram, 1).unwrap();
4511                }
4512
4513                assert!(aggregate.evidence.poisoned);
4514                let warnings = collected_warnings(&collector);
4515                assert!(warnings.contains(&format!(
4516                    "{}: dropped native histogram aggregate with incompatible schemas",
4517                    kind.name()
4518                )));
4519                assert!(warnings.contains(&format!(
4520                    "{}: native histogram counter reset hints contradict",
4521                    kind.name()
4522                )));
4523            }
4524
4525            let mut dropped_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4526            dropped_partial.push_histogram(reset.clone(), 1).unwrap();
4527            dropped_partial
4528                .push_histogram(incompatible_reset.clone(), 1)
4529                .unwrap();
4530            let dropped_states = dropped_partial
4531                .state()
4532                .unwrap()
4533                .into_iter()
4534                .map(|value| value.to_array_of_size(1).unwrap())
4535                .collect::<Vec<_>>();
4536
4537            let mut opposing_partial = NativeHistogramAggregateAccumulator::new(kind, None);
4538            opposing_partial
4539                .push_histogram(not_reset.clone(), 1)
4540                .unwrap();
4541            let opposing_states = opposing_partial
4542                .state()
4543                .unwrap()
4544                .into_iter()
4545                .map(|value| value.to_array_of_size(1).unwrap())
4546                .collect::<Vec<_>>();
4547
4548            for (first, second) in [
4549                (&dropped_states, &opposing_states),
4550                (&opposing_states, &dropped_states),
4551            ] {
4552                let collector = PromqlAnnotationCollector::default();
4553                let mut merged =
4554                    NativeHistogramAggregateAccumulator::new(kind, Some(collector.clone()));
4555                merged.merge_batch(first).unwrap();
4556                merged.merge_batch(second).unwrap();
4557
4558                assert!(merged.evidence.poisoned);
4559                assert!(collected_warnings(&collector).contains(&format!(
4560                    "{}: native histogram counter reset hints contradict",
4561                    kind.name()
4562                )));
4563            }
4564        }
4565
4566        for (kind, name) in [
4567            (
4568                NativeHistogramAggregateKind::Sum,
4569                NativeHistogramSumOverTime::name(),
4570            ),
4571            (
4572                NativeHistogramAggregateKind::Avg,
4573                NativeHistogramAvgOverTime::name(),
4574            ),
4575        ] {
4576            let collector = PromqlAnnotationCollector::default();
4577            assert!(
4578                range_fold_histograms(
4579                    vec![reset.clone(), incompatible_reset.clone(), not_reset.clone()],
4580                    kind,
4581                    name,
4582                    &Some(collector.clone()),
4583                )
4584                .is_none()
4585            );
4586            let warnings = collected_warnings(&collector);
4587            assert!(warnings.contains(&format!(
4588                "{name}: dropped native histogram range with incompatible schemas"
4589            )));
4590            assert!(warnings.contains(&format!(
4591                "{name}: native histogram counter reset hints contradict"
4592            )));
4593        }
4594    }
4595
4596    #[test]
4597    fn histogram_aggregate_accumulator_accounts_for_heap_allocations() {
4598        let histogram = sample_histogram(3.0, 3.0, vec![1.0, 2.0]);
4599        let sample = float_histogram(&histogram).unwrap();
4600        let mut accumulator =
4601            NativeHistogramAggregateAccumulator::new(NativeHistogramAggregateKind::Sum, None);
4602        let empty_size = accumulator.size();
4603
4604        accumulator.push_histogram(histogram, 1).unwrap();
4605
4606        // The fold keeps the sample's buckets and a compensation carrying the same layout, so at
4607        // least the sample's own heap is counted beyond the accumulator struct that holds it.
4608        assert!(sample.heap_bytes() > 0);
4609        assert!(accumulator.size() >= empty_size + sample.heap_bytes());
4610    }
4611
4612    #[test]
4613    fn absent_over_time_handles_histogram_ranges() {
4614        let values = vec![Some(sample_histogram(1.0, 1.0, vec![1.0]))];
4615        let timestamps = Arc::new(TimestampMillisecondArray::from_iter([Some(1000)]));
4616        let histograms = build_histogram_array(&values);
4617        let ranges = [(0, 1), (0, 0)];
4618        let ts_range = RangeArray::from_ranges(timestamps, ranges).unwrap();
4619        let value_range = RangeArray::from_ranges(histograms, ranges).unwrap();
4620
4621        let result = run_udf(
4622            NativeHistogramAbsentOverTime::scalar_udf(),
4623            vec![
4624                ColumnarValue::Array(Arc::new(ts_range.into_dict())),
4625                ColumnarValue::Array(Arc::new(value_range.into_dict())),
4626            ],
4627            DataType::Float64,
4628        );
4629        let result = extract_array(&result).unwrap();
4630        let result = result.as_any().downcast_ref::<Float64Array>().unwrap();
4631
4632        assert!(result.is_null(0));
4633        assert_eq!(result.value(1), 1.0);
4634    }
4635
4636    #[test]
4637    fn delta_requires_exact_layout() {
4638        let first = sample_histogram(2.0, 3.0, vec![1.0, 1.0]);
4639        let last = sample_histogram(5.0, 8.0, vec![2.0, 3.0]);
4640        let delta = histogram_delta(&[first, last], &[0, 1], false).unwrap();
4641        assert_eq!(delta.count, 3.0);
4642        assert_eq!(delta.sum, 5.0);
4643        assert_eq!(delta.reset_hint, GAUGE_RESET_HINT);
4644        assert_eq!(delta.positive_buckets, vec![1.0, 2.0]);
4645    }
4646
4647    #[test]
4648    fn reset_hint_shortcuts_detection() {
4649        let previous = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
4650
4651        let mut current = sample_histogram(7.0, 12.0, vec![3.0, 4.0]);
4652        current.reset_hint = COUNTER_RESET_HINT;
4653        assert!(current.detect_reset(&previous));
4654
4655        let mut current = sample_histogram(5.0, 8.0, vec![1.0, 4.0]);
4656        current.reset_hint = NOT_COUNTER_RESET_HINT;
4657        assert!(!current.detect_reset(&previous));
4658    }
4659
4660    #[test]
4661    fn start_timestamp_detects_counter_reset() {
4662        let first = sample_histogram(6.0, 10.0, vec![2.0, 4.0]);
4663        let mut last = sample_histogram(7.0, 12.0, vec![3.0, 4.0]);
4664        last.start_timestamp = Some(1500);
4665
4666        let delta = histogram_delta(&[first.clone(), last.clone()], &[1000, 2000], true).unwrap();
4667        assert_eq!(delta.count, 7.0);
4668        assert_eq!(delta.sum, 12.0);
4669
4670        let idelta = idelta_value(&[first, last], true, 1000, 2000, 1.0).unwrap();
4671        assert_eq!(idelta.count, 7.0);
4672        assert_eq!(idelta.sum, 12.0);
4673    }
4674
4675    #[test]
4676    fn extrapolated_rate_uses_start_timestamp_synthetic_zero() {
4677        let mut single = sample_histogram(1.0, 1.0, vec![1.0]);
4678        single.start_timestamp = Some(1_000);
4679
4680        let rate = extrapolated_histogram_result(
4681            NativeHistogramRate::scalar_udf(),
4682            vec![2_000],
4683            vec![single.clone()],
4684            3_000,
4685            3_000,
4686        )
4687        .unwrap();
4688        assert_eq!(rate.count, 1.0 / 3.0);
4689        assert_eq!(rate.sum, 1.0 / 3.0);
4690
4691        let increase = extrapolated_histogram_result(
4692            NativeHistogramIncrease::scalar_udf(),
4693            vec![2_000],
4694            vec![single],
4695            3_000,
4696            3_000,
4697        )
4698        .unwrap();
4699        assert_eq!(increase.count, 1.0);
4700        assert_eq!(increase.sum, 1.0);
4701
4702        let mut first = sample_histogram(2.0, 2.0, vec![2.0]);
4703        first.start_timestamp = Some(1_000);
4704        let last = sample_histogram(4.0, 4.0, vec![4.0]);
4705        let increase = extrapolated_histogram_result(
4706            NativeHistogramIncrease::scalar_udf(),
4707            vec![2_000, 3_000],
4708            vec![first, last],
4709            3_000,
4710            3_000,
4711        )
4712        .unwrap();
4713        assert_eq!(increase.count, 4.0);
4714        assert_eq!(increase.sum, 4.0);
4715    }
4716
4717    /// The raw range functions report a derived difference or quotient, so none of them keeps the
4718    /// start timestamp of the samples it read: the field names the start of the window one sample
4719    /// belongs to, and a result that spans several samples has no single such window.
4720    #[test]
4721    fn raw_range_functions_clear_the_start_timestamp() {
4722        let mut first = sample_histogram(2.0, 2.0, vec![2.0]);
4723        first.start_timestamp = Some(1_000);
4724        let mut last = sample_histogram(4.0, 4.0, vec![4.0]);
4725        last.start_timestamp = Some(2_000);
4726
4727        for udf in [
4728            NativeHistogramRate::scalar_udf(),
4729            NativeHistogramIncrease::scalar_udf(),
4730            NativeHistogramDelta::scalar_udf(),
4731        ] {
4732            let name = udf.name().to_string();
4733            let result = run_extrapolated_histogram_udf(udf, vec![first.clone(), last.clone()]);
4734            assert_eq!(
4735                result.start_timestamp, None,
4736                "{name}: the range functions derive a value of their own"
4737            );
4738        }
4739        for udf in [
4740            NativeHistogramIDelta::scalar_udf(),
4741            NativeHistogramIRate::scalar_udf(),
4742        ] {
4743            let name = udf.name().to_string();
4744            let result = run_histogram_range_udf(udf, vec![first.clone(), last.clone()]);
4745            assert_eq!(
4746                result.start_timestamp, None,
4747                "{name}: the range functions derive a value of their own"
4748            );
4749        }
4750    }
4751
4752    #[test]
4753    fn extrapolated_rate_requires_strictly_in_range_start_timestamp() {
4754        for (start_timestamp, range_end, range_length) in [
4755            (0, 3_000, 3_000),
4756            (500, 3_000, 2_000),
4757            (1_000, 3_000, 2_000),
4758            (2_000, 3_000, 3_000),
4759            (2_500, 3_000, 3_000),
4760        ] {
4761            let mut sample = sample_histogram(1.0, 1.0, vec![1.0]);
4762            sample.start_timestamp = Some(start_timestamp);
4763            assert!(
4764                extrapolated_histogram_result(
4765                    NativeHistogramRate::scalar_udf(),
4766                    vec![2_000],
4767                    vec![sample],
4768                    range_end,
4769                    range_length,
4770                )
4771                .is_none(),
4772                "start_timestamp={start_timestamp}"
4773            );
4774        }
4775
4776        let mut gauge = sample_histogram(1.0, 1.0, vec![1.0]);
4777        gauge.start_timestamp = Some(1_000);
4778        gauge.reset_hint = GAUGE_RESET_HINT;
4779        assert!(
4780            extrapolated_histogram_result(
4781                NativeHistogramDelta::scalar_udf(),
4782                vec![2_000],
4783                vec![gauge],
4784                3_000,
4785                3_000,
4786            )
4787            .is_none()
4788        );
4789    }
4790
4791    #[test]
4792    fn first_reset_ignores_incompatible_pre_reset_layout() {
4793        let first = sample_histogram(10.0, 10.0, vec![10.0]);
4794        let second = NativeHistogram {
4795            schema: CUSTOM_BUCKETS_SCHEMA,
4796            zero_threshold: 0.0,
4797            sum: 2.0,
4798            reset_hint: COUNTER_RESET_HINT,
4799            start_timestamp: None,
4800            custom_values: vec![1.0],
4801            positive_spans: vec![Span {
4802                offset: 0,
4803                length: 1,
4804            }],
4805            negative_spans: Vec::new(),
4806            count: 2.0,
4807            zero_count: 0.0,
4808            positive_buckets: vec![2.0],
4809            negative_buckets: Vec::new(),
4810        };
4811
4812        let delta = histogram_delta(&[first, second], &[1_000, 2_000], true).unwrap();
4813        assert_eq!(delta.schema, CUSTOM_BUCKETS_SCHEMA);
4814        assert_eq!(delta.count, 2.0);
4815        assert_eq!(delta.sum, 2.0);
4816        assert_eq!(delta.positive_buckets, vec![2.0]);
4817    }
4818
4819    #[test]
4820    fn counter_delta_handles_reset_segment_boundaries() {
4821        let first = sample_histogram(5.0, 5.0, vec![5.0]);
4822        let second = sample_histogram(7.0, 7.0, vec![7.0]);
4823        let mut reset = sample_histogram(2.0, 2.0, vec![2.0]);
4824        reset.reset_hint = COUNTER_RESET_HINT;
4825        let last = sample_histogram(4.0, 4.0, vec![4.0]);
4826
4827        let delta = histogram_delta(
4828            &[first, second, reset, last],
4829            &[1_000, 2_000, 3_000, 4_000],
4830            true,
4831        )
4832        .unwrap();
4833        assert_eq!(delta.count, 6.0);
4834        assert_eq!(delta.sum, 6.0);
4835        assert_eq!(delta.positive_buckets, vec![6.0]);
4836    }
4837}